<?php
/**
 * Contrôle et vérification des notes saisies
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin','school_admin','teacher']);
requirePermission('grades', 'view');

$schoolFilter  = currentSchoolId();
$class_id      = (int)($_GET['class_id']   ?? 0);
$subject_id    = (int)($_GET['subject_id'] ?? 0);
sessionClose();
$trimestre     = (int)($_GET['trimestre']  ?? getActivePeriod());
$academic_year = trim($_GET['academic_year'] ?? getDefaultAcademicYear($pdo, currentSchoolId()));

if (!in_array($trimestre,[1,2,3])) $trimestre = 1;

// ── Données filtres ──
if ($schoolFilter) {
    $classes = $pdo->query("SELECT c.id,c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
} else {
    $classes = $pdo->query("SELECT c.id,c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
}

// Matières (filtrées par classe si sélectionnée)
if ($class_id) {
    if ($schoolFilter) {
        $subjStmt = $pdo->prepare("SELECT DISTINCT s.id,s.name,s.code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id=? ORDER BY s.name");
        $subjStmt->execute([$class_id]);
    } else {
        $subjStmt = $pdo->prepare("SELECT DISTINCT s.id,s.name,s.code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id=? ORDER BY s.name");
        $subjStmt->execute([$class_id]);
    }
    $subjects = $subjStmt->fetchAll();
} else {
    $subjects = [];
}

$schoolsList = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();
$years = $pdo->query("SELECT DISTINCT year FROM academic_years WHERE school_id=" . (int)($schoolFilter ?: 0))->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) {
    $years = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
if (empty($years)) { $years = []; }
$years = array_unique(array_merge($years, [date('Y') . '-' . (date('Y')+1)]));

// ── Statistiques ──
$stats = [];
$grandTotal = ['students'=>0,'graded'=>0,'avg_interro'=>0,'avg_devoir'=>0,'avg_compo'=>0,'avg_moy'=>0,'count'=>0];

if ($class_id && $trimestre && $academic_year) {
    $totalStudents = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=?");
    $totalStudents->execute([$class_id]);
    $totalStudents = (int)$totalStudents->fetchColumn();

    if (!empty($subjects)) {
        $subjIds = array_column($subjects, 'id');
        $ph = implode(',', array_fill(0, count($subjIds), '?'));
        $grdAll = $pdo->prepare("SELECT subject_id,
            COUNT(*) AS cnt, AVG(note_interro) AS avg_i, AVG(note_devoir) AS avg_d,
            AVG(note_compo) AS avg_c, AVG(moy_classe) AS avg_m
            FROM grades WHERE class_id=? AND subject_id IN ($ph) AND trimestre=? AND academic_year=? GROUP BY subject_id");
        $grdAll->execute(array_merge([$class_id], $subjIds, [$trimestre, $academic_year]));
        $gradeRows = []; foreach ($grdAll as $r) $gradeRows[$r['subject_id']] = $r;

        foreach ($subjects as $subj) {
            $row = $gradeRows[$subj['id']] ?? null;
            $graded = $row ? (int)$row['cnt'] : 0;
            $stats[$subj['id']] = [
                'name'        => $subj['name'],
                'code'        => $subj['code'],
                'total'       => $totalStudents,
                'graded'      => $graded,
                'completion'  => $totalStudents > 0 ? round($graded/$totalStudents*100,1) : 0,
                'avg_interro' => $row && $row['avg_i'] !== null ? round((float)$row['avg_i'],2) : null,
                'avg_devoir'  => $row && $row['avg_d'] !== null ? round((float)$row['avg_d'],2) : null,
                'avg_compo'   => $row && $row['avg_c'] !== null ? round((float)$row['avg_c'],2) : null,
                'avg_moy'     => $row && $row['avg_m'] !== null ? round((float)$row['avg_m'],2) : null,
            ];
            $grandTotal['students'] = $totalStudents;
            $grandTotal['graded'] += $graded;
            $grandTotal['count']++;
            if ($row && $row['avg_i'] !== null) $grandTotal['avg_interro'] += (float)$row['avg_i'];
            if ($row && $row['avg_d'] !== null) $grandTotal['avg_devoir'] += (float)$row['avg_d'];
            if ($row && $row['avg_c'] !== null) $grandTotal['avg_compo'] += (float)$row['avg_c'];
            if ($row && $row['avg_m'] !== null) $grandTotal['avg_moy'] += (float)$row['avg_m'];
        }
        if ($grandTotal['count'] > 0) {
            $grandTotal['avg_interro'] = round($grandTotal['avg_interro']/$grandTotal['count'],2);
            $grandTotal['avg_devoir']  = round($grandTotal['avg_devoir']/$grandTotal['count'],2);
            $grandTotal['avg_compo']   = round($grandTotal['avg_compo']/$grandTotal['count'],2);
            $grandTotal['avg_moy']     = round($grandTotal['avg_moy']/$grandTotal['count'],2);
        }
    }
}

// ── Vue consolidée par école (quand aucune classe sélectionnée) ──
$schoolSummary = [];
$grandSchoolTotal = ['students'=>0,'graded'=>0,'expected'=>0,'subjects'=>0,'avg_interro'=>null,'avg_devoir'=>null,'avg_compo'=>null,'avg_moy'=>null,'class_count'=>0];
if (!$class_id) {
    $schoolIds = $schoolFilter ? [$schoolFilter] : array_column($pdo->query("SELECT id FROM schools ORDER BY name")->fetchAll(), 'id');
    foreach ($schoolIds as $sid) {
        $clList = $pdo->prepare("SELECT DISTINCT c.id,c.name FROM classes c JOIN students s ON s.class_id=c.id WHERE s.school_id=? ORDER BY " . getClassSortSQL('c'));
        $clList->execute([$sid]);
        $schoolData = ['name'=>'','classes'=>[],'totalStudents'=>0,'totalGraded'=>0,'totalExpected'=>0,'totalSubjects'=>0];
        $scName = $pdo->prepare("SELECT name FROM schools WHERE id=?");
        $scName->execute([$sid]); $schoolData['name'] = $scName->fetchColumn();

        $schoolInterro = []; $schoolDevoir = []; $schoolCompo = []; $schoolMoy = [];

        $classIds = array_column($clList->fetchAll(), 'id');
        if (empty($classIds)) continue;
        $placeholders = implode(',', array_fill(0, count($classIds), '?'));
        $paramsBatch = $classIds;

        // Requêtes groupées par école (1 requête par métrique au lieu de 4 par classe)
        $stStudents = $pdo->prepare("SELECT class_id, COUNT(*) AS cnt FROM students WHERE class_id IN ($placeholders) AND school_id=? GROUP BY class_id");
        $stStudents->execute(array_merge($classIds, [$sid]));
        $studentCounts = []; foreach ($stStudents as $r) $studentCounts[$r['class_id']] = (int)$r['cnt'];

        $stSubj = $pdo->prepare("SELECT class_id, COUNT(*) AS cnt FROM class_subjects WHERE class_id IN ($placeholders) AND school_id=? GROUP BY class_id");
        $stSubj->execute(array_merge($classIds, [$sid]));
        $subjCounts = []; foreach ($stSubj as $r) $subjCounts[$r['class_id']] = (int)$r['cnt'];

        $stGrades = $pdo->prepare("SELECT class_id,
            COUNT(DISTINCT CONCAT(student_id,'-',subject_id)) AS graded,
            AVG(note_interro) AS avg_i, AVG(note_devoir) AS avg_d,
            AVG(note_compo) AS avg_c, AVG(moy_classe) AS avg_m
            FROM grades WHERE class_id IN ($placeholders) AND trimestre=? AND academic_year=? GROUP BY class_id");
        $stGrades->execute(array_merge($classIds, [$trimestre, $academic_year]));
        $gradeData = []; foreach ($stGrades as $r) $gradeData[$r['class_id']] = $r;

        foreach ($classIds as $cid) {
            $clTotal = (int)($studentCounts[$cid] ?? 0);
            if (!$clTotal) continue;
            $subjCnt = (int)($subjCounts[$cid] ?? 0);
            if (!$subjCnt) continue;
            $grd = $gradeData[$cid] ?? null;
            $clGraded = $grd ? (int)$grd['graded'] : 0;
            $avgRow = $grd ?: ['avg_i'=>null,'avg_d'=>null,'avg_c'=>null,'avg_m'=>null];

            $expected = $clTotal * $subjCnt;
            $avgI = $avgRow['avg_i'] !== null ? round((float)$avgRow['avg_i'],2) : null;
            $avgD = $avgRow['avg_d'] !== null ? round((float)$avgRow['avg_d'],2) : null;
            $avgC = $avgRow['avg_c'] !== null ? round((float)$avgRow['avg_c'],2) : null;
            $avgM = $avgRow['avg_m'] !== null ? round((float)$avgRow['avg_m'],2) : null;

            if ($avgI !== null) $schoolInterro[] = $avgI;
            if ($avgD !== null) $schoolDevoir[] = $avgD;
            if ($avgC !== null) $schoolCompo[] = $avgC;
            if ($avgM !== null) $schoolMoy[] = $avgM;

            $schoolData['classes'][] = [
                'id' => $cid,
                'name' => '',
                'students' => $clTotal,
                'subjects' => $subjCnt,
                'graded' => $clGraded,
                'expected' => $expected,
                'completion' => $expected > 0 ? round($clGraded/$expected*100,1) : 0,
                'avg_interro' => $avgI,
                'avg_devoir'  => $avgD,
                'avg_compo'   => $avgC,
                'avg_moy'     => $avgM,
            ];
            $schoolData['totalStudents'] += $clTotal;
            $schoolData['totalGraded']   += $clGraded;
            $schoolData['totalExpected'] += $expected;
            $schoolData['totalSubjects'] += $subjCnt;
        }
        // Récupérer les noms des classes en une seule requête
        if (!empty($schoolData['classes'])) {
            $stNames = $pdo->prepare("SELECT id, name FROM classes WHERE id IN ($placeholders)");
            $stNames->execute($classIds);
            $names = []; foreach ($stNames as $r) $names[$r['id']] = $r['name'];
            foreach ($schoolData['classes'] as &$cd) $cd['name'] = $names[$cd['id']] ?? '';
            unset($cd);
        }
        if (!empty($schoolData['classes'])) {
            $schoolData['avg_interro'] = count($schoolInterro) ? round(array_sum($schoolInterro)/count($schoolInterro),2) : null;
            $schoolData['avg_devoir']  = count($schoolDevoir)  ? round(array_sum($schoolDevoir)/count($schoolDevoir),2)  : null;
            $schoolData['avg_compo']   = count($schoolCompo)   ? round(array_sum($schoolCompo)/count($schoolCompo),2)   : null;
            $schoolData['avg_moy']     = count($schoolMoy)     ? round(array_sum($schoolMoy)/count($schoolMoy),2)      : null;
            $schoolSummary[$sid] = $schoolData;
            $grandSchoolTotal['students']    += $schoolData['totalStudents'];
            $grandSchoolTotal['graded']      += $schoolData['totalGraded'];
            $grandSchoolTotal['expected']    += $schoolData['totalExpected'];
            $grandSchoolTotal['subjects']    += $schoolData['totalSubjects'];
            $grandSchoolTotal['class_count'] += count($schoolData['classes']);
            if ($schoolData['avg_interro'] !== null) { $grandSchoolTotal['avg_interro'] = ($grandSchoolTotal['avg_interro'] ?? 0) + $schoolData['avg_interro']; }
            if ($schoolData['avg_devoir'] !== null)  { $grandSchoolTotal['avg_devoir']  = ($grandSchoolTotal['avg_devoir'] ?? 0) + $schoolData['avg_devoir']; }
            if ($schoolData['avg_compo'] !== null)   { $grandSchoolTotal['avg_compo']   = ($grandSchoolTotal['avg_compo'] ?? 0) + $schoolData['avg_compo']; }
            if ($schoolData['avg_moy'] !== null)     { $grandSchoolTotal['avg_moy']     = ($grandSchoolTotal['avg_moy'] ?? 0) + $schoolData['avg_moy']; }
        }
    }
    if ($grandSchoolTotal['class_count'] > 0) {
        $grandSchoolTotal['avg_interro'] = $grandSchoolTotal['avg_interro'] !== null ? round($grandSchoolTotal['avg_interro']/$grandSchoolTotal['class_count'],2) : null;
        $grandSchoolTotal['avg_devoir']  = $grandSchoolTotal['avg_devoir']  !== null ? round($grandSchoolTotal['avg_devoir']/$grandSchoolTotal['class_count'],2)  : null;
        $grandSchoolTotal['avg_compo']   = $grandSchoolTotal['avg_compo']   !== null ? round($grandSchoolTotal['avg_compo']/$grandSchoolTotal['class_count'],2)   : null;
        $grandSchoolTotal['avg_moy']     = $grandSchoolTotal['avg_moy']     !== null ? round($grandSchoolTotal['avg_moy']/$grandSchoolTotal['class_count'],2)      : null;
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vérification des notes - Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root{--primary:#1F4E79;--accent:#2E75B6;--light:#D6E4F0;--success:#10B981;--warning:#F59E0B;--error:#EF4444;--bg:#F1F5F9;--text:#1E293B;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;}
.main-content{padding-top:0;}
.content{padding:30px;max-width:1400px;}
.selection-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:24px 30px;margin-bottom:25px;}
.selection-title{font-family:Georgia,serif;color:var(--primary);font-size:1.2rem;margin-bottom:20px;padding-bottom:10px;border-bottom:2px solid var(--light);}
.selection-row{display:flex;gap:25px;align-items:flex-end;flex-wrap:wrap;}
.select-group{display:flex;flex-direction:column;gap:8px;flex:1;min-width:200px;}
.select-label{font-weight:600;color:var(--primary);font-size:.85rem;}
.select-input{padding:12px 16px;border:1px solid #D1D5DB;border-radius:8px;font-size:.95rem;background:white;cursor:pointer;transition:all .2s;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 9L1 4h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 14px center;padding-right:36px;}
.select-input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(46,117,182,0.15);}
.btn{padding:12px 28px;border:none;border-radius:8px;font-size:.95rem;font-weight:600;cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:10px;text-decoration:none;}
.btn-primary{background:var(--primary);color:white;}
.btn-primary:hover{background:#163a5c;transform:translateY(-1px);}
.btn-success{background:var(--success);color:white;}
.btn-success:hover{background:#059669;transform:translateY(-1px);}
.btn-warning{background:var(--warning);color:white;}
.btn-warning:hover{background:#D97706;}
.btn-light{background:#E5E7EB;color:#374151;}
.btn-light:hover{background:#D1D5DB;}
.stats-row{display:flex;gap:20px;margin-bottom:25px;flex-wrap:wrap;}
.stat-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:20px 24px;flex:1;min-width:150px;display:flex;align-items:center;gap:16px;}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.5rem;flex-shrink:0;}
.stat-icon.blue{background:#DBEAFE;}.stat-icon.green{background:#D1FAE5;}.stat-icon.orange{background:#FEF3C7;}.stat-icon.purple{background:#E9E5FF;}.stat-icon.red{background:#FEE2E2;}
.stat-value{font-size:1.6rem;font-weight:700;color:var(--primary);}
.stat-label{font-size:.85rem;color:#6B7280;}
.saisie-table{width:100%;border-collapse:collapse;}
.saisie-table thead{background:var(--primary);color:white;}
.saisie-table th{padding:14px 16px;text-align:center;font-weight:600;font-size:.85rem;text-transform:uppercase;letter-spacing:.5px;}
.saisie-table th:first-child,.saisie-table th:nth-child(2){text-align:left;}
.saisie-table td{padding:10px 16px;border-bottom:1px solid #E5E7EB;text-align:center;font-size:.9rem;}
.saisie-table td:first-child{text-align:left;font-weight:500;}
.saisie-table tbody tr:hover{background:#F9FAFB;}
.saisie-table tbody tr:nth-child(even){background:#F9FAFB;}
.saisie-table tbody tr:nth-child(even):hover{background:#F3F4F6;}
.toast-container{position:fixed;bottom:30px;right:30px;z-index:2000;display:flex;flex-direction:column;gap:10px;}
.toast{background:white;padding:14px 20px;border-radius:8px;box-shadow:0 4px 20px rgba(0,0,0,0.15);display:flex;align-items:center;gap:12px;animation:slideIn .3s ease;border-left:4px solid var(--primary);}
.toast-success{border-left-color:#10B981;}
.toast-warning{border-left-color:#F59E0B;}
.toast-error{border-left-color:#EF4444;}
@keyframes slideIn{from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;}}
.empty-state{text-align:center;padding:3rem 1rem;color:#9CA3AF;}
.verif-actions{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;padding:.75rem 0;}
.verif-summary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:1rem;text-align:center;}
.school-accordion{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);margin-bottom:20px;overflow:hidden;}
.school-header{padding:18px 30px;background:var(--light);display:flex;justify-content:space-between;align-items:center;cursor:pointer;transition:background .2s;user-select:none;}
.school-header:hover{background:#C5D9EC;}
.school-title{font-family:Georgia,serif;color:var(--primary);font-size:1.15rem;display:flex;align-items:center;gap:12px;}
.school-toggle{font-size:1.2rem;color:var(--primary);transition:transform .3s;}
.school-accordion.open .school-toggle{transform:rotate(90deg);}
.school-body{max-height:0;overflow:hidden;transition:max-height .4s ease;}
.school-accordion.open .school-body{max-height:5000px;}
.school-inner{padding:24px 30px;}
.badge-completion{display:inline-block;padding:.25rem .75rem;border-radius:20px;font-size:.8rem;font-weight:600;}
.badge-completion.full{background:#D1FAE5;color:#065F46;}
.badge-completion.partial{background:#FEF3C7;color:#92400E;}
.badge-completion.empty{background:#FEE2E2;color:#991B1B;}
.school-row td{background:#EFF6FF;cursor:pointer;padding:14px 16px!important;border-bottom:2px solid #BFDBFE;transition:background .2s;}
.school-row td:hover{background:#DBEAFE;}
.school-row .school-name-cell{display:flex;align-items:center;gap:10px;font-size:1rem;font-weight:700;color:var(--primary);}
.school-row .school-cl-count{font-weight:400;font-size:.8rem;color:#6B7280;}
.school-row .school-name-cell i{font-size:1.15rem;}
.school-total-row td{background:#F8FAFC!important;border-top:2px solid #E2E8F0;border-bottom:2px solid #CBD5E1;}
.class-row td{transition:background .2s;}
.class-row.hidden{display:none;}
#verifTable tfoot td{font-size:.9rem;}
#verifTable tfoot td:first-child{font-size:.95rem;}
.selection-row{flex-direction:column;align-items:stretch;}
.select-group{min-width:100%;}
.verif-summary-grid{grid-template-columns:1fr 1fr;}
.content{padding:16px;}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-check-double"></i> Vérification des notes'; include '../includes/topbar.php'; ?>
        <?php if ($__flash??null): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>
        <?php $__flash = $_SESSION['flash_toast'] ?? null; unset($_SESSION['flash_toast']); ?>

        <div class="content">

        <!-- ═══ FILTRES ═══ -->
        <div class="selection-card">
            <div class="selection-title"><i class="fas fa-filter" style="color:var(--primary);"></i> Filtres de vérification</div>
            <form method="GET" class="selection-row">
                <?php if (!$schoolFilter): ?>
                <div class="select-group">
                    <label class="select-label">École</label>
                    <select name="school_id" class="select-input" onchange="this.form.submit()">
                        <option value="">Toutes</option>
                        <?php foreach ($schoolsList as $sc): ?>
                        <option value="<?=$sc['id']?>" <?=($schoolFilter?:$_GET['school_id']??'')==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="select-group">
                    <label class="select-label">Classe</label>
                    <select name="class_id" class="select-input" onchange="this.form.submit()">
                        <option value="">— Toutes les classes —</option>
                        <?php foreach($classes as $cl): ?>
                        <option value="<?=$cl['id']?>" <?=$cl['id']==$class_id?'selected':''?>>
                            <?=e($cl['name'])?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if ($class_id): ?>
                <div class="select-group">
                    <label class="select-label">Matière</label>
                    <select name="subject_id" class="select-input" onchange="this.form.submit()">
                        <option value="">— Toutes —</option>
                        <?php foreach($subjects as $subj): ?>
                        <option value="<?=$subj['id']?>" <?=$subj['id']==$subject_id?'selected':''?>>
                            <?=e($subj['code']?'['.$subj['code'].'] ':'').e($subj['name'])?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="select-group">
                    <label class="select-label">Trimestre</label>
                    <select name="trimestre" class="select-input" onchange="this.form.submit()">
                        <option value="1" <?=$trimestre==1?'selected':''?>>1er Trimestre</option>
                        <option value="2" <?=$trimestre==2?'selected':''?>>2ème Trimestre</option>
                        <option value="3" <?=$trimestre==3?'selected':''?>>3ème Trimestre</option>
                    </select>
                </div>
                <div class="select-group">
                    <label class="select-label">Année scolaire</label>
                    <select name="academic_year" class="select-input" onchange="this.form.submit()">
                        <?php foreach($years as $y): ?>
                        <option value="<?=e($y)?>" <?=$y===$academic_year?'selected':''?>><?=e($y)?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <a href="grade_verification.php" class="btn btn-light"><i class="fas fa-undo"></i> Réinitialiser</a>
            </form>
        </div>

        <?php if ($class_id): ?>
        <!-- ═══ IMPORT/EXPORT ═══ -->
        <div class="verif-actions">
            <span style="font-weight:600;font-size:.85rem;color:var(--primary);"><i class="fas fa-exchange-alt"></i> Import / Export</span>
            <a href="grades.php?class_id=<?= $class_id ?>&subject_id=<?= $subject_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&export=1&csrf_token=<?= csrfToken() ?>" class="btn btn-success" style="padding:.5rem 1rem;font-size:.82rem;"><i class="fas fa-download"></i> Export classe</a>
            <a href="grades.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>" class="btn btn-warning" style="padding:.5rem 1rem;font-size:.82rem;"><i class="fas fa-upload"></i> Import classe</a>
        </div>
        <?php endif; ?>

        <?php if (!$class_id): ?>
        <!-- ═══ VUE CONSOLIDÉE PAR ÉCOLE ═══ -->
        <?php if (empty($schoolSummary)): ?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-check-double" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Sélectionnez une classe pour voir le détail, ou vérifiez qu'il existe des élèves et des matières assignées.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="selection-card" style="padding:0;overflow:hidden;">
            <div style="overflow-x:auto;">
            <table class="saisie-table" id="verifTable">
                <thead>
                    <tr>
                        <th>École / Classe</th>
                        <th>Élèves</th>
                        <th>Matières</th>
                        <th>Notes saisies</th>
                        <th>Attendu</th>
                        <th>Complétion</th>
                        <th>Statut</th>
                        <th>Moy. Interro</th>
                        <th>Moy. Devoir</th>
                        <th>Moy. Compo</th>
                        <th>Moy. Générale</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php uasort($schoolSummary, function($a, $b) { return strcasecmp($a['name'], $b['name']); }); ?>
                    <?php $rowIdx = 0; foreach ($schoolSummary as $sid => $scData): ?>
                    <!-- School header row -->
                    <tr class="school-row" onclick="toggleSchoolRow(this)" data-target="<?=$rowIdx?>">
                        <td colspan="12"><span class="school-name-cell"><i class="fas fa-chevron-down school-toggle-icon" style="font-size:.75rem;color:#94A3B8;"></i> <i class="fas fa-school"></i> <?=e($scData['name'])?> <span class="school-cl-count">(<?=count($scData['classes'])?> classe<?=count($scData['classes'])>1?'s':''?>)</span></span></td>
                    </tr>
                    <?php foreach ($scData['classes'] as $cl): ?>
                    <tr class="class-row school-<?=$rowIdx?>">
                        <td style="padding-left:2.5rem;"><strong><?=e($cl['name'])?></strong></td>
                        <td><?=$cl['students']?></td>
                        <td><?=$cl['subjects']?></td>
                        <td><?=$cl['graded']?></td>
                        <td><?=$cl['expected']?></td>
                        <td>
                            <?php if ($cl['completion'] >= 100): ?>
                            <span class="badge-completion full"><i class="fas fa-check-circle"></i> 100%</span>
                            <?php elseif ($cl['completion'] > 0): ?>
                            <span class="badge-completion partial"><?=$cl['completion']?>%</span>
                            <?php else: ?>
                            <span class="badge-completion empty"><i class="fas fa-times-circle"></i> 0%</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $statusClass = 'empty';
                            $statusIcon = 'fa-times-circle';
                            $statusText = 'Aucune note';
                            if ($cl['completion'] >= 100) {
                                $statusClass = 'full';
                                $statusIcon = 'fa-check-circle';
                                $statusText = 'Complet';
                            } elseif ($cl['completion'] >= 50) {
                                $statusClass = 'partial';
                                $statusIcon = 'fa-exclamation-triangle';
                                $statusText = 'Partiel';
                            }
                            ?>
                            <span class="badge-completion <?=$statusClass?>"><i class="fas <?=$statusIcon?>"></i> <?=$statusText?></span>
                        </td>
                        <td><?=$cl['avg_interro'] !== null ? e($cl['avg_interro']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$cl['avg_devoir'] !== null ? e($cl['avg_devoir']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$cl['avg_compo'] !== null ? e($cl['avg_compo']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><strong><?=$cl['avg_moy'] !== null ? e($cl['avg_moy']) : '<span style="color:#D1D5DB;">—</span>'?></strong></td>
                        <td>
                            <a href="?class_id=<?=$cl['id']?>&trimestre=<?=$trimestre?>&academic_year=<?=urlencode($academic_year)?>" class="btn btn-primary" style="padding:.25rem .5rem;font-size:.72rem;"><i class="fas fa-search"></i></a>
                            <a href="grades.php?class_id=<?=$cl['id']?>&trimestre=<?=$trimestre?>&academic_year=<?=urlencode($academic_year)?>" class="btn btn-light" style="padding:.25rem .5rem;font-size:.72rem;"><i class="fas fa-pen-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <!-- School totals row -->
                    <tr class="school-total-row school-<?=$rowIdx?>">
                        <td style="padding-left:2rem;font-weight:600;color:var(--primary);">Total <?=e($scData['name'])?></td>
                        <td><strong><?=$scData['totalStudents']?></strong></td>
                        <td><?=$scData['totalSubjects']?></td>
                        <td><strong><?=$scData['totalGraded']?></strong></td>
                        <td><?=$scData['totalExpected']?></td>
                        <td>
                            <?php $scPct = $scData['totalExpected'] > 0 ? round($scData['totalGraded']/$scData['totalExpected']*100,1) : 0; ?>
                            <?php if ($scPct >= 100): ?>
                            <span class="badge-completion full">100%</span>
                            <?php elseif ($scPct > 0): ?>
                            <span class="badge-completion partial"><?=$scPct?>%</span>
                            <?php else: ?>
                            <span class="badge-completion empty">0%</span>
                            <?php endif; ?>
                        </td>
                        <td></td>
                        <td><?=$scData['avg_interro'] !== null ? e($scData['avg_interro']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$scData['avg_devoir'] !== null ? e($scData['avg_devoir']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$scData['avg_compo'] !== null ? e($scData['avg_compo']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><strong><?=$scData['avg_moy'] !== null ? e($scData['avg_moy']) : '<span style="color:#D1D5DB;">—</span>'?></strong></td>
                        <td></td>
                    </tr>
                    <?php $rowIdx++; endforeach; ?>
                </tbody>
                <tfoot style="font-weight:700;background:#F1F5F9;">
                    <tr>
                        <td><strong>Total général</strong></td>
                        <td><?=$grandSchoolTotal['students']?></td>
                        <td><?=$grandSchoolTotal['subjects']?></td>
                        <td><?=$grandSchoolTotal['graded']?></td>
                        <td><?=$grandSchoolTotal['expected']?></td>
                        <td>
                            <?php $gpct = $grandSchoolTotal['expected'] > 0 ? round($grandSchoolTotal['graded']/$grandSchoolTotal['expected']*100,1) : 0; ?>
                            <?php if ($gpct >= 100): ?>
                            <span class="badge-completion full">100%</span>
                            <?php elseif ($gpct > 0): ?>
                            <span class="badge-completion partial"><?=$gpct?>%</span>
                            <?php else: ?>
                            <span class="badge-completion empty">0%</span>
                            <?php endif; ?>
                        </td>
                        <td></td>
                        <td><?=$grandSchoolTotal['avg_interro'] !== null ? e($grandSchoolTotal['avg_interro']) : '—'?></td>
                        <td><?=$grandSchoolTotal['avg_devoir'] !== null ? e($grandSchoolTotal['avg_devoir']) : '—'?></td>
                        <td><?=$grandSchoolTotal['avg_compo'] !== null ? e($grandSchoolTotal['avg_compo']) : '—'?></td>
                        <td><strong><?=$grandSchoolTotal['avg_moy'] !== null ? e($grandSchoolTotal['avg_moy']) : '—'?></strong></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
            </div>
        </div>
        <?php endif; ?>

        <?php elseif (empty($stats)): ?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-inbox" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Aucune note trouvée pour cette classe.</p>
            </div>
        </div>

        <?php else: ?>
        <!-- ═══ STATS ROW ═══ -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-school"></i></div>
                <div class="stat-content"><div class="stat-value"><?=e($classes[array_search($class_id,array_column($classes,'id'))]['name']??'')?></div><div class="stat-label">Classe</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple"><i class="fas fa-layer-group"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$trimestre?><sup>er</sup></div><div class="stat-label">Trimestre</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fas fa-calendar"></i></div>
                <div class="stat-content"><div class="stat-value"><?=e($academic_year)?></div><div class="stat-label">Année</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-user-graduate"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$grandTotal['students']?></div><div class="stat-label">Élèves</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-pen"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$grandTotal['avg_interro'] !== null ? $grandTotal['avg_interro'] : '—'?></div><div class="stat-label">Moy. Interro</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple"><i class="fas fa-book"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$grandTotal['avg_devoir'] !== null ? $grandTotal['avg_devoir'] : '—'?></div><div class="stat-label">Moy. Devoir</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fas fa-file-alt"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$grandTotal['avg_compo'] !== null ? $grandTotal['avg_compo'] : '—'?></div><div class="stat-label">Moy. Compo</div></div>
            </div>
            <div class="stat-card">
                <div class="stat-icon red"><i class="fas fa-chart-line"></i></div>
                <div class="stat-content"><div class="stat-value"><?=$grandTotal['avg_moy'] !== null ? $grandTotal['avg_moy'] : '—'?></div><div class="stat-label">Moy. Générale</div></div>
            </div>
        </div>

        <!-- ═══ DÉTAIL PAR MATIÈRE ═══ -->
        <div class="selection-card" style="padding:0;overflow:hidden;">
            <div style="overflow-x:auto;">
            <table class="saisie-table">
                <thead>
                    <tr>
                        <th>Matière</th>
                        <th>Notes saisies</th>
                        <th>Total élèves</th>
                        <th>Complétion</th>
                        <th>Moy. Interro</th>
                        <th>Moy. Devoir</th>
                        <th>Moy. Compo</th>
                        <th>Moy. Classe</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($stats as $sid => $s): ?>
                    <?php if ($subject_id && $sid !== $subject_id) continue; ?>
                    <tr>
                        <td><strong><?=e($s['code']?'['.$s['code'].'] ':'').e($s['name'])?></strong></td>
                        <td><?=$s['graded']?></td>
                        <td><?=$s['total']?></td>
                        <td>
                            <?php if ($s['completion'] >= 100): ?>
                            <span class="badge-completion full"><i class="fas fa-check-circle"></i> 100%</span>
                            <?php elseif ($s['completion'] > 0): ?>
                            <span class="badge-completion partial"><?=$s['completion']?>%</span>
                            <?php else: ?>
                            <span class="badge-completion empty"><i class="fas fa-times-circle"></i> 0%</span>
                            <?php endif; ?>
                        </td>
                        <td><?=$s['avg_interro'] !== null ? e($s['avg_interro']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$s['avg_devoir'] !== null ? e($s['avg_devoir']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><?=$s['avg_compo'] !== null ? e($s['avg_compo']) : '<span style="color:#D1D5DB;">—</span>'?></td>
                        <td><strong><?=$s['avg_moy'] !== null ? e($s['avg_moy']) : '<span style="color:#D1D5DB;">—</span>'?></strong></td>
                        <td>
                            <a href="grades.php?class_id=<?=$class_id?>&subject_id=<?=$sid?>&trimestre=<?=$trimestre?>&academic_year=<?=urlencode($academic_year)?>" class="btn btn-primary" style="padding:.3rem .6rem;font-size:.75rem;"><i class="fas fa-pen-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot style="font-weight:700;background:#F1F5F9;">
                    <tr>
                        <td><strong>Total / Moyennes</strong></td>
                        <td><?=$grandTotal['graded']?></td>
                        <td><?=$grandTotal['students']?></td>
                        <td>
                            <?php $pct = $grandTotal['students'] > 0 && $grandTotal['count'] > 0 ? round($grandTotal['graded']/($grandTotal['students']*$grandTotal['count'])*100,1) : 0; ?>
                            <?php if ($pct >= 100): ?>
                            <span class="badge-completion full">100%</span>
                            <?php else: ?>
                            <span class="badge-completion partial"><?=$pct?>%</span>
                            <?php endif; ?>
                        </td>
                        <td><?=$grandTotal['avg_interro'] !== null ? e($grandTotal['avg_interro']) : '—'?></td>
                        <td><?=$grandTotal['avg_devoir'] !== null ? e($grandTotal['avg_devoir']) : '—'?></td>
                        <td><?=$grandTotal['avg_compo'] !== null ? e($grandTotal['avg_compo']) : '—'?></td>
                        <td><strong><?=$grandTotal['avg_moy'] !== null ? e($grandTotal['avg_moy']) : '—'?></strong></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
            </div>
        </div>
        <?php endif; ?>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
function toggleSchool(card){card.classList.toggle('open');}
function toggleSchoolRow(header){
    var idx = header.getAttribute('data-target');
    var rows = document.querySelectorAll('.class-row.school-'+idx+', .school-total-row.school-'+idx);
    rows.forEach(function(r){r.classList.toggle('hidden');});
    var icon = header.querySelector('.school-toggle-icon');
    if (icon) icon.classList.toggle('fa-chevron-down');
    if (icon) icon.classList.toggle('fa-chevron-right');
}
function showToast(message,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type||'success');var icons={success:'&#x2705;',warning:'&#x26A0;&#xFE0F;',error:'&#x274C;'};t.innerHTML='<span>'+(icons[type]||'&#x2139;&#xFE0F;')+'</span><span>'+message+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
</script>
</body>
</html>
