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

// 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 données de l'emploi du temps
$emplois = [];
try {
    $sql = "SELECT s.*, 
                   m.nom_matiere,
                   ens.nom as enseignant_nom, 
                   ens.prenom as enseignant_prenom,
                   g.nom_groupe,
                   sal.nom_salle
            FROM seance s
            LEFT JOIN matieres m ON s.id_matiere = m.id_matiere
            LEFT JOIN enseignant ens ON s.id_enseignant = ens.id_enseignant
            LEFT JOIN groupe g ON s.id_groupe = g.id_groupe
            LEFT JOIN salle sal ON s.id_salle = sal.id_salle
            ORDER BY FIELD(s.jour, 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'), 
                     s.heure_debut";
    
    $stmt = $pdo->query($sql);
    $emplois = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    echo "Erreur SQL : " . $e->getMessage();
}

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

// Créneaux horaires
$creneaux = [
    '08:00:00' => '8h - 10h',
    '10:00:00' => '10h - 12h',
    '14:00:00' => '14h - 16h',
    '16:00:00' => '16h - 18h',
    '18:00:00' => '18h - 20h'
];

// Traitement du formulaire d'ajout/modification
$message = '';
$form_action = 'ajouter_creneau';
$form_title = 'Nouveau cours';
$form_data = [];

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    
    // AJOUT d'un créneau
    if ($_POST['action'] == 'ajouter_creneau') {
        try {
            // Vérifier que tous les champs sont remplis
            if (empty($_POST['jour']) || empty($_POST['heure_debut']) || empty($_POST['heure_fin']) || 
                empty($_POST['id_matiere']) || empty($_POST['id_enseignant']) || 
                empty($_POST['id_groupe']) || empty($_POST['id_salle'])) {
                throw new Exception("Tous les champs sont obligatoires");
            }
            
            // Vérifier si la salle est disponible
            $check = $pdo->prepare("SELECT id_seance FROM seance 
                                   WHERE id_salle = ? AND jour = ? 
                                   AND ((heure_debut <= ? AND heure_fin > ?) 
                                   OR (heure_debut < ? AND heure_fin >= ?))");
            $check->execute([
                $_POST['id_salle'],
                $_POST['jour'],
                $_POST['heure_debut'] . ':00',
                $_POST['heure_debut'] . ':00',
                $_POST['heure_fin'] . ':00',
                $_POST['heure_fin'] . ':00'
            ]);
            
            if ($check->rowCount() > 0) {
                throw new Exception("Cette salle est déjà occupée à ces horaires");
            }
            
            // Vérifier si l'enseignant est disponible
            $check = $pdo->prepare("SELECT id_seance FROM seance 
                                   WHERE id_enseignant = ? AND jour = ? 
                                   AND ((heure_debut <= ? AND heure_fin > ?) 
                                   OR (heure_debut < ? AND heure_fin >= ?))");
            $check->execute([
                $_POST['id_enseignant'],
                $_POST['jour'],
                $_POST['heure_debut'] . ':00',
                $_POST['heure_debut'] . ':00',
                $_POST['heure_fin'] . ':00',
                $_POST['heure_fin'] . ':00'
            ]);
            
            if ($check->rowCount() > 0) {
                throw new Exception("Cet enseignant est déjà occupé à ces horaires");
            }
            
            $sql = "INSERT INTO seance (jour, heure_debut, heure_fin, id_matiere, id_enseignant, id_groupe, id_salle) 
                    VALUES (:jour, :heure_debut, :heure_fin, :id_matiere, :id_enseignant, :id_groupe, :id_salle)";
            
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([
                ':jour' => $_POST['jour'],
                ':heure_debut' => $_POST['heure_debut'] . ':00',
                ':heure_fin' => $_POST['heure_fin'] . ':00',
                ':id_matiere' => $_POST['id_matiere'],
                ':id_enseignant' => $_POST['id_enseignant'],
                ':id_groupe' => $_POST['id_groupe'],
                ':id_salle' => $_POST['id_salle']
            ]);
            
            if ($result) {
                $message = '<div class="alert-success">✅ Créneau ajouté avec succès!</div>';
                echo '<meta http-equiv="refresh" content="2">';
            }
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // MODIFICATION d'un créneau
    elseif ($_POST['action'] == 'modifier_creneau') {
        try {
            // Vérifier que tous les champs sont remplis
            if (empty($_POST['id_seance']) || empty($_POST['jour']) || empty($_POST['heure_debut']) || 
                empty($_POST['heure_fin']) || empty($_POST['id_matiere']) || 
                empty($_POST['id_enseignant']) || empty($_POST['id_groupe']) || empty($_POST['id_salle'])) {
                throw new Exception("Tous les champs sont obligatoires");
            }
            
            // Vérifier si la salle est disponible (sauf pour ce créneau)
            $check = $pdo->prepare("SELECT id_seance FROM seance 
                                   WHERE id_salle = ? AND jour = ? AND id_seance != ?
                                   AND ((heure_debut <= ? AND heure_fin > ?) 
                                   OR (heure_debut < ? AND heure_fin >= ?))");
            $check->execute([
                $_POST['id_salle'],
                $_POST['jour'],
                $_POST['id_seance'],
                $_POST['heure_debut'] . ':00',
                $_POST['heure_debut'] . ':00',
                $_POST['heure_fin'] . ':00',
                $_POST['heure_fin'] . ':00'
            ]);
            
            if ($check->rowCount() > 0) {
                throw new Exception("Cette salle est déjà occupée à ces horaires");
            }
            
            // Vérifier si l'enseignant est disponible (sauf pour ce créneau)
            $check = $pdo->prepare("SELECT id_seance FROM seance 
                                   WHERE id_enseignant = ? AND jour = ? AND id_seance != ?
                                   AND ((heure_debut <= ? AND heure_fin > ?) 
                                   OR (heure_debut < ? AND heure_fin >= ?))");
            $check->execute([
                $_POST['id_enseignant'],
                $_POST['jour'],
                $_POST['id_seance'],
                $_POST['heure_debut'] . ':00',
                $_POST['heure_debut'] . ':00',
                $_POST['heure_fin'] . ':00',
                $_POST['heure_fin'] . ':00'
            ]);
            
            if ($check->rowCount() > 0) {
                throw new Exception("Cet enseignant est déjà occupé à ces horaires");
            }
            
            $sql = "UPDATE seance SET 
                    jour = :jour,
                    heure_debut = :heure_debut,
                    heure_fin = :heure_fin,
                    id_matiere = :id_matiere,
                    id_enseignant = :id_enseignant,
                    id_groupe = :id_groupe,
                    id_salle = :id_salle
                    WHERE id_seance = :id_seance";
            
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([
                ':jour' => $_POST['jour'],
                ':heure_debut' => $_POST['heure_debut'] . ':00',
                ':heure_fin' => $_POST['heure_fin'] . ':00',
                ':id_matiere' => $_POST['id_matiere'],
                ':id_enseignant' => $_POST['id_enseignant'],
                ':id_groupe' => $_POST['id_groupe'],
                ':id_salle' => $_POST['id_salle'],
                ':id_seance' => $_POST['id_seance']
            ]);
            
            if ($result) {
                $message = '<div class="alert-success">✅ Créneau modifié avec succès!</div>';
                echo '<meta http-equiv="refresh" content="2">';
            }
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // SUPPRESSION d'un créneau
    elseif ($_POST['action'] == 'supprimer_creneau') {
        try {
            $stmt = $pdo->prepare("DELETE FROM seance WHERE id_seance = ?");
            $stmt->execute([$_POST['id_seance']]);
            $message = '<div class="alert-success">✅ Créneau supprimé avec succès!</div>';
            echo '<meta http-equiv="refresh" content="2">';
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // CHARGEMENT des données pour modification
    elseif ($_POST['action'] == 'charger_modification' && isset($_POST['id_seance'])) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM seance WHERE id_seance = ?");
            $stmt->execute([$_POST['id_seance']]);
            $form_data = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($form_data) {
                $form_action = 'modifier_creneau';
                $form_title = 'Modifier le cours';
                // Afficher le formulaire avec les données
                echo '<script>
                    document.addEventListener("DOMContentLoaded", function() {
                        document.getElementById("formulaireEmploi").style.display = "block";
                    });
                </script>';
            }
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

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

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

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

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

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

// Organiser les données pour un affichage facile
$emploi_organise = [];
foreach ($emplois as $cours) {
    $jour = $cours['jour'];
    $heure_debut = $cours['heure_debut'];
    $emploi_organise[$jour][$heure_debut] = $cours;
}

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

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

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

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

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

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

        .btn-ajouter span {
            font-size: 20px;
        }

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

        .form-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }

        .form-title h3 {
            color: #1e293b;
            font-size: 20px;
        }

        .btn-annuler-modif {
            background: #64748b;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }

        .btn-annuler-modif:hover {
            background: #475569;
        }

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

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

        .form-grid select:focus, .form-grid input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

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

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

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

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

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

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

        /* Emploi du temps table */
        .emploi-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;
        }

        .emploi-temps {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }

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

        .emploi-temps td {
            border: 1px solid #e2e8f0;
            padding: 0;
            vertical-align: top;
            height: 120px;
            width: 14%;
        }

        .heure-colonne {
            background: #f8fafc;
            font-weight: 600;
            color: #1e293b;
            width: 100px;
            text-align: center;
            vertical-align: middle;
        }

        .creneau {
            background: linear-gradient(135deg, #e0f2fe, #bae6fd);
            margin: 5px;
            padding: 8px;
            border-radius: 10px;
            border-left: 4px solid #667eea;
            font-size: 0.85rem;
            height: calc(100% - 10px);
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: relative;
            transition: all 0.3s;
        }

        .creneau:hover {
            transform: scale(0.98);
            background: linear-gradient(135deg, #d4eaff, #a5d8ff);
        }

        .creneau .matiere {
            font-weight: bold;
            color: #1e293b;
        }

        .creneau .enseignant {
            color: #475569;
            font-size: 0.8rem;
        }

        .creneau .salle {
            color: #667eea;
            font-weight: 500;
            font-size: 0.8rem;
            margin-top: 3px;
        }

        .creneau .groupe {
            color: #64748b;
            font-size: 0.75rem;
        }

        .creneau-actions {
            position: absolute;
            top: 5px;
            right: 5px;
            display: none;
            gap: 5px;
        }

        .creneau:hover .creneau-actions {
            display: flex;
        }

        .btn-action {
            border: none;
            border-radius: 6px;
            width: 26px;
            height: 26px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .btn-modifier {
            background: #f59e0b;
            color: white;
        }

        .btn-modifier:hover {
            background: #d97706;
            transform: scale(1.1);
        }

        .btn-delete-creneau {
            background: #ef4444;
            color: white;
        }

        .btn-delete-creneau:hover {
            background: #dc2626;
            transform: scale(1.1);
        }

        .creneau-vide {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #cbd5e1;
            font-size: 0.9rem;
        }

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

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

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

        .couleur.cours {
            background: linear-gradient(135deg, #e0f2fe, #bae6fd);
            border-left: 3px solid #667eea;
        }

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

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

        /* 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%;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </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>Emploi du Temps</h1>
                <p>Gestion des cours et planning</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 echo $message; ?>

        <!-- Page Header with Add Button -->
        <div class="page-header">
            <h2>
                <span>📅</span> Emploi du Temps
            </h2>
            <button class="btn-ajouter" onclick="nouveauCours()">
                <span>+</span> Ajouter un cours
            </button>
        </div>

        <!-- Formulaire d'ajout/modification -->
        <div id="formulaireEmploi" class="form-container">
            <div class="form-title">
                <h3 id="formTitle"><?php echo $form_title; ?></h3>
                <?php if (!empty($form_data)): ?>
                    <button class="btn-annuler-modif" onclick="annulerModification()">Annuler la modification</button>
                <?php endif; ?>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" id="formAction" value="<?php echo $form_action; ?>">
                <input type="hidden" name="id_seance" id="id_seance" value="<?php echo $form_data['id_seance'] ?? ''; ?>">
                <div class="form-grid">
                    <select name="jour" id="jour" required>
                        <option value="">Sélectionner un jour</option>
                        <?php foreach ($jours as $jour): ?>
                            <option value="<?php echo $jour; ?>" <?php echo (isset($form_data['jour']) && $form_data['jour'] == $jour) ? 'selected' : ''; ?>><?php echo $jour; ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="heure_debut" id="heure_debut" required>
                        <option value="">Heure début</option>
                        <option value="08:00" <?php echo (isset($form_data['heure_debut']) && substr($form_data['heure_debut'], 0, 5) == '08:00') ? 'selected' : ''; ?>>08:00</option>
                        <option value="10:00" <?php echo (isset($form_data['heure_debut']) && substr($form_data['heure_debut'], 0, 5) == '10:00') ? 'selected' : ''; ?>>10:00</option>
                        <option value="14:00" <?php echo (isset($form_data['heure_debut']) && substr($form_data['heure_debut'], 0, 5) == '14:00') ? 'selected' : ''; ?>>14:00</option>
                        <option value="16:00" <?php echo (isset($form_data['heure_debut']) && substr($form_data['heure_debut'], 0, 5) == '16:00') ? 'selected' : ''; ?>>16:00</option>
                        <option value="18:00" <?php echo (isset($form_data['heure_debut']) && substr($form_data['heure_debut'], 0, 5) == '18:00') ? 'selected' : ''; ?>>18:00</option>
                    </select>
                    
                    <select name="heure_fin" id="heure_fin" required>
                        <option value="">Heure fin</option>
                        <option value="10:00" <?php echo (isset($form_data['heure_fin']) && substr($form_data['heure_fin'], 0, 5) == '10:00') ? 'selected' : ''; ?>>10:00</option>
                        <option value="12:00" <?php echo (isset($form_data['heure_fin']) && substr($form_data['heure_fin'], 0, 5) == '12:00') ? 'selected' : ''; ?>>12:00</option>
                        <option value="16:00" <?php echo (isset($form_data['heure_fin']) && substr($form_data['heure_fin'], 0, 5) == '16:00') ? 'selected' : ''; ?>>16:00</option>
                        <option value="18:00" <?php echo (isset($form_data['heure_fin']) && substr($form_data['heure_fin'], 0, 5) == '18:00') ? 'selected' : ''; ?>>18:00</option>
                        <option value="20:00" <?php echo (isset($form_data['heure_fin']) && substr($form_data['heure_fin'], 0, 5) == '20:00') ? 'selected' : ''; ?>>20:00</option>
                    </select>
                    
                    <select name="id_matiere" id="id_matiere" required>
                        <option value="">Sélectionner matière</option>
                        <?php foreach ($matieres as $matiere): ?>
                            <option value="<?php echo $matiere['id_matiere']; ?>" <?php echo (isset($form_data['id_matiere']) && $form_data['id_matiere'] == $matiere['id_matiere']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($matiere['nom_matiere']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="id_enseignant" id="id_enseignant" required>
                        <option value="">Sélectionner enseignant</option>
                        <?php foreach ($enseignants as $ens): ?>
                            <option value="<?php echo $ens['id_enseignant']; ?>" <?php echo (isset($form_data['id_enseignant']) && $form_data['id_enseignant'] == $ens['id_enseignant']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($ens['nom'] . ' ' . $ens['prenom']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="id_groupe" id="id_groupe" required>
                        <option value="">Sélectionner groupe</option>
                        <?php foreach ($groupes as $g): ?>
                            <option value="<?php echo $g['id_groupe']; ?>" <?php echo (isset($form_data['id_groupe']) && $form_data['id_groupe'] == $g['id_groupe']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($g['nom_groupe'] ?? 'Groupe ' . $g['id_groupe']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <select name="id_salle" id="id_salle" required>
                        <option value="">Sélectionner salle</option>
                        <?php foreach ($salles as $salle): ?>
                            <option value="<?php echo $salle['id_salle']; ?>" <?php echo (isset($form_data['id_salle']) && $form_data['id_salle'] == $salle['id_salle']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($salle['nom_salle'] ?? 'Salle ' . $salle['id_salle']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-ajouter btn-success" id="btnSubmit">
                        <?php echo $form_action == 'ajouter_creneau' ? 'Enregistrer' : 'Modifier'; ?>
                    </button>
                    <button type="button" class="btn-ajouter btn-danger" onclick="fermerFormulaire()">Annuler</button>
                </div>
            </form>
        </div>

        <!-- Filtres -->
        <div class="filters-section">
            <select class="filtre-select" id="filtreGroupe" onchange="filtrerParGroupe(this.value)">
                <option value="">👥 Tous les groupes</option>
                <?php foreach ($groupes as $g): ?>
                    <option value="<?php echo $g['id_groupe']; ?>"><?php echo htmlspecialchars($g['nom_groupe'] ?? 'Groupe ' . $g['id_groupe']); ?></option>
                <?php endforeach; ?>
            </select>
            
            <select class="filtre-select" id="filtreEnseignant" onchange="filtrerParEnseignant(this.value)">
                <option value="">👨‍🏫 Tous les enseignants</option>
                <?php foreach ($enseignants as $ens): ?>
                    <option value="<?php echo $ens['id_enseignant']; ?>"><?php echo htmlspecialchars($ens['nom'] . ' ' . $ens['prenom']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Emploi du temps -->
        <div class="emploi-container">
            <table class="emploi-temps">
                <thead>
                    <tr>
                        <th>Horaire</th>
                        <?php foreach ($jours as $jour): ?>
                            <th><?php echo $jour; ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($creneaux as $heure_debut => $creneau_label): ?>
                        <tr>
                            <td class="heure-colonne"><?php echo $creneau_label; ?></td>
                            
                            <?php foreach ($jours as $jour): ?>
                                <td class="cellule-cours"> 
                                    <?php
                                    $cours_trouve = null;
                                    if (isset($emploi_organise[$jour])) {
                                        foreach ($emploi_organise[$jour] as $heure_cours => $cours) {
                                            if (substr($heure_cours, 0, 5) == substr($heure_debut, 0, 5)) {
                                                $cours_trouve = $cours;
                                                break;
                                            }
                                        }
                                    }
                                    
                                    if ($cours_trouve) {
                                        ?>
                                        <div class="creneau" 
                                             data-groupe="<?php echo $cours_trouve['id_groupe']; ?>" 
                                             data-enseignant="<?php echo $cours_trouve['id_enseignant']; ?>">
                                            <div class="creneau-actions">
                                                <form method="POST" style="display: inline;" onsubmit="return confirm('Supprimer ce cours ?');">
                                                    <input type="hidden" name="action" value="supprimer_creneau">
                                                    <input type="hidden" name="id_seance" value="<?php echo $cours_trouve['id_seance']; ?>">
                                                    <button type="submit" class="btn-action btn-delete-creneau" title="Supprimer">🗑️</button>
                                                </form>
                                                <button class="btn-action btn-modifier" title="Modifier" onclick="modifierCreneau(<?php echo $cours_trouve['id_seance']; ?>)">✏️</button>
                                            </div>
                                            <span class="matiere"><?php echo htmlspecialchars($cours_trouve['nom_matiere'] ?? 'Matière inconnue'); ?></span>
                                            <span class="enseignant"><?php echo htmlspecialchars(($cours_trouve['enseignant_nom'] ?? '') . ' ' . ($cours_trouve['enseignant_prenom'] ?? '')); ?></span>
                                            <span class="salle">Salle: <?php echo htmlspecialchars($cours_trouve['nom_salle'] ?? $cours_trouve['id_salle']); ?></span>
                                            <span class="groupe">Groupe: <?php echo htmlspecialchars($cours_trouve['nom_groupe'] ?? 'Groupe ' . $cours_trouve['id_groupe']); ?></span>
                                        </div>
                                        <?php
                                    } else {
                                        echo '<div class="creneau-vide">-</div>';
                                    }
                                    ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Légende -->
        <div class="legende">
            <div class="legende-item">
                <div class="couleur cours"></div>
                <span>Cours programmé</span>
            </div>
            <div class="legende-item">
                <span>✏️ Modifier | 🗑️ Supprimer</span>
            </div>
            <div class="legende-item">
                <span>📚 8h-10h | 10h-12h | 14h-16h | 16h-18h | 18h-20h</span>
            </div>
        </div>
    </div>

    <script>
        function toggleFormulaire() {
            let formulaire = document.getElementById('formulaireEmploi');
            formulaire.style.display = formulaire.style.display === 'none' ? 'block' : 'none';
            if (formulaire.style.display === 'block') {
                document.getElementById('formAction').value = 'ajouter_creneau';
                document.getElementById('formTitle').innerText = 'Nouveau cours';
                document.getElementById('btnSubmit').innerText = 'Enregistrer';
                document.getElementById('id_seance').value = '';
                document.getElementById('jour').value = '';
                document.getElementById('heure_debut').value = '';
                document.getElementById('heure_fin').value = '';
                document.getElementById('id_matiere').value = '';
                document.getElementById('id_enseignant').value = '';
                document.getElementById('id_groupe').value = '';
                document.getElementById('id_salle').value = '';
            }
        }

        function nouveauCours() {
            let formulaire = document.getElementById('formulaireEmploi');
            formulaire.style.display = 'block';
            document.getElementById('formAction').value = 'ajouter_creneau';
            document.getElementById('formTitle').innerText = 'Nouveau cours';
            document.getElementById('btnSubmit').innerText = 'Enregistrer';
            document.getElementById('id_seance').value = '';
            document.getElementById('jour').value = '';
            document.getElementById('heure_debut').value = '';
            document.getElementById('heure_fin').value = '';
            document.getElementById('id_matiere').value = '';
            document.getElementById('id_enseignant').value = '';
            document.getElementById('id_groupe').value = '';
            document.getElementById('id_salle').value = '';
            // Scroll to form
            formulaire.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function fermerFormulaire() {
            document.getElementById('formulaireEmploi').style.display = 'none';
        }

        function annulerModification() {
            window.location.href = 'emplois.php';
        }

        function modifierCreneau(id_seance) {
            let form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            let input1 = document.createElement('input');
            input1.type = 'hidden';
            input1.name = 'action';
            input1.value = 'charger_modification';
            
            let input2 = document.createElement('input');
            input2.type = 'hidden';
            input2.name = 'id_seance';
            input2.value = id_seance;
            
            form.appendChild(input1);
            form.appendChild(input2);
            document.body.appendChild(form);
            form.submit();
        }

        function filtrerParGroupe(groupe) {
            let creneaux = document.querySelectorAll('.creneau');
            let cellulesVides = document.querySelectorAll('.creneau-vide');
            
            if (groupe === '') {
                creneaux.forEach(cell => cell.style.display = 'flex');
                cellulesVides.forEach(vide => vide.style.display = 'flex');
            } else {
                creneaux.forEach(cell => {
                    if (cell.dataset.groupe == groupe) {
                        cell.style.display = 'flex';
                    } else {
                        cell.style.display = 'none';
                    }
                });
                cellulesVides.forEach(vide => vide.style.display = 'flex');
            }
        }

        function filtrerParEnseignant(enseignant) {
            let creneaux = document.querySelectorAll('.creneau');
            let cellulesVides = document.querySelectorAll('.creneau-vide');
            
            if (enseignant === '') {
                creneaux.forEach(cell => cell.style.display = 'flex');
                cellulesVides.forEach(vide => vide.style.display = 'flex');
            } else {
                creneaux.forEach(cell => {
                    if (cell.dataset.enseignant == enseignant) {
                        cell.style.display = 'flex';
                    } else {
                        cell.style.display = 'none';
                    }
                });
                cellulesVides.forEach(vide => vide.style.display = 'flex');
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('#formulaireEmploi form');
            if (form) {
                form.addEventListener('submit', function(e) {
                    const heureDebut = document.getElementById('heure_debut').value;
                    const heureFin = document.getElementById('heure_fin').value;
                    
                    if (heureDebut && heureFin && heureDebut >= heureFin) {
                        e.preventDefault();
                        alert('❌ Erreur : L\'heure de fin doit être après l\'heure de début !');
                    }
                });
            }
        });
    </script>
</body>
</html>