<?php
/**
 * MATRICE MONITORING TEMPS RÉEL - ENSEIGNANT
 * Supervision élèves pendant passage évaluation
 */

require_once '../config/config.php';
require_once '../config/database.php';
require_once '../config/session.php';

if (session_status() === PHP_SESSION_NONE) {
    SessionManager::startSession();
}

// Vérification enseignant
if (!isset($_SESSION['user_id']) || $_SESSION['type_libelle'] !== 'enseignant') {
    header('Location: ../auth/login.php');
    exit;
}

$id_evaluation = $_GET['id_evaluation'] ?? null;

if (!$id_evaluation) {
    die('❌ ID évaluation manquant');
}

try {
    $db = Database::getInstance()->getConnection();
    
    // Récupérer évaluation
    $stmt = $db->prepare("SELECT * FROM evaluations WHERE id_evaluation = ?");
    $stmt->execute([$id_evaluation]);
    $evaluation = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$evaluation) {
        die('❌ Évaluation non trouvée');
    }
    
    // Récupérer questions
    $stmt = $db->prepare("SELECT id_question, ordre, enonce FROM questions WHERE id_evaluation = ? ORDER BY ordre ASC");
    $stmt->execute([$id_evaluation]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $nb_questions = count($questions);
    
} catch (Exception $e) {
    die('Erreur: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Monitoring - <?= htmlspecialchars($evaluation['titre']) ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #333;
            font-size: 24px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .refresh-indicator {
            padding: 8px 16px;
            background: #f0f0f0;
            border-radius: 5px;
            font-size: 14px;
            color: #666;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .refresh-indicator.active {
            background: #d4edda;
            color: #155724;
        }
        
        .stats-bar {
            background: white;
            padding: 15px 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        
        .monitoring-table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        thead th {
            padding: 15px 10px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            white-space: nowrap;
        }
        
        thead th.question-col {
            text-align: center;
            min-width: 40px;
        }
        
        tbody tr {
            border-bottom: 1px solid #f0f0f0;
            transition: background 0.2s;
        }
        
        tbody tr:hover {
            background: #f8f9fa;
        }
        
        tbody td {
            padding: 12px 10px;
            font-size: 14px;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        
        .status-en-ligne { background: #28a745; }
        .status-en-cours { background: #ffc107; }
        .status-inactif { background: #fd7e14; }
        .status-hors-ligne { background: #dc3545; }
        .status-termine { background: #6c757d; }
        
        .question-cell {
            text-align: center;
            font-size: 18px;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .question-cell:hover {
            transform: scale(1.2);
        }
        
        .progress-bar-container {
            background: #e9ecef;
            border-radius: 10px;
            height: 20px;
            overflow: hidden;
            position: relative;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 11px;
            font-weight: bold;
        }
        
        .progress-text {
            font-size: 12px;
            color: #666;
            margin-top: 3px;
        }
        
        .eleve-name {
            font-weight: 600;
            color: #333;
        }
        
        .eleve-classe {
            font-size: 12px;
            color: #666;
            display: block;
        }
        
        .time-info {
            font-size: 12px;
            color: #666;
        }
        
        .legende {
            background: white;
            padding: 15px 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-top: 20px;
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
            align-items: center;
        }
        
        .legende-title {
            font-weight: 600;
            color: #333;
        }
        
        .legende-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }
        
        .btn-retour {
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 14px;
            transition: background 0.2s;
        }
        
        .btn-retour:hover {
            background: #5a6268;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .spinner {
            animation: spin 1s linear infinite;
        }
        
        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>
                📊 Monitoring Temps Réel
                <span style="font-size: 18px; font-weight: normal; color: #666;">
                    - <?= htmlspecialchars($evaluation['titre']) ?>
                </span>
            </h1>
            <div style="display: flex; gap: 15px; align-items: center;">
                <div class="refresh-indicator" id="refreshIndicator">
                    <span id="refreshIcon">🔄</span>
                    <span id="refreshText">Chargement...</span>
                </div>
                <a href="dashboard.php" class="btn-retour">← Retour</a>
            </div>
        </div>
        
        <!-- Statistiques -->
        <div class="stats-bar" id="statsBar">
            <div class="stat-item">
                <div class="stat-value" id="statTotal">-</div>
                <div class="stat-label">Total élèves</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" style="color: #28a745;" id="statActifs">-</div>
                <div class="stat-label">🟢 En ligne</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" style="color: #ffc107;" id="statEnCours">-</div>
                <div class="stat-label">🟡 En cours</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" style="color: #dc3545;" id="statInactifs">-</div>
                <div class="stat-label">🔴 Inactifs</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" style="color: #6c757d;" id="statTermines">-</div>
                <div class="stat-label">⚫ Terminés</div>
            </div>
        </div>
        
        <!-- Tableau monitoring -->
        <div class="monitoring-table">
            <table>
                <thead>
                    <tr>
                        <th style="width: 40px;">Statut</th>
                        <th style="width: 200px;">Élève</th>
                        <th style="width: 200px;">Progression</th>
                        <th style="width: 120px;">Temps écoulé</th>
                        <th style="width: 120px;">Dernière activité</th>
                        <?php foreach ($questions as $q): ?>
                            <th class="question-col" title="<?= htmlspecialchars($q['enonce']) ?>">
                                Q<?= $q['ordre'] ?>
                            </th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody id="monitoringBody">
                    <tr>
                        <td colspan="<?= 5 + $nb_questions ?>" class="no-data">
                            🔄 Chargement des données...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Légende -->
        <div class="legende">
            <div class="legende-title">Légende :</div>
            <div class="legende-item">
                <span class="status-indicator status-en-ligne"></span>
                <span>En ligne (&lt;1 min)</span>
            </div>
            <div class="legende-item">
                <span class="status-indicator status-en-cours"></span>
                <span>En cours (&lt;3 min)</span>
            </div>
            <div class="legende-item">
                <span class="status-indicator status-inactif"></span>
                <span>Inactif (3-5 min)</span>
            </div>
            <div class="legende-item">
                <span class="status-indicator status-hors-ligne"></span>
                <span>Hors ligne (&gt;5 min)</span>
            </div>
            <div class="legende-item">
                <span class="status-indicator status-termine"></span>
                <span>Terminé</span>
            </div>
            <div class="legende-item" style="margin-left: 30px;">
                <span>⬜ Vide</span>
                <span style="margin-left: 15px;">✅ Répondu</span>
                <span style="margin-left: 15px;">✔️ Correct</span>
                <span style="margin-left: 15px;">❌ Incorrect</span>
            </div>
        </div>
    </div>
    
    <script>
        const ID_EVALUATION = <?= $id_evaluation ?>;
        const NB_QUESTIONS = <?= $nb_questions ?>;
        let refreshInterval;
        
        // Charger données initiales
        loadMonitoringData();
        
        // Auto-refresh toutes les 10 secondes
        refreshInterval = setInterval(loadMonitoringData, 10000);
        
        function loadMonitoringData() {
            const refreshIcon = document.getElementById('refreshIcon');
            const refreshText = document.getElementById('refreshText');
            const refreshIndicator = document.getElementById('refreshIndicator');
            
            // Animation chargement
            refreshIcon.classList.add('spinner');
            refreshText.textContent = 'Actualisation...';
            refreshIndicator.classList.add('active');
            
            fetch(`monitoring_ajax.php?id_evaluation=${ID_EVALUATION}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateStats(data.stats);
                        updateTable(data.tentatives);
                        
                        // Animation succès
                        refreshIcon.textContent = '✅';
                        refreshText.textContent = 'Mis à jour ' + new Date().toLocaleTimeString('fr-FR');
                        
                        setTimeout(() => {
                            refreshIcon.textContent = '🔄';
                            refreshIndicator.classList.remove('active');
                        }, 2000);
                    } else {
                        throw new Error(data.error || 'Erreur inconnue');
                    }
                })
                .catch(error => {
                    console.error('Erreur:', error);
                    refreshIcon.textContent = '❌';
                    refreshText.textContent = 'Erreur de chargement';
                    refreshIndicator.style.background = '#f8d7da';
                    refreshIndicator.style.color = '#721c24';
                })
                .finally(() => {
                    refreshIcon.classList.remove('spinner');
                });
        }
        
        function updateStats(stats) {
            document.getElementById('statTotal').textContent = stats.total;
            document.getElementById('statActifs').textContent = stats.en_ligne;
            document.getElementById('statEnCours').textContent = stats.en_cours;
            document.getElementById('statInactifs').textContent = stats.inactif + stats.hors_ligne;
            document.getElementById('statTermines').textContent = stats.termine;
        }
        
        function updateTable(tentatives) {
            const tbody = document.getElementById('monitoringBody');
            
            if (tentatives.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="${5 + NB_QUESTIONS}" class="no-data">
                            📭 Aucun élève n'a encore commencé cette évaluation
                        </td>
                    </tr>
                `;
                return;
            }
            
            tbody.innerHTML = tentatives.map(t => `
                <tr>
                    <td>
                        <span class="status-indicator status-${t.statut_connexion}"></span>
                    </td>
                    <td>
                        <div class="eleve-name">${escapeHtml(t.nom)} ${escapeHtml(t.prenom)}</div>
                        <span class="eleve-classe">${escapeHtml(t.classe || 'Libre')}</span>
                    </td>
                    <td>
                        <div class="progress-bar-container">
                            <div class="progress-bar" style="width: ${t.pourcentage_progression}%">
                                ${t.pourcentage_progression}%
                            </div>
                        </div>
                        <div class="progress-text">${t.nb_reponses}/${NB_QUESTIONS} questions</div>
                    </td>
                    <td class="time-info">
                        ⏱️ ${t.temps_ecoule}
                    </td>
                    <td class="time-info">
                        ${t.derniere_activite}
                    </td>
                    ${t.reponses_details.map(r => `
                        <td class="question-cell" title="${r.tooltip}">
                            ${r.icone}
                        </td>
                    `).join('')}
                </tr>
            `).join('');
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Nettoyer interval au déchargement
        window.addEventListener('beforeunload', () => {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });
    </script>
</body>
</html>
