<?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 = '';

// Redirection après POST pour éviter la double soumission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    
    // Traitement AJOUT STAGIAIRE
    if ($_POST['action'] == 'ajouter_stagiaire') {
        try {
            $check = $pdo->prepare("SELECT id_stagiaire FROM stagiaire WHERE id_stagiaire = ?");
            $check->execute([$_POST['id_stagiaire']]);
            if ($check->rowCount() > 0) {
                $_SESSION['message'] = '<div class="alert-error">❌ Cet ID stagiaire existe déjà !</div>';
            } else {
                $pdo->beginTransaction();
                
                $login = $_POST['id_stagiaire'];
                $mot_de_passe = 'stagiaire1';
                $email = $_POST['email'];
                
                $sql_user = "INSERT INTO utilisateur (id_user, nom, prenom, email, login, mot_de_passe, role, etat_compte) 
                            VALUES (:id_user, :nom, :prenom, :email, :login, :mot_de_passe, 'stagiaire', 'actif')";
                $stmt_user = $pdo->prepare($sql_user);
                $stmt_user->execute([
                    ':id_user' => $_POST['id_stagiaire'],
                    ':nom' => $_POST['nom'],
                    ':prenom' => $_POST['prenom'],
                    ':email' => $email,
                    ':login' => $login,
                    ':mot_de_passe' => $mot_de_passe
                ]);
                
                $sql = "INSERT INTO stagiaire (id_stagiaire, id_user, nom, prenom, domaine, telephone, email) 
                        VALUES (:id_stagiaire, :id_user, :nom, :prenom, :domaine, :telephone, :email)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':id_stagiaire' => $_POST['id_stagiaire'],
                    ':id_user' => $_POST['id_stagiaire'],
                    ':nom' => $_POST['nom'],
                    ':prenom' => $_POST['prenom'],
                    ':domaine' => $_POST['domaine'],
                    ':telephone' => $_POST['telephone'],
                    ':email' => $email
                ]);
                
                $pdo->commit();
                $_SESSION['message'] = '<div class="alert-success">✅ Stagiaire ajouté ! Login: ' . $login . ' | Mot de passe: stagiaire1</div>';
            }
        } catch(PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
    
    // Traitement MODIFICATION STAGIAIRE
    if ($_POST['action'] == 'modifier_stagiaire' && isset($_POST['id_stagiaire'])) {
        try {
            $pdo->beginTransaction();
            
            $sql = "UPDATE stagiaire SET nom=:nom, prenom=:prenom, domaine=:domaine, telephone=:telephone, email=:email 
                    WHERE id_stagiaire=:id_stagiaire";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nom' => $_POST['nom'],
                ':prenom' => $_POST['prenom'],
                ':domaine' => $_POST['domaine'],
                ':telephone' => $_POST['telephone'],
                ':email' => $_POST['email'],
                ':id_stagiaire' => $_POST['id_stagiaire']
            ]);
            
            $sql_user = "UPDATE utilisateur SET nom=:nom, prenom=:prenom, email=:email WHERE id_user=:id_user";
            $stmt_user = $pdo->prepare($sql_user);
            $stmt_user->execute([
                ':nom' => $_POST['nom'],
                ':prenom' => $_POST['prenom'],
                ':email' => $_POST['email'],
                ':id_user' => $_POST['id_stagiaire']
            ]);
            
            $pdo->commit();
            $_SESSION['message'] = '<div class="alert-success">✅ Stagiaire modifié avec succès !</div>';
        } catch(PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
    
    // Traitement SUPPRESSION STAGIAIRE
    if ($_POST['action'] == 'supprimer_stagiaire' && isset($_POST['id_stagiaire'])) {
        try {
            $pdo->beginTransaction();
            
            // Supprimer les fichiers rapports associés
            $stmt_rapports = $pdo->prepare("SELECT rapport_stage FROM stage WHERE id_stagiaire = ? AND rapport_stage IS NOT NULL AND rapport_stage != ''");
            $stmt_rapports->execute([$_POST['id_stagiaire']]);
            $rapports = $stmt_rapports->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rapports as $rapport) {
                if (!empty($rapport['rapport_stage'])) {
                    $file_path = 'uploads/' . $rapport['rapport_stage'];
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                }
            }
            
            // Supprimer les stages
            $pdo->prepare("DELETE FROM stage WHERE id_stagiaire = ?")->execute([$_POST['id_stagiaire']]);
            // Supprimer le stagiaire
            $pdo->prepare("DELETE FROM stagiaire WHERE id_stagiaire = ?")->execute([$_POST['id_stagiaire']]);
            // Supprimer l'utilisateur
            $pdo->prepare("DELETE FROM utilisateur WHERE id_user = ?")->execute([$_POST['id_stagiaire']]);
            
            $pdo->commit();
            $_SESSION['message'] = '<div class="alert-success">✅ Stagiaire supprimé avec succès !</div>';
        } catch(PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
    
    // Traitement AJOUT STAGE
    if ($_POST['action'] == 'ajouter_stage') {
        try {
            $sql = "INSERT INTO stage (id_stagiaire, titre_stage, nature_stage, duree, date_debut, date_fin, etat_stage) 
                    VALUES (:id_stagiaire, :titre_stage, :nature_stage, :duree, :date_debut, :date_fin, :etat_stage)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_stagiaire' => $_POST['id_stagiaire'],
                ':titre_stage' => $_POST['titre_stage'],
                ':nature_stage' => $_POST['nature_stage'],
                ':duree' => $_POST['duree'],
                ':date_debut' => $_POST['date_debut'],
                ':date_fin' => $_POST['date_fin'],
                ':etat_stage' => $_POST['etat_stage']
            ]);
            $_SESSION['message'] = '<div class="alert-success">✅ Stage ajouté avec succès !</div>';
        } catch(PDOException $e) {
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
    
    // Traitement MODIFICATION STAGE
    if ($_POST['action'] == 'modifier_stage') {
        try {
            $sql = "UPDATE stage SET titre_stage=:titre_stage, nature_stage=:nature_stage, duree=:duree, 
                    date_debut=:date_debut, date_fin=:date_fin, etat_stage=:etat_stage 
                    WHERE id_stage=:id_stage";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':titre_stage' => $_POST['titre_stage'],
                ':nature_stage' => $_POST['nature_stage'],
                ':duree' => $_POST['duree'],
                ':date_debut' => $_POST['date_debut'],
                ':date_fin' => $_POST['date_fin'],
                ':etat_stage' => $_POST['etat_stage'],
                ':id_stage' => $_POST['id_stage']
            ]);
            $_SESSION['message'] = '<div class="alert-success">✅ Stage modifié avec succès !</div>';
        } catch(PDOException $e) {
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
    
    // Traitement SUPPRESSION STAGE
    if ($_POST['action'] == 'supprimer_stage') {
        try {
            $stmt = $pdo->prepare("SELECT rapport_stage FROM stage WHERE id_stage = ?");
            $stmt->execute([$_POST['id_stage']]);
            $rapport = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($rapport && !empty($rapport['rapport_stage'])) {
                $file_path = 'uploads/' . $rapport['rapport_stage'];
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
            }
            
            $pdo->prepare("DELETE FROM stage WHERE id_stage = ?")->execute([$_POST['id_stage']]);
            $_SESSION['message'] = '<div class="alert-success">✅ Stage supprimé avec succès !</div>';
        } catch(PDOException $e) {
            $_SESSION['message'] = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
        header('Location: gestion_stagiaire.php');
        exit();
    }
}

// Récupérer le message de session
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

// Récupérer les stagiaires avec leurs stages
$stagiaires = [];
try {
    $sql = "SELECT s.*, u.login, u.etat_compte 
            FROM stagiaire s
            LEFT JOIN utilisateur u ON s.id_user = u.id_user
            ORDER BY s.id_stagiaire DESC";
    $stmt = $pdo->query($sql);
    $stagiaires = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($stagiaires as &$s) {
        $sql_stages = "SELECT * FROM stage WHERE id_stagiaire = ? ORDER BY date_debut DESC";
        $stmt_stages = $pdo->prepare($sql_stages);
        $stmt_stages->execute([$s['id_stagiaire']]);
        $s['stages'] = $stmt_stages->fetchAll(PDO::FETCH_ASSOC);
    }
} catch(PDOException $e) {
    $message = '<div class="alert-error">❌ Erreur chargement des données : ' . $e->getMessage() . '</div>';
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion Stagiaires | CPN</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
            background: linear-gradient(135deg, #f2f3f6 0%, #f0f4f6 100%);
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100%;
            background: linear-gradient(135deg, #e3e5ee 0%, #2f6d8c 50%, #095175 100%);
            box-shadow: 5px 0 30px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            z-index: 1000;
            overflow-y: auto;
        }

        .sidebar-header {
            padding: 40px 20px;
            text-align: center;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 20px;
        }

        .sidebar-header .logo-area {
            margin-bottom: 15px;
        }

        .sidebar-header .logo-area img {
            max-width: 150px;
            height: auto;
            border-radius: 20px;
            padding: 10px;
            transition: transform 0.3s ease;
        }

        .sidebar-header .logo-area img:hover {
            transform: scale(1.05);
        }

        .sidebar-header h2 {
            color: white;
            font-size: 24px;
            font-weight: 700;
            margin-top: 15px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
        }

        .sidebar-header p {
            color: rgba(255, 255, 255, 0.9);
            font-size: 13px;
            margin-top: 5px;
            font-weight: 500;
        }

        .sidebar-nav {
            padding: 0 15px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 14px 18px;
            margin-bottom: 8px;
            color: white;
            text-decoration: none;
            border-radius: 12px;
            transition: all 0.3s ease;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-nav a:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateX(8px);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .sidebar-nav a.active {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
            color: white;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.4);
        }

        .sidebar-nav .logout {
            margin-top: 40px;
            background: rgba(220, 53, 69, 0.8);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .sidebar-nav .logout:hover {
            background: #dc3545;
            color: white;
            transform: translateX(8px);
        }

        /* Main content */
        .main-content {
            margin-left: 280px;
            padding: 20px 30px;
        }

        /* Top header */
        .top-header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 20px 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            backdrop-filter: blur(10px);
        }

        .header-info h1 {
            font-size: 24px;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .header-info p {
            color: #64748b;
            font-size: 14px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: linear-gradient(135deg, #667eea20, #764ba220);
            padding: 10px 20px;
            border-radius: 50px;
            border: 1px solid rgba(102, 126, 234, 0.2);
        }

        .user-avatar {
            width: 45px;
            height: 45px;
            background: linear-gradient(135deg, #667eea, #e8e2ee);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        /* Card */
        .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 h2 {
            color: #1e293b;
            font-size: 20px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }

        .header-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        /* Form containers */
        .form-container {
            background: #f8fafc;
            padding: 25px;
            border-radius: 16px;
            margin-bottom: 25px;
            display: none;
            border: 2px solid rgba(102, 126, 234, 0.3);
        }

        .form-container h3 {
            color: #1e293b;
            margin-bottom: 20px;
            font-size: 18px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #1e293b;
            font-size: 14px;
        }

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

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

        .full-width {
            grid-column: span 2;
        }

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

        /* Search box */
        .search-box {
            margin-bottom: 20px;
        }

        .search-box input {
            width: 100%;
            padding: 14px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.3s;
        }

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

        /* Table */
        .table-wrapper {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        table th {
            background: linear-gradient(135deg, #334155, #1e293b);
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
        }

        table td {
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
            color: #475569;
            vertical-align: top;
        }

        table tr:hover td {
            background: #f0f8ff;
        }

        /* Badges */
        .badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
            background: #e0f2fe;
            color: #0369a1;
        }

        .rapport-badge {
            background: #d4edda;
            color: #155724;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 10px;
            margin-left: 8px;
        }

        /* Stages list */
        .stages-list {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .stage-item {
            background: #f8fafc;
            padding: 12px;
            margin-bottom: 10px;
            border-radius: 12px;
            border-left: 3px solid #667eea;
            transition: all 0.2s ease;
        }

        .stage-item:hover {
            background: #f1f5f9;
            transform: translateX(3px);
        }

        .stage-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .stage-details {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .stage-actions {
            margin-top: 8px;
        }

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

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

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

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

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            box-shadow: 0 5px 15px rgba(245, 158, 11, 0.3);
            color: white;
        }

        .btn-info {
            background: linear-gradient(135deg, #06b6d4, #0891b2);
            box-shadow: 0 5px 15px rgba(6, 182, 212, 0.3);
        }

        .btn-action {
            padding: 6px 12px;
            margin: 0 3px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
            display: inline-block;
        }

        .btn-action:hover {
            transform: scale(1.05);
        }

        .btn-stage {
            padding: 4px 10px;
            font-size: 12px;
            margin: 2px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 650px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-close {
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
            transition: color 0.2s;
        }

        .modal-close:hover {
            color: #dc3545;
        }

        .modal-content h3 {
            color: #1e293b;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }

        /* Alerts */
        .alert-success {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #065f46;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #10b981;
            font-weight: 500;
        }

        .alert-error {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 4px solid #ef4444;
            font-weight: 500;
        }

        /* Stats bar */
        .stats-bar {
            margin-top: 20px;
            padding: 15px;
            background: #f8fafc;
            border-radius: 12px;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            border: 1px solid rgba(102, 126, 234, 0.2);
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                position: fixed;
                z-index: 1000;
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .full-width {
                grid-column: span 1;
            }
            
            .top-header {
                flex-direction: column;
                text-align: center;
            }
            
            .header-actions {
                flex-direction: column;
            }
            
            .btn-ajouter {
                width: 100%;
                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>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 class="main-content">
        <div class="top-header">
            <div class="header-info">
                <h1>Gestion des Stagiaires</h1>
                <p>Ajouter, modifier, supprimer des stagiaires et gérer leurs stages</p>
            </div>
            <div class="user-info">
                <div class="user-avatar"><?php echo strtoupper(substr($current_user['nom'] ?? 'A', 0, 1)); ?></div>
                <div>
                    <strong><?php echo htmlspecialchars(($current_user['nom'] ?? 'Admin') . ' ' . ($current_user['prenom'] ?? '')); ?></strong><br>
                    <small><?php echo isset($_SESSION['user_role']) ? ucfirst(str_replace('_', ' ', $_SESSION['user_role'])) : 'Admin'; ?></small>
                </div>
            </div>
        </div>

        <?php echo $message; ?>

        <div class="card">
            <div class="header-actions">
                <h2>📋 Liste des stagiaires</h2>
                <button class="btn-ajouter" onclick="toggleFormulaire()">➕ Ajouter un stagiaire</button>
            </div>
            
            <!-- Formulaire ajout stagiaire -->
            <div id="formulaireStagiaire" class="form-container">
                <h3>➕ Nouveau stagiaire</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="ajouter_stagiaire">
                    <div class="form-grid">
                        <div class="form-group"><label>ID Stagiaire *</label><input type="text" name="id_stagiaire" placeholder="Ex: 12345" required></div>
                        <div class="form-group"><label>Nom *</label><input type="text" name="nom" required></div>
                        <div class="form-group"><label>Prénom *</label><input type="text" name="prenom" required></div>
                        <div class="form-group"><label>Email *</label><input type="email" name="email" required></div>
                        <div class="form-group"><label>Téléphone *</label><input type="tel" name="telephone" required></div>
                        <div class="form-group full-width"><label>Domaine *</label><input type="text" name="domaine" placeholder="Ex: Développement Web, Infographie..." required></div>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-ajouter btn-success">✅ Créer</button>
                        <button type="button" class="btn-ajouter btn-danger" onclick="toggleFormulaire()">❌ Annuler</button>
                    </div>
                </form>
                <div style="margin-top: 15px; padding: 12px; background: #e0f2fe; border-radius: 12px; font-size: 13px;">
                    <strong>ℹ️ Info :</strong> Login = ID stagiaire | Mot de passe par défaut = <strong>stagiaire1</strong>
                </div>
            </div>
            
            <!-- Formulaire ajout stage -->
            <div id="formulaireStage" class="form-container">
                <h3>➕ Nouveau stage</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="ajouter_stage">
                    <input type="hidden" name="id_stagiaire" id="stage_id_stagiaire" value="">
                    <div class="form-grid">
                        <div class="form-group full-width"><label>Titre du stage *</label><input type="text" name="titre_stage" id="stage_titre" required></div>
                        <div class="form-group"><label>Nature du stage *</label>
                            <select name="nature_stage" required>
                                <option value="PFE">PFE</option>
                                <option value="Stage d'été">Stage d'été</option>
                                <option value="Stage pratique">Stage pratique</option>
                                <option value="Stage ouvrier">Stage ouvrier</option>
                            </select>
                        </div>
                        <div class="form-group"><label>Durée (jours) *</label><input type="number" name="duree" id="stage_duree" required></div>
                        <div class="form-group"><label>Date début *</label><input type="date" name="date_debut" id="stage_date_debut" required></div>
                        <div class="form-group"><label>Date fin *</label><input type="date" name="date_fin" id="stage_date_fin" required></div>
                        <div class="form-group"><label>État *</label>
                            <select name="etat_stage" required>
                                <option value="reçue">Reçue</option>
                                <option value="en_cours">En cours</option>
                                <option value="validée">Validée</option>
                                <option value="non_validée">Non validée</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-ajouter btn-success">✅ Ajouter le stage</button>
                        <button type="button" class="btn-ajouter btn-danger" onclick="fermerFormulaireStage()">❌ Annuler</button>
                    </div>
                </form>
            </div>
            
            <div class="search-box">
                <input type="text" id="searchStagiaire" placeholder="🔍 Rechercher un stagiaire (ID, nom, prénom, email, domaine)..." onkeyup="filtrerStagiaires()">
            </div>
            
            <div class="table-wrapper">
                <table id="stagiairesTable">
                    <thead>
                        <tr><th>ID</th><th>Nom complet</th><th>Email</th><th>Téléphone</th><th>Domaine</th><th>Stages</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php if (empty($stagiaires)): ?>
                            <tr><td colspan="7" style="text-align: center; padding: 60px; color: #999;">
                                <div style="font-size: 60px; margin-bottom: 20px;">📭</div>
                                <h3 style="color: #666;">Aucun stagiaire enregistré</h3>
                                <p>Cliquez sur "Ajouter un stagiaire" pour commencer.</p>
                            </td></tr>
                        <?php else: ?>
                            <?php foreach ($stagiaires as $s): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($s['id_stagiaire']); ?></strong></td>
                                <td><?php echo htmlspecialchars($s['nom'] . ' ' . $s['prenom']); ?></td>
                                <td><?php echo htmlspecialchars($s['email']); ?></td>
                                <td><?php echo htmlspecialchars($s['telephone']); ?></td>
                                <td><span class="badge"><?php echo htmlspecialchars($s['domaine']); ?></span></td>
                                <td>
                                    <?php if (!empty($s['stages'])): ?>
                                        <?php foreach ($s['stages'] as $stage): ?>
                                            <div class="stage-item">
                                                <div class="stage-title">
                                                    📄 <?php echo htmlspecialchars($stage['titre_stage']); ?>
                                                    <?php if (!empty($stage['rapport_stage'])): ?>
                                                        <span class="rapport-badge">📎 PDF</span>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="stage-details">
                                                    <?php echo $stage['nature_stage']; ?> | <?php echo $stage['duree']; ?> jours<br>
                                                    Du <?php echo date('d/m/Y', strtotime($stage['date_debut'])); ?> au <?php echo date('d/m/Y', strtotime($stage['date_fin'])); ?>
                                                </div>
                                                <div class="stage-actions">
                                                    <button class="btn-action btn-warning btn-stage" onclick='ouvrirModalStage(<?php echo htmlspecialchars(json_encode($stage)); ?>)'>✏️ Modifier</button>
                                                    <form method="POST" style="display:inline;" onsubmit="return confirm('⚠️ Supprimer ce stage ?');">
                                                        <input type="hidden" name="action" value="supprimer_stage">
                                                        <input type="hidden" name="id_stage" value="<?php echo $stage['id_stage']; ?>">
                                                        <button type="submit" class="btn-action btn-danger btn-stage">🗑️ Supprimer</button>
                                                    </form>
                                                    <?php if (!empty($stage['rapport_stage'])): ?>
                                                        <?php if (file_exists('uploads/' . $stage['rapport_stage'])): ?>
                                                            <a href="uploads/<?php echo $stage['rapport_stage']; ?>" target="_blank" class="btn-action btn-info btn-stage">📄 Voir PDF</a>
                                                        <?php else: ?>
                                                            <span class="btn-action btn-danger btn-stage" style="opacity:0.5;">❌ PDF manquant</span>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <span style="color: #94a3b8;">📭 Aucun stage</span>
                                    <?php endif; ?>
                                    <button class="btn-action btn-info btn-stage" style="margin-top: 8px;" onclick="ouvrirFormulaireStage('<?php echo $s['id_stagiaire']; ?>')">➕ Ajouter un stage</button>
                                 </td>
                                <td>
                                    <div style="display: flex; gap: 8px;">
                                        <button class="btn-action btn-warning" onclick='ouvrirModal(<?php echo htmlspecialchars(json_encode($s)); ?>)'>✏️</button>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('⚠️ Supprimer ce stagiaire ? Tous ses stages seront supprimés.');">
                                            <input type="hidden" name="action" value="supprimer_stagiaire">
                                            <input type="hidden" name="id_stagiaire" value="<?php echo $s['id_stagiaire']; ?>">
                                            <button type="submit" class="btn-action btn-danger">🗑️</button>
                                        </form>
                                    </div>
                                 </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="stats-bar">
                <div>
                    <strong>📊 Statistiques :</strong> 
                    Total stagiaires : <strong><?php echo count($stagiaires); ?></strong>
                    <?php 
                    $total_rapports = 0;
                    foreach ($stagiaires as $s) {
                        foreach ($s['stages'] as $stage) {
                            if (!empty($stage['rapport_stage'])) $total_rapports++;
                        }
                    }
                    ?>
                    | 📄 Rapports PDF : <strong><?php echo $total_rapports; ?></strong>
                </div>
                <div><small>🕐 Dernière mise à jour : <?php echo date('d/m/Y H:i:s'); ?></small></div>
            </div>
        </div>
    </div>

    <!-- Modal Modification Stagiaire -->
    <div id="modalStagiaire" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="fermerModal()">&times;</span>
            <h3>✏️ Modifier le stagiaire</h3>
            <form method="POST">
                <input type="hidden" name="action" value="modifier_stagiaire">
                <input type="hidden" name="id_stagiaire" id="edit_id">
                <div class="form-grid">
                    <div class="form-group"><label>ID</label><input type="text" id="edit_id_display" disabled style="background:#f1f5f9;"></div>
                    <div class="form-group"><label>Nom *</label><input type="text" name="nom" id="edit_nom" required></div>
                    <div class="form-group"><label>Prénom *</label><input type="text" name="prenom" id="edit_prenom" required></div>
                    <div class="form-group"><label>Email *</label><input type="email" name="email" id="edit_email" required></div>
                    <div class="form-group"><label>Téléphone *</label><input type="tel" name="telephone" id="edit_tel" required></div>
                    <div class="form-group full-width"><label>Domaine *</label><input type="text" name="domaine" id="edit_domaine" required></div>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-ajouter btn-success">💾 Enregistrer</button>
                    <button type="button" class="btn-ajouter btn-danger" onclick="fermerModal()">❌ Annuler</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Modification Stage -->
    <div id="modalStage" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="fermerModalStage()">&times;</span>
            <h3>✏️ Modifier le stage</h3>
            <form method="POST">
                <input type="hidden" name="action" value="modifier_stage">
                <input type="hidden" name="id_stage" id="edit_stage_id">
                <div class="form-grid">
                    <div class="form-group full-width"><label>Titre du stage *</label><input type="text" name="titre_stage" id="edit_stage_titre" required></div>
                    <div class="form-group"><label>Nature *</label>
                        <select name="nature_stage" id="edit_stage_nature" required>
                            <option value="PFE">PFE</option>
                            <option value="Stage d'été">Stage d'été</option>
                            <option value="Stage pratique">Stage pratique</option>
                            <option value="Stage ouvrier">Stage ouvrier</option>
                        </select>
                    </div>
                    <div class="form-group"><label>Durée (jours) *</label><input type="number" name="duree" id="edit_stage_duree" required></div>
                    <div class="form-group"><label>Date début *</label><input type="date" name="date_debut" id="edit_stage_date_debut" required></div>
                    <div class="form-group"><label>Date fin *</label><input type="date" name="date_fin" id="edit_stage_date_fin" required></div>
                    <div class="form-group"><label>État *</label>
                        <select name="etat_stage" id="edit_stage_etat" required>
                            <option value="reçue">Reçue</option>
                            <option value="en_cours">En cours</option>
                            <option value="validée">Validée</option>
                            <option value="non_validée">Non validée</option>
                        </select>
                    </div>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-ajouter btn-success">💾 Enregistrer</button>
                    <button type="button" class="btn-ajouter btn-danger" onclick="fermerModalStage()">❌ Annuler</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function toggleFormulaire() {
            let form = document.getElementById('formulaireStagiaire');
            form.style.display = form.style.display === 'none' || form.style.display === '' ? 'block' : 'none';
        }
        
        function ouvrirFormulaireStage(idStagiaire) {
            document.getElementById('stage_id_stagiaire').value = idStagiaire;
            document.getElementById('stage_titre').value = '';
            document.getElementById('stage_duree').value = '';
            document.getElementById('stage_date_debut').value = '';
            document.getElementById('stage_date_fin').value = '';
            document.getElementById('formulaireStage').style.display = 'block';
            document.getElementById('formulaireStage').scrollIntoView({ behavior: 'smooth' });
        }
        
        function fermerFormulaireStage() {
            document.getElementById('formulaireStage').style.display = 'none';
        }
        
        function filtrerStagiaires() {
            let input = document.getElementById('searchStagiaire');
            let filter = input.value.toLowerCase();
            let rows = document.querySelectorAll('#stagiairesTable tbody tr');
            rows.forEach(row => {
                let text = row.textContent.toLowerCase();
                row.style.display = text.includes(filter) ? '' : 'none';
            });
        }
        
        function ouvrirModal(stagiaire) {
            document.getElementById('edit_id').value = stagiaire.id_stagiaire;
            document.getElementById('edit_id_display').value = stagiaire.id_stagiaire;
            document.getElementById('edit_nom').value = stagiaire.nom;
            document.getElementById('edit_prenom').value = stagiaire.prenom;
            document.getElementById('edit_email').value = stagiaire.email || '';
            document.getElementById('edit_tel').value = stagiaire.telephone;
            document.getElementById('edit_domaine').value = stagiaire.domaine;
            document.getElementById('modalStagiaire').style.display = 'block';
        }
        
        function fermerModal() {
            document.getElementById('modalStagiaire').style.display = 'none';
        }
        
        function ouvrirModalStage(stage) {
            document.getElementById('edit_stage_id').value = stage.id_stage;
            document.getElementById('edit_stage_titre').value = stage.titre_stage;
            document.getElementById('edit_stage_nature').value = stage.nature_stage;
            document.getElementById('edit_stage_duree').value = stage.duree;
            document.getElementById('edit_stage_date_debut').value = stage.date_debut;
            document.getElementById('edit_stage_date_fin').value = stage.date_fin;
            document.getElementById('edit_stage_etat').value = stage.etat_stage;
            document.getElementById('modalStage').style.display = 'block';
        }
        
        function fermerModalStage() {
            document.getElementById('modalStage').style.display = 'none';
        }
        
        window.onclick = function(event) {
            if (event.target == document.getElementById('modalStagiaire')) fermerModal();
            if (event.target == document.getElementById('modalStage')) fermerModalStage();
        }
    </script>
</body>
</html>