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

require_once 'config.php';

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

$id_etudiant = $_SESSION['id_etudiant'] ?? 0;
$current_user = getUserInfo($pdo);

// Récupérer toutes les données avec les fonctions du config.php
$etudiant = getInfosEtudiant($pdo, $id_etudiant);

if (!$etudiant) {
    die("Étudiant non trouvé. Veuillez contacter l'administrateur.");
}

// Mettre à jour l'ID étudiant dans la session si nécessaire
if (!isset($_SESSION['id_etudiant']) && isset($etudiant['id_etudiant'])) {
    $_SESSION['id_etudiant'] = $etudiant['id_etudiant'];
    $id_etudiant = $etudiant['id_etudiant'];
}

// Récupérer les données
$absences = getAbsencesEtudiant($pdo, $id_etudiant);
$notes = getNotesEtudiant($pdo, $id_etudiant);
$emploi_temps = getEmploiTempsEtudiant($pdo, $etudiant['id_groupe'] ?? 0);
$examens = getExamensEtudiant($pdo, $etudiant['id_groupe'] ?? 0);

// Calculer les statistiques
$stats_absences = calculerStatsAbsences($absences);
$stats_notes = calculerMoyenneGenerale($notes);

// Récupérer les paiements mensuels
$paiements_mensuels = [];
if (!empty($etudiant['paiements_mensuels'])) {
    $paiements_mensuels = json_decode($etudiant['paiements_mensuels'], true);
}

// Initialiser les mois par défaut si vides
if (empty($paiements_mensuels)) {
    for ($i = 1; $i <= 12; $i++) {
        $paiements_mensuels[$i] = 'non_paye';
    }
}

// Liste des mois
$mois_liste = [
    1 => ['nom' => 'Janvier', 'abbr' => 'Jan', 'annee' => 2026],
    2 => ['nom' => 'Février', 'abbr' => 'Fév', 'annee' => 2026],
    3 => ['nom' => 'Mars', 'abbr' => 'Mar', 'annee' => 2026],
    4 => ['nom' => 'Avril', 'abbr' => 'Avr', 'annee' => 2026],
    5 => ['nom' => 'Mai', 'abbr' => 'Mai', 'annee' => 2026],
    6 => ['nom' => 'Juin', 'abbr' => 'Juin', 'annee' => 2026],
    7 => ['nom' => 'Juillet', 'abbr' => 'Juil', 'annee' => 2026],
    8 => ['nom' => 'Août', 'abbr' => 'Aoû', 'annee' => 2026],
    9 => ['nom' => 'Septembre', 'abbr' => 'Sep', 'annee' => 2025],
    10 => ['nom' => 'Octobre', 'abbr' => 'Oct', 'annee' => 2025],
    11 => ['nom' => 'Novembre', 'abbr' => 'Nov', 'annee' => 2025],
    12 => ['nom' => 'Décembre', 'abbr' => 'Déc', 'annee' => 2025]
];

$mois_actuel = date('n');
$annee_actuelle = date('Y');

// Déterminer la couleur pour chaque mois
foreach ($mois_liste as $num => &$mois) {
    $statut = $paiements_mensuels[$num] ?? 'non_paye';
    
    if ($statut == 'paye') {
        $mois['couleur'] = 'vert';
        $mois['statut_texte'] = 'Payé ✅';
    } else {
        // Vérifier si le mois est passé ou futur
        if ($mois['annee'] < $annee_actuelle) {
            $mois['couleur'] = 'rouge';
            $mois['statut_texte'] = 'Non payé ❌';
        } elseif ($mois['annee'] == $annee_actuelle && $num < $mois_actuel) {
            $mois['couleur'] = 'rouge';
            $mois['statut_texte'] = 'Non payé ❌';
        } elseif ($mois['annee'] == $annee_actuelle && $num == $mois_actuel) {
            $mois['couleur'] = 'rouge';
            $mois['statut_texte'] = 'Non payé ❌';
        } else {
            $mois['couleur'] = 'bleu';
            $mois['statut_texte'] = 'Non dû 🔵';
        }
    }
}

// Compter les statistiques
$nb_payes = 0;
$nb_non_payes = 0;
foreach ($paiements_mensuels as $statut) {
    if ($statut == 'paye') {
        $nb_payes++;
    } else {
        $nb_non_payes++;
    }
}

// Debug
debug_log($id_etudiant, "ID Étudiant");
debug_log(count($absences), "Nombre d'absences");
?>

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

        /* Stats grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: linear-gradient(135deg, #f8fafc, #f1f5f9);
            border-radius: 16px;
            padding: 20px;
            text-align: center;
            border-left: 4px solid #2f6d8c;
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .stat-value {
            font-size: 36px;
            font-weight: 800;
            color: #1e293b;
        }

        .stat-label {
            color: #64748b;
            font-size: 13px;
            font-weight: 500;
            margin-top: 5px;
        }

        /* Calendar Paiements - Style comme dans l'image */
        .calendar-container {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 1px;
            background: #ddd;
        }

        .month-card {
            background: white;
            padding: 20px;
            text-align: center;
            transition: transform 0.2s;
            cursor: default;
        }

        .month-card:hover {
            transform: scale(1.02);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            z-index: 1;
        }

        .month-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .month-year {
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
        }

        .month-status {
            display: inline-block;
            padding: 8px 15px;
            border-radius: 25px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-vert {
            background: #28a745;
            color: white;
        }

        .status-rouge {
            background: #dc3545;
            color: white;
        }

        .status-bleu {
            background: #17a2b8;
            color: white;
        }

        /* 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-danger {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .alert-info {
            background: linear-gradient(135deg, #d1ecf1, #bee5eb);
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }

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

        /* Note styling */
        .note-excellent { background: #d1fae5; }
        .note-bien { background: #e0f2fe; }
        .note-insuffisant { background: #fee2e2; }

        /* Legend */
        .legend {
            display: flex;
            gap: 30px;
            margin-top: 20px;
            padding: 15px 20px;
            background: #f8f9fa;
            border-radius: 12px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }

        /* 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;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .calendar-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        /* 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 Étudiant</p>
        </div>
        
        <div class="sidebar-nav">
            <a onclick="showSection('emploi_temps')" class="active">
                <span>📅</span>
                <span>Emploi du temps</span>
            </a>
            <a onclick="showSection('absences')">
                <span>❌</span>
                <span>Absences</span>
            </a>
            <a onclick="showSection('notes')">
                <span>📊</span>
                <span>Notes</span>
            </a>
            <a onclick="showSection('examens')">
                <span>📝</span>
                <span>Emplois D'Examens</span>
            </a>
            <a onclick="showSection('paiements')">
                <span>💰</span>
                <span>Paiements</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 Étudiant</h1>
                <p>Bienvenue, <?php echo htmlspecialchars(($etudiant['nom'] ?? '') . ' ' . ($etudiant['prenom'] ?? '')); ?></p>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($etudiant['nom'] ?? 'E', 0, 1)); ?>
                </div>
                <div>
                    <strong><?php echo htmlspecialchars(($etudiant['nom'] ?? '') . ' ' . ($etudiant['prenom'] ?? '')); ?></strong>
                    <br>
                    <small style="color: #64748b;">Groupe: <?php echo htmlspecialchars($etudiant['groupe_nom'] ?? 'Non assigné'); ?></small>
                </div>
            </div>
        </div>

        <!-- SECTION EMPLOI DU TEMPS -->
        <section id="emploi_temps" class="section active">
            <h2>📅 Mon emploi du temps</h2>
            <div class="table-container">
                <?php if (!empty($emploi_temps)): ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Jour</th>
                                <th>Matière</th>
                                <th>Enseignant</th>
                                <th>Salle</th>
                                <th>Horaire</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($emploi_temps as $cours): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($cours['jour'] ?? ''); ?></strong></td>
                                    <td><?php echo htmlspecialchars($cours['matiere_nom'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($cours['enseignant_nom'] ?? 'Non assigné'); ?></td>
                                    <td><?php echo htmlspecialchars($cours['salle_nom'] ?? 'N/A'); ?></td>
                                    <td><?php 
                                        $debut = !empty($cours['heure_debut']) ? date('H:i', strtotime($cours['heure_debut'])) : 'N/A';
                                        $fin = !empty($cours['heure_fin']) ? date('H:i', strtotime($cours['heure_fin'])) : 'N/A';
                                        echo $debut . ' - ' . $fin; 
                                    ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="no-data">📭 Aucun cours planifié pour votre groupe</div>
                <?php endif; ?>
            </div>
        </section>

        <!-- SECTION ABSENCES -->
        <section id="absences" class="section">
            <h2>❌ Mes absences</h2>
            
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats_absences['total']; ?></div>
                    <div class="stat-label">Total absences</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats_absences['non_justifiees']; ?></div>
                    <div class="stat-label">Non justifiées</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats_absences['justifiees']; ?></div>
                    <div class="stat-label">Justifiées</div>
                </div>
            </div>

            <?php 
            if ($stats_absences['non_justifiees'] > 5) {
                echo "<div class='alert alert-danger'>⚠️ Attention ! Vous avez " . $stats_absences['non_justifiees'] . " absences non justifiées. Veuillez régulariser votre situation.</div>";
            } elseif ($stats_absences['non_justifiees'] > 0) {
                echo "<div class='alert alert-warning'>⚠️ Vous avez " . $stats_absences['non_justifiees'] . " absence(s) non justifiée(s)</div>";
            } else {
                echo "<div class='alert alert-success'>✅ Félicitations ! Aucune absence non justifiée</div>";
            }
            ?>

            <div class="table-container">
                <?php if (empty($absences)): ?>
                    <div class="no-data">✅ Aucune absence enregistrée</div>
                <?php else: ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Matière</th>
                                <th>Horaire</th>
                                <th>Justifié</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($absences as $a): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($a['date_affichage'])); ?></td>
                                    <td><?php echo htmlspecialchars($a['matiere_nom']); ?></td>
                                    <td><?php echo date('H:i', strtotime($a['heure_debut'])) . ' - ' . date('H:i', strtotime($a['heure_fin'])); ?></td>
                                    <td class="<?php echo $a['justifie_class']; ?>"><strong><?php echo $a['justifie_texte']; ?></strong></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </section>

        <!-- SECTION NOTES -->
        <section id="notes" class="section">
            <h2>📊 Mes notes</h2>
            
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats_notes['nb_matieres']; ?></div>
                    <div class="stat-label">Matières notées</div>
                </div>
                <?php if ($stats_notes['nb_matieres'] > 0): ?>
                <div class="stat-card">
                    <div class="stat-value"><?php echo number_format($stats_notes['moyenne'], 2); ?><span style="font-size: 18px;">/20</span></div>
                    <div class="stat-label">Moyenne générale</div>
                </div>
                <?php endif; ?>
            </div>

            <div class="table-container">
                <?php if (empty($notes)): ?>
                    <div class="no-data">📭 Aucune note disponible</div>
                <?php else: ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Matière</th>
                                <th>Test 1</th>
                                <th>Test 2</th>
                                <th>Examen</th>
                                <th>Moyenne</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($notes as $n): ?>
                                <?php
                                $row_class = '';
                                if (!empty($n['moyenne'])) {
                                    if ($n['moyenne'] >= 16) $row_class = 'note-excellent';
                                    elseif ($n['moyenne'] >= 12) $row_class = 'note-bien';
                                    elseif ($n['moyenne'] < 10) $row_class = 'note-insuffisant';
                                }
                                ?>
                                <tr class="<?php echo $row_class; ?>">
                                    <td><strong><?php echo htmlspecialchars($n['matiere_nom']); ?></strong></td>
                                    <td><?php echo !empty($n['test1']) ? number_format($n['test1'], 2) . '/20' : '-'; ?></td>
                                    <td><?php echo !empty($n['test2']) ? number_format($n['test2'], 2) . '/20' : '-'; ?></td>
                                    <td><?php echo !empty($n['examen']) ? number_format($n['examen'], 2) . '/20' : '-'; ?></td>
                                    <td><strong><?php echo !empty($n['moyenne']) ? number_format($n['moyenne'], 2) . '/20' : '-'; ?></strong></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <p style="margin-top: 15px; font-size: 12px; color: #64748b;">
                        * La moyenne est calculée selon la formule : (Examen × 2 + Test 1 + Test 2) ÷ 4
                    </p>
                <?php endif; ?>
            </div>
        </section>

        <!-- SECTION EXAMENS -->
        <section id="examens" class="section">
            <h2>📝 Planning des examens</h2>
            <div class="table-container">
                <?php if (empty($examens)): ?>
                    <div class="no-data">📭 Aucun examen planifié pour votre groupe</div>
                <?php else: ?>
                    <?php 
                    $today = date('Y-m-d');
                    $examens_a_venir = array_filter($examens, function($e) use ($today) {
                        return isset($e['date_examen']) && $e['date_examen'] >= $today;
                    });
                    $examens_passes = array_filter($examens, function($e) use ($today) {
                        return isset($e['date_examen']) && $e['date_examen'] < $today;
                    });
                    ?>

                    <?php if (!empty($examens_a_venir)): ?>
                        <h3 style="color: #1e293b; margin: 20px 0 15px;">📅 Examens à venir</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Matière</th>
                                    <th>Type</th>
                                    <th>Salle</th>
                                    <th>Horaire</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($examens_a_venir as $e): ?>
                                    <tr>
                                        <td><strong><?php echo date('d/m/Y', strtotime($e['date_examen'])); ?></strong></td>
                                        <td><?php echo htmlspecialchars($e['matiere_nom']); ?></td>
                                        <td>
                                            <span class="badge 
                                                <?php 
                                                if($e['type_examen'] == 'test1') echo 'badge-test1';
                                                elseif($e['type_examen'] == 'test2') echo 'badge-test2';
                                                else echo 'badge-examen';
                                                ?>">
                                                <?php echo $e['type_label']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($e['salle_nom']); ?></td>
                                        <td><?php echo date('H:i', strtotime($e['heure_debut'])) . ' - ' . date('H:i', strtotime($e['heure_fin'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>

                    <?php if (!empty($examens_passes)): ?>
                        <h3 style="color: #1e293b; margin: 30px 0 15px;">📋 Examens passés</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Matière</th>
                                    <th>Type</th>
                                    <th>Salle</th>
                                    <th>Horaire</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($examens_passes as $e): ?>
                                    <tr style="opacity: 0.7;">
                                        <td><?php echo date('d/m/Y', strtotime($e['date_examen'])); ?></td>
                                        <td><?php echo htmlspecialchars($e['matiere_nom']); ?></td>
                                        <td>
                                            <span class="badge 
                                                <?php 
                                                if($e['type_examen'] == 'test1') echo 'badge-test1';
                                                elseif($e['type_examen'] == 'test2') echo 'badge-test2';
                                                else echo 'badge-examen';
                                                ?>">
                                                <?php echo $e['type_label']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($e['salle_nom']); ?></td>
                                        <td><?php echo date('H:i', strtotime($e['heure_debut'])) . ' - ' . date('H:i', strtotime($e['heure_fin'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </section>

        <!-- SECTION PAIEMENTS - CALENDRIER MENSUEL -->
        <section id="paiements" class="section">
            <h2>💰 Calendrier des paiements</h2>
            
            <!-- Statistiques -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value" style="color: #28a745;"><?php echo $nb_payes; ?></div>
                    <div class="stat-label">Mois payés ✅</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" style="color: #dc3545;"><?php echo $nb_non_payes; ?></div>
                    <div class="stat-label">Mois non payés ❌</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $nb_payes + $nb_non_payes; ?></div>
                    <div class="stat-label">Total des mois</div>
                </div>
            </div>
            
            <?php if ($nb_non_payes == 0): ?>
                <div class="alert alert-success">
                    ✅ Félicitations ! Tous vos mois sont payés.
                </div>
            <?php else: ?>
                <div class="alert alert-warning">
                    ⚠️ Attention ! Vous avez <?php echo $nb_non_payes; ?> mois non payés. Veuillez régulariser votre situation.
                </div>
            <?php endif; ?>
            
            <!-- Calendrier -->
            <div class="calendar-container">
                <div class="calendar-grid">
                    <?php foreach ($mois_liste as $num => $mois): ?>
                        <div class="month-card">
                            <div class="month-name"><?php echo $mois['nom']; ?></div>
                            <div class="month-year"><?php echo $mois['annee']; ?></div>
                            <div class="month-status status-<?php echo $mois['couleur']; ?>">
                                <?php echo $mois['statut_texte']; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Légende -->
            <div class="legend">
                <div class="legend-item">
                    <div class="legend-color" style="background: #28a745;"></div>
                    <span>Payé (Vert)</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background: #dc3545;"></div>
                    <span>Non payé (Rouge)</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background: #17a2b8;"></div>
                    <span>Non dû / Mois futur (Bleu)</span>
                </div>
            </div>
            
            <div class="alert alert-info" style="margin-top: 20px;">
                📌 <strong>Informations :</strong><br>
                • Les paiements se font par mois<br>
                • Les mois en vert sont payés<br>
                • Les mois en rouge sont impayés<br>
                • Les mois en bleu ne sont pas encore dus (mois futurs)
            </div>
        </section>
    </div>

    <script>
        function showSection(sectionId) {
            // Cacher toutes les sections
            document.querySelectorAll('.section').forEach(section => {
                section.classList.remove('active');
            });
            
            // Afficher la section sélectionnée
            document.getElementById(sectionId).classList.add('active');
            
            // Mettre à jour les liens actifs
            document.querySelectorAll('.sidebar-nav a').forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('onclick') && link.getAttribute('onclick').includes(sectionId)) {
                    link.classList.add('active');
                }
            });
            
            // Mettre à jour l'URL
            history.pushState(null, null, '?section=' + sectionId);
        }

        // Activer la section basée sur l'URL au chargement
        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>