<?php
/**
 * Page de connexion
 */
require_once '../config/database.php';
require_once '../includes/functions.php';

// Déjà connecté → redirection directe selon le rôle
if (isset($_SESSION['user_id'])) {
    $dash = in_array($_SESSION['user_role'] ?? '', ['student', 'parent']) ? '../portal/dashboard.php' : '../admin/dashboard.php';
    header("Location: $dash");
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ── Vérification CSRF ────────────────────────────────────────────────────
    verifyCsrf();

    // ── Protection brute-force ───────────────────────────────────────────────
    if (!checkLoginAttempts()) {
        $remaining = remainingLockTime();
        $minutes   = max(1, ceil($remaining / 60));
        $error = "Trop de tentatives. Compte temporairement bloqué. Réessayez dans {$minutes} minute(s).";
    } else {
        $email    = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            $error = 'Veuillez remplir tous les champs.';
        } elseif (!validateEmail($email)) {
            $error = 'Adresse email invalide.';
        } else {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                // ── Compte désactivé (déconnecté) ────────────────────────────
                if ((int)($user['active'] ?? 1) !== 1) {
                    resetLoginAttempts();
                    $error = 'Votre compte a été désactivé. Contactez l\'administration.';
                } else {
                // ── Login réussi ─────────────────────────────────────────────
                resetLoginAttempts();

                // Régénérer l'ID de session → protection fixation de session
                session_regenerate_id(true);

                $_SESSION['user_id']     = (int)$user['id'];
                $_SESSION['user_name']   = $user['name'];
                $_SESSION['user_role']   = $user['role'];
                $_SESSION['user_email']  = $user['email'];
                $_SESSION['school_id']   = $user['school_id'];
                $_SESSION['user_active'] = (int)($user['active'] ?? 1);
                $_SESSION['user_photo']  = $user['photo'] ?? null;
                $_SESSION['_fingerprint'] = hash('sha256', $_SERVER['HTTP_USER_AGENT'] ?? '');

                // Redirection basée sur le rôle
                $redirect = $_SESSION['redirect_after_login'] ?? '';
                unset($_SESSION['redirect_after_login']);

                if (!empty($redirect)) {
                    $safePath = parse_url($redirect, PHP_URL_PATH);
                    $bp = defined('BASE_PATH') ? BASE_PATH : '/';
                    $isAppPath = strpos($safePath, $bp . 'admin/') !== false || strpos($safePath, $bp . 'portal/') !== false;
                    if (!empty($safePath) && $isAppPath) {
                        $clean = $safePath;
                        if ($bp !== '/' && strpos($clean, $bp) === 0) {
                            $clean = substr($clean, strlen($bp));
                        }
                        header('Location: ' . BASE_URL . ltrim($clean, '/'));
                        exit;
                    }
                }
                $dashboard = in_array($user['role'], ['student', 'parent']) ? 'portal/dashboard.php' : 'admin/dashboard.php';
                header('Location: ' . BASE_URL . $dashboard);
                exit;
                }

            } else {
                // ── Échec de connexion ───────────────────────────────────────
                recordFailedLogin();
                // Message volontairement générique pour ne pas indiquer si l'email existe
                $error = 'Email ou mot de passe incorrect.';

                // Pause anti-timing attack (200 ms fixe)
                usleep(200000);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion - Nukunu Mofiala</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="login-page">
    <div class="login-box">
        <h2><i class="fas fa-school"></i> Nukunu Mofiala</h2>

        <?php if ($error): ?>
            <div class="error-message"><?= e($error) ?></div>
        <?php endif; ?>

        <form method="POST" action="" autocomplete="off">
            <?= csrfField() ?>
            <div class="form-group">
                <label><i class="fas fa-envelope"></i> Email</label>
                <input type="email" name="email" required placeholder="votre@email.com"
                       value="<?= e($_POST['email'] ?? '') ?>" autocomplete="email">
            </div>
            <div class="form-group">
                <label><i class="fas fa-lock"></i> Mot de passe</label>
                <input type="password" name="password" required placeholder="••••••••" autocomplete="current-password">
            </div>
            <button type="submit" class="btn-submit">
                <i class="fas fa-sign-in-alt"></i> Se connecter
            </button>
        </form>
    </div>
</body>
</html>
