<?php
session_start();

// Vérification session admin
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['super_admin', 'admin'])) {
    header('Location: login.php');
    exit();
}

// Connexion à la base de données
$host = 'localhost';
$dbname = 'cpn';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Erreur de connexion : " . $e->getMessage());
}

// Récupérer les informations de l'utilisateur courant
$current_user = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
    $stmt->execute([$_SESSION['user_id'] ?? 0]);
    $current_user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(Exception $e) {
    $current_user = ['nom' => 'Admin', 'prenom' => ''];
}

// Récupérer la date d'aujourd'hui pour la validation
$date_aujourdhui = date('Y-m-d');

// Récupérer les examens
$examens = [];
try {
    $sql = "SELECT e.*, 
                   m.nom_matiere,
                   g.nom_groupe,
                   s.nom_salle
            FROM examen e
            LEFT JOIN matieres m ON e.id_matieres = m.id_matiere
            LEFT JOIN groupe g ON e.id_groupe = g.id_groupe
            LEFT JOIN salle s ON e.id_salle = s.id_salle
            ORDER BY e.date_examen DESC, e.heure_debut";
    
    $stmt = $pdo->query($sql);
    $examens = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $examens = [];
}

// Jours de la semaine
$jours = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];

// Traitement du formulaire d'ajout
$message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    if ($_POST['action'] == 'ajouter_examen') {
        try {
            if (empty($_POST['id_matieres']) || empty($_POST['id_groupe']) || empty($_POST['id_salle'])) {
                throw new Exception("Tous les champs sont obligatoires");
            }
            
            $date_examen = $_POST['date_examen'];
            
            if ($date_examen < $date_aujourdhui) {
                $message = '<div class="alert-error">❌ Vous ne pouvez pas programmer un examen à une date passée ('.date('d/m/Y', strtotime($date_examen)).').</div>';
            } else {
                $check = $pdo->prepare("SELECT id_examen FROM examen 
                                        WHERE date_examen = ? 
                                        AND id_salle = ? 
                                        AND ((heure_debut <= ? AND heure_fin > ?) 
                                        OR (heure_debut < ? AND heure_fin >= ?))");
                
                $check->execute([
                    $date_examen,
                    $_POST['id_salle'],
                    $_POST['heure_fin'],
                    $_POST['heure_debut'],
                    $_POST['heure_fin'],
                    $_POST['heure_debut']
                ]);
                
                if ($check->rowCount() > 0) {
                    $message = '<div class="alert-error">❌ Un examen est déjà programmé dans cette salle aux mêmes horaires !</div>';
                } else {
                    $sql = "INSERT INTO examen (id_matieres, id_groupe, date_examen, heure_debut, heure_fin, id_salle, type_examen) 
                            VALUES (:id_matieres, :id_groupe, :date_examen, :heure_debut, :heure_fin, :id_salle, :type_examen)";
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        ':id_matieres' => $_POST['id_matieres'],
                        ':id_groupe' => $_POST['id_groupe'],
                        ':date_examen' => $date_examen,
                        ':heure_debut' => $_POST['heure_debut'],
                        ':heure_fin' => $_POST['heure_fin'],
                        ':id_salle' => $_POST['id_salle'],
                        ':type_examen' => $_POST['type_examen']
                    ]);
                    
                    $message = '<div class="alert-success">✅ Examen ajouté avec succès!</div>';
                    echo '<meta http-equiv="refresh" content="2">';
                }
            }
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    } elseif ($_POST['action'] == 'supprimer_examen' && isset($_POST['id_examen'])) {
        try {
            $stmt = $pdo->prepare("DELETE FROM examen WHERE id_examen = ?");
            $stmt->execute([$_POST['id_examen']]);
            $message = '<div class="alert-success">✅ Examen supprimé avec succès!</div>';
            echo '<meta http-equiv="refresh" content="1">';
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

// Récupérer les données pour les formulaires
$matieres = [];
$groupes = [];
$salles = [];

try {
    $matieres = $pdo->query("SELECT * FROM matieres ORDER BY nom_matiere")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

try {
    $groupes = $pdo->query("SELECT * FROM groupe ORDER BY id_groupe")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

try {
    $salles = $pdo->query("SELECT * FROM salle ORDER BY id_salle")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion Examens | CPN</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
            background: linear-gradient(135deg, #f2f3f6 0%, #f0f4f6 100%);
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100%;
            background: linear-gradient(135deg, #e3e5ee 0%, #2f6d8c 50%, #095175 100%);
            box-shadow: 5px 0 30px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            z-index: 1000;
            overflow-y: auto;
        }

        .sidebar-header {
            padding: 40px 20px;
            text-align: center;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 20px;
        }

        .sidebar-header .logo-area {
            margin-bottom: 15px;
        }

        .sidebar-header .logo-area img {
            max-width: 150px;
            height: auto;
            border-radius: 20px;
            padding: 10px;
            transition: transform 0.3s ease;
        }

        .sidebar-header .logo-area img:hover {
            transform: scale(1.05);
        }

        .sidebar-header h2 {
            color: white;
            font-size: 24px;
            font-weight: 700;
            margin-top: 15px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
        }

        .sidebar-header p {
            color: rgba(255, 255, 255, 0.9);
            font-size: 13px;
            margin-top: 5px;
            font-weight: 500;
        }

        .sidebar-nav {
            padding: 0 15px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 14px 18px;
            margin-bottom: 8px;
            color: white;
            text-decoration: none;
            border-radius: 12px;
            transition: all 0.3s ease;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-nav a:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateX(8px);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .sidebar-nav a.active {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
            color: white;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.4);
        }

        .sidebar-nav .logout {
            margin-top: 40px;
            background: rgba(220, 53, 69, 0.8);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .sidebar-nav .logout:hover {
            background: #dc3545;
            color: white;
            transform: translateX(8px);
        }

        /* Main content */
        .main-content {
            margin-left: 280px;
            padding: 20px 30px;
        }

        /* Top header */
        .top-header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 20px 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            backdrop-filter: blur(10px);
        }

        .header-info h1 {
            font-size: 24px;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .header-info p {
            color: #64748b;
            font-size: 14px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: linear-gradient(135deg, #667eea20, #764ba220);
            padding: 10px 20px;
            border-radius: 50px;
            border: 1px solid rgba(102, 126, 234, 0.2);
        }

        .user-avatar {
            width: 45px;
            height: 45px;
            background: linear-gradient(135deg, #2f6d8c, #095175);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        /* Page header */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-header h2 {
            color: #1e293b;
            font-size: 28px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn-ajouter {
            background: linear-gradient(135deg, #2f6d8c, #095175);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(47, 109, 140, 0.3);
        }

        .btn-ajouter:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(47, 109, 140, 0.4);
        }

        /* Date info */
        .date-info {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            padding: 12px 20px;
            margin-bottom: 25px;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            backdrop-filter: blur(10px);
            font-weight: 500;
            color: #1e293b;
        }

        /* Form container */
        .form-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            display: none;
            border: 2px solid rgba(47, 109, 140, 0.3);
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .form-container h3 {
            color: #1e293b;
            font-size: 20px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .form-grid select, .form-grid input {
            padding: 12px 15px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.3s;
            background: white;
        }

        .form-grid select:focus, .form-grid input:focus {
            outline: none;
            border-color: #2f6d8c;
            box-shadow: 0 0 0 3px rgba(47, 109, 140, 0.1);
        }

        .form-grid input.invalid-date {
            border-color: #ef4444;
            background: #fee2e2;
        }

        .date-warning {
            color: #ef4444;
            font-size: 12px;
            margin-top: 10px;
            display: none;
            font-weight: 500;
        }

        .form-buttons {
            margin-top: 20px;
            display: flex;
            gap: 15px;
            justify-content: flex-end;
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981, #059669);
            box-shadow: 0 5px 15px rgba(16, 185, 129, 0.3);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            box-shadow: 0 5px 15px rgba(239, 68, 68, 0.3);
        }

        /* Filters */
        .filters-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .filtre-select {
            padding: 12px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            min-width: 200px;
            background: white;
            transition: all 0.3s;
        }

        .filtre-select:focus {
            outline: none;
            border-color: #2f6d8c;
        }

        /* Examens container */
        .examens-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            overflow-x: auto;
        }

        .examens-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .examens-table th {
            background: linear-gradient(135deg, #1e293b, #0f172a);
            color: white;
            padding: 14px 12px;
            font-weight: 600;
            text-align: center;
            border: 1px solid #334155;
        }

        .examens-table td {
            border: 1px solid #e2e8f0;
            padding: 12px;
            text-align: center;
        }

        .examens-table tbody tr:hover {
            background: #f8fafc;
        }

        .examens-table tr.examen-passe {
            background: #f8fafc;
            opacity: 0.7;
        }

        .examens-table tr.examen-aujourdhui {
            background: #fef3c7;
        }

        /* Badges */
        .type-examen {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .type-test1 { background: #cff4fc; color: #055160; }
        .type-test2 { background: #d1e7dd; color: #0a3622; }
        .type-examen-badge { background: #fff3cd; color: #664d03; }

        .badge-passe {
            background: #e2e8f0;
            color: #475569;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            margin-left: 5px;
            font-weight: 600;
        }

        .badge-aujourdhui {
            background: #fef3c7;
            color: #92400e;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            margin-left: 5px;
            font-weight: 600;
        }

        /* Button delete */
        .btn-supprimer {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            border: none;
            padding: 8px 14px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .btn-supprimer:hover {
            transform: scale(1.05);
            box-shadow: 0 3px 10px rgba(239, 68, 68, 0.4);
        }

        /* Alerts */
        .alert-success {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #065f46;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #10b981;
            font-weight: 500;
        }

        .alert-error {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #ef4444;
            font-weight: 500;
        }

        /* Legend */
        .legend {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 20px;
            margin-top: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            display: flex;
            gap: 25px;
            flex-wrap: wrap;
            align-items: center;
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #2f6d8c, #095175);
            border-radius: 10px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            
            .top-header {
                flex-direction: column;
                text-align: center;
            }
            
            .filters-section {
                flex-direction: column;
            }
            
            .filtre-select {
                width: 100%;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="logo-area">
                <img src="logo.png" alt="Logo CPN" onerror="this.src='https://via.placeholder.com/80x80?text=CPN'">
            </div>
            <h2>CPN Formation</h2>
            <p>Plateforme de gestion</p>
        </div>
        
        <div class="sidebar-nav">
            <a href="admin.php" class="active">
                <span>📊</span>
                <span>Tableau de bord</span>
            </a>
            <a href="gestion_etudiant.php">
                <span>🎓</span>
                <span>Gestion Étudiants</span>
            </a>
            <a href="gestion_enseignant.php">
                <span>👨‍🏫</span>
                <span>Gestion Enseignants</span>
            </a>
            <a href="gestion_stagiaire.php">
                <span>🏢</span>
                <span>Gestion Stagiaires</span>
            </a>
            <a href="emplois.php">
                <span>📅</span>
                <span>Emploi du Temps</span>
            </a>
            <a href="examens.php">
                <span>📝</span>
                <span>Gestion Examens</span>
            </a>
            <a href="releve.php">
                <span>✏️</span>
                <span>Relevé des notes</span>
            </a>
            <a href="gestion_formation.php">
                <span>📘</span>
                <span>Gestion de Formation</span>
            </a>
            <a href="gestion_site.php">
            <span>🌐</span>
            <span>Gestion du Site</span>
            </a>
            <a href="gestion_inscriptions.php">
            <span>✍️</span>
            <span>Gestion Inscriptions</span>
            </a>
            <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'super_admin'): ?>
            <a href="gestion_admin.php" style="background: rgba(255, 255, 255, 0.2);">
                <span>👥</span>
                <span>Gestion Admins</span>
            </a>
            <?php endif; ?>
            <a href="logout.php" class="logout">
                <span>🚪</span>
                <span>Déconnexion</span>
            </a>
        </div>
    </div>
    <!-- Main content -->
    <div class="main-content">
        <!-- Top header -->
        <div class="top-header">
            <div class="header-info">
                <h1>Gestion des Examens</h1>
                <p>Planification et suivi des examens</p>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($current_user['nom'] ?? 'A', 0, 1)); ?>
                </div>
                <div>
                    <strong><?php echo htmlspecialchars(($current_user['nom'] ?? 'Admin') . ' ' . ($current_user['prenom'] ?? '')); ?></strong>
                    <br>
                    <small style="color: #64748b;"><?php echo isset($_SESSION['user_role']) ? ucfirst(str_replace('_', ' ', $_SESSION['user_role'])) : 'Admin'; ?></small>
                </div>
            </div>
        </div>

        <!-- Page header with add button -->
        <div class="page-header">
            <h2>
                <span>📝</span> Gestion des Examens
            </h2>
            <button class="btn-ajouter" onclick="toggleFormulaire()">
                <span>+</span> Planifier un examen
            </button>
        </div>

        <!-- Date info -->
        <div class="date-info">
            📅 Aujourd'hui : <?php echo date('d/m/Y'); ?>
        </div>

        <?php echo $message; ?>

        <!-- Formulaire d'ajout -->
        <div id="formulaireExamen" class="form-container">
            <h3>➕ Nouvel examen</h3>
            <form method="POST" action="" onsubmit="return validerDate()">
                <input type="hidden" name="action" value="ajouter_examen">
                <div class="form-grid">
                    <select name="id_matieres" required>
                        <option value="">Sélectionner matière</option>
                        <?php foreach ($matieres as $matiere): ?>
                            <option value="<?php echo $matiere['id_matiere']; ?>"><?php echo htmlspecialchars($matiere['nom_matiere']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="id_groupe" required>
                        <option value="">Sélectionner groupe</option>
                        <?php foreach ($groupes as $g): ?>
                            <option value="<?php echo $g['id_groupe']; ?>"><?php echo htmlspecialchars($g['nom_groupe'] ?? 'Groupe ' . $g['id_groupe']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <input type="date" 
                           name="date_examen" 
                           id="date_examen" 
                           min="<?php echo $date_aujourdhui; ?>" 
                           value="<?php echo $date_aujourdhui; ?>"
                           onchange="verifierDate(this)"
                           required>
                    
                    <select name="heure_debut" id="heure_debut" required>
                        <option value="">Heure début</option>
                        <option value="08:00">08:00</option>
                        <option value="09:00">09:00</option>
                        <option value="10:00">10:00</option>
                        <option value="11:00">11:00</option>
                        <option value="14:00">14:00</option>
                        <option value="15:00">15:00</option>
                        <option value="16:00">16:00</option>
                    </select>
                    
                    <select name="heure_fin" id="heure_fin" required>
                        <option value="">Heure fin</option>
                        <option value="10:00">10:00</option>
                        <option value="11:00">11:00</option>
                        <option value="12:00">12:00</option>
                        <option value="13:00">13:00</option>
                        <option value="16:00">16:00</option>
                        <option value="17:00">17:00</option>
                        <option value="18:00">18:00</option>
                    </select>
                    
                    <select name="id_salle" required>
                        <option value="">Sélectionner salle</option>
                        <?php foreach ($salles as $salle): ?>
                            <option value="<?php echo $salle['id_salle']; ?>"><?php echo htmlspecialchars($salle['nom_salle'] ?? 'Salle ' . $salle['id_salle']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="type_examen" required>
                        <option value="">Type d'examen</option>
                        <option value="test1">Test 1</option>
                        <option value="test2">Test 2</option>
                        <option value="examen">Examen final</option>
                    </select>
                </div>
                <div class="date-warning" id="dateWarning">
                    ⚠️ Attention : La date sélectionnée est antérieure à aujourd'hui !
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-ajouter btn-success">✅ Enregistrer</button>
                    <button type="button" class="btn-ajouter btn-danger" onclick="toggleFormulaire()">❌ Annuler</button>
                </div>
            </form>
        </div>

        <!-- Filtres -->
        <div class="filters-section">
            <select class="filtre-select" id="filtreGroupe" onchange="filtrerParGroupe(this.value)">
                <option value="">👥 Tous les groupes</option>
                <?php foreach ($groupes as $g): ?>
                    <option value="<?php echo $g['id_groupe']; ?>"><?php echo htmlspecialchars($g['nom_groupe'] ?? 'Groupe ' . $g['id_groupe']); ?></option>
                <?php endforeach; ?>
            </select>
            
            <select class="filtre-select" id="filtreType" onchange="filtrerParType(this.value)">
                <option value="">📋 Tous les types</option>
                <option value="test1">Test 1</option>
                <option value="test2">Test 2</option>
                <option value="examen">Examen final</option>
            </select>
        </div>

        <!-- Liste des examens -->
        <div class="examens-container">
            <table class="examens-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Matière</th>
                        <th>Groupe</th>
                        <th>Horaire</th>
                        <th>Salle</th>
                        <th>Type</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($examens)): ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 50px; color: #94a3b8;">
                                📭 Aucun examen planifié. Cliquez sur "Planifier un examen" pour commencer.
                            </td>
                        </tr>
                    <?php else: 
                        $aujourdhui = date('Y-m-d');
                        foreach ($examens as $examen): 
                            $date_examen = $examen['date_examen'];
                            $est_passe = $date_examen < $aujourdhui;
                            $est_aujourdhui = $date_examen == $aujourdhui;
                            $row_class = '';
                            if ($est_passe) $row_class = 'examen-passe';
                            elseif ($est_aujourdhui) $row_class = 'examen-aujourdhui';
                        ?>
                            <tr class="examen-row <?php echo $row_class; ?>" 
                                data-groupe="<?php echo $examen['id_groupe']; ?>" 
                                data-type="<?php echo $examen['type_examen']; ?>">
                                <td>
                                    <?php echo date('d/m/Y', strtotime($examen['date_examen'])); ?>
                                    <?php if ($est_passe): ?>
                                        <span class="badge-passe">Passé</span>
                                    <?php elseif ($est_aujourdhui): ?>
                                        <span class="badge-aujourdhui">Aujourd'hui</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo htmlspecialchars($examen['nom_matiere'] ?? 'N/A'); ?></strong></td>
                                <td><?php echo htmlspecialchars($examen['nom_groupe'] ?? 'Groupe ' . $examen['id_groupe']); ?></td>
                                <td><?php echo substr($examen['heure_debut'], 0, 5) . ' - ' . substr($examen['heure_fin'], 0, 5); ?></td>
                                <td><?php echo htmlspecialchars($examen['nom_salle'] ?? 'Salle ' . $examen['id_salle']); ?></td>
                                <td>
                                    <?php
                                    $type_class = '';
                                    $type_label = '';
                                    switch($examen['type_examen']) {
                                        case 'test1':
                                            $type_class = 'type-test1';
                                            $type_label = 'Test 1';
                                            break;
                                        case 'test2':
                                            $type_class = 'type-test2';
                                            $type_label = 'Test 2';
                                            break;
                                        case 'examen':
                                            $type_class = 'type-examen-badge';
                                            $type_label = 'Examen final';
                                            break;
                                        default:
                                            $type_label = $examen['type_examen'];
                                    }
                                    ?>
                                    <span class="type-examen <?php echo $type_class; ?>"><?php echo $type_label; ?></span>
                                </td>
                                <td>
                                    <button class="btn-supprimer" onclick="supprimerExamen(<?php echo $examen['id_examen']; ?>)">🗑️ Supprimer</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Légende -->
        <div class="legend">
            <span class="type-examen type-test1">Test 1</span>
            <span class="type-examen type-test2">Test 2</span>
            <span class="type-examen type-examen-badge">Examen final</span>
            <span class="badge-passe" style="background: #e2e8f0;">Examen passé</span>
            <span class="badge-aujourdhui" style="background: #fef3c7;">Examen aujourd'hui</span>
        </div>
    </div>

    <script>
        function toggleFormulaire() {
            let formulaire = document.getElementById('formulaireExamen');
            if (formulaire.style.display === 'none' || formulaire.style.display === '') {
                formulaire.style.display = 'block';
                document.getElementById('date_examen').value = '<?php echo $date_aujourdhui; ?>';
                document.getElementById('dateWarning').style.display = 'none';
                formulaire.scrollIntoView({ behavior: 'smooth', block: 'start' });
            } else {
                formulaire.style.display = 'none';
            }
        }

        function verifierDate(input) {
            let dateWarning = document.getElementById('dateWarning');
            let dateValue = input.value;
            let aujourdhui = '<?php echo $date_aujourdhui; ?>';
            
            if (dateValue < aujourdhui) {
                input.classList.add('invalid-date');
                dateWarning.style.display = 'block';
            } else {
                input.classList.remove('invalid-date');
                dateWarning.style.display = 'none';
            }
        }

        function validerDate() {
            let dateInput = document.getElementById('date_examen');
            let dateValue = dateInput.value;
            let aujourdhui = '<?php echo $date_aujourdhui; ?>';
            
            if (dateValue < aujourdhui) {
                alert('❌ Erreur : Vous ne pouvez pas programmer un examen à une date passée !\nVeuillez choisir une date à partir d\'aujourd\'hui.');
                return false;
            }
            
            let heureDebut = document.getElementById('heure_debut').value;
            let heureFin = document.getElementById('heure_fin').value;
            
            if (heureDebut && heureFin && heureDebut >= heureFin) {
                alert('❌ Erreur : L\'heure de fin doit être après l\'heure de début !');
                return false;
            }
            
            return true;
        }

        function filtrerParGroupe(groupe) {
            let rows = document.querySelectorAll('.examen-row');
            let typeFiltre = document.getElementById('filtreType').value;
            
            rows.forEach(row => {
                let groupeMatch = groupe === '' || row.dataset.groupe === groupe;
                let typeMatch = typeFiltre === '' || row.dataset.type === typeFiltre;
                row.style.display = (groupeMatch && typeMatch) ? '' : 'none';
            });
        }

        function filtrerParType(type) {
            let rows = document.querySelectorAll('.examen-row');
            let groupeFiltre = document.getElementById('filtreGroupe').value;
            
            rows.forEach(row => {
                let groupeMatch = groupeFiltre === '' || row.dataset.groupe === groupeFiltre;
                let typeMatch = type === '' || row.dataset.type === type;
                row.style.display = (groupeMatch && typeMatch) ? '' : 'none';
            });
        }

        function supprimerExamen(id_examen) {
            if (confirm('Êtes-vous sûr de vouloir supprimer cet examen ?')) {
                let form = document.createElement('form');
                form.method = 'POST';
                form.action = '';
                
                let input1 = document.createElement('input');
                input1.type = 'hidden';
                input1.name = 'action';
                input1.value = 'supprimer_examen';
                
                let input2 = document.createElement('input');
                input2.type = 'hidden';
                input2.name = 'id_examen';
                input2.value = id_examen;
                
                form.appendChild(input1);
                form.appendChild(input2);
                document.body.appendChild(form);
                form.submit();
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            let dateInput = document.getElementById('date_examen');
            if (dateInput) {
                dateInput.addEventListener('change', function() { verifierDate(this); });
            }
        });
    </script>
</body>
</html>