<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';

// Vérifier que l'utilisateur est enseignant
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'enseignant') {
    header('Location: login.php');
    exit();
}

// Récupération de l'ID enseignant
$id_enseignant = $_SESSION['id_enseignant'] ?? 0;
$id_user = $_SESSION['id_user'] ?? 0;

// Si l'ID enseignant n'est pas défini, le récupérer depuis id_user
if (!$id_enseignant && $id_user) {
    try {
        $stmt = $pdo->prepare("SELECT id_enseignant, nom, prenom FROM enseignant WHERE id_user = ?");
        $stmt->execute([$id_user]);
        $ens = $stmt->fetch();
        if ($ens) {
            $_SESSION['id_enseignant'] = $ens['id_enseignant'];
            $id_enseignant = $ens['id_enseignant'];
        }
    } catch(Exception $e) {
        error_log("Erreur récupération enseignant: " . $e->getMessage());
    }
}

$current_user = getUserInfo($pdo);
$message = "";
$message_type = "";

/* ================= RÉCUPÉRER LES DONNÉES ================= */

$etudiants = getEtudiants($pdo);
$matieres = getMatieres($pdo);
$groupes = getGroupes($pdo);
$salles = getSalles($pdo);

// Récupérer l'emploi du temps
function getEmploiTempsEnseignantCorrige($pdo, $id_enseignant) {
    $emploi = [];
    if (!$id_enseignant) return $emploi;
    
    try {
        $sql = "SELECT 
                    s.*, 
                    COALESCE(m.nom_matiere, 'Matière non assignée') as nom_matiere,
                    COALESCE(g.nom_groupe, CONCAT('Groupe ', s.id_groupe)) as nom_groupe,
                    COALESCE(sal.nom_salle, CONCAT('Salle ', s.id_salle)) as nom_salle,
                    s.jour,
                    TIME_FORMAT(s.heure_debut, '%H:%i') as heure_debut_formatted,
                    TIME_FORMAT(s.heure_fin, '%H:%i') as heure_fin_formatted,
                    COALESCE(m.nbr_heure_semaine, 0) as nbr_heure_semaine
                FROM seance s
                LEFT JOIN matieres m ON s.id_matiere = m.id_matiere
                LEFT JOIN groupe g ON s.id_groupe = g.id_groupe
                LEFT JOIN salle sal ON s.id_salle = sal.id_salle
                WHERE s.id_enseignant = :id_enseignant
                ORDER BY FIELD(s.jour, 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'), s.heure_debut";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':id_enseignant' => $id_enseignant]);
        $emploi = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(Exception $e) {
        error_log("Erreur getEmploiTempsEnseignant: " . $e->getMessage());
    }
    return $emploi;
}

$emploi_enseignant = getEmploiTempsEnseignantCorrige($pdo, $id_enseignant);

// Organiser par jour
$emploi_organise = [];
$jours_semaine = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
foreach ($emploi_enseignant as $cours) {
    $jour = $cours['jour'] ?? '';
    $heure = $cours['heure_debut'] ?? '';
    if (!isset($emploi_organise[$jour])) $emploi_organise[$jour] = [];
    $emploi_organise[$jour][$heure] = $cours;
}

// Récupérer les séances
$seances = [];
$seances_par_matiere = [];
try {
    $seances = $pdo->query("SELECT s.id_seance, s.id_matiere, s.id_groupe, m.nom_matiere 
                           FROM seance s
                           JOIN matieres m ON s.id_matiere = m.id_matiere
                           ORDER BY m.nom_matiere")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($seances as $s) {
        $seances_par_matiere[$s['id_matiere']] = $s;
    }
} catch(Exception $e) {}

// ============ FONCTIONS CORRIGÉES ============

function getGroupesWithStudents($pdo) {
    try {
        $sql = "SELECT DISTINCT g.id_groupe, g.nom_groupe, COUNT(e.id_etudiant) as nb_etudiants
                FROM groupe g
                LEFT JOIN etudiants e ON g.id_groupe = e.id_groupe
                WHERE e.id_etudiant IS NOT NULL AND e.id_etudiant != ''
                GROUP BY g.id_groupe, g.nom_groupe
                HAVING COUNT(e.id_etudiant) > 0
                ORDER BY g.nom_groupe";
        
        $stmt = $pdo->query($sql);
        $resultats = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($resultats)) {
            $sql2 = "SELECT id_groupe, nom_groupe FROM groupe ORDER BY nom_groupe";
            $stmt2 = $pdo->query($sql2);
            $tousGroupes = $stmt2->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($tousGroupes as $g) {
                $stmtCount = $pdo->prepare("SELECT COUNT(*) FROM etudiants WHERE id_groupe = ?");
                $stmtCount->execute([$g['id_groupe']]);
                $nb = $stmtCount->fetchColumn();
                if ($nb > 0) {
                    $resultats[] = [
                        'id_groupe' => $g['id_groupe'],
                        'nom_groupe' => $g['nom_groupe'],
                        'nb_etudiants' => $nb
                    ];
                }
            }
        }
        return $resultats;
    } catch(Exception $e) {
        error_log("Erreur getGroupesWithStudents: " . $e->getMessage());
        return [];
    }
}

function getEtudiantsByGroupe($pdo, $id_groupe) {
    try {
        $stmt = $pdo->prepare("SELECT e.id_etudiant, e.nom, e.prenom, g.nom_groupe
                               FROM etudiants e
                               JOIN groupe g ON e.id_groupe = g.id_groupe
                               WHERE e.id_groupe = ? AND e.id_etudiant IS NOT NULL
                               ORDER BY e.nom, e.prenom");
        $stmt->execute([$id_groupe]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(Exception $e) {
        error_log("Erreur getEtudiantsByGroupe: " . $e->getMessage());
        return [];
    }
}

$groupes_avec_etudiants = getGroupesWithStudents($pdo);

/* ================= GESTION DES ABSENCES ================= */

// AJOUTER une absence
if(isset($_POST['save_absence'])){
    $etudiant = $_POST['etudiant'] ?? 0;
    $matiere  = (int)($_POST['matiere'] ?? 0);
    $date     = $_POST['date'] ?? date('Y-m-d');
    
    $id_seance = null;
    
    // Chercher l'id_seance
    if (isset($seances_par_matiere[$matiere])) {
        $id_seance = $seances_par_matiere[$matiere]['id_seance'];
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id_seance FROM seance WHERE id_matiere = ? LIMIT 1");
            $stmt->execute([$matiere]);
            $seance = $stmt->fetch();
            if ($seance) $id_seance = $seance['id_seance'];
        } catch(Exception $e) {}
    }
    
    // Si toujours pas de séance, en créer une temporaire
    if (!$id_seance && $etudiant && $matiere) {
        try {
            $stmt = $pdo->prepare("SELECT id_groupe FROM etudiants WHERE id_etudiant = ?");
            $stmt->execute([$etudiant]);
            $etudiantInfo = $stmt->fetch();
            $groupe_id = $etudiantInfo['id_groupe'] ?? 1;
            
            $stmt = $pdo->prepare("INSERT INTO seance (jour, id_matiere, id_enseignant, id_groupe, id_salle, date_seance, heure_debut, heure_fin)
                                   VALUES ('Lundi', ?, ?, ?, 1, CURDATE(), '08:00:00', '10:00:00')");
            $stmt->execute([$matiere, $id_enseignant, $groupe_id]);
            $id_seance = $pdo->lastInsertId();
        } catch(Exception $e) {}
    }

    if ($etudiant && $matiere && $date && $id_seance) {
        try {
            $check = $pdo->prepare("SELECT id_absence FROM absence_etudiant WHERE id_etudiant = ? AND id_seance = ? AND date_absence = ?");
            $check->execute([$etudiant, $id_seance, $date]);
            
            if ($check->rowCount() == 0) {
                $stmt = $pdo->prepare("INSERT INTO absence_etudiant(id_etudiant, id_seance, date_absence, justifie) VALUES (?, ?, ?, 'non')");
                $stmt->execute([$etudiant, $id_seance, $date]);
                $message = "✅ Absence enregistrée avec succès";
                $message_type = "success";
            } else {
                $message = "⚠️ Cette absence existe déjà";
                $message_type = "warning";
            }
            header("Location: " . $_SERVER['PHP_SELF'] . "?section=absences&msg=" . urlencode($message) . "&type=" . $message_type);
            exit();
        } catch(Exception $e) {
            $message = "❌ Erreur : " . $e->getMessage();
            $message_type = "error";
        }
    } else {
        $message = "❌ Veuillez remplir tous les champs";
        $message_type = "error";
    }
}

// MODIFIER une absence
if(isset($_POST['modifier_absence'])){
    $id = (int)($_POST['absence_id'] ?? 0);
    $date = $_POST['date'] ?? '';
    $justifie = $_POST['justifie'] ?? 'non';

    try {
        $stmt = $pdo->prepare("UPDATE absence_etudiant SET date_absence=?, justifie=? WHERE id_absence=?");
        $stmt->execute([$date, $justifie, $id]);
        $message = "✅ Absence modifiée avec succès";
        $message_type = "success";
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=absences&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

// SUPPRIMER une absence
if(isset($_GET['delete_absence'])){
    $id = (int)$_GET['delete_absence'];
    try {
        $pdo->prepare("DELETE FROM absence_etudiant WHERE id_absence=?")->execute([$id]);
        $message = "✅ Absence supprimée avec succès";
        $message_type = "success";
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=absences&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

$absences_list = getAbsencesEnseignant($pdo);

/* ================= GESTION DES NOTES ================= */

// AJOUTER une note
if(isset($_POST['save_note'])){
    $etudiant = $_POST['etudiant_note'] ?? 0;
    $matiere  = (int)($_POST['matiere_note'] ?? 0);

    $test1  = ($_POST['test1'] !== "") ? floatval($_POST['test1']) : null;
    $test2  = ($_POST['test2'] !== "") ? floatval($_POST['test2']) : null;
    $examen = ($_POST['examen'] !== "") ? floatval($_POST['examen']) : null;

    if($etudiant && $matiere) {
        if($test1 === null && $test2 === null && $examen === null){
            $message = "❌ Vous devez saisir au moins une note !";
            $message_type = "error";
        } else {
            $moyenne = calculerMoyenne($test1, $test2, $examen);
            try {
                $stmt = $pdo->prepare("SELECT id_note FROM notes WHERE id_etudiant = ? AND id_matiere = ?");
                $stmt->execute([$etudiant, $matiere]);
                $existing = $stmt->fetch();

                if ($existing) {
                    $stmt = $pdo->prepare("UPDATE notes SET test1 = ?, test2 = ?, examen = ?, moyenne = ? WHERE id_etudiant = ? AND id_matiere = ?");
                    $stmt->execute([$test1, $test2, $examen, $moyenne, $etudiant, $matiere]);
                    $message = "✅ Note mise à jour avec succès";
                } else {
                    $stmt = $pdo->prepare("INSERT INTO notes(id_etudiant, id_matiere, test1, test2, examen, moyenne) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$etudiant, $matiere, $test1, $test2, $examen, $moyenne]);
                    $message = "✅ Note ajoutée avec succès";
                }
                $message_type = "success";
                header("Location: " . $_SERVER['PHP_SELF'] . "?section=notes&msg=" . urlencode($message) . "&type=" . $message_type);
                exit();
            } catch(Exception $e) {
                $message = "❌ Erreur : " . $e->getMessage();
                $message_type = "error";
            }
        }
    } else {
        $message = "❌ Veuillez sélectionner un étudiant et une matière";
        $message_type = "error";
    }
}

// MODIFIER une note
if(isset($_POST['modifier_note'])){
    $note_id = (int)($_POST['note_id'] ?? 0);
    $test1 = ($_POST['test1'] !== "") ? floatval($_POST['test1']) : null;
    $test2 = ($_POST['test2'] !== "") ? floatval($_POST['test2']) : null;
    $examen = ($_POST['examen'] !== "") ? floatval($_POST['examen']) : null;
    $moyenne = calculerMoyenne($test1, $test2, $examen);

    try {
        $stmt = $pdo->prepare("UPDATE notes SET test1 = ?, test2 = ?, examen = ?, moyenne = ? WHERE id_note = ?");
        $stmt->execute([$test1, $test2, $examen, $moyenne, $note_id]);
        $message = "✅ Note modifiée avec succès";
        $message_type = "success";
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=notes&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

// SUPPRIMER une note
if(isset($_GET['delete_note'])){
    $note_id = (int)$_GET['delete_note'];
    try {
        $stmt = $pdo->prepare("DELETE FROM notes WHERE id_note = ?");
        $stmt->execute([$note_id]);
        $message = "✅ Note supprimée avec succès";
        $message_type = "success";
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=notes&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

$notes_list = getNotesEnseignant($pdo);

/* ================= GESTION DES EXAMENS ================= */

// AJOUTER un examen
if(isset($_POST['ajouter_examen'])){
    $matiere_id = (int)($_POST['matiere_examen'] ?? 0);
    $groupe_id = (int)($_POST['groupe_examen'] ?? 0);
    $date = $_POST['date_examen'] ?? '';
    $heure_debut = $_POST['heure_debut'] ?? '';
    $heure_fin = $_POST['heure_fin'] ?? '';
    $salle_id = (int)($_POST['salle_examen'] ?? 0);
    $type_examen = $_POST['type_examen'] ?? 'examen';

    if ($matiere_id && $groupe_id && $date && $heure_debut && $heure_fin && $salle_id) {
        try {
            $date_examen = new DateTime($date);
            $aujourdhui = new DateTime('today');
            
            if ($date_examen < $aujourdhui) {
                $message = "⚠️ Vous ne pouvez pas planifier un examen à une date passée";
                $message_type = "warning";
            } else {
                $check = $pdo->prepare("SELECT id_examen FROM examen WHERE id_salle = ? AND date_examen = ? AND ((heure_debut <= ? AND heure_fin > ?) OR (heure_debut < ? AND heure_fin >= ?))");
                $check->execute([$salle_id, $date, $heure_debut, $heure_debut, $heure_fin, $heure_fin]);
                
                if ($check->rowCount() > 0) {
                    $message = "⚠️ Conflit : cette salle est déjà occupée à ces horaires";
                    $message_type = "warning";
                } else {
                    $stmt = $pdo->prepare("INSERT INTO examen(id_matieres, id_groupe, date_examen, heure_debut, heure_fin, id_salle, type_examen) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$matiere_id, $groupe_id, $date, $heure_debut, $heure_fin, $salle_id, $type_examen]);
                    $message = "✅ Examen ajouté avec succès";
                    $message_type = "success";
                }
            }
            header("Location: " . $_SERVER['PHP_SELF'] . "?section=examens&msg=" . urlencode($message) . "&type=" . $message_type);
            exit();
        } catch(Exception $e) {
            $message = "❌ Erreur : " . $e->getMessage();
            $message_type = "error";
        }
    } else {
        $message = "❌ Veuillez remplir tous les champs";
        $message_type = "error";
    }
}

// MODIFIER un examen
if(isset($_POST['modifier_examen'])){
    $examen_id = (int)($_POST['examen_id'] ?? 0);
    $matiere_id = (int)($_POST['matiere_examen'] ?? 0);
    $groupe_id = (int)($_POST['groupe_examen'] ?? 0);
    $date = $_POST['date_examen'] ?? '';
    $heure_debut = $_POST['heure_debut'] ?? '';
    $heure_fin = $_POST['heure_fin'] ?? '';
    $salle_id = (int)($_POST['salle_examen'] ?? 0);
    $type_examen = $_POST['type_examen'] ?? 'examen';

    try {
        $date_examen = new DateTime($date);
        $aujourdhui = new DateTime('today');
        
        if ($date_examen < $aujourdhui) {
            $message = "⚠️ Vous ne pouvez pas modifier un examen avec une date passée";
            $message_type = "warning";
        } else {
            $stmt = $pdo->prepare("UPDATE examen SET id_matieres = ?, id_groupe = ?, date_examen = ?, heure_debut = ?, heure_fin = ?, id_salle = ?, type_examen = ? WHERE id_examen = ?");
            $stmt->execute([$matiere_id, $groupe_id, $date, $heure_debut, $heure_fin, $salle_id, $type_examen, $examen_id]);
            $message = "✅ Examen modifié avec succès";
            $message_type = "success";
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=examens&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

// SUPPRIMER un examen
if(isset($_GET['delete_examen'])){
    $examen_id = (int)$_GET['delete_examen'];
    try {
        $stmt = $pdo->prepare("DELETE FROM examen WHERE id_examen = ?");
        $stmt->execute([$examen_id]);
        $message = "✅ Examen supprimé avec succès";
        $message_type = "success";
        header("Location: " . $_SERVER['PHP_SELF'] . "?section=examens&msg=" . urlencode($message) . "&type=" . $message_type);
        exit();
    } catch(Exception $e) {
        $message = "❌ Erreur : " . $e->getMessage();
        $message_type = "error";
    }
}

$examens = getExamensEnseignant($pdo);

// Récupérer les éléments à modifier
$absence_edit = null;
if(isset($_GET['edit_absence'])){
    $id = (int)$_GET['edit_absence'];
    $stmt = $pdo->prepare("SELECT * FROM absence_etudiant WHERE id_absence=?");
    $stmt->execute([$id]);
    $absence_edit = $stmt->fetch(PDO::FETCH_ASSOC);
}

$note_edit = null;
if(isset($_GET['edit_note'])){
    $id = (int)$_GET['edit_note'];
    $stmt = $pdo->prepare("SELECT * FROM notes WHERE id_note=?");
    $stmt->execute([$id]);
    $note_edit = $stmt->fetch(PDO::FETCH_ASSOC);
}

$examen_edit = null;
if(isset($_GET['edit_examen'])){
    $examen_id = (int)$_GET['edit_examen'];
    $stmt = $pdo->prepare("SELECT * FROM examen WHERE id_examen = ?");
    $stmt->execute([$examen_id]);
    $examen_edit = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Récupérer les messages de l'URL
if (isset($_GET['msg'])) {
    $message = urldecode($_GET['msg']);
    $message_type = isset($_GET['type']) ? $_GET['type'] : 'success';
}

$groupe_filtre_absences = isset($_GET['groupe_absences']) ? (int)$_GET['groupe_absences'] : 0;
$groupe_filtre_notes = isset($_GET['groupe_notes']) ? (int)$_GET['groupe_notes'] : 0;
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Espace Enseignant | 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);
            cursor: pointer;
        }

        .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;
        }

        /* Sections */
        .section {
            display: none;
            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);
        }

        .section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

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

        .section h2 {
            color: #1e293b;
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* Formulaires */
        .form-card {
            background: #f8fafc;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            border-left: 4px solid #2f6d8c;
        }

        .form-card h4 {
            color: #1e293b;
            font-size: 18px;
            margin-bottom: 20px;
        }

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

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-size: 13px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 8px;
        }

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

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

        /* Boutons */
        .btn-primary {
            background: linear-gradient(135deg, #2f6d8c, #095175);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 20px;
            width: 100%;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(47, 109, 140, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981, #059669);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }

        .btn-edit {
            background: #f59e0b;
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            margin-right: 8px;
            display: inline-block;
            transition: all 0.3s;
        }

        .btn-edit:hover {
            background: #d97706;
        }

        .btn-delete {
            background: #ef4444;
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
            transition: all 0.3s;
        }

        .btn-delete:hover {
            background: #dc2626;
        }

        .btn-cancel {
            background: #64748b;
            color: white;
            padding: 10px 20px;
            border-radius: 10px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 600;
            display: inline-block;
            text-align: center;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .action-buttons button, .action-buttons a {
            flex: 1;
        }

        /* Filtres */
        .filters-section {
            background: #f8fafc;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .filters-section .form-group {
            flex: 1;
            min-width: 200px;
        }

        /* Alertes */
        .alert {
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 500;
        }

        .alert-success {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-warning {
            background: linear-gradient(135deg, #fef3c7, #fde68a);
            color: #92400e;
            border-left: 4px solid #f59e0b;
        }

        .alert-error {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        /* Tableaux */
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
        }

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

        table thead tr {
            background: linear-gradient(135deg, #1e293b, #0f172a);
            color: white;
        }

        table th {
            padding: 14px 12px;
            text-align: left;
            font-weight: 600;
        }

        table td {
            padding: 12px;
            border-bottom: 1px solid #e2e8f0;
        }

        table tbody tr:hover {
            background: #f8fafc;
        }

        .no-data {
            text-align: center;
            padding: 50px;
            color: #94a3b8;
            font-size: 15px;
        }

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

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

        .justifie-oui { color: #10b981; font-weight: 600; }
        .justifie-non { color: #ef4444; font-weight: 600; }

        /* Cours card */
        .cours-card {
            background: linear-gradient(135deg, #e0f2fe, #bae6fd);
            padding: 10px 15px;
            border-radius: 10px;
            border-left: 4px solid #2f6d8c;
            margin: 5px;
        }

        /* 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;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .filters-section {
                flex-direction: column;
            }
        }

        /* 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;
        }
    </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>Espace Enseignant</p>
        </div>
        
        <div class="sidebar-nav">
            <a onclick="showSection('cours')" class="active">
                <span>📚</span>
                <span>Mes Cours</span>
            </a>
            <a onclick="showSection('absences')">
                <span>❌</span>
                <span>Gestion Absences</span>
            </a>
            <a onclick="showSection('notes')">
                <span>📊</span>
                <span>Gestion Notes</span>
            </a>
            <a onclick="showSection('examens')">
                <span>📝</span>
                <span>Gestion Examens</span>
            </a>
            <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>👨‍🏫 Espace Enseignant</h1>
                <p>Bienvenue, <?php echo htmlspecialchars($current_user['nom'] . ' ' . ($current_user['prenom'] ?? '')); ?></p>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($current_user['nom'] ?? 'E', 0, 1)); ?>
                </div>
                <div>
                    <strong><?php echo htmlspecialchars(($current_user['nom'] ?? '') . ' ' . ($current_user['prenom'] ?? '')); ?></strong>
                    <br>
                    <small style="color: #64748b;">Enseignant</small>
                </div>
            </div>
        </div>

        <?php 
        if ($message) {
            $alert_class = $message_type == 'error' ? 'alert-error' : ($message_type == 'warning' ? 'alert-warning' : 'alert-success');
            echo "<div class='alert $alert_class'>$message</div>";
        }
        ?>

        <!-- SECTION COURS -->
        <section id="cours" class="section active">
            <h2>📚 Mon emploi du temps</h2>
            <div class="table-container">
                <?php if(empty($emploi_enseignant)): ?>
                    <div class="no-data">📭 Aucun cours programmé pour le moment</div>
                <?php else: ?>
                    <table>
                        <thead>
                            <tr><th>Jour</th><th>Matière</th><th>Groupe</th><th>Horaire</th><th>Salle</th><th>Heures/Semaine</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($emploi_enseignant as $cours): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($cours['jour'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($cours['nom_matiere'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($cours['nom_groupe'] ?? ''); ?></td>
                                    <td><?php echo ($cours['heure_debut_formatted'] ?? '') . ' - ' . ($cours['heure_fin_formatted'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($cours['nom_salle'] ?? ''); ?></td>
                                    <td><?php echo $cours['nbr_heure_semaine'] ?? '-'; ?>h</td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </section>

        <!-- SECTION ABSENCES -->
        <section id="absences" class="section">
            <h2>❌ Gestion des absences</h2>

            <?php if(!$absence_edit): ?>
            <div class="form-card">
                <h4>➕ Ajouter une absence</h4>
                <form method="POST">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Groupe *</label>
                            <select name="groupe_abs" id="groupe_abs" required onchange="chargerEtudiantsParGroupe(this.value, 'etudiant_abs')">
                                <option value="">-- Sélectionner un groupe --</option>
                                <?php foreach($groupes_avec_etudiants as $groupe): ?>
                                    <option value="<?php echo $groupe['id_groupe']; ?>"><?php echo htmlspecialchars($groupe['nom_groupe']); ?> (<?php echo $groupe['nb_etudiants']; ?> étudiants)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Étudiant *</label>
                            <select name="etudiant" id="etudiant_abs" required>
                                <option value="">-- D'abord sélectionnez un groupe --</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Matière *</label>
                            <select name="matiere" required>
                                <option value="">-- Sélectionner --</option>
                                <?php foreach($matieres as $matiere): ?>
                                    <option value="<?php echo $matiere['id_matiere']; ?>"><?php echo htmlspecialchars($matiere['nom_matiere']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Date *</label>
                            <input type="date" name="date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                    </div>
                    <button type="submit" name="save_absence" class="btn-primary btn-success">✅ Enregistrer Absence</button>
                </form>
            </div>
            <?php endif; ?>

            <?php if($absence_edit): ?>
            <div class="form-card" style="border-left-color: #f59e0b;">
                <h4>✏️ Modifier Absence</h4>
                <form method="POST">
                    <input type="hidden" name="absence_id" value="<?php echo $absence_edit['id_absence']; ?>">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Étudiant</label>
                            <input type="text" value="<?php 
                                $stmt = $pdo->prepare("SELECT nom, prenom FROM etudiants WHERE id_etudiant = ?");
                                $stmt->execute([$absence_edit['id_etudiant']]);
                                $etu = $stmt->fetch();
                                echo htmlspecialchars(($etu['nom'] ?? '') . ' ' . ($etu['prenom'] ?? ''));
                            ?>" readonly style="background:#f5f5f5">
                        </div>
                        <div class="form-group">
                            <label>Date</label>
                            <input type="date" name="date" value="<?php echo $absence_edit['date_absence']; ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Justifié</label>
                            <select name="justifie">
                                <option value="non" <?php echo (($absence_edit['justifie'] ?? 'non') == 'non') ? 'selected' : ''; ?>>Non</option>
                                <option value="oui" <?php echo (($absence_edit['justifie'] ?? '') == 'oui') ? 'selected' : ''; ?>>Oui</option>
                            </select>
                        </div>
                    </div>
                    <div class="action-buttons">
                        <button type="submit" name="modifier_absence" class="btn-primary btn-warning">✅ Enregistrer</button>
                        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?section=absences" class="btn-cancel">❌ Annuler</a>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <div class="filters-section">
                <form method="GET" action="" style="display: flex; gap: 15px; flex-wrap: wrap; width: 100%;">
                    <input type="hidden" name="section" value="absences">
                    <div class="form-group" style="flex: 1;">
                        <label>🔍 Filtrer par groupe</label>
                        <select name="groupe_absences" onchange="this.form.submit()">
                            <option value="0">-- Tous les groupes --</option>
                            <?php foreach($groupes as $g): ?>
                                <option value="<?php echo $g['id_groupe']; ?>" <?php echo ($groupe_filtre_absences == $g['id_groupe']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($g['nom_groupe']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if($groupe_filtre_absences > 0): ?>
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <a href="?section=absences" class="btn-cancel" style="padding: 10px 20px;">✖️ Réinitialiser</a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>

            <div class="table-container">
                <table>
                    <thead><tr><th>Groupe</th><th>Étudiant</th><th>Matière</th><th>Date</th><th>Justifié</th><th>Actions</th></tr></thead>
                    <tbody>
                        <?php
                        $absences_filtrees = $absences_list;
                        if ($groupe_filtre_absences > 0) {
                            $absences_filtrees = array_filter($absences_list, function($abs) use ($groupe_filtre_absences) {
                                return ($abs['groupe_id'] ?? 0) == $groupe_filtre_absences;
                            });
                        }
                        if(!empty($absences_filtrees)){
                            foreach($absences_filtrees as $abs){
                                $justifie_text = (isset($abs['justifie']) && $abs['justifie'] == 'oui') ? 'Oui' : 'Non';
                                $justifie_class = (isset($abs['justifie']) && $abs['justifie'] == 'oui') ? 'justifie-oui' : 'justifie-non';
                                echo "<tr>
                                    <td>" . htmlspecialchars($abs['groupe_nom'] ?? '') . "</td>
                                    <td><strong>" . htmlspecialchars(($abs['etudiant_nom'] ?? '') . ' ' . ($abs['etudiant_prenom'] ?? '')) . "</strong></td>
                                    <td>" . htmlspecialchars($abs['matiere_nom'] ?? '') . "</td>
                                    <td>" . (!empty($abs['date_absence']) ? date('d/m/Y', strtotime($abs['date_absence'])) : 'N/A') . "</td>
                                    <td class='$justifie_class'><strong>$justifie_text</strong></td>
                                    <td>
                                        <a href='?edit_absence=" . $abs['id_absence'] . "&section=absences' class='btn-edit'>✏️ Modifier</a>
                                        <a href='?delete_absence=" . $abs['id_absence'] . "&section=absences' class='btn-delete' onclick='return confirm(\"Supprimer ?\");'>🗑️ Supprimer</a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='6' class='no-data'>📭 Aucune absence enregistrée</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- SECTION NOTES -->
        <section id="notes" class="section">
            <h2>📊 Gestion des notes</h2>

            <?php if(!$note_edit): ?>
            <div class="form-card">
                <h4>➕ Ajouter une note</h4>
                <form method="POST" onsubmit="return verifierNotes()">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Groupe *</label>
                            <select name="groupe_note" id="groupe_note" required onchange="chargerEtudiantsParGroupe(this.value, 'etudiant_note')">
                                <option value="">-- Sélectionner un groupe --</option>
                                <?php foreach($groupes_avec_etudiants as $groupe): ?>
                                    <option value="<?php echo $groupe['id_groupe']; ?>"><?php echo htmlspecialchars($groupe['nom_groupe']); ?> (<?php echo $groupe['nb_etudiants']; ?> étudiants)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Étudiant *</label>
                            <select name="etudiant_note" id="etudiant_note" required>
                                <option value="">-- D'abord sélectionnez un groupe --</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Matière *</label>
                            <select name="matiere_note" required>
                                <option value="">-- Sélectionner --</option>
                                <?php foreach($matieres as $matiere): ?>
                                    <option value="<?php echo $matiere['id_matiere']; ?>"><?php echo htmlspecialchars($matiere['nom_matiere']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group"><label>Test 1 /20</label><input type="number" name="test1" id="test1" min="0" max="20" step="0.25" placeholder="0-20"></div>
                        <div class="form-group"><label>Test 2 /20</label><input type="number" name="test2" id="test2" min="0" max="20" step="0.25" placeholder="0-20"></div>
                        <div class="form-group"><label>Examen /20</label><input type="number" name="examen" id="examen" min="0" max="20" step="0.25" placeholder="0-20"></div>
                    </div>
                    <button type="submit" name="save_note" class="btn-primary btn-success">✅ Enregistrer Note</button>
                </form>
            </div>
            <?php endif; ?>

            <?php if($note_edit): ?>
            <div class="form-card" style="border-left-color: #f59e0b;">
                <h4>✏️ Modifier Note</h4>
                <form method="POST">
                    <input type="hidden" name="note_id" value="<?php echo $note_edit['id_note']; ?>">
                    <div class="form-grid">
                        <div class="form-group"><label>Étudiant</label><input type="text" value="<?php 
                            $stmt = $pdo->prepare("SELECT nom, prenom FROM etudiants WHERE id_etudiant = ?");
                            $stmt->execute([$note_edit['id_etudiant']]);
                            $etu = $stmt->fetch();
                            echo htmlspecialchars(($etu['nom'] ?? '') . ' ' . ($etu['prenom'] ?? ''));
                        ?>" readonly style="background:#f5f5f5"></div>
                        <div class="form-group"><label>Matière</label><input type="text" value="<?php 
                            $stmt = $pdo->prepare("SELECT nom_matiere FROM matieres WHERE id_matiere = ?");
                            $stmt->execute([$note_edit['id_matiere']]);
                            $mat = $stmt->fetch();
                            echo htmlspecialchars($mat['nom_matiere'] ?? '');
                        ?>" readonly style="background:#f5f5f5"></div>
                        <div class="form-group"><label>Test 1</label><input type="number" name="test1" min="0" max="20" step="0.25" value="<?php echo $note_edit['test1'] ?? ''; ?>"></div>
                        <div class="form-group"><label>Test 2</label><input type="number" name="test2" min="0" max="20" step="0.25" value="<?php echo $note_edit['test2'] ?? ''; ?>"></div>
                        <div class="form-group"><label>Examen</label><input type="number" name="examen" min="0" max="20" step="0.25" value="<?php echo $note_edit['examen'] ?? ''; ?>"></div>
                    </div>
                    <div class="action-buttons">
                        <button type="submit" name="modifier_note" class="btn-primary btn-warning">✅ Enregistrer</button>
                        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?section=notes" class="btn-cancel">❌ Annuler</a>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <div class="filters-section">
                <form method="GET" action="" style="display: flex; gap: 15px; flex-wrap: wrap; width: 100%;">
                    <input type="hidden" name="section" value="notes">
                    <div class="form-group" style="flex: 1;">
                        <label>🔍 Filtrer par groupe</label>
                        <select name="groupe_notes" onchange="this.form.submit()">
                            <option value="0">-- Tous les groupes --</option>
                            <?php foreach($groupes as $g): ?>
                                <option value="<?php echo $g['id_groupe']; ?>" <?php echo ($groupe_filtre_notes == $g['id_groupe']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($g['nom_groupe']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if($groupe_filtre_notes > 0): ?>
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <a href="?section=notes" class="btn-cancel" style="padding: 10px 20px;">✖️ Réinitialiser</a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>

            <div class="table-container">
                <table>
                    <thead><tr><th>Groupe</th><th>Étudiant</th><th>Matière</th><th>Test 1</th><th>Test 2</th><th>Examen</th><th>Moyenne</th><th>Actions</th></tr></thead>
                    <tbody>
                        <?php 
                        $notes_filtrees = $notes_list;
                        if ($groupe_filtre_notes > 0) {
                            $notes_filtrees = array_filter($notes_list, function($note) use ($groupe_filtre_notes) {
                                return ($note['groupe_id'] ?? 0) == $groupe_filtre_notes;
                            });
                        }
                        if (!empty($notes_filtrees)) {
                            foreach($notes_filtrees as $note) {
                                $moyenne = $note['moyenne'] ?? null;
                                $row_style = '';
                                if ($moyenne && $moyenne >= 16) $row_style = 'style="background-color:#d1fae5;"';
                                elseif ($moyenne && $moyenne >= 12) $row_style = 'style="background-color:#e0f2fe;"';
                                elseif ($moyenne && $moyenne < 10) $row_style = 'style="background-color:#fee2e2;"';
                                echo "<tr $row_style>
                                    <td>" . htmlspecialchars($note['groupe_nom'] ?? '') . "</td>
                                    <td><strong>" . htmlspecialchars(($note['etudiant_nom'] ?? '') . ' ' . ($note['etudiant_prenom'] ?? '')) . "</strong></td>
                                    <td>" . htmlspecialchars($note['matiere_nom'] ?? '') . "</td>
                                    <td>" . (!empty($note['test1']) ? number_format($note['test1'], 2) . '/20' : '-') . "</td>
                                    <td>" . (!empty($note['test2']) ? number_format($note['test2'], 2) . '/20' : '-') . "</td>
                                    <td>" . (!empty($note['examen']) ? number_format($note['examen'], 2) . '/20' : '-') . "</td>
                                    <td><strong>" . (!empty($moyenne) ? number_format($moyenne, 2) . '/20' : '-') . "</strong></td>
                                    <td>
                                        <a href='?edit_note=" . $note['id_note'] . "&section=notes' class='btn-edit'>✏️ Modifier</a>
                                        <a href='?delete_note=" . $note['id_note'] . "&section=notes' class='btn-delete' onclick='return confirm(\"Supprimer ?\");'>🗑️ Supprimer</a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='8' class='no-data'>📭 Aucune note enregistrée</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- SECTION EXAMENS -->
        <section id="examens" class="section">
            <h2>📝 Gestion des examens</h2>

            <?php if(!$examen_edit): ?>
            <div class="form-card">
                <h4>➕ Ajouter un examen</h4>
                <form method="POST">
                    <div class="form-grid">
                        <div class="form-group"><label>Groupe</label><select name="groupe_examen" required><?php foreach($groupes as $g): ?><option value="<?php echo $g['id_groupe']; ?>"><?php echo htmlspecialchars($g['nom_groupe']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Matière</label><select name="matiere_examen" required><?php foreach($matieres as $m): ?><option value="<?php echo $m['id_matiere']; ?>"><?php echo htmlspecialchars($m['nom_matiere']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Type</label><select name="type_examen" required><option value="test1">Test 1</option><option value="test2">Test 2</option><option value="examen">Examen final</option></select></div>
                        <div class="form-group"><label>Salle</label><select name="salle_examen" required><?php foreach($salles as $s): ?><option value="<?php echo $s['id_salle']; ?>"><?php echo htmlspecialchars($s['nom_salle']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Date</label><input type="date" name="date_examen" value="<?php echo date('Y-m-d'); ?>" required></div>
                        <div class="form-group"><label>Heure début</label><input type="time" name="heure_debut" value="09:00" required></div>
                        <div class="form-group"><label>Heure fin</label><input type="time" name="heure_fin" value="11:00" required></div>
                    </div>
                    <button type="submit" name="ajouter_examen" class="btn-primary btn-success">✅ Ajouter</button>
                </form>
            </div>
            <?php endif; ?>

            <?php if($examen_edit): ?>
            <div class="form-card" style="border-left-color: #f59e0b;">
                <h4>✏️ Modifier Examen</h4>
                <form method="POST">
                    <input type="hidden" name="examen_id" value="<?php echo $examen_edit['id_examen']; ?>">
                    <div class="form-grid">
                        <div class="form-group"><label>Groupe</label><select name="groupe_examen"><?php foreach($groupes as $g): ?><option value="<?php echo $g['id_groupe']; ?>" <?php echo ($g['id_groupe'] == ($examen_edit['id_groupe'] ?? '')) ? 'selected' : ''; ?>><?php echo htmlspecialchars($g['nom_groupe']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Matière</label><select name="matiere_examen"><?php foreach($matieres as $m): ?><option value="<?php echo $m['id_matiere']; ?>" <?php echo ($m['id_matiere'] == ($examen_edit['id_matieres'] ?? '')) ? 'selected' : ''; ?>><?php echo htmlspecialchars($m['nom_matiere']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Type</label><select name="type_examen"><option value="test1" <?php echo ($examen_edit['type_examen'] ?? '') == 'test1' ? 'selected' : ''; ?>>Test 1</option><option value="test2" <?php echo ($examen_edit['type_examen'] ?? '') == 'test2' ? 'selected' : ''; ?>>Test 2</option><option value="examen" <?php echo ($examen_edit['type_examen'] ?? '') == 'examen' ? 'selected' : ''; ?>>Examen final</option></select></div>
                        <div class="form-group"><label>Salle</label><select name="salle_examen"><?php foreach($salles as $s): ?><option value="<?php echo $s['id_salle']; ?>" <?php echo ($s['id_salle'] == ($examen_edit['id_salle'] ?? '')) ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['nom_salle']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>Date</label><input type="date" name="date_examen" value="<?php echo $examen_edit['date_examen'] ?? ''; ?>" required></div>
                        <div class="form-group"><label>Heure début</label><input type="time" name="heure_debut" value="<?php echo $examen_edit['heure_debut'] ?? '09:00'; ?>" required></div>
                        <div class="form-group"><label>Heure fin</label><input type="time" name="heure_fin" value="<?php echo $examen_edit['heure_fin'] ?? '11:00'; ?>" required></div>
                    </div>
                    <div class="action-buttons">
                        <button type="submit" name="modifier_examen" class="btn-primary btn-warning">✅ Modifier</button>
                        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?section=examens" class="btn-cancel">❌ Annuler</a>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <div class="filters-section">
                <div class="form-group">
                    <label>🔍 Filtrer par groupe</label>
                    <select class="filtre-select" id="filtreGroupe" onchange="filtrerExamens()">
                        <option value="">Tous les groupes</option>
                        <?php foreach($groupes as $g): ?><option value="<?php echo $g['id_groupe']; ?>"><?php echo htmlspecialchars($g['nom_groupe']); ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>🔍 Filtrer par type</label>
                    <select class="filtre-select" id="filtreType" onchange="filtrerExamens()">
                        <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>
            </div>

            <div class="table-container">
                <table id="examensTable">
                    <thead><tr><th>Groupe</th><th>Matière</th><th>Type</th><th>Salle</th><th>Date</th><th>Horaire</th><th>Actions</th></tr></thead>
                    <tbody>
                        <?php if (!empty($examens)) {
                            foreach($examens as $examen) {
                                $is_past = isset($examen['date_examen']) && $examen['date_examen'] < date('Y-m-d');
                                echo "<tr class='examen-row' data-groupe='{$examen['id_groupe']}' data-type='{$examen['type_examen']}' " . ($is_past ? "style='opacity:0.7'" : "") . ">
                                    <td>" . htmlspecialchars($examen['groupe_nom'] ?? '') . "</td>
                                    <td>" . htmlspecialchars($examen['matiere_nom'] ?? '') . "</td>
                                    <td><span class='badge " . (($examen['type_examen'] == 'test1') ? 'badge-test1' : (($examen['type_examen'] == 'test2') ? 'badge-test2' : 'badge-examen')) . "'>" . ($examen['type_label'] ?? $examen['type_examen']) . "</span></td>
                                    <td>" . htmlspecialchars($examen['salle_nom'] ?? '') . "</td>
                                    <td>" . (isset($examen['date_examen']) ? date('d/m/Y', strtotime($examen['date_examen'])) : 'N/A') . ($is_past ? ' <span style="color:gray;">(Passé)</span>' : '') . "</td>
                                    <td>" . (isset($examen['heure_debut']) ? date('H:i', strtotime($examen['heure_debut'])) : '') . " - " . (isset($examen['heure_fin']) ? date('H:i', strtotime($examen['heure_fin'])) : '') . "</td>
                                    <td><a href='?edit_examen={$examen['id_examen']}&section=examens' class='btn-edit'>✏️ Modifier</a> <a href='?delete_examen={$examen['id_examen']}&section=examens' class='btn-delete' onclick='return confirm(\"Supprimer ?\");'>🗑️ Supprimer</a></td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='7' class='no-data'>📭 Aucun examen planifié</td></tr>";
                        } ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>

    <script>
        // Stockage des étudiants par groupe
        let etudiantsParGroupe = {};
        
        <?php
        // Charger TOUS les étudiants dans JavaScript
        try {
            $sql = "SELECT g.id_groupe, g.nom_groupe, e.id_etudiant, e.nom, e.prenom 
                    FROM groupe g
                    LEFT JOIN etudiants e ON g.id_groupe = e.id_groupe
                    WHERE e.id_etudiant IS NOT NULL AND e.id_etudiant != ''
                    ORDER BY g.id_groupe, e.nom, e.prenom";
            $stmt = $pdo->query($sql);
            $allStudents = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $groupes_data = [];
            foreach ($allStudents as $student) {
                $groupe_id = $student['id_groupe'];
                if (!isset($groupes_data[$groupe_id])) {
                    $groupes_data[$groupe_id] = [];
                }
                if ($student['id_etudiant']) {
                    $groupes_data[$groupe_id][] = [
                        'id' => $student['id_etudiant'],
                        'nom' => addslashes($student['nom']),
                        'prenom' => addslashes($student['prenom'])
                    ];
                }
            }
            
            foreach ($groupes_data as $groupe_id => $etudiants) {
                echo "etudiantsParGroupe[" . $groupe_id . "] = [";
                $items = [];
                foreach ($etudiants as $e) {
                    $items[] = "{id: '" . $e['id'] . "', nom: '" . $e['nom'] . "', prenom: '" . $e['prenom'] . "'}";
                }
                echo implode(",", $items);
                echo "];\n";
            }
        } catch(Exception $e) {
            echo "console.error('Erreur: " . addslashes($e->getMessage()) . "');\n";
        }
        ?>
        
        function chargerEtudiantsParGroupe(groupeId, selectId) {
            let select = document.getElementById(selectId);
            if (!select) return;
            
            select.innerHTML = '<option value="">-- Sélectionner un étudiant --</option>';
            
            if (groupeId && etudiantsParGroupe[groupeId] && etudiantsParGroupe[groupeId].length > 0) {
                for (let i = 0; i < etudiantsParGroupe[groupeId].length; i++) {
                    let option = document.createElement('option');
                    option.value = etudiantsParGroupe[groupeId][i].id;
                    option.textContent = etudiantsParGroupe[groupeId][i].nom + ' ' + etudiantsParGroupe[groupeId][i].prenom;
                    select.appendChild(option);
                }
            } else {
                select.innerHTML = '<option value="">-- Aucun étudiant dans ce groupe --</option>';
            }
        }

        function showSection(sectionId) {
            document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
            document.getElementById(sectionId).classList.add('active');
            document.querySelectorAll('.sidebar-nav a').forEach(link => link.classList.remove('active'));
            let activeLink = Array.from(document.querySelectorAll('.sidebar-nav a')).find(link => 
                link.getAttribute('onclick') && link.getAttribute('onclick').includes(sectionId)
            );
            if (activeLink) activeLink.classList.add('active');
            history.pushState(null, null, '?section=' + sectionId);
        }

        function verifierNotes() {
            let t1 = document.getElementById("test1")?.value;
            let t2 = document.getElementById("test2")?.value;
            let ex = document.getElementById("examen")?.value;
            if ((!t1 || t1 === "") && (!t2 || t2 === "") && (!ex || ex === "")) {
                alert("Vous devez remplir au moins une note !");
                return false;
            }
            return true;
        }

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

        window.onload = function() {
            const urlParams = new URLSearchParams(window.location.search);
            const section = urlParams.get('section');
            if (section && document.getElementById(section)) showSection(section);
        }
    </script>
</body>
</html>