<?php
// Fichier: login.php
require 'includes/db.php';
session_start();

$error = '';

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

    // Recherche de l'utilisateur
    $stmt = $pdo->prepare("SELECT * FROM utilisateurs WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['mot_de_passe_hash'])) {
        // Succès : On enregistre l'utilisateur dans la session
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_nom'] = $user['nom'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['entreprise_id'] = $user['entreprise_id'];
        
        // Redirection vers le tableau de bord
        header('Location: dashboard.php');
        exit();
    } else {
        $error = "Email ou mot de passe incorrect.";
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion - Naïta</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body style="background-color: #f4f6f9;">

    <div class="container">
        <div class="login-container text-center">
            <img src="assets/logo.jpg" alt="Naïta Nature" style="max-width: 150px; margin-bottom: 20px;">
            
            <h4 class="mb-4">Espace Professionnel</h4>
            
            <?php if ($error): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php endif; ?>

            <form method="POST">
                <div class="mb-3 text-start">
                    <label class="form-label">Adresse Email</label>
                    <input type="email" name="email" class="form-control" required placeholder="exemple@cse.fr">
                </div>
                <div class="mb-3 text-start">
                    <label class="form-label">Mot de passe</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-gold w-100 py-2">Se connecter</button>
            </form>
            
            <div class="mt-3 text-muted" style="font-size: 0.9em;">
                Accès réservé aux gestionnaires CSE
            </div>
        </div>
    </div>

</body>
</html>