<?php
session_start();
require_once 'config/database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    $db = Database::getInstance()->getConnection();

    try {
        // Проверяем пользователя
        $stmt = $db->prepare("
            SELECT user_id, email, password_hash, full_name
            FROM users
            WHERE email = ? AND is_active = TRUE
        ");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            // Сохраняем в сессию
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['isLoggedIn'] = true;
            $_SESSION['login_time'] = time();

            // Обновляем время последнего входа
            $update_stmt = $db->prepare("
                UPDATE users
                SET updated_at = CURRENT_TIMESTAMP
                WHERE user_id = ?
            ");
            $update_stmt->execute([$user['user_id']]);

            header('Location: catalog.php');
            exit();
        } else {
            header('Location: вход.php?error=invalid_credentials');
            exit();
        }
    } catch (PDOException $e) {
        header('Location: вход.php?error=db_error');
        exit();
    }
}
?>