<?php
session_start();
require_once 'config.php';
require_once 'function.php';

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

$current_user = getCurrentUserInfo($pdo);
$message = '';
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'evenements';

// Créer les dossiers si nécessaire
$folders = ['uploads/events', 'uploads/gallery'];
foreach ($folders as $folder) {
    if (!file_exists($folder)) {
        mkdir($folder, 0777, true);
    }
}

// ==================== GESTION DES ÉVÉNEMENTS ====================

// Ajouter un événement
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action_evenement'])) {
    if ($_POST['action_evenement'] == 'ajouter') {
        try {
            $image_name = '';
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (in_array($file_ext, $allowed)) {
                    $image_name = 'event_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                    move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/events/' . $image_name);
                }
            }
            
            $sql = "INSERT INTO evenement (titre, description, date_debut, date_fin, heure_debut, heure_fin, lieu, image, statut) 
                    VALUES (:titre, :description, :date_debut, :date_fin, :heure_debut, :heure_fin, :lieu, :image, :statut)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':titre' => $_POST['titre'],
                ':description' => $_POST['description'],
                ':date_debut' => $_POST['date_debut'],
                ':date_fin' => $_POST['date_fin'] ?: null,
                ':heure_debut' => $_POST['heure_debut'] ?: null,
                ':heure_fin' => $_POST['heure_fin'] ?: null,
                ':lieu' => $_POST['lieu'],
                ':image' => $image_name,
                ':statut' => $_POST['statut']
            ]);
            $message = '<div class="alert-success">✅ Événement ajouté avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=evenements"; }, 1000);</script>';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Modifier un événement
    if ($_POST['action_evenement'] == 'modifier') {
        try {
            $image_name = $_POST['image_actuelle'];
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                if (in_array($file_ext, $allowed)) {
                    if (!empty($_POST['image_actuelle']) && file_exists('uploads/events/' . $_POST['image_actuelle'])) {
                        unlink('uploads/events/' . $_POST['image_actuelle']);
                    }
                    $image_name = 'event_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                    move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/events/' . $image_name);
                }
            }
            
            $sql = "UPDATE evenement SET 
                    titre = :titre,
                    description = :description,
                    date_debut = :date_debut,
                    date_fin = :date_fin,
                    heure_debut = :heure_debut,
                    heure_fin = :heure_fin,
                    lieu = :lieu,
                    image = :image,
                    statut = :statut
                    WHERE id_evenement = :id_evenement";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':titre' => $_POST['titre'],
                ':description' => $_POST['description'],
                ':date_debut' => $_POST['date_debut'],
                ':date_fin' => $_POST['date_fin'] ?: null,
                ':heure_debut' => $_POST['heure_debut'] ?: null,
                ':heure_fin' => $_POST['heure_fin'] ?: null,
                ':lieu' => $_POST['lieu'],
                ':image' => $image_name,
                ':statut' => $_POST['statut'],
                ':id_evenement' => $_POST['id_evenement']
            ]);
            $message = '<div class="alert-success">✅ Événement modifié avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=evenements"; }, 1000);</script>';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Supprimer un événement
    if ($_POST['action_evenement'] == 'supprimer') {
        try {
            $stmt = $pdo->prepare("SELECT image FROM evenement WHERE id_evenement = ?");
            $stmt->execute([$_POST['id_evenement']]);
            $event = $stmt->fetch();
            if ($event && !empty($event['image']) && file_exists('uploads/events/' . $event['image'])) {
                unlink('uploads/events/' . $event['image']);
            }
            
            $stmt = $pdo->prepare("DELETE FROM evenement WHERE id_evenement = ?");
            $stmt->execute([$_POST['id_evenement']]);
            $message = '<div class="alert-success">✅ Événement supprimé avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=evenements"; }, 1000);</script>';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

// ==================== GESTION DE LA GALERIE ====================

// Ajouter un média
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action_galerie'])) {
    if ($_POST['action_galerie'] == 'ajouter') {
        try {
            $fichier_name = '';
            $type = 'image';
            if (isset($_FILES['fichier']) && $_FILES['fichier']['error'] == 0) {
                $allowed_images = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $allowed_videos = ['mp4', 'webm', 'ogg', 'mov'];
                $file_ext = strtolower(pathinfo($_FILES['fichier']['name'], PATHINFO_EXTENSION));
                
                if (in_array($file_ext, $allowed_images)) {
                    $type = 'image';
                    $fichier_name = 'gallery_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                } elseif (in_array($file_ext, $allowed_videos)) {
                    $type = 'video';
                    $fichier_name = 'gallery_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                } else {
                    throw new Exception("Format de fichier non supporté");
                }
                move_uploaded_file($_FILES['fichier']['tmp_name'], 'uploads/gallery/' . $fichier_name);
            } else {
                throw new Exception("Aucun fichier téléchargé");
            }
            
            $sql = "INSERT INTO galerie (titre, description, fichier, type, categorie, ordre, date_creation) 
                    VALUES (:titre, :description, :fichier, :type, :categorie, :ordre, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':titre' => $_POST['titre'],
                ':description' => $_POST['description'],
                ':fichier' => $fichier_name,
                ':type' => $type,
                ':categorie' => $_POST['categorie'],
                ':ordre' => intval($_POST['ordre'] ?? 0)
            ]);
            $message = '<div class="alert-success">✅ Média ajouté avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=galerie"; }, 1000);</script>';
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Modifier un média
    if ($_POST['action_galerie'] == 'modifier') {
        try {
            // Récupérer les infos actuelles
            $stmt = $pdo->prepare("SELECT fichier FROM galerie WHERE id_galerie = ?");
            $stmt->execute([$_POST['id_galerie']]);
            $media_actuel = $stmt->fetch();
            
            $fichier_name = $media_actuel['fichier'];
            $type = $_POST['type_actuel'];
            
            // Si nouveau fichier uploadé
            if (isset($_FILES['fichier']) && $_FILES['fichier']['error'] == 0) {
                $allowed_images = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $allowed_videos = ['mp4', 'webm', 'ogg', 'mov'];
                $file_ext = strtolower(pathinfo($_FILES['fichier']['name'], PATHINFO_EXTENSION));
                
                // Supprimer l'ancien fichier
                if (!empty($media_actuel['fichier']) && file_exists('uploads/gallery/' . $media_actuel['fichier'])) {
                    unlink('uploads/gallery/' . $media_actuel['fichier']);
                }
                
                if (in_array($file_ext, $allowed_images)) {
                    $type = 'image';
                    $fichier_name = 'gallery_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                } elseif (in_array($file_ext, $allowed_videos)) {
                    $type = 'video';
                    $fichier_name = 'gallery_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                }
                move_uploaded_file($_FILES['fichier']['tmp_name'], 'uploads/gallery/' . $fichier_name);
            }
            
            $sql = "UPDATE galerie SET 
                    titre = :titre,
                    description = :description,
                    fichier = :fichier,
                    type = :type,
                    categorie = :categorie,
                    ordre = :ordre
                    WHERE id_galerie = :id_galerie";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':titre' => $_POST['titre'],
                ':description' => $_POST['description'],
                ':fichier' => $fichier_name,
                ':type' => $type,
                ':categorie' => $_POST['categorie'],
                ':ordre' => intval($_POST['ordre'] ?? 0),
                ':id_galerie' => $_POST['id_galerie']
            ]);
            $message = '<div class="alert-success">✅ Média modifié avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=galerie"; }, 1000);</script>';
        } catch(Exception $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Supprimer un média
    if ($_POST['action_galerie'] == 'supprimer') {
        try {
            $stmt = $pdo->prepare("SELECT fichier FROM galerie WHERE id_galerie = ?");
            $stmt->execute([$_POST['id_galerie']]);
            $media = $stmt->fetch();
            if ($media && !empty($media['fichier']) && file_exists('uploads/gallery/' . $media['fichier'])) {
                unlink('uploads/gallery/' . $media['fichier']);
            }
            
            $stmt = $pdo->prepare("DELETE FROM galerie WHERE id_galerie = ?");
            $stmt->execute([$_POST['id_galerie']]);
            $message = '<div class="alert-success">✅ Média supprimé avec succès!</div>';
            echo '<script>setTimeout(function(){ window.location.href = "gestion_site.php?tab=galerie"; }, 1000);</script>';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

// Récupérer les données
$evenements = [];
$galerie = [];

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

try {
    $galerie = $pdo->query("SELECT * FROM galerie ORDER BY ordre ASC, date_creation DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion du Site | CPN</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body { background: #f0f4f6; }
        
        /* 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);
            z-index: 1000;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 40px 20px;
            text-align: center;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
        }
        
        .sidebar-header .logo-area img {
            max-width: 150px;
            border-radius: 20px;
            padding: 10px;
        }
        
        .sidebar-header h2 {
            color: white;
            font-size: 24px;
            margin-top: 15px;
        }
        
        .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;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s;
        }
        
        .sidebar-nav a:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateX(8px);
        }
        
        .sidebar-nav a.active {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
        }
        
        .sidebar-nav .logout {
            margin-top: 40px;
            background: rgba(220, 53, 69, 0.8);
        }
        
        .sidebar-nav .logout:hover {
            background: #dc3545;
        }
        
        /* 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;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: rgba(102, 126, 234, 0.1);
            padding: 10px 20px;
            border-radius: 50px;
        }
        
        .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;
        }
        
        /* Tabs */
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .tab-btn {
            padding: 12px 28px;
            background: white;
            border: none;
            border-radius: 14px;
            font-weight: 600;
            cursor: pointer;
            color: #1e293b;
            transition: all 0.3s;
        }
        
        .tab-btn.active {
            background: linear-gradient(135deg, #2f6d8c, #095175);
            color: white;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Cards Grid */
        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 25px;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: all 0.3s;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        
        .card-content {
            padding: 20px;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 700;
            color: #1e293b;
        }
        
        .card-date {
            font-size: 12px;
            color: #64748b;
            margin: 10px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .card-description {
            font-size: 14px;
            color: #475569;
            line-height: 1.5;
        }
        
        .card-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        /* Gallery Grid */
        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }
        
        .gallery-item {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            transition: all 0.3s;
        }
        
        .gallery-item:hover {
            transform: translateY(-5px);
        }
        
        .gallery-media {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        
        .gallery-info {
            padding: 15px;
        }
        
        .gallery-title {
            font-weight: 600;
            font-size: 16px;
            color: #1e293b;
        }
        
        .gallery-description {
            font-size: 13px;
            color: #64748b;
            margin: 5px 0;
        }
        
        .gallery-category {
            font-size: 11px;
            color: #2f6d8c;
            background: #e0f2fe;
            padding: 3px 10px;
            border-radius: 20px;
            display: inline-block;
            margin-top: 8px;
        }
        
        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, #2f6d8c, #095175);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(47, 109, 140, 0.3);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: #000;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #1e7e34);
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        /* Modal */
        .form-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1100;
            justify-content: center;
            align-items: center;
        }
        
        .form-modal.active {
            display: flex;
        }
        
        .form-modal-content {
            background: white;
            width: 90%;
            max-width: 600px;
            max-height: 85vh;
            overflow-y: auto;
            padding: 30px;
            border-radius: 20px;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            font-weight: 500;
            margin-bottom: 5px;
            color: #1e293b;
        }
        
        .form-group input, .form-group textarea, .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
        }
        
        .form-group input:focus, .form-group textarea:focus, .form-group select:focus {
            outline: none;
            border-color: #2f6d8c;
        }
        
        .form-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        /* Alertes */
        .alert-success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid #dc3545;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 20px;
        }
        
        .empty-icon {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .statut-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .statut-a_venir { background: #17a2b8; color: white; }
        .statut-en_cours { background: #28a745; color: white; }
        .statut-termine { background: #6c757d; color: white; }
        .statut-annule { background: #dc3545; color: white; }
        
        .add-button {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2f6d8c, #095175);
            color: white;
            border: none;
            font-size: 30px;
            cursor: pointer;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            z-index: 100;
            transition: all 0.3s;
        }
        
        .add-button:hover {
            transform: scale(1.1);
        }
        
        /* Preview image */
        .image-preview {
            margin-top: 10px;
            max-width: 100px;
            border-radius: 8px;
        }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); }
            .main-content { margin-left: 0; padding: 15px; }
            .cards-grid, .gallery-grid { grid-template-columns: 1fr; }
            .tabs { flex-direction: column; }
            .tab-btn { justify-content: center; }
        }
    </style>
</head>
<body>
    <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>Gestion du site</p>
        </div>
               <div class="sidebar-nav">
            <a href="admin.php">
                <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" class="active">
                <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>
    
    <div class="main-content">
        <div class="top-header">
            <div>
                <h1>🌐 Gestion du Site</h1>
                <p>Gérez les événements et la galerie d'images</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'] . ' ' . ($current_user['prenom'] ?? '')); ?></strong>
                    <br><small><?php echo isset($_SESSION['user_role']) ? ucfirst(str_replace('_', ' ', $_SESSION['user_role'])) : 'Admin'; ?></small>
                </div>
            </div>
        </div>
        
        <?php echo $message; ?>
        
        <div class="tabs">
            <button class="tab-btn <?php echo $active_tab == 'evenements' ? 'active' : ''; ?>" onclick="showTab('evenements')">📅 Événements</button>
            <button class="tab-btn <?php echo $active_tab == 'galerie' ? 'active' : ''; ?>" onclick="showTab('galerie')">🖼️ Galerie</button>
        </div>
        
        <!-- TAB ÉVÉNEMENTS -->
        <div id="tab-evenements" class="tab-content <?php echo $active_tab == 'evenements' ? 'active' : ''; ?>">
            <div class="cards-grid">
                <?php if(empty($evenements)): ?>
                <div class="empty-state" style="grid-column:1/-1;">
                    <div class="empty-icon">📭</div>
                    <h3>Aucun événement</h3>
                    <p>Cliquez sur le bouton + pour ajouter un événement</p>
                </div>
                <?php else: ?>
                <?php foreach($evenements as $event): ?>
                <div class="card">
                    <?php if(!empty($event['image']) && file_exists('uploads/events/' . $event['image'])): ?>
                        <img src="uploads/events/<?php echo $event['image']; ?>" class="card-image">
                    <?php else: ?>
                        <div class="card-image" style="background: linear-gradient(135deg, #2f6d8c, #095175); display: flex; align-items: center; justify-content: center; font-size: 48px;">📅</div>
                    <?php endif; ?>
                    <div class="card-content">
                        <div class="card-title"><?php echo htmlspecialchars($event['titre']); ?></div>
                        <div class="card-date">
                            📅 <?php echo date('d/m/Y', strtotime($event['date_debut'])); ?>
                            <?php if($event['lieu']): ?> | 📍 <?php echo htmlspecialchars($event['lieu']); ?><?php endif; ?>
                            <span class="statut-badge statut-<?php echo $event['statut']; ?>">
                                <?php echo $event['statut'] == 'a_venir' ? 'À venir' : ($event['statut'] == 'en_cours' ? 'En cours' : ($event['statut'] == 'termine' ? 'Terminé' : 'Annulé')); ?>
                            </span>
                        </div>
                        <div class="card-description"><?php echo nl2br(htmlspecialchars(substr($event['description'] ?? '', 0, 150))); ?></div>
                        <div class="card-actions">
                            <button class="btn-primary btn-sm" onclick='editEvent(<?php echo json_encode($event); ?>)'>✏️ Modifier</button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Supprimer cet événement ?')">
                                <input type="hidden" name="action_evenement" value="supprimer">
                                <input type="hidden" name="id_evenement" value="<?php echo $event['id_evenement']; ?>">
                                <button type="submit" class="btn-primary btn-sm btn-danger">🗑️ Supprimer</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <button class="add-button" onclick="openEventModal()">+</button>
        </div>
        
        <!-- TAB GALERIE -->
        <div id="tab-galerie" class="tab-content <?php echo $active_tab == 'galerie' ? 'active' : ''; ?>">
            <div class="gallery-grid">
                <?php if(empty($galerie)): ?>
                <div class="empty-state" style="grid-column:1/-1;">
                    <div class="empty-icon">🖼️</div>
                    <h3>Aucun média</h3>
                    <p>Cliquez sur le bouton + pour ajouter des images ou vidéos</p>
                </div>
                <?php else: ?>
                <?php foreach($galerie as $media): ?>
                <div class="gallery-item">
                    <?php if($media['type'] == 'image' && !empty($media['fichier']) && file_exists('uploads/gallery/' . $media['fichier'])): ?>
                        <img src="uploads/gallery/<?php echo $media['fichier']; ?>" class="gallery-media">
                    <?php elseif($media['type'] == 'video' && !empty($media['fichier']) && file_exists('uploads/gallery/' . $media['fichier'])): ?>
                        <video src="uploads/gallery/<?php echo $media['fichier']; ?>" class="gallery-media" controls></video>
                    <?php else: ?>
                        <div class="gallery-media" style="background: #e2e8f0; display: flex; align-items: center; justify-content: center; font-size: 48px;">🎬</div>
                    <?php endif; ?>
                    <div class="gallery-info">
                        <div class="gallery-title"><?php echo htmlspecialchars($media['titre'] ?? 'Sans titre'); ?></div>
                        <?php if(!empty($media['description'])): ?>
                        <div class="gallery-description"><?php echo htmlspecialchars(substr($media['description'], 0, 80)); ?></div>
                        <?php endif; ?>
                        <div class="gallery-category">📁 <?php echo htmlspecialchars($media['categorie'] ?? 'Non catégorisé'); ?></div>
                        <div class="card-actions" style="margin-top: 12px;">
                            <button class="btn-primary btn-sm" onclick='editGallery(<?php echo json_encode($media); ?>)'>✏️ Modifier</button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Supprimer ce média ?')">
                                <input type="hidden" name="action_galerie" value="supprimer">
                                <input type="hidden" name="id_galerie" value="<?php echo $media['id_galerie']; ?>">
                                <button type="submit" class="btn-primary btn-sm btn-danger">🗑️ Supprimer</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <button class="add-button" onclick="openGalleryModal()">+</button>
        </div>
    </div>
    
    <!-- MODAL ÉVÉNEMENT -->
    <div id="eventModal" class="form-modal">
        <div class="form-modal-content">
            <h2 id="eventModalTitle">➕ Nouvel événement</h2>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action_evenement" id="eventAction" value="ajouter">
                <input type="hidden" name="id_evenement" id="eventId">
                <input type="hidden" name="image_actuelle" id="eventImageActuelle">
                
                <div class="form-group">
                    <label>Titre *</label>
                    <input type="text" name="titre" id="eventTitre" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" id="eventDescription" rows="4"></textarea>
                </div>
                <div class="form-group">
                    <label>Date début *</label>
                    <input type="date" name="date_debut" id="eventDateDebut" required>
                </div>
                <div class="form-group">
                    <label>Date fin</label>
                    <input type="date" name="date_fin" id="eventDateFin">
                </div>
                <div class="form-group">
                    <label>Heure début</label>
                    <input type="time" name="heure_debut" id="eventHeureDebut">
                </div>
                <div class="form-group">
                    <label>Heure fin</label>
                    <input type="time" name="heure_fin" id="eventHeureFin">
                </div>
                <div class="form-group">
                    <label>Lieu</label>
                    <input type="text" name="lieu" id="eventLieu">
                </div>
                <div class="form-group">
                    <label>Image</label>
                    <input type="file" name="image" accept="image/*" id="eventImage">
                    <div id="eventImagePreview" style="margin-top:10px;"></div>
                </div>
                <div class="form-group">
                    <label>Statut</label>
                    <select name="statut" id="eventStatut">
                        <option value="a_venir">À venir</option>
                        <option value="en_cours">En cours</option>
                        <option value="termine">Terminé</option>
                        <option value="annule">Annulé</option>
                    </select>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-primary">💾 Enregistrer</button>
                    <button type="button" class="btn-primary btn-danger" onclick="closeEventModal()">❌ Annuler</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- MODAL GALERIE (AJOUT) -->
    <div id="galleryModal" class="form-modal">
        <div class="form-modal-content">
            <h2 id="galleryModalTitle">➕ Ajouter un média</h2>
            <form method="POST" enctype="multipart/form-data" id="galleryForm">
                <input type="hidden" name="action_galerie" id="galleryAction" value="ajouter">
                <input type="hidden" name="id_galerie" id="galleryId">
                <input type="hidden" name="type_actuel" id="galleryTypeActuel">
                
                <div class="form-group">
                    <label>Titre</label>
                    <input type="text" name="titre" id="galleryTitre">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" id="galleryDescription" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label>Fichier (image ou vidéo) <span id="fileRequired">*</span></label>
                    <input type="file" name="fichier" id="galleryFichier" accept="image/*,video/*">
                    <div id="galleryFilePreview" style="margin-top:10px;"></div>
                </div>
                <div class="form-group">
                    <label>Catégorie</label>
                    <select name="categorie" id="galleryCategorie">
                        <option value="">Sélectionner</option>
                        <option value="evenements">📅 Événements</option>
                        <option value="formations">📚 Formations</option>
                        <option value="vie_etudiante">👥 Vie étudiante</option>
                        <option value="certificats">📜 Certificats</option>
                        <option value="diplomes">🎓 Diplômes</option>
                        <option value="activites">⚽ Activités</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Ordre d'affichage</label>
                    <input type="number" name="ordre" id="galleryOrdre" value="0">
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-primary">💾 Enregistrer</button>
                    <button type="button" class="btn-primary btn-danger" onclick="closeGalleryModal()">❌ Annuler</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // Tab management
        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.getElementById('tab-' + tab).classList.add('active');
            
            // Update active button class
            const buttons = document.querySelectorAll('.tab-btn');
            for(let i = 0; i < buttons.length; i++) {
                if(buttons[i].innerText.includes(tab === 'evenements' ? 'Événements' : 'Galerie')) {
                    buttons[i].classList.add('active');
                    break;
                }
            }
            
            history.pushState(null, null, '?tab=' + tab);
        }
        
        // Event Modal
        function openEventModal() {
            document.getElementById('eventModal').classList.add('active');
            document.getElementById('eventModalTitle').innerText = '➕ Nouvel événement';
            document.getElementById('eventAction').value = 'ajouter';
            document.getElementById('eventId').value = '';
            document.getElementById('eventTitre').value = '';
            document.getElementById('eventDescription').value = '';
            document.getElementById('eventDateDebut').value = '';
            document.getElementById('eventDateFin').value = '';
            document.getElementById('eventHeureDebut').value = '';
            document.getElementById('eventHeureFin').value = '';
            document.getElementById('eventLieu').value = '';
            document.getElementById('eventStatut').value = 'a_venir';
            document.getElementById('eventImagePreview').innerHTML = '';
            document.getElementById('eventImage').value = '';
        }
        
        function editEvent(event) {
            document.getElementById('eventModal').classList.add('active');
            document.getElementById('eventModalTitle').innerText = '✏️ Modifier événement';
            document.getElementById('eventAction').value = 'modifier';
            document.getElementById('eventId').value = event.id_evenement;
            document.getElementById('eventTitre').value = event.titre;
            document.getElementById('eventDescription').value = event.description || '';
            document.getElementById('eventDateDebut').value = event.date_debut;
            document.getElementById('eventDateFin').value = event.date_fin || '';
            document.getElementById('eventHeureDebut').value = event.heure_debut || '';
            document.getElementById('eventHeureFin').value = event.heure_fin || '';
            document.getElementById('eventLieu').value = event.lieu || '';
            document.getElementById('eventStatut').value = event.statut;
            document.getElementById('eventImageActuelle').value = event.image || '';
            if (event.image) {
                document.getElementById('eventImagePreview').innerHTML = `<img src="uploads/events/${event.image}" class="image-preview">`;
            } else {
                document.getElementById('eventImagePreview').innerHTML = '';
            }
        }
        
        function closeEventModal() {
            document.getElementById('eventModal').classList.remove('active');
        }
        
        // Gallery Modal
        function openGalleryModal() {
            document.getElementById('galleryModal').classList.add('active');
            document.getElementById('galleryModalTitle').innerText = '➕ Ajouter un média';
            document.getElementById('galleryAction').value = 'ajouter';
            document.getElementById('galleryId').value = '';
            document.getElementById('galleryTitre').value = '';
            document.getElementById('galleryDescription').value = '';
            document.getElementById('galleryCategorie').value = '';
            document.getElementById('galleryOrdre').value = '0';
            document.getElementById('galleryFichier').value = '';
            document.getElementById('galleryFilePreview').innerHTML = '';
            document.getElementById('fileRequired').innerHTML = '*';
            document.getElementById('galleryFichier').required = true;
        }
        
        function editGallery(media) {
            document.getElementById('galleryModal').classList.add('active');
            document.getElementById('galleryModalTitle').innerText = '✏️ Modifier média';
            document.getElementById('galleryAction').value = 'modifier';
            document.getElementById('galleryId').value = media.id_galerie;
            document.getElementById('galleryTitre').value = media.titre || '';
            document.getElementById('galleryDescription').value = media.description || '';
            document.getElementById('galleryCategorie').value = media.categorie || '';
            document.getElementById('galleryOrdre').value = media.ordre || 0;
            document.getElementById('galleryTypeActuel').value = media.type || 'image';
            document.getElementById('galleryFichier').required = false;
            document.getElementById('fileRequired').innerHTML = '';
            
            // Preview current file
            if (media.fichier) {
                const fileUrl = 'uploads/gallery/' + media.fichier;
                if (media.type === 'image') {
                    document.getElementById('galleryFilePreview').innerHTML = `<img src="${fileUrl}" class="image-preview"><p style="font-size:12px; margin-top:5px;">Fichier actuel: ${media.fichier}</p>`;
                } else {
                    document.getElementById('galleryFilePreview').innerHTML = `<video src="${fileUrl}" controls style="max-width:100px; border-radius:8px;"></video><p style="font-size:12px; margin-top:5px;">Fichier actuel: ${media.fichier}</p>`;
                }
            }
        }
        
        function closeGalleryModal() {
            document.getElementById('galleryModal').classList.remove('active');
            document.getElementById('galleryFichier').required = false;
        }
        
        // Close modals on outside click
        window.onclick = function(e) {
            if (e.target.classList.contains('form-modal')) {
                e.target.classList.remove('active');
            }
        }
        
        // Handle active tab from URL
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab');
        if (tab && document.getElementById('tab-' + tab)) {
            document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.getElementById('tab-' + tab).classList.add('active');
            const buttons = document.querySelectorAll('.tab-btn');
            for(let i = 0; i < buttons.length; i++) {
                if(buttons[i].innerText.includes(tab === 'evenements' ? 'Événements' : 'Galerie')) {
                    buttons[i].classList.add('active');
                    break;
                }
            }
        }
    </script>
</body>
</html>