<?php
declare(strict_types=1);
require_once __DIR__ . "/config/database.php";
require_once __DIR__ . "/includes/auth.php";
require_once __DIR__ . "/includes/helpers.php";

if (isAuthenticated()) {
    header("Location: /PIS/index.php");
    exit;
}

$error = "";

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

    $stmt = $pdo->prepare("SELECT id, nom, role, mot_de_passe FROM utilisateurs WHERE email = :email LIMIT 1");
    $stmt->execute(["email" => $email]);
    $user = $stmt->fetch();

    $isValidPassword = false;
    if ($user) {
        $isValidPassword = password_verify($password, $user["mot_de_passe"]) || hash_equals($user["mot_de_passe"], $password);
    }

    if ($user && $isValidPassword) {
        if (!str_starts_with((string) $user["mot_de_passe"], '$2y$')) {
            $newHash = password_hash($password, PASSWORD_DEFAULT);
            $updateStmt = $pdo->prepare("UPDATE utilisateurs SET mot_de_passe = :mot_de_passe WHERE id = :id");
            $updateStmt->execute([
                "mot_de_passe" => $newHash,
                "id" => (int) $user["id"],
            ]);
        }
        $_SESSION["user_id"] = (int) $user["id"];
        $_SESSION["user_nom"] = $user["nom"];
        $_SESSION["user_role"] = $user["role"] ?? "utilisateur";
        header("Location: /PIS/index.php");
        exit;
    }

    $error = "Identifiants invalides.";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion - PIS</title>
    <link rel="stylesheet" href="/PIS/assets/css/style.css">
</head>
<body>
<main class="container login-box">
    <h2>Connexion</h2>
    <?php if ($error !== ""): ?>
        <p class="message" style="background:#fee2e2;color:#991b1b;"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>
    <form method="POST">
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="password" placeholder="Mot de passe" required>
        <button type="submit">Se connecter</button>
    </form>
</main>
</body>
</html>
