<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/session.php';
if (session_status() === PHP_SESSION_NONE) SessionManager::startSession();
header('Content-Type: application/json');
if (!isset($_SESSION['user_id']) || $_SESSION['type_libelle'] !== 'enseignant') die(json_encode(['success' => false, 'error' => 'Accès refusé']));
$id = isset($_GET['id_evaluation']) ? (int)$_GET['id_evaluation'] : 0;
if ($id <= 0) die(json_encode(['success' => false, 'error' => 'ID invalide']));
try {
    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT titre, duree_minutes, note_totale FROM evaluations WHERE id_evaluation = ?");
    $stmt->execute([$id]);
    $eval = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$eval) die(json_encode(['success' => false, 'error' => 'Évaluation introuvable']));
    $stmt = $db->prepare("SELECT id_question, ordre FROM questions WHERE id_evaluation = ? ORDER BY ordre");
    $stmt->execute([$id]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt = $db->prepare("SELECT te.note, te.note_sur, te.pourcentage, te.temps_passe, te.statut, te.date_fin, u.nom, u.prenom, c.nom_classe FROM (SELECT id_eleve, MAX(id_tentative) as max_id FROM tentatives_eleves WHERE id_evaluation = ? GROUP BY id_eleve) d JOIN tentatives_eleves te ON te.id_tentative = d.max_id JOIN utilisateurs u ON te.id_eleve = u.id_utilisateur LEFT JOIN classes c ON u.id_classe = c.id_classe ORDER BY te.note DESC");
    $stmt->execute([$id]);
    $tents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $notes = []; $temps_total = 0; $nb_ok = 0; $nb_cours = 0;
    foreach ($tents as $t) {
        if ($t['statut'] === 'terminee') { $notes[] = (float)$t['note']; $temps_total += (int)$t['temps_passe']; $nb_ok++; } else { $nb_cours++; }
    }
    $mediane = 0;
    if (!empty($notes)) { sort($notes); $count = count($notes); $mediane = ($count % 2 === 0) ? ($notes[$count/2 - 1] + $notes[$count/2]) / 2 : $notes[floor($count/2)]; }
    $ecart_type = 0;
    if (count($notes) > 1) { $moyenne = array_sum($notes) / count($notes); $variance = 0; foreach ($notes as $note) { $variance += pow($note - $moyenne, 2); } $ecart_type = sqrt($variance / count($notes)); }
    $temps_moyen = '00:00:00';
    if ($nb_ok > 0) { $sec_moy = $temps_total / $nb_ok; $h = floor($sec_moy / 3600); $m = floor(($sec_moy % 3600) / 60); $s = $sec_moy % 60; $temps_moyen = sprintf("%02d:%02d:%02d", $h, $m, $s); }
    $nb_reussis = 0; foreach ($notes as $n) { if ($n >= 10) $nb_reussis++; }
    $taux_reussite = $nb_ok > 0 ? ($nb_reussis / $nb_ok) * 100 : 0;
    $stats = ['total_eleves' => count($tents), 'termines' => $nb_ok, 'en_cours' => $nb_cours, 'taux_participation' => count($tents) > 0 ? ($nb_ok / count($tents)) * 100 : 0, 'moyenne' => $nb_ok > 0 ? array_sum($notes) / $nb_ok : 0, 'mediane' => $mediane, 'min' => $nb_ok > 0 ? min($notes) : 0, 'max' => $nb_ok > 0 ? max($notes) : 0, 'ecart_type' => $ecart_type, 'taux_reussite' => $taux_reussite, 'temps_moyen' => $temps_moyen];
    $list = []; $rang = 1;
    foreach ($tents as $t) { $sec = (int)$t['temps_passe']; $list[] = ['rang' => $t['statut'] === 'terminee' ? $rang : '-', 'nom' => $t['nom'], 'prenom' => $t['prenom'], 'classe' => $t['nom_classe'] ?? 'Sans classe', 'note' => (float)$t['note'], 'note_sur' => (float)$t['note_sur'], 'pourcentage' => (float)$t['pourcentage'], 'temps' => sprintf("%02d:%02d:%02d", floor($sec/3600), floor(($sec%3600)/60), $sec%60), 'statut' => $t['statut'], 'date_fin' => $t['date_fin'] ? date('d/m/Y H:i', strtotime($t['date_fin'])) : '-']; if ($t['statut'] === 'terminee') $rang++; }
    $classes = []; foreach ($tents as $t) { if ($t['statut'] !== 'terminee') continue; $c = $t['nom_classe'] ?? 'Sans classe'; if (!isset($classes[$c])) $classes[$c] = ['notes' => [], 'nom' => $c]; $classes[$c]['notes'][] = (float)$t['note']; }
    $stats_classes = []; foreach ($classes as $c) { if (empty($c['notes'])) continue; $stats_classes[] = ['nom' => $c['nom'], 'nb_eleves' => count($c['notes']), 'moyenne' => array_sum($c['notes']) / count($c['notes'])]; }
    usort($stats_classes, function($a, $b) { return $b['moyenne'] <=> $a['moyenne']; });
    echo json_encode(['success' => true, 'evaluation' => ['titre' => $eval['titre'], 'duree_minutes' => (int)$eval['duree_minutes'], 'note_totale' => (float)$eval['note_totale'], 'nb_questions' => count($questions)], 'stats' => $stats, 'stats_classes' => $stats_classes, 'stats_questions' => [], 'tentatives' => $list, 'graphiques' => ['histogramme_classes' => ['labels' => [], 'datasets' => []], 'progression_eleves' => ['labels' => [], 'datasets' => []]]], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage(), 'line' => $e->getLine()]); }
