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

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

    if (empty($email) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Заполните все поля']);
        exit();
    }

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

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

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
            exit();
        }

        if (!$user['is_active']) {
            echo json_encode(['success' => false, 'message' => 'Аккаунт заблокирован']);
            exit();
        }

        // Проверяем пароль
        if (!password_verify($password, $user['password_hash'])) {
            echo json_encode(['success' => false, 'message' => 'Неверный пароль']);
            exit();
        }

        // Сохраняем в сессию
        $_SESSION['user_id'] = $user['user_id'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['user_phone'] = $user['phone'] ?? '';
        $_SESSION['user_city'] = $user['city'] ?? '';
        $_SESSION['isLoggedIn'] = true;
        $_SESSION['isAdmin'] = (bool)$user['is_admin'];
        $_SESSION['login_time'] = time();

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

        echo json_encode(['success' => true, 'redirect' => 'catalog.php']);

    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Ошибка базы данных']);
    }

} else {
    echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
?>