<?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 = '';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$formation_filter = isset($_GET['formation']) ? $_GET['formation'] : '';

// Traitement des actions
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['action'])) {
        switch($_POST['action']) {
            case 'changer_statut':
                try {
                    $sql = "UPDATE inscription SET statut = :statut WHERE id_inscription = :id";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        ':statut' => $_POST['nouveau_statut'],
                        ':id' => $_POST['id_inscription']
                    ]);
                    $message = '<div class="alert-success">✅ Statut mis à jour avec succès!</div>';
                } catch(PDOException $e) {
                    $message = '<div class="alert-error">❌ Erreur: ' . $e->getMessage() . '</div>';
                }
                break;
                
            case 'supprimer':
                try {
                    $stmt = $pdo->prepare("DELETE FROM inscription WHERE id_inscription = ?");
                    $stmt->execute([$_POST['id_inscription']]);
                    $message = '<div class="alert-success">✅ Inscription supprimée!</div>';
                } catch(PDOException $e) {
                    $message = '<div class="alert-error">❌ Erreur: ' . $e->getMessage() . '</div>';
                }
                break;
                
            case 'ajouter_etudiant':
                try {
                    $code_etudiant = isset($_POST['code_etudiant']) ? trim($_POST['code_etudiant']) : '';
                    
                    if (empty($code_etudiant)) {
                        throw new Exception("Le code étudiant est requis");
                    }
                    
                    $check_sql = "SELECT id_etudiant FROM etudiants WHERE id_etudiant = :code";
                    $check_stmt = $pdo->prepare($check_sql);
                    $check_stmt->execute([':code' => $code_etudiant]);
                    if ($check_stmt->rowCount() > 0) {
                        throw new Exception("Ce code étudiant existe déjà. Veuillez en utiliser un autre.");
                    }
                    
                    $check_sql2 = "SELECT id_user FROM utilisateur WHERE id_user = :code OR login = :code";
                    $check_stmt2 = $pdo->prepare($check_sql2);
                    $check_stmt2->execute([':code' => $code_etudiant]);
                    if ($check_stmt2->rowCount() > 0) {
                        throw new Exception("Ce code étudiant existe déjà dans le système.");
                    }
                    
                    $mot_de_passe = 'etudiant123';
                    
                    $sql_user = "INSERT INTO utilisateur (id_user, nom, prenom, login, mot_de_passe, role, etat_compte) 
                                 VALUES (:id_user, :nom, :prenom, :login, :mot_de_passe, 'etudiant', 'actif')";
                    $stmt_user = $pdo->prepare($sql_user);
                    $stmt_user->execute([
                        ':id_user' => $code_etudiant,
                        ':nom' => $_POST['nom'],
                        ':prenom' => $_POST['prenom'],
                        ':login' => $code_etudiant,
                        ':mot_de_passe' => $mot_de_passe
                    ]);
                    
                    $paiements_init = [];
                    for ($i = 1; $i <= 12; $i++) {
                        $paiements_init[$i] = 'non_paye';
                    }
                    $paiements_json = json_encode($paiements_init);
                    
                    $sql = "INSERT INTO etudiants (id_etudiant, id_user, nom, prenom, telephone, adresse, date_naissance, paiement, paiements_mensuels) 
                            VALUES (:id_etudiant, :id_user, :nom, :prenom, :telephone, :adresse, :date_naissance, 'impaye', :paiements)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        ':id_etudiant' => $code_etudiant,
                        ':id_user' => $code_etudiant,
                        ':nom' => $_POST['nom'],
                        ':prenom' => $_POST['prenom'],
                        ':telephone' => $_POST['telephone'],
                        ':adresse' => $_POST['adresse'],
                        ':date_naissance' => $_POST['date_naissance'],
                        ':paiements' => $paiements_json
                    ]);
                    
                    $sql2 = "UPDATE inscription SET statut = 'confirmee', id_etudiant_genere = :id_etudiant WHERE id_inscription = :id";
                    $stmt2 = $pdo->prepare($sql2);
                    $stmt2->execute([
                        ':id_etudiant' => $code_etudiant,
                        ':id' => $_POST['id_inscription']
                    ]);
                    
                    $message = '<div class="alert-success">✅ Étudiant ajouté avec succès! ID: ' . htmlspecialchars($code_etudiant) . ' | Mot de passe: ' . $mot_de_passe . '</div>';
                    
                } catch(PDOException $e) {
                    $message = '<div class="alert-error">❌ Erreur: ' . $e->getMessage() . '</div>';
                } catch(Exception $e) {
                    $message = '<div class="alert-error">❌ ' . $e->getMessage() . '</div>';
                }
                break;
        }
    }
}

// Ajouter les colonnes si elles n'existent pas
try {
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS statut ENUM('en_attente', 'confirmee', 'annulee', 'liste_attente') DEFAULT 'en_attente'");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS id_etudiant_genere VARCHAR(50) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS notes_admin TEXT DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS sexe VARCHAR(20) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS ville VARCHAR(255) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS code_postale VARCHAR(20) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS niveau_etudes VARCHAR(100) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS formation_souhaitee VARCHAR(255) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS mode_formation VARCHAR(100) DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS message TEXT DEFAULT NULL");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS newsletter ENUM('oui','non') DEFAULT 'non'");
    $pdo->exec("ALTER TABLE inscription ADD COLUMN IF NOT EXISTS id_formation INT(11) DEFAULT NULL");
} catch(PDOException $e) {
    // Colonnes existent déjà
}

// Récupérer les inscriptions avec filtres
$inscriptions = [];
$total = 0;
$en_attente = 0;
$confirmees = 0;
$annulees = 0;

try {
    $sql = "SELECT i.*, f.nom_formation as formation_nom 
            FROM inscription i 
            LEFT JOIN formation f ON i.id_formation = f.id_formation 
            WHERE 1=1";
    $params = [];
    
    if (!empty($search)) {
        $sql .= " AND (i.nom LIKE :search OR i.prenom LIKE :search OR i.email LIKE :search OR i.telephone LIKE :search)";
        $params[':search'] = "%$search%";
    }
    
    if (!empty($status)) {
        $sql .= " AND i.statut = :status";
        $params[':status'] = $status;
    }
    
    if (!empty($formation_filter)) {
        $sql .= " AND i.id_formation = :formation";
        $params[':formation'] = $formation_filter;
    }
    
    $sql .= " ORDER BY i.date_inscription DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $inscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Compter par statut
    $stmt2 = $pdo->query("SELECT statut, COUNT(*) as count FROM inscription GROUP BY statut");
    while($row = $stmt2->fetch()) {
        switch($row['statut']) {
            case 'en_attente': $en_attente = $row['count']; break;
            case 'confirmee': $confirmees = $row['count']; break;
            case 'annulee': $annulees = $row['count']; break;
        }
    }
    $total = count($inscriptions);
    
} catch(PDOException $e) {
    $message = '<div class="alert-error">❌ Erreur de chargement: ' . $e->getMessage() . '</div>';
}

// Récupérer les formations pour le filtre
$formations = [];
try {
    $formations = $pdo->query("SELECT id_formation, nom_formation FROM formation ORDER BY nom_formation")->fetchAll();
} catch(PDOException $e) {}
// Dans la partie ajout d'inscription, après avoir reçu formation_souhaitee
if (!empty($_POST['formation_souhaitee'])) {
    $stmtForm = $pdo->prepare("SELECT id_formation FROM formation WHERE nom_formation = ?");
    $stmtForm->execute([$_POST['formation_souhaitee']]);
    $formation = $stmtForm->fetch();
    if ($formation) {
        $id_formation = $formation['id_formation'];
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Inscriptions | 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 {
            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 img {
            max-width: 150px;
            height: auto;
            border-radius: 20px;
            padding: 10px;
        }
        
        .sidebar-header h2 {
            color: white;
            font-size: 24px;
            font-weight: 700;
            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;
            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);
        }
        
        .sidebar-nav a.active {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .sidebar-nav .logout {
            margin-top: 40px;
            background: rgba(220, 53, 69, 0.8);
        }
        
        .main-content {
            margin-left: 280px;
            padding: 20px 30px;
        }
        
        .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;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: linear-gradient(135deg, #667eea20, #764ba220);
            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;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s;
        }
        
        .stat-card:hover { transform: translateY(-5px); }
        .stat-card.total { border-top: 4px solid #2f6d8c; }
        .stat-card.en-attente { border-top: 4px solid #ffc107; }
        .stat-card.confirmees { border-top: 4px solid #28a745; }
        .stat-card.annulees { border-top: 4px solid #dc3545; }
        
        .stat-number {
            font-size: 36px;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 14px;
            margin-top: 5px;
        }
        
        .filters-bar {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        
        .filter-group {
            flex: 1;
            min-width: 150px;
        }
        
        .filter-group label {
            display: block;
            font-size: 12px;
            font-weight: 600;
            color: #64748b;
            margin-bottom: 5px;
        }
        
        .filter-group input, .filter-group select {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
        }
        
        .btn-filter {
            background: #2f6d8c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
        }
        
        .btn-reset {
            background: #64748b;
        }
        
        .table-container {
            background: white;
            border-radius: 20px;
            overflow-x: auto;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th {
            background: #f8fafc;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #1e293b;
            border-bottom: 2px solid #e2e8f0;
        }
        
        td {
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
            vertical-align: middle;
        }
        
        tr:hover {
            background: #f8fafc;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-en_attente { background: #ffc107; color: #000; }
        .badge-confirmee { background: #28a745; color: white; }
        .badge-annulee { background: #dc3545; color: white; }
        .badge-liste_attente { background: #17a2b8; color: white; }
        
        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .btn-icon {
            padding: 6px 12px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .btn-view { background: #2f6d8c; color: white; }
        .btn-confirm { background: #28a745; color: white; }
        .btn-cancel { background: #dc3545; color: white; }
        .btn-delete { background: #6c757d; color: white; }
        
        .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;
        }
        
        .modal.active { display: flex; }
        
        .modal-content {
            background: white;
            width: 90%;
            max-width: 650px;
            border-radius: 20px;
            padding: 25px;
            max-height: 85vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
        }
        
        .detail-row {
            margin-bottom: 12px;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .detail-label {
            font-weight: 600;
            color: #64748b;
            font-size: 12px;
        }
        
        .detail-value {
            font-size: 14px;
            color: #1e293b;
            margin-top: 3px;
        }
        
        .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;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            font-weight: 500;
            margin-bottom: 5px;
            font-size: 13px;
        }
        
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
        }
        
        .form-group small {
            display: block;
            font-size: 11px;
            color: #64748b;
            margin-top: 4px;
        }
        
        .code-input {
            font-family: monospace;
            text-transform: uppercase;
            background: #f8fafc;
        }
        
        .info-badge {
            background: #e0f2fe;
            color: #0369a1;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            display: inline-block;
        }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); }
            .main-content { margin-left: 0; padding: 15px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
        }
    </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 des inscriptions</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 des Inscriptions</h1>
                <p>Gérez les demandes d'inscription des étudiants</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; ?>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card total">
                <div class="stat-number"><?php echo $total; ?></div>
                <div class="stat-label">Total inscriptions</div>
            </div>
            <div class="stat-card en-attente">
                <div class="stat-number"><?php echo $en_attente; ?></div>
                <div class="stat-label">En attente</div>
            </div>
            <div class="stat-card confirmees">
                <div class="stat-number"><?php echo $confirmees; ?></div>
                <div class="stat-label">Confirmées</div>
            </div>
            <div class="stat-card annulees">
                <div class="stat-number"><?php echo $annulees; ?></div>
                <div class="stat-label">Annulées</div>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filters-bar">
            <div class="filter-group">
                <label>🔍 Rechercher</label>
                <input type="text" id="searchInput" placeholder="Nom, prénom, email, téléphone..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="filter-group">
                <label>📊 Statut</label>
                <select id="statusFilter">
                    <option value="">Tous</option>
                    <option value="en_attente" <?php echo $status == 'en_attente' ? 'selected' : ''; ?>>En attente</option>
                    <option value="confirmee" <?php echo $status == 'confirmee' ? 'selected' : ''; ?>>Confirmée</option>
                    <option value="annulee" <?php echo $status == 'annulee' ? 'selected' : ''; ?>>Annulée</option>
                    <option value="liste_attente" <?php echo $status == 'liste_attente' ? 'selected' : ''; ?>>Liste d'attente</option>
                </select>
            </div>
            <div class="filter-group">
                <label>📚 Formation (filtre)</label>
                <select id="formationFilter">
                    <option value="">Toutes</option>
                    <?php foreach($formations as $f): ?>
                    <option value="<?php echo $f['id_formation']; ?>" <?php echo $formation_filter == $f['id_formation'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($f['nom_formation']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="filter-group">
                <button class="btn-filter" onclick="applyFilters()">🔍 Filtrer</button>
                <button class="btn-filter btn-reset" onclick="resetFilters()">🗑️ Réinitialiser</button>
            </div>
        </div>
        
        <!-- Table -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Code Étudiant</th>
                        <th>Date inscription</th>
                        <th>Nom & Prénom</th>
                        <th>Contact</th>
                        <th>Date naissance</th>
                        <th>Formation souhaitée</th>
                        <th>Statut</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($inscriptions)): ?>
                    <tr>
                        <td colspan="9" style="text-align: center; padding: 40px;">📭 Aucune inscription trouvée</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach($inscriptions as $insc): ?>
                    <tr>
                        <td>#<?php echo $insc['id_inscription']; ?></td>
                        <td>
                            <?php if(!empty($insc['id_etudiant_genere'])): ?>
                                <span class="badge" style="background: #e0f2fe; color: #0369a1;"><?php echo htmlspecialchars($insc['id_etudiant_genere']); ?></span>
                            <?php else: ?>
                                <span style="color: #94a3b8; font-size: 12px;">Non assigné</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo date('d/m/Y', strtotime($insc['date_inscription'])); ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($insc['prenom'] . ' ' . $insc['nom']); ?></strong>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($insc['email']); ?><br>
                            <small><?php echo htmlspecialchars($insc['telephone']); ?></small>
                        </td>
                        <td>
                            <?php echo $insc['date_naissance'] ? date('d/m/Y', strtotime($insc['date_naissance'])) : '<span style="color:#999;">Non renseignée</span>'; ?>
                        </td>
                        <td>
                            <?php 
                            $formation_display = !empty($insc['formation_souhaitee']) 
                                ? $insc['formation_souhaitee'] 
                                : ($insc['formation_nom'] ?? '-');
                            if(strlen($formation_display) > 35) {
                                $formation_display = substr($formation_display, 0, 32) . '...';
                            }
                            echo htmlspecialchars($formation_display);
                            ?>
                        </td>
                        <td>
                            <span class="badge badge-<?php echo $insc['statut'] ?? 'en_attente'; ?>">
                                <?php 
                                switch($insc['statut']) {
                                    case 'confirmee': echo '✓ Confirmée'; break;
                                    case 'annulee': echo '✗ Annulée'; break;
                                    case 'liste_attente': echo '⏳ Liste d\'attente'; break;
                                    default: echo '⏰ En attente';
                                }
                                ?>
                            </span>
                        </td>
                        <td class="action-buttons">
                            <button class="btn-icon btn-view" onclick='viewDetails(<?php echo json_encode($insc); ?>)'>👁️ Voir</button>
                            <?php if(($insc['statut'] ?? 'en_attente') == 'en_attente'): ?>
                            <button class="btn-icon btn-confirm" onclick='confirmInscription(<?php echo $insc['id_inscription']; ?>, <?php echo json_encode($insc['prenom']); ?>, <?php echo json_encode($insc['nom']); ?>, <?php echo json_encode($insc['telephone']); ?>, <?php echo json_encode($insc['date_naissance'] ?? ''); ?>, <?php echo json_encode($insc['adresse'] ?? ''); ?>)'>✓ Confirmer</button>
                            <button class="btn-icon btn-cancel" onclick="changeStatus(<?php echo $insc['id_inscription']; ?>, 'annulee')">✗ Annuler</button>
                            <?php endif; ?>
                            <button class="btn-icon btn-delete" onclick="deleteInscription(<?php echo $insc['id_inscription']; ?>)">🗑️ Supprimer</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Modal Détails -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📋 Détails de l'inscription</h3>
                <button class="modal-close" onclick="closeModal('detailsModal')">&times;</button>
            </div>
            <div id="detailsContent"></div>
        </div>
    </div>
    
    <!-- Modal Confirmation -->
    <div id="confirmModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>✓ Confirmer l'inscription</h3>
                <button class="modal-close" onclick="closeModal('confirmModal')">&times;</button>
            </div>
            <form method="POST" id="confirmForm">
                <input type="hidden" name="action" value="ajouter_etudiant">
                <input type="hidden" name="id_inscription" id="confirmId">
                
                <div class="form-group">
                    <label>🎓 Code Étudiant *</label>
                    <input type="text" name="code_etudiant" id="confirmCode" required 
                           placeholder="Ex: ET2025001 ou AT0280"
                           class="code-input">
                    <small>Code unique pour identifier l'étudiant (lettres et chiffres, sans espaces)</small>
                </div>
                
                <div class="form-group">
                    <label>📅 Date de naissance *</label>
                    <input type="date" name="date_naissance" id="confirmDateNaissance" required>
                </div>
                
                <div class="form-group">
                    <label>📍 Adresse *</label>
                    <input type="text" name="adresse" id="confirmAdresse" required>
                </div>
                
                <div class="form-group">
                    <label>📞 Téléphone</label>
                    <input type="text" name="telephone" id="confirmTelephone" readonly>
                </div>
                
                <div class="form-group">
                    <label>👤 Nom</label>
                    <input type="text" name="nom" id="confirmNom" readonly>
                </div>
                
                <div class="form-group">
                    <label>👤 Prénom</label>
                    <input type="text" name="prenom" id="confirmPrenom" readonly>
                </div>
                
                <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                    <button type="submit" class="btn-icon btn-confirm">✓ Confirmer l'inscription</button>
                    <button type="button" class="btn-icon btn-delete" onclick="closeModal('confirmModal')">Annuler</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function applyFilters() {
            const search = document.getElementById('searchInput').value;
            const status = document.getElementById('statusFilter').value;
            const formation = document.getElementById('formationFilter').value;
            window.location.href = `gestion_inscriptions.php?search=${encodeURIComponent(search)}&status=${status}&formation=${formation}`;
        }
        
        function resetFilters() {
            window.location.href = 'gestion_inscriptions.php';
        }
        
        function viewDetails(inscription) {
            const formationValue = inscription.formation_souhaitee || inscription.formation_nom || '-';
            const modeValue = inscription.mode_formation || '-';
            const niveauValue = inscription.niveau_etudes || '-';
            const villeValue = inscription.ville || '-';
            const codePostaleValue = inscription.code_postale || '-';
            const sexeValue = inscription.sexe || '-';
            const messageValue = inscription.message || '-';
            const newsletterValue = inscription.newsletter === 'oui' ? '✓ Inscrit à la newsletter' : '✗ Non inscrit';
            
            const content = `
                <div class="detail-row">
                    <div class="detail-label">ID Inscription</div>
                    <div class="detail-value">#${inscription.id_inscription}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Code Étudiant</div>
                    <div class="detail-value">${inscription.id_etudiant_genere ? inscription.id_etudiant_genere : '<span class="info-badge">Non assigné</span>'}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Date d'inscription</div>
                    <div class="detail-value">${new Date(inscription.date_inscription).toLocaleString('fr-FR')}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Nom complet</div>
                    <div class="detail-value"><strong>${inscription.prenom} ${inscription.nom}</strong></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Sexe</div>
                    <div class="detail-value">${sexeValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Date de naissance</div>
                    <div class="detail-value">${inscription.date_naissance ? new Date(inscription.date_naissance).toLocaleDateString('fr-FR') : '-'}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Email</div>
                    <div class="detail-value">${inscription.email || '-'}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Téléphone</div>
                    <div class="detail-value">${inscription.telephone || '-'}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Adresse</div>
                    <div class="detail-value">${inscription.adresse || '-'}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Ville</div>
                    <div class="detail-value">${villeValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Code Postal</div>
                    <div class="detail-value">${codePostaleValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Niveau d'études</div>
                    <div class="detail-value">${niveauValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Formation souhaitée</div>
                    <div class="detail-value"><strong>${formationValue}</strong></div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Mode de formation</div>
                    <div class="detail-value">${modeValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Message / Questions</div>
                    <div class="detail-value">${messageValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Newsletter</div>
                    <div class="detail-value">${newsletterValue}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Statut</div>
                    <div class="detail-value"><span class="badge badge-${inscription.statut || 'en_attente'}">${inscription.statut === 'confirmee' ? '✓ Confirmée' : (inscription.statut === 'annulee' ? '✗ Annulée' : '⏰ En attente')}</span></div>
                </div>
            `;
            document.getElementById('detailsContent').innerHTML = content;
            document.getElementById('detailsModal').classList.add('active');
        }
        
        function confirmInscription(id, prenom, nom, telephone, dateNaissance, adresse) {
            document.getElementById('confirmId').value = id;
            document.getElementById('confirmNom').value = nom;
            document.getElementById('confirmPrenom').value = prenom;
            document.getElementById('confirmTelephone').value = telephone || '';
            
            if (dateNaissance && dateNaissance !== '0000-00-00') {
                document.getElementById('confirmDateNaissance').value = dateNaissance;
            } else {
                document.getElementById('confirmDateNaissance').value = '';
            }
            
            if (adresse) {
                document.getElementById('confirmAdresse').value = adresse;
            } else {
                document.getElementById('confirmAdresse').value = '';
            }
            
            document.getElementById('confirmCode').value = '';
            document.getElementById('confirmCode').focus();
            
            document.getElementById('confirmModal').classList.add('active');
        }
        
        function changeStatus(id, status) {
            if(confirm('Changer le statut de cette inscription ?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="changer_statut">
                    <input type="hidden" name="id_inscription" value="${id}">
                    <input type="hidden" name="nouveau_statut" value="${status}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function deleteInscription(id) {
            if(confirm('⚠️ Êtes-vous sûr de vouloir supprimer cette inscription définitivement ?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="supprimer">
                    <input type="hidden" name="id_inscription" value="${id}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        window.onclick = function(e) {
            if (e.target.classList.contains('modal')) {
                e.target.classList.remove('active');
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            const codeInput = document.getElementById('confirmCode');
            if (codeInput) {
                codeInput.addEventListener('input', function() {
                    this.value = this.value.toUpperCase().replace(/[^A-Z0-9_\-]/g, '');
                });
            }
            
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') applyFilters();
                });
            }
        });
    </script>
</body>
</html>