<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/lib/session.php';
require_once __DIR__ . '/../src/lib/auth.php';

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

    if ($email === '' || $pass === '') {
        $errors[] = "Email et mot de passe requis.";
    } else {
        $user = verify_login($email, $pass);
        if ($user) {
            start_secure_session();
            $_SESSION['user'] = $user;
            header('Location: ' . $basePath . '/dashboard');
            exit;
        } else {
            $errors[] = "Identifiants invalides.";
        }
    }
}

include __DIR__ . '/partials/header.php';
?>

<style>
    .login-container {
        max-width: 400px;
        margin: 40px auto;
        background: #1e293b;
        padding: 25px;
        border-radius: 10px;
        color: white;
        box-shadow: 0 4px 15px rgba(0,0,0,0.4);
    }
    .login-container h2 {
        color: #38bdf8;
        text-align: center;
        margin-bottom: 20px;
    }
    .login-container label {
        display: block;
        margin-top: 10px;
        font-weight: bold;
    }
    .login-container input {
        width: 95%;
        padding: 10px;
        margin-top: 5px;
        border-radius: 6px;
        border: 1px solid #334155;
        background-color: #0f172a;
        color: white;
        font-size: 14px;
        transition: border-color 0.3s, box-shadow 0.3s;
    }
    .login-container input:focus {
        border-color: #38bdf8;
        box-shadow: 0 0 5px #38bdf8;
        outline: none;
    }
    .login-container button {
        width: 100%;
        padding: 12px;
        background: #38bdf8;
        border: none;
        color: #0f172a;
        font-weight: bold;
        font-size: 16px;
        border-radius: 6px;
        margin-top: 15px;
        cursor: pointer;
        transition: background 0.3s, transform 0.2s;
    }
    .login-container button:hover {
        background: #0ea5e9;
        transform: scale(1.02);
    }
    .error-message {
        background: rgba(239, 68, 68, 0.15);
        border: 1px solid #ef4444;
        color: #f87171;
        padding: 8px;
        border-radius: 6px;
        margin-bottom: 10px;
        font-size: 14px;
    }
</style>

<div class="login-container">
    <h2>Connexion</h2>

    <?php foreach ($errors as $e): ?>
        <div class="error-message"><?= htmlspecialchars($e) ?></div>
    <?php endforeach; ?>

    <form method="post">
        <label>Email</label>
        <input type="email" name="email" placeholder="Votre email" required>

        <label>Mot de passe</label>
        <input type="password" name="password" placeholder="Votre mot de passe" required>

        <button type="submit">Se connecter</button>
    </form>
</div>

<?php include __DIR__ . '/partials/footer.php'; ?>
