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

// Vérifier que l'utilisateur est un stagiaire
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'stagiaire') {
    header('Location: login.php');
    exit();
}

$current_user = getCurrentUserInfo($pdo);
$message = '';

// Traitement de l'upload de fichier PDF
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'upload_rapport') {
    
    $id_stage = $_POST['id_stage'];
    $id_stagiaire = $_POST['id_stagiaire'];
    
    if (isset($_FILES['rapport_pdf']) && $_FILES['rapport_pdf']['error'] == 0) {
        $file = $_FILES['rapport_pdf'];
        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size = $file['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        if ($file_ext != 'pdf') {
            $message = '<div class="alert-error">❌ Seuls les fichiers PDF sont acceptés !</div>';
        } elseif ($file_size > 5 * 1024 * 1024) {
            $message = '<div class="alert-error">❌ Le fichier est trop volumineux (max 5 Mo) !</div>';
        } else {
            if (!file_exists('uploads')) {
                mkdir('uploads', 0777, true);
            }
            
            $new_file_name = 'rapport_' . $id_stagiaire . '_' . $id_stage . '_' . time() . '.pdf';
            $upload_path = 'uploads/' . $new_file_name;
            
            if (move_uploaded_file($file_tmp, $upload_path)) {
                try {
                    $sql = "UPDATE stage SET rapport_stage = :rapport WHERE id_stage = :id_stage AND id_stagiaire = :id_stagiaire";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        ':rapport' => $new_file_name,
                        ':id_stage' => $id_stage,
                        ':id_stagiaire' => $id_stagiaire
                    ]);
                    
                    $message = '<div class="alert-success">✅ Rapport PDF importé avec succès !</div>';
                    echo '<meta http-equiv="refresh" content="2">';
                } catch(PDOException $e) {
                    $message = '<div class="alert-error">❌ Erreur base de données : ' . $e->getMessage() . '</div>';
                }
            } else {
                $message = '<div class="alert-error">❌ Erreur lors de l\'upload du fichier.</div>';
            }
        }
    } else {
        $message = '<div class="alert-error">❌ Veuillez sélectionner un fichier PDF.</div>';
    }
}

// Récupérer les informations du stagiaire connecté
$stagiaire = [];
$stages = [];

try {
    // Récupérer le stagiaire via id_user
    $sql = "SELECT s.*, u.email, u.login, u.etat_compte, u.nom as user_nom, u.prenom as user_prenom
            FROM stagiaire s
            LEFT JOIN utilisateur u ON s.id_user = u.id_user
            WHERE s.id_user = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_SESSION['id_user']]);
    $stagiaire = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$stagiaire) {
        // Essayer avec id_stagiaire
        $sql = "SELECT s.*, u.email, u.login, u.etat_compte, u.nom as user_nom, u.prenom as user_prenom
                FROM stagiaire s
                LEFT JOIN utilisateur u ON s.id_user = u.id_user
                WHERE s.id_stagiaire = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$_SESSION['id_user']]);
        $stagiaire = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    if ($stagiaire && isset($stagiaire['id_stagiaire'])) {
        // Récupérer tous les stages du stagiaire
        $sql_stages = "SELECT * FROM stage 
                       WHERE id_stagiaire = ? 
                       ORDER BY date_debut DESC";
        $stmt_stages = $pdo->prepare($sql_stages);
        $stmt_stages->execute([$stagiaire['id_stagiaire']]);
        $stages = $stmt_stages->fetchAll(PDO::FETCH_ASSOC);
    }
    
} catch(PDOException $e) {
    $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
}

if (!$stagiaire) {
    $message = '<div class="alert-error">❌ Impossible de charger vos informations. Veuillez contacter l\'administration.</div>';
}
?>

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

        /* Cards */
        .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;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 25px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            padding: 25px;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(10px);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, #667eea20, #764ba220);
            border-radius: 0 0 0 100%;
        }

        .stat-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .stat-card .stat-icon {
            font-size: 40px;
            margin-bottom: 15px;
        }

        .stat-card h3 {
            color: #64748b;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-number {
            font-size: 36px;
            font-weight: 800;
            background: linear-gradient(135deg, #667eea, #e8e2ed);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }

        /* Profile Grid */
        .profile-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .profile-item {
            padding: 18px;
            background: #f8fafc;
            border-radius: 16px;
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
        }

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

        .profile-label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .profile-value {
            font-size: 18px;
            font-weight: 600;
            color: #1e293b;
        }

        /* Timeline Stages */
        .timeline {
            position: relative;
            padding: 20px 0;
        }

        .timeline::before {
            content: '';
            position: absolute;
            left: 20px;
            top: 0;
            bottom: 0;
            width: 3px;
            background: linear-gradient(135deg, #667eea, #764ba2);
        }

        .timeline-item {
            position: relative;
            padding-left: 60px;
            margin-bottom: 25px;
        }

        .timeline-dot {
            position: absolute;
            left: 12px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: 4px solid white;
            box-shadow: 0 0 0 2px #667eea;
        }

        .timeline-content {
            background: #f8fafc;
            padding: 20px;
            border-radius: 16px;
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
        }

        .timeline-content:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .timeline-date {
            color: #667eea;
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .timeline-title {
            font-size: 18px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 10px;
        }

        .timeline-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .detail-item {
            font-size: 14px;
        }

        .detail-label {
            color: #64748b;
            margin-right: 8px;
        }

        .detail-value {
            font-weight: 600;
            color: #1e293b;
        }

        /* Badges */
        .badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }

        .badge-success { background: #d4edda; color: #155724; }
        .badge-warning { background: #fff3cd; color: #856404; }
        .badge-danger { background: #f8d7da; color: #721c24; }
        .badge-info { background: #d1ecf1; color: #0c5460; }

        /* Buttons */
        .btn-upload {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin: 5px;
        }

        .btn-upload:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-telecharger {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin: 5px;
        }

        .btn-telecharger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }

        .btn-exporter {
            background: linear-gradient(135deg, #17a2b8, #138496);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin: 5px;
            text-decoration: none;
        }

        .btn-exporter:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(23, 162, 184, 0.3);
        }

        .btn-upload-large {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

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

        /* Upload Section */
        .upload-section {
            background: linear-gradient(135deg, #f8fafc, #eef2ff);
            border-radius: 20px;
            padding: 30px;
            text-align: center;
            border: 2px dashed #667eea;
            margin-bottom: 30px;
        }

        .upload-section h3 {
            color: #1e293b;
            margin-bottom: 10px;
        }

        .upload-section p {
            color: #64748b;
            margin-bottom: 20px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1100;
            animation: fadeIn 0.3s ease;
        }

        .modal-content {
            background: white;
            width: 90%;
            max-width: 500px;
            margin: 80px auto;
            padding: 30px;
            border-radius: 20px;
            animation: slideIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

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

        .modal-close {
            float: right;
            font-size: 28px;
            cursor: pointer;
            color: #94a3b8;
            transition: color 0.3s;
        }

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

        .upload-area {
            border: 2px dashed #cbd5e1;
            padding: 30px;
            text-align: center;
            border-radius: 16px;
            margin: 20px 0;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .upload-area:hover {
            border-color: #667eea;
            background: #f8fafc;
        }

        .file-info {
            font-size: 12px;
            color: #64748b;
            margin-top: 10px;
        }

        #fileSelected {
            background: #d4edda;
            padding: 12px;
            border-radius: 10px;
            margin: 15px 0;
            color: #155724;
        }

        /* Alertes */
        .alert-success {
            background: #d4edda;
            color: #155724;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 5px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            border-left: 5px solid #dc3545;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: #f8fafc;
            border-radius: 16px;
        }

        .empty-icon {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-state h3 {
            color: #1e293b;
            margin-bottom: 10px;
        }

        .empty-state p {
            color: #64748b;
        }

        /* Button Group */
        .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .main-content {
                margin-left: 0;
                padding: 15px;
            }
            
            .top-header {
                flex-direction: column;
                text-align: center;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .profile-grid {
                grid-template-columns: 1fr;
            }
            
            .timeline::before {
                left: 15px;
            }
            
            .timeline-item {
                padding-left: 45px;
            }
            
            .timeline-dot {
                left: 7px;
            }
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #eae4f1);
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="logo-area">
                <img src="logo.png" alt="Logo CPN" onerror="this.src='https://via.placeholder.com/80x80?text=CPN'">
            </div>
            <h2>CPN Formation</h2>
            <p>Espace Stagiaire</p>
        </div>
        
        <div class="sidebar-nav">
            <a href="stagiaire.php" class="active">
                <span>🏠</span>
                <span>Mon tableau de bord</span>
            </a>
            <a href="logout.php" class="logout">
                <span>🚪</span>
                <span>Déconnexion</span>
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Top Header -->
        <div class="top-header">
            <div class="header-info">
                <h1>Mon espace stagiaire</h1>
                <p>Gérez vos stages, importez et exportez vos rapports</p>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr(($current_user['prenom'] ?? ($stagiaire['prenom'] ?? 'S')), 0, 1)); ?>
                </div>
                <div>
                    <strong><?php echo htmlspecialchars(($current_user['prenom'] ?? ($stagiaire['prenom'] ?? '')) . ' ' . ($current_user['nom'] ?? ($stagiaire['nom'] ?? 'Stagiaire'))); ?></strong>
                    <br>
                    <small style="color: #64748b;">Stagiaire</small>
                </div>
            </div>
        </div>

        <?php echo $message; ?>

        <?php if ($stagiaire && isset($stagiaire['id_stagiaire'])): ?>
            <!-- Cartes statistiques -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">📋</div>
                    <h3>Total Stages</h3>
                    <div class="stat-number"><?php echo count($stages); ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">⏳</div>
                    <h3>Stages en cours</h3>
                    <div class="stat-number">
                        <?php 
                        $en_cours = 0;
                        foreach ($stages as $s) {
                            if ($s['etat_stage'] == 'en_cours') $en_cours++;
                        }
                        echo $en_cours;
                        ?>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">✅</div>
                    <h3>Stages validés</h3>
                    <div class="stat-number">
                        <?php 
                        $valides = 0;
                        foreach ($stages as $s) {
                            if ($s['etat_stage'] == 'validée') $valides++;
                        }
                        echo $valides;
                        ?>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📄</div>
                    <h3>Rapports importés</h3>
                    <div class="stat-number">
                        <?php 
                        $rapports = 0;
                        foreach ($stages as $s) {
                            if (!empty($s['rapport_stage'])) $rapports++;
                        }
                        echo $rapports;
                        ?>
                    </div>
                </div>
            </div>

            <!-- Informations personnelles -->
            <div class="card">
                <h2>👤 Mes informations personnelles</h2>
                <div class="profile-grid">
                    <div class="profile-item">
                        <div class="profile-label">ID Stagiaire</div>
                        <div class="profile-value">#<?php echo $stagiaire['id_stagiaire']; ?></div>
                    </div>
                    <div class="profile-item">
                        <div class="profile-label">Nom complet</div>
                        <div class="profile-value"><?php echo htmlspecialchars(($stagiaire['nom'] ?? $stagiaire['user_nom'] ?? '') . ' ' . ($stagiaire['prenom'] ?? $stagiaire['user_prenom'] ?? '')); ?></div>
                    </div>
                    <div class="profile-item">
                        <div class="profile-label">Email</div>
                        <div class="profile-value"><?php echo htmlspecialchars($stagiaire['email'] ?? 'Non renseigné'); ?></div>
                    </div>
                    <div class="profile-item">
                        <div class="profile-label">Téléphone</div>
                        <div class="profile-value"><?php echo $stagiaire['telephone'] ?? 'Non renseigné'; ?></div>
                    </div>
                    <div class="profile-item">
                        <div class="profile-label">Domaine</div>
                        <div class="profile-value"><?php echo htmlspecialchars($stagiaire['domaine'] ?? 'Non renseigné'); ?></div>
                    </div>
                    <div class="profile-item">
                        <div class="profile-label">Login</div>
                        <div class="profile-value"><?php echo htmlspecialchars($stagiaire['login'] ?? $_SESSION['id_user']); ?></div>
                    </div>
                </div>
            </div>

            <!-- Upload rapide -->
            <div class="upload-section">
                <h3>📤 Déposer mon rapport de stage</h3>
                <p>Format accepté : PDF uniquement (taille max : 5 Mo)</p>
                <button class="btn-upload-large" onclick="ouvrirModalUpload('0', '<?php echo $stagiaire['id_stagiaire']; ?>')">
                    📁 Choisir un fichier
                </button>
            </div>

            <!-- Historique des stages -->
            <div class="card">
                <h2>📋 Mes stages</h2>
                
                <?php if (empty($stages)): ?>
                    <div class="empty-state">
                        <div class="empty-icon">📭</div>
                        <h3>Aucun stage pour le moment</h3>
                        <p>Vous n'avez pas encore de stage enregistré dans le système.</p>
                    </div>
                <?php else: ?>
                    <div class="timeline">
                        <?php foreach ($stages as $stage): 
                            $etat_class = '';
                            switch($stage['etat_stage']) {
                                case 'validée': $etat_class = 'badge-success'; break;
                                case 'en_cours': $etat_class = 'badge-warning'; break;
                                case 'non_validée': $etat_class = 'badge-danger'; break;
                                default: $etat_class = 'badge-info';
                            }
                        ?>
                            <div class="timeline-item">
                                <div class="timeline-dot"></div>
                                <div class="timeline-content">
                                    <div class="timeline-date">
                                        📅 <?php echo date('d/m/Y', strtotime($stage['date_debut'])); ?> - <?php echo date('d/m/Y', strtotime($stage['date_fin'])); ?>
                                    </div>
                                    <div class="timeline-title">
                                        <?php echo htmlspecialchars($stage['titre_stage']); ?>
                                    </div>
                                    <div style="margin-bottom: 15px;">
                                        <span class="badge <?php echo $etat_class; ?>">
                                            <?php 
                                                $etat_label = '';
                                                switch($stage['etat_stage']) {
                                                    case 'validée': $etat_label = 'Validé'; break;
                                                    case 'en_cours': $etat_label = 'En cours'; break;
                                                    case 'non_validée': $etat_label = 'Non validé'; break;
                                                    default: $etat_label = ucfirst($stage['etat_stage']);
                                                }
                                                echo $etat_label;
                                            ?>
                                        </span>
                                    </div>
                                    
                                    <div class="timeline-details">
                                        <div class="detail-item">
                                            <span class="detail-label">Nature :</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($stage['nature_stage']); ?></span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">Durée :</span>
                                            <span class="detail-value"><?php echo $stage['duree']; ?> jours</span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">Rapport :</span>
                                            <span class="detail-value">
                                                <div class="button-group">
                                                    <?php if (!empty($stage['rapport_stage'])): ?>
                                                        <a href="uploads/<?php echo $stage['rapport_stage']; ?>" target="_blank" class="btn-telecharger">
                                                            📄 Voir
                                                        </a>
                                                        <a href="uploads/<?php echo $stage['rapport_stage']; ?>" download="<?php echo $stage['titre_stage']; ?>_rapport.pdf" class="btn-exporter">
                                                            💾 Exporter PDF
                                                        </a>
                                                        <button class="btn-upload" onclick="ouvrirModalUpload(<?php echo $stage['id_stage']; ?>, <?php echo $stagiaire['id_stagiaire']; ?>)">
                                                            🔄 Remplacer
                                                        </button>
                                                    <?php else: ?>
                                                        <button class="btn-upload" onclick="ouvrirModalUpload(<?php echo $stage['id_stage']; ?>, <?php echo $stagiaire['id_stagiaire']; ?>)">
                                                            📤 Importer
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="empty-state">
                    <div class="empty-icon">❌</div>
                    <h3>Informations non disponibles</h3>
                    <p>Nous n'avons pas pu charger vos informations. Veuillez contacter l'administration.</p>
                    <p style="margin-top: 15px; font-size: 14px;">ID User: <?php echo htmlspecialchars($_SESSION['id_user'] ?? 'Non défini'); ?></p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- MODAL UPLOAD -->
    <div id="modalUpload" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="fermerModal()">&times;</span>
            <h3 style="color: #1e293b; margin-bottom: 20px;">📤 Importer mon rapport de stage</h3>
            
            <form method="POST" action="" enctype="multipart/form-data" id="uploadForm">
                <input type="hidden" name="action" value="upload_rapport">
                <input type="hidden" name="id_stage" id="upload_id_stage" value="">
                <input type="hidden" name="id_stagiaire" id="upload_id_stagiaire" value="">
                
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <div style="font-size: 50px; margin-bottom: 10px;">📁</div>
                    <p style="font-weight: 500;">Cliquez ici pour sélectionner votre fichier</p>
                    <p class="file-info">Format accepté : PDF (max 5 Mo)</p>
                </div>
                
                <input type="file" id="fileInput" name="rapport_pdf" accept=".pdf" style="display: none;" required>
                
                <div id="fileSelected" style="display: none;">
                    <p>✅ Fichier sélectionné : <span id="fileName"></span></p>
                </div>
                
                <div style="margin-top: 25px; display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="submit" style="background: linear-gradient(135deg, #28a745, #20c997); color: white; border: none; padding: 10px 20px; border-radius: 10px; cursor: pointer;">Importer</button>
                    <button type="button" onclick="fermerModal()" style="background: linear-gradient(135deg, #dc3545, #c82333); color: white; border: none; padding: 10px 20px; border-radius: 10px; cursor: pointer;">Annuler</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let modal = document.getElementById('modalUpload');
        let fileInput = document.getElementById('fileInput');
        
        function ouvrirModalUpload(idStage, idStagiaire) {
            document.getElementById('upload_id_stage').value = idStage;
            document.getElementById('upload_id_stagiaire').value = idStagiaire;
            modal.style.display = 'block';
            fileInput.value = '';
            document.getElementById('fileSelected').style.display = 'none';
        }
        
        function fermerModal() {
            modal.style.display = 'none';
        }
        
        if (fileInput) {
            fileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    let fileName = this.files[0].name;
                    let fileSize = this.files[0].size;
                    let fileExt = fileName.split('.').pop().toLowerCase();
                    
                    if (fileSize > 5 * 1024 * 1024) {
                        alert('❌ Le fichier est trop volumineux ! Taille maximum : 5 Mo');
                        this.value = '';
                        return;
                    }
                    
                    if (fileExt !== 'pdf') {
                        alert('❌ Seuls les fichiers PDF sont acceptés !');
                        this.value = '';
                        return;
                    }
                    
                    document.getElementById('fileName').textContent = fileName;
                    document.getElementById('fileSelected').style.display = 'block';
                }
            });
        }
        
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>