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

// Vérifier si l'utilisateur est admin ou super_admin
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['super_admin', 'admin'])) {
    header('Location: login.php');
    exit();
}

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

// --- Gestion des MATIÈRES ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ajouter une matière
    if (isset($_POST['action_matiere']) && $_POST['action_matiere'] === 'add') {
        $nom_matiere = trim($_POST['nom_matiere']);
        $code = trim($_POST['code']);
        $nbr_heure = (int)$_POST['nbr_heure_semaine'];
        
        if (!empty($nom_matiere) && !empty($code)) {
            $stmt = $pdo->prepare("INSERT INTO matieres (nom_matiere, code, nbr_heure_semaine) VALUES (?, ?, ?)");
            if ($stmt->execute([$nom_matiere, $code, $nbr_heure])) {
                $message = "Matière ajoutée avec succès.";
            } else {
                $error = "Erreur lors de l'ajout de la matière.";
            }
        } else {
            $error = "Le nom et le code de la matière sont requis.";
        }
    }
    
    // Modifier une matière
    elseif (isset($_POST['action_matiere']) && $_POST['action_matiere'] === 'edit') {
        $id_matiere = (int)$_POST['id_matiere'];
        $nom_matiere = trim($_POST['nom_matiere']);
        $code = trim($_POST['code']);
        $nbr_heure = (int)$_POST['nbr_heure_semaine'];
        
        $stmt = $pdo->prepare("UPDATE matieres SET nom_matiere = ?, code = ?, nbr_heure_semaine = ? WHERE id_matiere = ?");
        if ($stmt->execute([$nom_matiere, $code, $nbr_heure, $id_matiere])) {
            $message = "Matière modifiée avec succès.";
        } else {
            $error = "Erreur lors de la modification.";
        }
    }
    
    // Supprimer une matière
    elseif (isset($_POST['action_matiere']) && $_POST['action_matiere'] === 'delete') {
        $id_matiere = (int)$_POST['id_matiere'];
        // Vérifier si la matière est utilisée dans des formations
        $check = $pdo->prepare("SELECT COUNT(*) FROM formation_matiere WHERE id_matiere = ?");
        $check->execute([$id_matiere]);
        if ($check->fetchColumn() > 0) {
            $error = "Impossible de supprimer : cette matière est associée à des formations.";
        } else {
            $stmt = $pdo->prepare("DELETE FROM matieres WHERE id_matiere = ?");
            if ($stmt->execute([$id_matiere])) {
                $message = "Matière supprimée.";
            } else {
                $error = "Erreur lors de la suppression.";
            }
        }
    }
}

// --- Traitement des FORMATIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Ajouter une formation (avec matières associées)
    if ($_POST['action'] === 'add_formation') {
        $nom = trim($_POST['nom_formation']);
        $type = $_POST['type_formation'];
        $duree = (int)$_POST['duree'];
        $diplome = trim($_POST['diplome_obtenu']);
        $matieres = isset($_POST['matieres']) ? $_POST['matieres'] : [];
        
        // Gestion de la nouvelle matière si ajoutée
        if (!empty($_POST['new_matiere_nom']) && !empty($_POST['new_matiere_code'])) {
            $new_nom = trim($_POST['new_matiere_nom']);
            $new_code = trim($_POST['new_matiere_code']);
            $new_heure = (int)$_POST['new_matiere_heure'];
            
            $stmt = $pdo->prepare("INSERT INTO matieres (nom_matiere, code, nbr_heure_semaine) VALUES (?, ?, ?)");
            if ($stmt->execute([$new_nom, $new_code, $new_heure])) {
                $new_id = $pdo->lastInsertId();
                $matieres[] = $new_id;
                $message = "Nouvelle matière ajoutée.";
            } else {
                $error = "Erreur lors de l'ajout de la nouvelle matière.";
            }
        }
        
        if (!empty($nom) && !empty($type) && $duree > 0) {
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("INSERT INTO formation (nom_formation, type_formation, duree, diplome_obtenu) VALUES (?, ?, ?, ?)");
                $stmt->execute([$nom, $type, $duree, $diplome]);
                $id_formation = $pdo->lastInsertId();
                
                if (!empty($matieres)) {
                    $insertMatiere = $pdo->prepare("INSERT INTO formation_matiere (id_formation, id_matiere) VALUES (?, ?)");
                    foreach ($matieres as $id_matiere) {
                        if (!empty($id_matiere)) {
                            $insertMatiere->execute([$id_formation, $id_matiere]);
                        }
                    }
                }
                $pdo->commit();
                $message = "Formation ajoutée avec succès. " . count($matieres) . " matière(s) associée(s).";
                $active_tab = 'formations';
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Erreur lors de l'ajout : " . $e->getMessage();
            }
        } else {
            $error = "Veuillez remplir tous les champs obligatoires.";
        }
    }
    
    // Modifier une formation
    elseif ($_POST['action'] === 'edit_formation') {
        $id = (int)$_POST['id_formation'];
        $nom = trim($_POST['nom_formation']);
        $type = $_POST['type_formation'];
        $duree = (int)$_POST['duree'];
        $diplome = trim($_POST['diplome_obtenu']);
        
        $stmt = $pdo->prepare("UPDATE formation SET nom_formation = ?, type_formation = ?, duree = ?, diplome_obtenu = ? WHERE id_formation = ?");
        if ($stmt->execute([$nom, $type, $duree, $diplome, $id])) {
            $message = "Formation mise à jour.";
        } else {
            $error = "Erreur lors de la mise à jour.";
        }
    }
    
    // Supprimer une formation
    elseif ($_POST['action'] === 'delete_formation') {
        $id = (int)$_POST['id_formation'];
        $check = $pdo->prepare("SELECT COUNT(*) FROM groupe WHERE id_formation = ?");
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            $error = "Impossible de supprimer : cette formation a des groupes associés.";
        } else {
            try {
                $pdo->beginTransaction();
                $delMat = $pdo->prepare("DELETE FROM formation_matiere WHERE id_formation = ?");
                $delMat->execute([$id]);
                $delForm = $pdo->prepare("DELETE FROM formation WHERE id_formation = ?");
                $delForm->execute([$id]);
                $pdo->commit();
                $message = "Formation supprimée.";
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Erreur lors de la suppression.";
            }
        }
    }
    
    // Ajouter une matière à une formation
    elseif ($_POST['action'] === 'add_matiere') {
        $id_formation = (int)$_POST['id_formation'];
        $id_matiere = (int)$_POST['id_matiere'];
        
        $check = $pdo->prepare("SELECT COUNT(*) FROM formation_matiere WHERE id_formation = ? AND id_matiere = ?");
        $check->execute([$id_formation, $id_matiere]);
        if ($check->fetchColumn() == 0) {
            $stmt = $pdo->prepare("INSERT INTO formation_matiere (id_formation, id_matiere) VALUES (?, ?)");
            if ($stmt->execute([$id_formation, $id_matiere])) {
                $message = "Matière ajoutée à la formation.";
            } else {
                $error = "Erreur lors de l'ajout.";
            }
        } else {
            $error = "Cette matière est déjà associée.";
        }
    }
    
    // Ajouter une nouvelle matière rapidement depuis la page de gestion formation
    elseif ($_POST['action'] === 'add_matiere_quick') {
        $id_formation = (int)$_POST['id_formation'];
        $new_nom = trim($_POST['new_matiere_nom']);
        $new_code = trim($_POST['new_matiere_code']);
        $new_heure = (int)$_POST['new_matiere_heure'];
        
        if (!empty($new_nom) && !empty($new_code)) {
            $stmt = $pdo->prepare("INSERT INTO matieres (nom_matiere, code, nbr_heure_semaine) VALUES (?, ?, ?)");
            if ($stmt->execute([$new_nom, $new_code, $new_heure])) {
                $new_id = $pdo->lastInsertId();
                
                // Ajouter à la formation
                $stmt2 = $pdo->prepare("INSERT INTO formation_matiere (id_formation, id_matiere) VALUES (?, ?)");
                if ($stmt2->execute([$id_formation, $new_id])) {
                    $message = "Nouvelle matière créée et ajoutée à la formation.";
                } else {
                    $error = "Matière créée mais erreur lors de l'association.";
                }
            } else {
                $error = "Erreur lors de la création de la matière.";
            }
        } else {
            $error = "Veuillez remplir le nom et le code de la matière.";
        }
    }
    
    // Retirer une matière d'une formation
    elseif ($_POST['action'] === 'remove_matiere') {
        $id_formation = (int)$_POST['id_formation'];
        $id_matiere = (int)$_POST['id_matiere'];
        $stmt = $pdo->prepare("DELETE FROM formation_matiere WHERE id_formation = ? AND id_matiere = ?");
        if ($stmt->execute([$id_formation, $id_matiere])) {
            $message = "Matière retirée de la formation.";
        } else {
            $error = "Erreur lors du retrait.";
        }
    }
}

// Récupérer toutes les formations
$formations = [];
$stmt = $pdo->query("
    SELECT f.*, COUNT(fm.id_matiere) as nb_matieres 
    FROM formation f 
    LEFT JOIN formation_matiere fm ON f.id_formation = fm.id_formation 
    GROUP BY f.id_formation 
    ORDER BY f.nom_formation
");
$formations = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Récupérer toutes les matières
$matieres = [];
$stmt = $pdo->query("SELECT * FROM matieres ORDER BY nom_matiere");
$matieres = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Pour l'affichage des matières d'une formation
$selected_formation = null;
$formation_matieres = [];
if (isset($_GET['manage']) && is_numeric($_GET['manage'])) {
    $id = (int)$_GET['manage'];
    $stmt = $pdo->prepare("SELECT * FROM formation WHERE id_formation = ?");
    $stmt->execute([$id]);
    $selected_formation = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($selected_formation) {
        $stmt2 = $pdo->prepare("
            SELECT m.* FROM matieres m
            JOIN formation_matiere fm ON m.id_matiere = fm.id_matiere
            WHERE fm.id_formation = ?
            ORDER BY m.nom_matiere
        ");
        $stmt2->execute([$id]);
        $formation_matieres = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        $active_tab = 'formations';
    }
}

// Matière à modifier
$edit_matiere = null;
if (isset($_GET['edit_matiere']) && is_numeric($_GET['edit_matiere'])) {
    $stmt = $pdo->prepare("SELECT * FROM matieres WHERE id_matiere = ?");
    $stmt->execute([$_GET['edit_matiere']]);
    $edit_matiere = $stmt->fetch(PDO::FETCH_ASSOC);
    $active_tab = 'matieres';
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des formations | CPN</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', 'Inter', system-ui, sans-serif; background: linear-gradient(135deg, #f2f3f6 0%, #f0f4f6 100%); min-height: 100vh; }
        .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; transition: transform 0.3s ease; }
        .sidebar-header h2 { color: white; font-size: 24px; font-weight: 700; margin-top: 15px; }
        .sidebar-header p { color: rgba(255,255,255,0.9); font-size: 13px; }
        .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); border: 1px solid rgba(255,255,255,0.4); }
        .sidebar-nav .logout { margin-top: 40px; background: rgba(220,53,69,0.8); }
        .sidebar-nav .logout:hover { background: #dc3545; transform: translateX(8px); }
        .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; }
        .header-info h1 { font-size: 24px; color: #1e293b; }
        .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, #667eea, #e8e2ee); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 18px; }
        .alert { padding: 15px 20px; border-radius: 12px; margin-bottom: 20px; }
        .alert-success { background: #d1fae5; color: #065f46; border-left: 5px solid #10b981; }
        .alert-error { background: #fee2e2; color: #991b1b; border-left: 5px solid #ef4444; }
        
        /* Tabs */
        .tabs { display: flex; gap: 10px; margin-bottom: 25px; border-bottom: 2px solid #e2e8f0; }
        .tab-btn { padding: 12px 25px; background: none; border: none; font-size: 16px; font-weight: 600; cursor: pointer; color: #64748b; transition: 0.3s; border-radius: 12px 12px 0 0; }
        .tab-btn.active { color: #667eea; background: rgba(102,126,234,0.1); border-bottom: 3px solid #667eea; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        .card { 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); }
        .card h3 { color: #1e293b; font-size: 20px; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        .btn { display: inline-block; padding: 8px 16px; border-radius: 10px; font-weight: 500; text-decoration: none; cursor: pointer; border: none; font-size: 14px; transition: 0.2s; }
        .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.4); }
        .btn-danger { background: #ef4444; color: white; }
        .btn-warning { background: #f59e0b; color: white; }
        .btn-secondary { background: #64748b; color: white; }
        .btn-success { background: #10b981; color: white; }
        .btn-sm { padding: 5px 12px; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #e2e8f0; }
        th { background: #f8fafc; font-weight: 600; color: #1e293b; }
        tr:hover { background: #f1f5f9; }
        .actions { display: flex; gap: 8px; flex-wrap: wrap; }
        .badge { background: #e2e8f0; padding: 4px 10px; border-radius: 20px; font-size: 12px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: 500; color: #1e293b; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 10px; font-family: inherit; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 2000; }
        .modal-content { background: white; border-radius: 20px; padding: 30px; width: 90%; max-width: 850px; max-height: 85vh; overflow-y: auto; }
        .close { float: right; font-size: 28px; cursor: pointer; font-weight: bold; }
        .close:hover { color: #667eea; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .new-matiere-section { background: #f8fafc; padding: 15px; border-radius: 12px; margin-top: 15px; border: 1px dashed #cbd5e1; }
        .new-matiere-section h4 { margin-bottom: 10px; color: #667eea; }
        hr { margin: 15px 0; border: none; border-top: 1px solid #e2e8f0; }
        
        /* Style pour les cases à cocher des matières */
        .matieres-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 10px;
            max-height: 350px;
            overflow-y: auto;
            border: 1px solid #cbd5e1;
            border-radius: 10px;
            padding: 15px;
            background: #f8fafc;
        }
        .matiere-checkbox {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            padding: 8px;
            border-radius: 8px;
            transition: background 0.2s;
        }
        .matiere-checkbox:hover {
            background: #e2e8f0;
        }
        .matiere-checkbox input {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        .matiere-info {
            flex: 1;
        }
        .matiere-code {
            font-weight: bold;
            color: #1e293b;
        }
        .matiere-nom {
            font-size: 13px;
            color: #475569;
        }
        .matiere-heure {
            font-size: 11px;
            color: #64748b;
        }
        .select-all-btn {
            margin-bottom: 10px;
            padding: 5px 10px;
            font-size: 12px;
        }
        @media (max-width: 768px) { .sidebar { transform: translateX(-100%); } .main-content { margin-left: 0; padding: 15px; } .form-row { grid-template-columns: 1fr; } .matieres-grid { grid-template-columns: 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>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>
</div>

<div class="main-content">
    <div class="top-header">
        <div class="header-info">
            <h1>Gestion des formations et matières</h1>
            <p>Créez des formations, gérez les matières et associez-les</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 ucfirst(str_replace('_', ' ', $_SESSION['user_role'])); ?></small>
            </div>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <!-- Tabs navigation -->
    <div class="tabs">
        <button class="tab-btn <?php echo $active_tab == 'formations' ? 'active' : ''; ?>" onclick="showTab('formations')">📋 Formations</button>
        <button class="tab-btn <?php echo $active_tab == 'matieres' ? 'active' : ''; ?>" onclick="showTab('matieres')">📚 Matières</button>
    </div>

    <!-- Tab Formations -->
    <div id="tab-formations" class="tab-content <?php echo $active_tab == 'formations' ? 'active' : ''; ?>">
        <!-- Liste des formations -->
        <div class="card">
            <h3>
                📋 Toutes les formations
                <button class="btn btn-primary" onclick="openModal('addFormationModal')">+ Nouvelle formation</button>
            </h3>
            <div style="overflow-x: auto;">
                <table>
                    <thead>
                        <tr><th>ID</th><th>Nom</th><th>Type</th><th>Durée (mois)</th><th>Diplôme</th><th>Matières</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php if (count($formations) > 0): ?>
                            <?php foreach ($formations as $f): ?>
                            <tr>
                                <td><?= $f['id_formation'] ?></td>
                                <td><?= htmlspecialchars($f['nom_formation']) ?></td>
                                <td><?= htmlspecialchars($f['type_formation']) ?></td>
                                <td><?= $f['duree'] ?></td>
                                <td><?= htmlspecialchars($f['diplome_obtenu']) ?></td>
                                <td><span class="badge"><?= $f['nb_matieres'] ?> matière(s)</span></td>
                                <td class="actions">
                                    <button class="btn btn-warning btn-sm" onclick="editFormation(<?= htmlspecialchars(json_encode($f)) ?>)">✏️ Modifier</button>
                                    <button class="btn btn-danger btn-sm" onclick="confirmDelete(<?= $f['id_formation'] ?>, '<?= addslashes(htmlspecialchars($f['nom_formation'])) ?>')">🗑️ Supprimer</button>
                                    <a href="?manage=<?= $f['id_formation'] ?>" class="btn btn-secondary btn-sm">📚 Gérer matières</a>
                                 </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" style="text-align: center;">Aucune formation trouvée.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Gestion des matières pour une formation spécifique -->
        <?php if ($selected_formation): ?>
        <div class="card">
            <h3>
                🧩 Matières de la formation : <?= htmlspecialchars($selected_formation['nom_formation']) ?>
                <a href="gestion_formation.php?tab=formations" class="btn btn-secondary btn-sm">↩️ Retour à la liste</a>
            </h3>
            
            <div style="display: flex; gap: 30px; flex-wrap: wrap;">
                <div style="flex: 1;">
                    <h4>📖 Matières incluses</h4>
                    <?php if (count($formation_matieres) > 0): ?>
                        <table>
                            <thead>
                                <tr><th>Code</th><th>Nom matière</th><th>Heures/sem</th><th>Action</th></tr>
                            </thead>
                            <tbody>
                            <?php foreach ($formation_matieres as $m): ?>
                            <tr>
                                <td><?= htmlspecialchars($m['code']) ?></td>
                                <td><?= htmlspecialchars($m['nom_matiere']) ?></td>
                                <td><?= $m['nbr_heure_semaine'] ?></td>
                                <td>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="action" value="remove_matiere">
                                        <input type="hidden" name="id_formation" value="<?= $selected_formation['id_formation'] ?>">
                                        <input type="hidden" name="id_matiere" value="<?= $m['id_matiere'] ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Retirer cette matière ?')">Retirer</button>
                                    </form>
                                 </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <p>Aucune matière associée pour le moment.</p>
                    <?php endif; ?>
                </div>
                
                <div style="flex: 1;">
                    <h4>➕ Ajouter une matière existante</h4>
                    <form method="post">
                        <input type="hidden" name="action" value="add_matiere">
                        <input type="hidden" name="id_formation" value="<?= $selected_formation['id_formation'] ?>">
                        <div class="form-group">
                            <select name="id_matiere" required style="width: 100%; padding: 10px;">
                                <option value="">-- Sélectionner une matière --</option>
                                <?php foreach ($matieres as $mat): ?>
                                    <?php 
                                        $already = false;
                                        foreach ($formation_matieres as $fm) {
                                            if ($fm['id_matiere'] == $mat['id_matiere']) { $already = true; break; }
                                        }
                                        if (!$already):
                                    ?>
                                    <option value="<?= $mat['id_matiere'] ?>"><?= htmlspecialchars($mat['nom_matiere']) ?> (<?= htmlspecialchars($mat['code']) ?>)</option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary">Ajouter</button>
                    </form>
                    
                    <hr>
                    
                    <div class="new-matiere-section">
                        <h4>✨ Créer une nouvelle matière</h4>
                        <form method="post" action="gestion_formation.php?manage=<?= $selected_formation['id_formation'] ?>">
                            <input type="hidden" name="action" value="add_matiere_quick">
                            <input type="hidden" name="id_formation" value="<?= $selected_formation['id_formation'] ?>">
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Nom de la matière *</label>
                                    <input type="text" name="new_matiere_nom" required>
                                </div>
                                <div class="form-group">
                                    <label>Code *</label>
                                    <input type="text" name="new_matiere_code" required placeholder="Ex: INF-101">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Nombre d'heures/semaine</label>
                                <input type="number" name="new_matiere_heure" value="2">
                            </div>
                            <button type="submit" class="btn btn-success">Créer et ajouter à la formation</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Tab Matières -->
    <div id="tab-matieres" class="tab-content <?php echo $active_tab == 'matieres' ? 'active' : ''; ?>">
        <div class="card">
            <h3>
                📚 Toutes les matières
                <button class="btn btn-primary" onclick="openModal('addMatiereModal')">+ Nouvelle matière</button>
            </h3>
            <div style="overflow-x: auto;">
                <table>
                    <thead>
                        <tr><th>ID</th><th>Code</th><th>Nom de la matière</th><th>Heures/semaine</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php if (count($matieres) > 0): ?>
                            <?php foreach ($matieres as $m): ?>
                            <tr>
                                <td><?= $m['id_matiere'] ?></td>
                                <td><?= htmlspecialchars($m['code']) ?></td>
                                <td><?= htmlspecialchars($m['nom_matiere']) ?></td>
                                <td><?= $m['nbr_heure_semaine'] ?></td>
                                <td class="actions">
                                    <a href="?tab=matieres&edit_matiere=<?= $m['id_matiere'] ?>" class="btn btn-warning btn-sm">✏️ Modifier</a>
                                    <form method="post" style="display:inline;" onsubmit="return confirm('Supprimer cette matière ? Elle ne doit être associée à aucune formation.');">
                                        <input type="hidden" name="action_matiere" value="delete">
                                        <input type="hidden" name="id_matiere" value="<?= $m['id_matiere'] ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">🗑️ Supprimer</button>
                                    </form>
                                  </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" style="text-align: center;">Aucune matière trouvée.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Formulaire de modification de matière -->
        <?php if ($edit_matiere): ?>
        <div class="card">
            <h3>✏️ Modifier la matière</h3>
            <form method="post">
                <input type="hidden" name="action_matiere" value="edit">
                <input type="hidden" name="id_matiere" value="<?= $edit_matiere['id_matiere'] ?>">
                <div class="form-row">
                    <div class="form-group">
                        <label>Code *</label>
                        <input type="text" name="code" value="<?= htmlspecialchars($edit_matiere['code']) ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Nom de la matière *</label>
                        <input type="text" name="nom_matiere" value="<?= htmlspecialchars($edit_matiere['nom_matiere']) ?>" required>
                    </div>
                </div>
                <div class="form-group">
                    <label>Nombre d'heures par semaine</label>
                    <input type="number" name="nbr_heure_semaine" value="<?= $edit_matiere['nbr_heure_semaine'] ?>">
                </div>
                <button type="submit" class="btn btn-primary">Enregistrer les modifications</button>
                <a href="?tab=matieres" class="btn btn-secondary">Annuler</a>
            </form>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal Ajout Formation AVEC SÉLECTION MULTIPLE PAR CASES À COCHER -->
<div id="addFormationModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('addFormationModal')">&times;</span>
        <h3>➕ Ajouter une formation</h3>
        <form method="post" id="addFormationForm">
            <input type="hidden" name="action" value="add_formation">
            
            <div class="form-row">
                <div class="form-group">
                    <label>Nom de la formation *</label>
                    <input type="text" name="nom_formation" required>
                </div>
                <div class="form-group">
                    <label>Durée (en mois) *</label>
                    <input type="number" name="duree" min="1" required>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>Type de formation *</label>
                    <select name="type_formation" required>
                        <option value="homologué">Homologué</option>
                        <option value="privé">Privé</option>
                        <option value="certifiant">Certifiant</option>
                        <option value="accéléré">Accéléré</option>
                        <option value="à la carte">À la carte</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Diplôme obtenu</label>
                    <input type="text" name="diplome_obtenu" placeholder="Ex: Certificat de Fin de Formation">
                </div>
            </div>
            
            <div class="form-group">
                <label>
                    📖 Sélectionner les matières à associer 
                    <span style="background: #667eea; color: white; padding: 2px 10px; border-radius: 20px; font-size: 12px; margin-left: 10px;" id="selectedCount">0</span> sélectionnée(s)
                </label>
                <div style="margin-bottom: 10px;">
                    <button type="button" class="btn btn-secondary btn-sm select-all-btn" onclick="selectAllMatieres(true)">✅ Tout sélectionner</button>
                    <button type="button" class="btn btn-secondary btn-sm select-all-btn" onclick="selectAllMatieres(false)">❌ Tout désélectionner</button>
                </div>
                <div class="matieres-grid" id="matieresGrid">
                    <?php foreach ($matieres as $mat): ?>
                        <label class="matiere-checkbox">
                            <input type="checkbox" name="matieres[]" value="<?= $mat['id_matiere'] ?>" onchange="updateSelectedCount()">
                            <div class="matiere-info">
                                <div class="matiere-code"><?= htmlspecialchars($mat['code']) ?></div>
                                <div class="matiere-nom"><?= htmlspecialchars($mat['nom_matiere']) ?></div>
                                <div class="matiere-heure"><?= $mat['nbr_heure_semaine'] ?> heure(s)/semaine</div>
                            </div>
                        </label>
                    <?php endforeach; ?>
                </div>
                <small style="color: #64748b; display: block; margin-top: 10px;">💡 Cochez plusieurs matières (5, 10 ou plus) pour les associer à cette formation.</small>
            </div>
            
            <div class="new-matiere-section">
                <h4>✨ Ou créer une nouvelle matière</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>Nom de la matière</label>
                        <input type="text" name="new_matiere_nom" placeholder="Ex: Programmation Web">
                    </div>
                    <div class="form-group">
                        <label>Code</label>
                        <input type="text" name="new_matiere_code" placeholder="Ex: WEB-101">
                    </div>
                </div>
                <div class="form-group">
                    <label>Nombre d'heures/semaine</label>
                    <input type="number" name="new_matiere_heure" value="2">
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 15px;">Créer la formation</button>
        </form>
    </div>
</div>

<!-- Modal Ajout Matière -->
<div id="addMatiereModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('addMatiereModal')">&times;</span>
        <h3>➕ Ajouter une matière</h3>
        <form method="post">
            <input type="hidden" name="action_matiere" value="add">
            <div class="form-row">
                <div class="form-group">
                    <label>Code *</label>
                    <input type="text" name="code" required placeholder="Ex: INF-101">
                </div>
                <div class="form-group">
                    <label>Nom de la matière *</label>
                    <input type="text" name="nom_matiere" required>
                </div>
            </div>
            <div class="form-group">
                <label>Nombre d'heures par semaine</label>
                <input type="number" name="nbr_heure_semaine" value="2">
            </div>
            <button type="submit" class="btn btn-primary">Ajouter la matière</button>
        </form>
    </div>
</div>

<!-- Modal Modification Formation -->
<div id="editFormationModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('editFormationModal')">&times;</span>
        <h3>✏️ Modifier la formation</h3>
        <form method="post" id="editForm">
            <input type="hidden" name="action" value="edit_formation">
            <input type="hidden" name="id_formation" id="edit_id">
            <div class="form-group">
                <label>Nom *</label>
                <input type="text" name="nom_formation" id="edit_nom" required>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Type *</label>
                    <select name="type_formation" id="edit_type" required>
                        <option value="homologué">Homologué</option>
                        <option value="privé">Privé</option>
                        <option value="certifiant">Certifiant</option>
                        <option value="accéléré">Accéléré</option>
                        <option value="à la carte">À la carte</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Durée (mois) *</label>
                    <input type="number" name="duree" id="edit_duree" required>
                </div>
            </div>
            <div class="form-group">
                <label>Diplôme obtenu</label>
                <input type="text" name="diplome_obtenu" id="edit_diplome">
            </div>
            <button type="submit" class="btn btn-primary">Enregistrer</button>
            <button type="button" class="btn btn-secondary" onclick="closeModal('editFormationModal')">Annuler</button>
        </form>
    </div>
</div>

<!-- Formulaire de suppression -->
<form id="deleteForm" method="post" style="display:none;">
    <input type="hidden" name="action" value="delete_formation">
    <input type="hidden" name="id_formation" id="delete_id">
</form>

<script>
    function showTab(tabName) {
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.getElementById('tab-' + tabName).classList.add('active');
        event.target.classList.add('active');
        
        const url = new URL(window.location.href);
        url.searchParams.set('tab', tabName);
        window.history.pushState({}, '', url);
    }
    
    function openModal(id) {
        document.getElementById(id).style.display = 'flex';
        if (id === 'addFormationModal') {
            updateSelectedCount();
        }
    }
    
    function closeModal(id) {
        document.getElementById(id).style.display = 'none';
    }
    
    function updateSelectedCount() {
        const checkboxes = document.querySelectorAll('#addFormationForm input[type="checkbox"]');
        const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const counter = document.getElementById('selectedCount');
        if (counter) {
            counter.textContent = selectedCount;
            if (selectedCount > 0) {
                counter.style.background = '#10b981';
            } else {
                counter.style.background = '#667eea';
            }
        }
    }
    
    function selectAllMatieres(selectAll) {
        const checkboxes = document.querySelectorAll('#addFormationForm input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = selectAll;
        });
        updateSelectedCount();
    }
    
    function editFormation(formation) {
        document.getElementById('edit_id').value = formation.id_formation;
        document.getElementById('edit_nom').value = formation.nom_formation;
        document.getElementById('edit_type').value = formation.type_formation;
        document.getElementById('edit_duree').value = formation.duree;
        document.getElementById('edit_diplome').value = formation.diplome_obtenu || '';
        openModal('editFormationModal');
    }
    
    function confirmDelete(id, name) {
        if (confirm(`Supprimer définitivement la formation "${name}" ?\nCette action est irréversible.`)) {
            document.getElementById('delete_id').value = id;
            document.getElementById('deleteForm').submit();
        }
    }
    
    window.onclick = function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    }
    
    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab');
        if (tab === 'matieres') {
            const matieresBtn = document.querySelectorAll('.tab-btn')[1];
            if (matieresBtn) matieresBtn.click();
        }
    });
</script>
</body>
</html>