<?php
session_start();

// 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());
}

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

// Récupérer les formations disponibles
$formations = [];
try {
    $sql = "SELECT * FROM formation ORDER BY nom_formation";
    $stmt = $pdo->query($sql);
    $formations = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $formations = [];
}

// Récupérer les groupes avec leurs formations
$groupes = [];
try {
    $sql = "SELECT g.*, f.nom_formation 
            FROM groupe g
            LEFT JOIN formation f ON g.id_formation = f.id_formation
            ORDER BY g.id_groupe";
    $stmt = $pdo->query($sql);
    $groupes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $groupes = [];
}

// Récupérer les matières par formation
$matieres_par_formation = [];
try {
    $sql = "SELECT fm.id_formation, m.* 
            FROM formation_matiere fm
            JOIN matieres m ON fm.id_matiere = m.id_matiere
            ORDER BY fm.id_formation, m.nom_matiere";
    $stmt = $pdo->query($sql);
    $resultats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($resultats as $r) {
        $matieres_par_formation[$r['id_formation']][] = $r;
    }
} catch(PDOException $e) {
    $matieres_par_formation = [];
}

// Récupérer tous les étudiants avec leurs formations
$etudiants = [];
$notes_etudiants = [];

try {
    // Récupérer les étudiants avec leur formation via le groupe
    $sql = "SELECT e.*, g.nom_groupe, g.id_formation, f.nom_formation
            FROM etudiants e
            LEFT JOIN groupe g ON e.id_groupe = g.id_groupe
            LEFT JOIN formation f ON g.id_formation = f.id_formation
            ORDER BY f.nom_formation, e.nom, e.prenom";
    $stmt = $pdo->query($sql);
    $etudiants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Récupérer toutes les notes
    $sql = "SELECT n.*, m.nom_matiere 
            FROM notes n
            LEFT JOIN matieres m ON n.id_matiere = m.id_matiere
            ORDER BY n.id_etudiant, m.nom_matiere";
    $stmt = $pdo->query($sql);
    $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Organiser les notes par étudiant
    foreach ($notes as $note) {
        $notes_etudiants[$note['id_etudiant']][$note['id_matiere']] = $note;
    }
    
} catch(PDOException $e) {
    $error_message = "Erreur: " . $e->getMessage();
}

// Fonction pour calculer la moyenne selon le format Excel
function calculerMoyenneMatiere($test1, $test2, $examen) {
    $coefficients = 0;
    $somme = 0;
    
    if ($test1 !== null && $test1 !== '' && floatval($test1) > 0) {
        $somme += floatval($test1);
        $coefficients += 1;
    }
    if ($test2 !== null && $test2 !== '' && floatval($test2) > 0) {
        $somme += floatval($test2);
        $coefficients += 1;
    }
    if ($examen !== null && $examen !== '' && floatval($examen) > 0) {
        $somme += floatval($examen) * 2;
        $coefficients += 2;
    }
    
    if ($coefficients > 0) {
        return round($somme / $coefficients, 2);
    }
    return null;
}

// Fonction pour calculer la moyenne générale
function calculerMoyenneGenerale($notes_etudiant) {
    $somme = 0;
    $nb = 0;
    foreach ($notes_etudiant as $matiere_id => $note) {
        if (isset($note['moyenne']) && $note['moyenne'] > 0) {
            $somme += $note['moyenne'];
            $nb++;
        }
    }
    return $nb > 0 ? round($somme / $nb, 2) : '-';
}

// Traitement du formulaire d'ajout de notes
$message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    if ($_POST['action'] == 'ajouter_note') {
        try {
            $test1 = !empty($_POST['test1']) ? floatval($_POST['test1']) : null;
            $test2 = !empty($_POST['test2']) ? floatval($_POST['test2']) : null;
            $examen = !empty($_POST['examen']) ? floatval($_POST['examen']) : null;
            
            // Vérifier qu'au moins une note est saisie
            if ($test1 === null && $test2 === null && $examen === null) {
                throw new Exception("Vous devez saisir au moins une note");
            }
            
            // Calculer la moyenne selon la formule
            $moyenne = calculerMoyenneMatiere($test1, $test2, $examen);
            
            // Vérifier si une note existe déjà
            $check = $pdo->prepare("SELECT id_note FROM notes WHERE id_etudiant = ? AND id_matiere = ?");
            $check->execute([$_POST['id_etudiant'], $_POST['id_matiere']]);
            
            if ($check->rowCount() > 0) {
                // Mise à jour
                $sql = "UPDATE notes 
                        SET test1 = :test1, test2 = :test2, examen = :examen, moyenne = :moyenne 
                        WHERE id_etudiant = :id_etudiant AND id_matiere = :id_matiere";
            } else {
                // Insertion
                $sql = "INSERT INTO notes (id_etudiant, id_matiere, test1, test2, examen, moyenne) 
                        VALUES (:id_etudiant, :id_matiere, :test1, :test2, :examen, :moyenne)";
            }
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_etudiant' => $_POST['id_etudiant'],
                ':id_matiere' => $_POST['id_matiere'],
                ':test1' => $test1,
                ':test2' => $test2,
                ':examen' => $examen,
                ':moyenne' => $moyenne
            ]);
            
            $message = '<div class="alert-success">✓ Note enregistrée avec succès!</div>';
            
        } catch(Exception $e) {
            $message = '<div class="alert-error">✗ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Traitement de la suppression d'une note
    if ($_POST['action'] == 'supprimer_note') {
        try {
            $sql = "DELETE FROM notes WHERE id_etudiant = :id_etudiant AND id_matiere = :id_matiere";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_etudiant' => $_POST['id_etudiant'],
                ':id_matiere' => $_POST['id_matiere']
            ]);
            
            $message = '<div class="alert-success">✓ Note supprimée avec succès!</div>';
        } catch(Exception $e) {
            $message = '<div class="alert-error">✗ Erreur lors de la suppression : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Traitement de la modification d'une note (via AJAX)
    if ($_POST['action'] == 'modifier_note') {
        try {
            $test1 = !empty($_POST['test1']) ? floatval($_POST['test1']) : null;
            $test2 = !empty($_POST['test2']) ? floatval($_POST['test2']) : null;
            $examen = !empty($_POST['examen']) ? floatval($_POST['examen']) : null;
            
            $moyenne = calculerMoyenneMatiere($test1, $test2, $examen);
            
            $sql = "UPDATE notes 
                    SET test1 = :test1, test2 = :test2, examen = :examen, moyenne = :moyenne 
                    WHERE id_etudiant = :id_etudiant AND id_matiere = :id_matiere";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_etudiant' => $_POST['id_etudiant'],
                ':id_matiere' => $_POST['id_matiere'],
                ':test1' => $test1,
                ':test2' => $test2,
                ':examen' => $examen,
                ':moyenne' => $moyenne
            ]);
            
            echo json_encode(['success' => true, 'moyenne' => $moyenne]);
            exit();
        } catch(Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            exit();
        }
    }
}

// Récupérer les étudiants pour le formulaire
$liste_etudiants = [];
try {
    $sql = "SELECT e.id_etudiant, e.nom, e.prenom, g.id_formation, f.nom_formation 
            FROM etudiants e
            LEFT JOIN groupe g ON e.id_groupe = g.id_groupe
            LEFT JOIN formation f ON g.id_formation = f.id_formation
            ORDER BY e.nom, e.prenom";
    $stmt = $pdo->query($sql);
    $liste_etudiants = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $liste_etudiants = [];
}

$current_user = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM utilisateur WHERE id_user = ?");
    $stmt->execute([$_SESSION['id_user'] ?? 0]);
    $current_user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(Exception $e) {
    $current_user = ['nom' => 'Admin', 'prenom' => ''];
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relevé de Notes | 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, #667eea, #e8e2ee);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        /* Form section */
        .form-section {
            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);
            border: 2px solid rgba(102, 126, 234, 0.3);
        }

        .form-section 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;
            margin-bottom: 20px;
        }

        .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: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 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: 220px;
            background: white;
            transition: all 0.3s;
            flex: 1;
        }

        .filtre-select:focus {
            outline: none;
            border-color: #667eea;
        }

        /* Excel table */
        .excel-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;
        }

        .formation-separator {
            background: linear-gradient(135deg, #1e293b, #0f172a);
            color: white;
            padding: 15px 20px;
            margin: 30px 0 15px 0;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .formation-separator:first-of-type {
            margin-top: 0;
        }

        .formation-separator span:last-child {
            font-size: 0.85rem;
            background: rgba(255, 255, 255, 0.2);
            padding: 3px 12px;
            border-radius: 20px;
        }

        .excel-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1200px;
            font-size: 0.85rem;
            margin-bottom: 30px;
        }

        .excel-table:last-child {
            margin-bottom: 0;
        }

        .excel-table th {
            background: linear-gradient(135deg, #334155, #1e293b);
            color: white;
            padding: 12px 8px;
            border: 1px solid #475569;
            font-weight: 600;
            text-align: center;
            vertical-align: middle;
        }

        .excel-table td {
            border: 1px solid #e2e8f0;
            padding: 8px 5px;
            text-align: center;
            vertical-align: middle;
        }

        .excel-table .matiere-group {
            background: linear-gradient(135deg, #475569, #334155);
            font-size: 0.85rem;
        }

        .excel-table .sous-titre th {
            background: linear-gradient(135deg, #475569, #334155);
            font-size: 0.75rem;
            font-weight: 500;
            padding: 8px 5px;
        }

        .excel-table .etudiant-info {
            background: #f8fafc;
            font-weight: 500;
            text-align: left;
            padding-left: 10px;
        }

        .code-eleve {
            font-weight: 600;
            color: #667eea;
        }

        .note-test1 { color: #0891b2; font-weight: 500; }
        .note-test2 { color: #059669; font-weight: 500; }
        .note-examen { color: #ea580c; font-weight: 500; }
        .note-moyenne { 
            font-weight: bold; 
            background: #e0f2fe;
            color: #1e293b;
        }
        .moyenne-generale {
            font-weight: bold;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        .rang {
            font-weight: bold;
            background: #fef3c7;
            color: #92400e;
        }
        .note-absente {
            color: #cbd5e1;
            font-style: italic;
        }

        .excel-table tbody tr:hover td {
            background: #f0f8ff;
        }

        .excel-table tbody tr:hover .note-moyenne {
            background: #bae6fd;
        }

        .badge-excellence {
            background: linear-gradient(135deg, #fbbf24, #f59e0b);
            color: #000;
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: bold;
            margin-left: 5px;
        }

        .stats-mini {
            display: flex;
            gap: 20px;
            margin: 10px 0 20px 0;
            padding: 12px 20px;
            background: #f8fafc;
            border-radius: 12px;
            font-size: 13px;
            color: #475569;
        }

        /* Action buttons for notes */
        .note-actions {
            display: inline-flex;
            gap: 5px;
            margin-left: 5px;
        }
        .btn-edit-note, .btn-delete-note {
            padding: 2px 6px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            transition: all 0.2s ease;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }
        .btn-edit-note {
            background: #3b82f6;
            color: white;
        }
        .btn-edit-note:hover {
            background: #2563eb;
            transform: scale(1.05);
        }
        .btn-delete-note {
            background: #ef4444;
            color: white;
        }
        .btn-delete-note:hover {
            background: #dc2626;
            transform: scale(1.05);
        }

        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            backdrop-filter: blur(5px);
        }
        .modal-content {
            background: white;
            margin: 10% auto;
            padding: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: modalSlideIn 0.3s ease;
        }
        @keyframes modalSlideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        .modal-content h3 {
            margin-bottom: 20px;
            color: #1e293b;
        }
        .modal-content input {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
        }
        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        .modal-buttons button {
            padding: 10px 20px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 500;
        }
        .btn-save {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }
        .btn-cancel {
            background: #e2e8f0;
            color: #475569;
        }
        .close {
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }
        .close:hover {
            color: #000;
        }

        /* Buttons */
        .btn-ajouter {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-ajouter:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

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

        .btn-info {
            background: linear-gradient(135deg, #06b6d4, #0891b2);
            box-shadow: 0 5px 15px rgba(6, 182, 212, 0.3);
        }

        /* Actions */
        .actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
        }

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

        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: #475569;
        }

        .color-box {
            width: 20px;
            height: 20px;
            border-radius: 6px;
        }

        /* 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;
        }

        .form-helper {
            font-size: 0.85rem;
            color: #64748b;
        }

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

        /* Notification toast */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #1e293b;
            color: white;
            padding: 12px 20px;
            border-radius: 10px;
            z-index: 10001;
            animation: slideIn 0.3s ease;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            
            .filters-section {
                flex-direction: column;
            }
            
            .filtre-select {
                width: 100%;
            }
            
            .actions {
                flex-direction: column;
            }
            
            .actions .btn-ajouter {
                width: 100%;
                justify-content: center;
            }
        }

        @media print {
            .sidebar, .filters-section, .form-section, .btn-ajouter, .logout, .actions, .legend, .note-actions {
                display: none !important;
            }
            .main-content { margin-left: 0; padding: 0; }
            .excel-container { box-shadow: none; padding: 0; }
            .excel-table th { background: #1e293b !important; color: white !important; -webkit-print-color-adjust: exact; }
            .formation-separator { background: #1e293b !important; color: white !important; -webkit-print-color-adjust: exact; }
        }
    </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 Formations </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>Relevé de Notes</h1>
                <p>Gestion des notes par formation</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>

        <?php if ($message) echo $message; ?>

        <!-- Formulaire de saisie -->
        <div class="form-section">
            <h3>➕ Saisie des notes</h3>
            <form method="POST" action="" id="noteForm">
                <input type="hidden" name="action" value="ajouter_note">
                <div class="form-grid">
                    <select name="id_etudiant" id="etudiant_select" required onchange="chargerMatieresEtudiant()">
                        <option value="">📋 Sélectionner un étudiant</option>
                        <?php foreach ($liste_etudiants as $e): ?>
                            <option value="<?php echo $e['id_etudiant']; ?>" data-formation="<?php echo $e['id_formation']; ?>">
                                <?php echo htmlspecialchars($e['nom'] . ' ' . $e['prenom'] . ' (' . ($e['nom_formation'] ?? 'Formation inconnue') . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="id_matiere" id="matiere_select" required>
                        <option value="">📚 D'abord sélectionner un étudiant</option>
                    </select>
                    
                    <input type="number" name="test1" step="0.25" min="0" max="20" placeholder="Test 1 (0-20)" id="test1">
                    <input type="number" name="test2" step="0.25" min="0" max="20" placeholder="Test 2 (0-20)" id="test2">
                    <input type="number" name="examen" step="0.25" min="0" max="20" placeholder="Examen (0-20)" id="examen">
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                    <p class="form-helper">
                        <strong>📐 Formule :</strong> (Examen × 2 + Test 1 + Test 2) ÷ 4 (les notes manquantes sont ignorées)
                    </p>
                    <button type="submit" class="btn-ajouter btn-success" onclick="return verifierNotes()">
                        <span>✓</span> Enregistrer
                    </button>
                </div>
            </form>
        </div>

        <!-- Filtres -->
        <div class="filters-section">
            <select class="filtre-select" id="filtreFormation" onchange="filtrerParFormation(this.value)">
                <option value="">📚 Toutes les formations</option>
                <?php foreach ($formations as $f): ?>
                    <option value="<?php echo $f['id_formation']; ?>">
                        <?php echo htmlspecialchars($f['nom_formation']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <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']; ?>" data-formation="<?php echo $g['id_formation']; ?>">
                        <?php echo htmlspecialchars($g['nom_groupe'] ?? 'Groupe ' . $g['id_groupe']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <input type="text" class="filtre-select" id="recherche" placeholder="🔍 Rechercher un étudiant..." onkeyup="rechercherEtudiant()">
        </div>

        <!-- Tableau des notes -->
        <div class="excel-container">
            <?php
            // Grouper les étudiants par formation
            $etudiants_par_formation = [];
            foreach ($etudiants as $etudiant) {
                $id_formation = $etudiant['id_formation'] ?? 0;
                if (!isset($etudiants_par_formation[$id_formation])) {
                    $etudiants_par_formation[$id_formation] = [
                        'nom' => $etudiant['nom_formation'] ?? 'Formation non assignée',
                        'etudiants' => []
                    ];
                }
                $etudiants_par_formation[$id_formation]['etudiants'][] = $etudiant;
            }
            ?>
            
            <?php if (empty($etudiants_par_formation)): ?>
                <div style="text-align: center; padding: 60px; color: #999;">
                    <div style="font-size: 60px; margin-bottom: 20px;">📭</div>
                    <h3 style="color: #666;">Aucun étudiant trouvé</h3>
                    <p>Commencez par ajouter des étudiants dans la section "Gestion Étudiants".</p>
                </div>
            <?php else: ?>
                <?php foreach ($etudiants_par_formation as $id_formation => $data): 
                    if (empty($data['etudiants'])) continue;
                    $matieres_formation = $matieres_par_formation[$id_formation] ?? [];
                    if (empty($matieres_formation)) {
                        continue;
                    }
                ?>
                    <div class="formation-separator">
                        <span>📚 <?php echo htmlspecialchars($data['nom']); ?></span>
                        <span><?php echo count($data['etudiants']); ?> étudiant(s) • <?php echo count($matieres_formation); ?> matière(s)</span>
                    </div>
                    
                    <table class="excel-table formation-<?php echo $id_formation; ?>">
                        <thead>
                            <tr>
                                <th rowspan="2">Code</th>
                                <th rowspan="2">Nom</th>
                                <th rowspan="2">Prénom</th>
                                <th rowspan="2">Groupe</th>
                                <?php foreach ($matieres_formation as $matiere): ?>
                                    <th colspan="4" class="matiere-group"><?php echo htmlspecialchars($matiere['nom_matiere']); ?></th>
                                <?php endforeach; ?>
                                <th rowspan="2">Moy. Gén.</th>
                                <th rowspan="2">Rang</th>
                            </tr>
                            <tr class="sous-titre">
                                <?php foreach ($matieres_formation as $matiere): ?>
                                    <th>T1</th>
                                    <th>T2</th>
                                    <th>Ex</th>
                                    <th>Moy</th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $moyennes_formation = [];
                            foreach ($data['etudiants'] as $etudiant): 
                                $id_etudiant = $etudiant['id_etudiant'];
                                $moy_gen = calculerMoyenneGenerale($notes_etudiants[$id_etudiant] ?? []);
                                $moyennes_formation[$id_etudiant] = $moy_gen;
                            ?>
                                <tr class="etudiant-row" 
                                    data-formation="<?php echo $id_formation; ?>" 
                                    data-groupe="<?php echo $etudiant['id_groupe']; ?>"
                                    data-nom="<?php echo strtolower($etudiant['nom'] . ' ' . $etudiant['prenom']); ?>"
                                    data-id-etudiant="<?php echo $id_etudiant; ?>">
                                    
                                    <td class="code-eleve"><?php echo htmlspecialchars($etudiant['id_etudiant']); ?></td>
                                    <td class="etudiant-info"><?php echo htmlspecialchars($etudiant['nom']); ?></td>
                                    <td class="etudiant-info"><?php echo htmlspecialchars($etudiant['prenom']); ?></td>
                                    <td><?php echo htmlspecialchars($etudiant['nom_groupe'] ?? 'Groupe ' . $etudiant['id_groupe']); ?></td>
                                    
                                    <?php foreach ($matieres_formation as $matiere): 
                                        $id_matiere = $matiere['id_matiere'];
                                        $note = $notes_etudiants[$id_etudiant][$id_matiere] ?? null;
                                    ?>
                                        <td class="note-test1" data-matiere="<?php echo $id_matiere; ?>" data-type="test1">
                                            <?php echo ($note && isset($note['test1']) && $note['test1'] > 0) ? number_format($note['test1'], 2) : '<span class="note-absente">-</span>'; ?>
                                        </td>
                                        <td class="note-test2" data-matiere="<?php echo $id_matiere; ?>" data-type="test2">
                                            <?php echo ($note && isset($note['test2']) && $note['test2'] > 0) ? number_format($note['test2'], 2) : '<span class="note-absente">-</span>'; ?>
                                        </td>
                                        <td class="note-examen" data-matiere="<?php echo $id_matiere; ?>" data-type="examen">
                                            <?php echo ($note && isset($note['examen']) && $note['examen'] > 0) ? number_format($note['examen'], 2) : '<span class="note-absente">-</span>'; ?>
                                        </td>
                                        <td class="note-moyenne" data-matiere="<?php echo $id_matiere; ?>" data-type="moyenne">
                                            <?php 
                                            if ($note && isset($note['moyenne']) && $note['moyenne'] > 0) {
                                                echo number_format($note['moyenne'], 2);
                                                if ($note['moyenne'] >= 16) {
                                                    echo ' <span class="badge-excellence">⭐</span>';
                                                }
                                                echo '<div class="note-actions">
                                                        <button class="btn-edit-note" onclick="editNote(\'' . $id_etudiant . '\', ' . $id_matiere . ', \'' . htmlspecialchars($matiere['nom_matiere']) . '\')">✏️</button>
                                                        <button class="btn-delete-note" onclick="deleteNote(\'' . $id_etudiant . '\', ' . $id_matiere . ', \'' . htmlspecialchars($matiere['nom_matiere']) . '\')">🗑️</button>
                                                      </div>';
                                            } else {
                                                echo '<span class="note-absente">-</span>';
                                            }
                                            ?>
                                        </td>
                                    <?php endforeach; ?>
                                    
                                    <td class="moyenne-generale" id="moyenne-gen-<?php echo $id_etudiant; ?>">
                                        <?php 
                                        echo $moy_gen;
                                        if (is_numeric($moy_gen) && $moy_gen >= 16) {
                                            echo ' ⭐';
                                        }
                                        ?>
                                    </td>
                                    <td class="rang">-</td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <!-- Statistiques -->
                    <?php
                    $total_etudiants = count($data['etudiants']);
                    $moyennes_valides = array_filter($moyennes_formation, function($m) { return is_numeric($m); });
                    $moyenne_formation = count($moyennes_valides) > 0 ? round(array_sum($moyennes_valides) / count($moyennes_valides), 2) : 'N/A';
                    $meilleur_etudiant = !empty($moyennes_valides) ? max($moyennes_valides) : 'N/A';
                    ?>
                    <div class="stats-mini">
                        <span>📊 Moyenne de la formation : <strong><?php echo $moyenne_formation; ?></strong></span>
                        <span>🏆 Meilleure moyenne : <strong><?php echo $meilleur_etudiant; ?></strong></span>
                        <span>📝 Étudiants notés : <strong><?php echo count($moyennes_valides); ?>/<?php echo $total_etudiants; ?></strong></span>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Modal de modification -->
        <div id="editModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal()">&times;</span>
                <h3>✏️ Modifier les notes</h3>
                <p id="modalMatiereInfo" style="margin-bottom: 15px; color: #667eea;"></p>
                <input type="hidden" id="edit_id_etudiant">
                <input type="hidden" id="edit_id_matiere">
                <label>Test 1 (0-20)</label>
                <input type="number" id="edit_test1" step="0.25" min="0" max="20" placeholder="Test 1">
                <label>Test 2 (0-20)</label>
                <input type="number" id="edit_test2" step="0.25" min="0" max="20" placeholder="Test 2">
                <label>Examen (0-20)</label>
                <input type="number" id="edit_examen" step="0.25" min="0" max="20" placeholder="Examen">
                <div class="modal-buttons">
                    <button class="btn-cancel" onclick="closeModal()">Annuler</button>
                    <button class="btn-save" onclick="saveEditedNote()">Enregistrer</button>
                </div>
            </div>
        </div>

        <!-- Modal de confirmation suppression -->
        <div id="deleteModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeDeleteModal()">&times;</span>
                <h3>🗑️ Confirmation de suppression</h3>
                <p>Êtes-vous sûr de vouloir supprimer les notes de <strong id="deleteMatiereInfo"></strong> ?</p>
                <p style="color: #ef4444; margin-top: 10px;">Cette action est irréversible.</p>
                <div class="modal-buttons">
                    <button class="btn-cancel" onclick="closeDeleteModal()">Annuler</button>
                    <button class="btn-save" id="confirmDeleteBtn" style="background: #ef4444;">Supprimer</button>
                </div>
            </div>
        </div>

        <!-- Légende -->
        <div class="legend">
            <div class="legend-item">
                <div class="color-box" style="background: #0891b2;"></div>
                <span>Test 1</span>
            </div>
            <div class="legend-item">
                <div class="color-box" style="background: #059669;"></div>
                <span>Test 2</span>
            </div>
            <div class="legend-item">
                <div class="color-box" style="background: #ea580c;"></div>
                <span>Examen</span>
            </div>
            <div class="legend-item">
                <div class="color-box" style="background: #e0f2fe; border: 1px solid #667eea;"></div>
                <span>Moyenne matière</span>
            </div>
            <div class="legend-item">
                <div class="color-box" style="background: linear-gradient(135deg, #667eea, #764ba2);"></div>
                <span>Moyenne générale</span>
            </div>
            <div class="legend-item">
                <span class="badge-excellence" style="background: linear-gradient(135deg, #fbbf24, #f59e0b);">⭐</span>
                <span>Excellence (≥16)</span>
            </div>
            <div class="legend-item">
                <span>✏️ Modifier une note</span>
            </div>
            <div class="legend-item">
                <span>🗑️ Supprimer une note</span>
            </div>
            <div class="legend-item">
                <span>📐 Formule: (Examen × 2 + Test1 + Test2) ÷ 4</span>
            </div>
        </div>

        <!-- Actions -->
        <div class="actions">
            <button class="btn-ajouter btn-info" onclick="exporterExcel()">
                📥 Exporter Excel
            </button>
            <button class="btn-ajouter btn-success" onclick="window.print()">
                🖨️ Imprimer
            </button>
            <button class="btn-ajouter" onclick="resetFiltres()">
                🔄 Réinitialiser les filtres
            </button>
        </div>
    </div>

    <script>
        const matieresParFormation = <?php echo json_encode($matieres_par_formation); ?>;
        let currentDeleteData = null;
        
        function chargerMatieresEtudiant() {
            const etudiantSelect = document.getElementById('etudiant_select');
            const matiereSelect = document.getElementById('matiere_select');
            const selectedOption = etudiantSelect.options[etudiantSelect.selectedIndex];
            
            if (!selectedOption || !selectedOption.value) {
                matiereSelect.innerHTML = '<option value="">📚 D\'abord sélectionner un étudiant</option>';
                return;
            }
            
            const formationId = selectedOption.dataset.formation;
            
            if (formationId && matieresParFormation[formationId] && matieresParFormation[formationId].length > 0) {
                matiereSelect.innerHTML = '<option value="">📚 Sélectionner une matière</option>';
                matieresParFormation[formationId].forEach(matiere => {
                    const option = document.createElement('option');
                    option.value = matiere.id_matiere;
                    option.textContent = matiere.nom_matiere;
                    matiereSelect.appendChild(option);
                });
            } else {
                matiereSelect.innerHTML = '<option value="">❌ Aucune matière disponible pour cette formation</option>';
            }
        }

        function verifierNotes() {
            const test1 = document.getElementById('test1').value;
            const test2 = document.getElementById('test2').value;
            const examen = document.getElementById('examen').value;
            
            if (test1 === '' && test2 === '' && examen === '') {
                alert('❌ Vous devez saisir au moins une note !');
                return false;
            }
            
            if (test1 !== '' && (parseFloat(test1) < 0 || parseFloat(test1) > 20)) {
                alert('❌ La note du Test 1 doit être comprise entre 0 et 20');
                return false;
            }
            if (test2 !== '' && (parseFloat(test2) < 0 || parseFloat(test2) > 20)) {
                alert('❌ La note du Test 2 doit être comprise entre 0 et 20');
                return false;
            }
            if (examen !== '' && (parseFloat(examen) < 0 || parseFloat(examen) > 20)) {
                alert('❌ La note de l\'Examen doit être comprise entre 0 et 20');
                return false;
            }
            
            return true;
        }

        function filtrerParFormation(formationId) {
            const rows = document.querySelectorAll('.etudiant-row');
            const groupeSelect = document.getElementById('filtreGroupe');
            const groupeValue = groupeSelect.value;
            
            Array.from(groupeSelect.options).forEach(option => {
                if (option.value === '') return;
                if (formationId === '' || option.dataset.formation === formationId) {
                    option.style.display = '';
                } else {
                    option.style.display = 'none';
                }
            });
            
            if (groupeValue !== '' && groupeSelect.selectedOptions[0] && groupeSelect.selectedOptions[0].style.display === 'none') {
                groupeSelect.value = '';
            }
            
            rows.forEach(row => {
                const rowFormation = row.dataset.formation;
                const rowGroupe = row.dataset.groupe;
                
                const formationMatch = formationId === '' || rowFormation === formationId;
                const groupeMatch = groupeValue === '' || rowGroupe === groupeValue;
                
                row.style.display = (formationMatch && groupeMatch) ? '' : 'none';
            });
            
            rechercherEtudiant();
            mettreAJourSeparateurs();
        }

        function filtrerParGroupe(groupeId) {
            const rows = document.querySelectorAll('.etudiant-row');
            const formationSelect = document.getElementById('filtreFormation');
            const formationValue = formationSelect.value;
            
            rows.forEach(row => {
                const rowFormation = row.dataset.formation;
                const rowGroupe = row.dataset.groupe;
                
                const formationMatch = formationValue === '' || rowFormation === formationValue;
                const groupeMatch = groupeId === '' || rowGroupe === groupeId;
                
                row.style.display = (formationMatch && groupeMatch) ? '' : 'none';
            });
            
            rechercherEtudiant();
            mettreAJourSeparateurs();
        }

        function rechercherEtudiant() {
            const recherche = document.getElementById('recherche').value.toLowerCase().trim();
            const rows = document.querySelectorAll('.etudiant-row');
            
            rows.forEach(row => {
                if (row.style.display !== 'none') {
                    const nom = row.dataset.nom;
                    if (recherche === '' || nom.includes(recherche)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                }
            });
            
            mettreAJourSeparateurs();
        }

        function mettreAJourSeparateurs() {
            const formations = document.querySelectorAll('.formation-separator');
            formations.forEach(separator => {
                const nextTable = separator.nextElementSibling;
                if (nextTable && nextTable.classList.contains('excel-table')) {
                    const rows = nextTable.querySelectorAll('.etudiant-row');
                    let hasVisibleRows = false;
                    rows.forEach(row => {
                        if (row.style.display !== 'none') {
                            hasVisibleRows = true;
                        }
                    });
                    separator.style.display = hasVisibleRows ? 'flex' : 'none';
                    nextTable.style.display = hasVisibleRows ? 'table' : 'none';
                    
                    const stats = nextTable.nextElementSibling;
                    if (stats && stats.classList.contains('stats-mini')) {
                        stats.style.display = hasVisibleRows ? 'flex' : 'none';
                    }
                }
            });
        }

        function resetFiltres() {
            document.getElementById('filtreFormation').value = '';
            document.getElementById('filtreGroupe').value = '';
            document.getElementById('recherche').value = '';
            
            const rows = document.querySelectorAll('.etudiant-row');
            rows.forEach(row => row.style.display = '');
            
            Array.from(document.getElementById('filtreGroupe').options).forEach(option => {
                option.style.display = '';
            });
            
            mettreAJourSeparateurs();
        }

        function exporterExcel() {
            let csv = [];
            csv.push('"RELEVÉ DE NOTES - CPN"');
            csv.push('"Généré le ' + new Date().toLocaleDateString('fr-FR') + '"');
            csv.push('');
            
            const formations = document.querySelectorAll('.formation-separator');
            
            formations.forEach((separator, index) => {
                if (separator.style.display === 'none') return;
                
                const formationName = separator.querySelector('span:first-child').innerText;
                csv.push('"' + formationName + '"');
                
                const table = separator.nextElementSibling;
                if (table && table.classList.contains('excel-table')) {
                    const rows = table.querySelectorAll('tr');
                    rows.forEach(row => {
                        if (row.style.display !== 'none') {
                            const rowData = [];
                            row.querySelectorAll('th, td').forEach(cell => {
                                let text = cell.innerText || cell.textContent;
                                text = text.replace(/"/g, '""').replace(/[⭐❌✅📚📊📝✏️🗑️]/g, '').trim();
                                rowData.push('"' + text + '"');
                            });
                            if (rowData.length > 0) {
                                csv.push(rowData.join(','));
                            }
                        }
                    });
                    csv.push('');
                }
            });
            
            const csvContent = csv.join('\n');
            const blob = new Blob(["\uFEFF" + csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'releve_notes_' + new Date().toISOString().slice(0,10) + '.csv');
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Fonctions pour la modification des notes
        function editNote(idEtudiant, idMatiere, matiereNom) {
            // Récupérer les notes actuelles
            const row = document.querySelector(`tr[data-id-etudiant="${idEtudiant}"]`);
            if (!row) return;
            
            const test1Cell = row.querySelector(`td.note-test1[data-matiere="${idMatiere}"]`);
            const test2Cell = row.querySelector(`td.note-test2[data-matiere="${idMatiere}"]`);
            const examenCell = row.querySelector(`td.note-examen[data-matiere="${idMatiere}"]`);
            
            let test1Value = '', test2Value = '', examenValue = '';
            
            if (test1Cell && test1Cell.innerText.trim() !== '-') {
                test1Value = test1Cell.innerText.trim();
            }
            if (test2Cell && test2Cell.innerText.trim() !== '-') {
                test2Value = test2Cell.innerText.trim();
            }
            if (examenCell && examenCell.innerText.trim() !== '-') {
                examenValue = examenCell.innerText.trim();
            }
            
            document.getElementById('edit_id_etudiant').value = idEtudiant;
            document.getElementById('edit_id_matiere').value = idMatiere;
            document.getElementById('edit_test1').value = test1Value;
            document.getElementById('edit_test2').value = test2Value;
            document.getElementById('edit_examen').value = examenValue;
            document.getElementById('modalMatiereInfo').innerHTML = `Matière : <strong>${matiereNom}</strong>`;
            
            document.getElementById('editModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        function saveEditedNote() {
            const idEtudiant = document.getElementById('edit_id_etudiant').value;
            const idMatiere = document.getElementById('edit_id_matiere').value;
            const test1 = document.getElementById('edit_test1').value;
            const test2 = document.getElementById('edit_test2').value;
            const examen = document.getElementById('edit_examen').value;
            
            if (test1 === '' && test2 === '' && examen === '') {
                alert('❌ Vous devez saisir au moins une note !');
                return;
            }
            
            fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'action': 'modifier_note',
                    'id_etudiant': idEtudiant,
                    'id_matiere': idMatiere,
                    'test1': test1,
                    'test2': test2,
                    'examen': examen
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Mettre à jour l'affichage
                    const row = document.querySelector(`tr[data-id-etudiant="${idEtudiant}"]`);
                    if (row) {
                        const test1Cell = row.querySelector(`td.note-test1[data-matiere="${idMatiere}"]`);
                        const test2Cell = row.querySelector(`td.note-test2[data-matiere="${idMatiere}"]`);
                        const examenCell = row.querySelector(`td.note-examen[data-matiere="${idMatiere}"]`);
                        const moyenneCell = row.querySelector(`td.note-moyenne[data-matiere="${idMatiere}"]`);
                        
                        test1Cell.innerHTML = test1 !== '' ? parseFloat(test1).toFixed(2) : '<span class="note-absente">-</span>';
                        test2Cell.innerHTML = test2 !== '' ? parseFloat(test2).toFixed(2) : '<span class="note-absente">-</span>';
                        examenCell.innerHTML = examen !== '' ? parseFloat(examen).toFixed(2) : '<span class="note-absente">-</span>';
                        
                        if (data.moyenne && data.moyenne > 0) {
                            let excellence = data.moyenne >= 16 ? ' <span class="badge-excellence">⭐</span>' : '';
                            moyenneCell.innerHTML = data.moyenne.toFixed(2) + excellence + 
                                '<div class="note-actions">' +
                                '<button class="btn-edit-note" onclick="editNote(\'' + idEtudiant + '\', ' + idMatiere + ', \'' + (moyenneCell.closest('table').querySelector('th.matiere-group').innerText || '') + '\')">✏️</button>' +
                                '<button class="btn-delete-note" onclick="deleteNote(\'' + idEtudiant + '\', ' + idMatiere + ', \'' + (moyenneCell.closest('table').querySelector('th.matiere-group').innerText || '') + '\')">🗑️</button>' +
                                '</div>';
                        } else {
                            moyenneCell.innerHTML = '<span class="note-absente">-</span>';
                        }
                        
                        // Mettre à jour la moyenne générale
                        location.reload();
                    }
                    closeModal();
                    showToast('✓ Notes modifiées avec succès !');
                } else {
                    alert('Erreur : ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Erreur lors de la modification');
            });
        }

        // Fonctions pour la suppression des notes
        function deleteNote(idEtudiant, idMatiere, matiereNom) {
            currentDeleteData = { idEtudiant, idMatiere, matiereNom };
            document.getElementById('deleteMatiereInfo').innerText = matiereNom;
            document.getElementById('deleteModal').style.display = 'block';
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
            currentDeleteData = null;
        }

        document.getElementById('confirmDeleteBtn')?.addEventListener('click', function() {
            if (!currentDeleteData) return;
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = window.location.href;
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'supprimer_note';
            form.appendChild(actionInput);
            
            const etudiantInput = document.createElement('input');
            etudiantInput.type = 'hidden';
            etudiantInput.name = 'id_etudiant';
            etudiantInput.value = currentDeleteData.idEtudiant;
            form.appendChild(etudiantInput);
            
            const matiereInput = document.createElement('input');
            matiereInput.type = 'hidden';
            matiereInput.name = 'id_matiere';
            matiereInput.value = currentDeleteData.idMatiere;
            form.appendChild(matiereInput);
            
            document.body.appendChild(form);
            form.submit();
        });

        function showToast(message) {
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.innerHTML = message;
            document.body.appendChild(toast);
            setTimeout(() => {
                toast.remove();
            }, 3000);
        }

        // Fermer les modals en cliquant en dehors
        window.onclick = function(event) {
            const editModal = document.getElementById('editModal');
            const deleteModal = document.getElementById('deleteModal');
            if (event.target == editModal) {
                closeModal();
            }
            if (event.target == deleteModal) {
                closeDeleteModal();
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const formationSelect = document.getElementById('filtreFormation');
            if (formationSelect) {
                filtrerParFormation(formationSelect.value);
            }
            
            document.getElementById('noteForm').addEventListener('submit', verifierNotes);
            
            // Recalculer les rangs après chargement
            setTimeout(() => {
                document.querySelectorAll('.excel-table').forEach(table => {
                    const formationRows = table.querySelectorAll('.etudiant-row');
                    const moyennes = [];
                    
                    formationRows.forEach(row => {
                        const moyenneCell = row.querySelector('.moyenne-generale');
                        if (moyenneCell) {
                            const moyenneText = moyenneCell.innerText.replace('⭐', '').trim();
                            const moyenne = parseFloat(moyenneText);
                            if (!isNaN(moyenne)) {
                                moyennes.push({ row: row, moyenne: moyenne });
                            }
                        }
                    });
                    
                    moyennes.sort((a, b) => b.moyenne - a.moyenne);
                    
                    moyennes.forEach((item, index) => {
                        const rangCell = item.row.querySelector('.rang');
                        if (rangCell) {
                            rangCell.innerText = index + 1;
                        }
                    });
                });
            }, 100);
        });
    </script>
</body>
</html>