<?php
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();
$trimestre     = (int)($_GET['trimestre']     ?? $_POST['trimestre']     ?? getActivePeriod());
$academic_year = trim($_GET['academic_year']  ?? $_POST['academic_year'] ?? getDefaultAcademicYear($pdo, currentSchoolId()));
$subject_id    = (int)($_GET['subject_id']    ?? $_POST['subject_id']   ?? 0);
$teacher_filter = (int)($_GET['teacher_filter'] ?? 0);
$error = $success = '';

// Session persistence
if (isset($_GET['set_session'])) {
    if (isset($_GET['trimestre'])) setActivePeriod((int)$_GET['trimestre']);
    if (isset($_GET['academic_year'])) $_SESSION['active_academic_year'] = $_GET['academic_year'] ?: null;
    if (isset($_GET['school_id'])) $_SESSION['active_school_filter'] = (int)$_GET['school_id'] ?: null;
    header('Location: grades.php?subject_id=' . $subject_id);
    exit;
}
$sessionYear   = $_SESSION['active_academic_year'] ?? $academic_year;
$sessionPeriod = getActivePeriod();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;

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

// ── Teacher ──
$teacherId = null;
if (hasRole('teacher')) {
    $tidStmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id=?");
    $tidStmt->execute([$_SESSION['user_id']]);
    $teacherId = $tidStmt->fetchColumn();
}

// ── Seuils (school-wide via school_settings) ──
$COUNCIL_PASS = 14; $COUNCIL_ADMIT = 10; $COUNCIL_COUNCIL = 8;
$thSt = $pdo->prepare("SELECT pass_threshold, admit_threshold, council_threshold FROM school_settings WHERE school_id=?");
$thSt->execute([$schoolFilter ?: 0]);
$thRow = $thSt->fetch();
if ($thRow) {
    $COUNCIL_PASS    = (float)($thRow['pass_threshold'] ?? 14);
    $COUNCIL_ADMIT   = (float)($thRow['admit_threshold'] ?? 10);
    $COUNCIL_COUNCIL = (float)($thRow['council_threshold'] ?? 8);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_thresholds'])) {
    $pt = max(0, min(20, (float)($_POST['pass_threshold'] ?? 14)));
    $at = max(0, min(20, (float)($_POST['admit_threshold'] ?? 10)));
    $ct = max(0, min(20, (float)($_POST['council_threshold'] ?? 8)));
    $sid = $schoolFilter ?: 0;
    $pdo->prepare("INSERT INTO school_settings (school_id, pass_threshold, admit_threshold, council_threshold) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE pass_threshold=?, admit_threshold=?, council_threshold=?")
        ->execute([$sid, $pt, $at, $ct, $pt, $at, $ct]);
    $_SESSION['flash_toast'] = ['message' => 'Seuils mis à jour.', 'type' => 'success'];
    header('Location: grades.php?subject_id=' . $subject_id . '&trimestre=' . $trimestre . '&academic_year=' . urlencode($academic_year));
    exit;
}

// ── Export template CSV (toutes classes) ──
if (isset($_GET['template']) && $subject_id && $schoolFilter) {
    verifyCsrf();
    $cl = $pdo->query("SELECT id, name, level FROM classes c ORDER BY " . getClassSortSQL('c'));
    $classes = $cl->fetchAll();
    $sb = $pdo->prepare("SELECT code, name FROM subjects WHERE id=?");
    $sb->execute([$subject_id]); $subj = $sb->fetch();
    $code = $subj['code'] ?: $subj['name'];
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=template_' . $code . '_T' . $trimestre . '.csv');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Niveau','Classe','N°','NOM & PRENOMS','SEXE','Interro','Devoir','Compo'], ';');
    $i = 1;
    foreach ($classes as $c) {
        $st = $pdo->prepare("SELECT id, first_name, last_name, gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
        $st->execute([$c['id']]);
        foreach ($st->fetchAll() as $s) {
            fputcsv($out, [$c['level']??'', $c['name'], $i++, $s['last_name'].' '.$s['first_name'], $s['gender']??'', '', '', ''], ';');
        }
    }
    fclose($out);
    exit;
}

// ── Export CSV (toutes classes) ──
if (isset($_GET['export']) && $subject_id && $schoolFilter) {
    verifyCsrf();
    $cl = $pdo->query("SELECT id, name, level FROM classes c ORDER BY " . getClassSortSQL('c'));
    $classes = $cl->fetchAll();
    $sb = $pdo->prepare("SELECT code, name FROM subjects WHERE id=?");
    $sb->execute([$subject_id]); $subj = $sb->fetch();
    $code = $subj['code'] ?: $subj['name'];
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $code . '_T' . $trimestre . '_' . $academic_year . '.csv');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Niveau','Classe','N°','NOM & PRENOMS','SEXE','Interro','Devoir','Compo'], ';');
    $i = 1;
    foreach ($classes as $c) {
        $st = $pdo->prepare("SELECT id, first_name, last_name, gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
        $st->execute([$c['id']]); $students = $st->fetchAll();
        $gr = $pdo->prepare("SELECT * FROM grades WHERE class_id=? AND trimestre=? AND academic_year=? AND subject_id=?");
        $gr->execute([$c['id'], $trimestre, $academic_year, $subject_id]); $grades = [];
        foreach ($gr->fetchAll() as $r) $grades[$r['student_id']] = $r;
        foreach ($students as $s) {
            $g = $grades[$s['id']] ?? [];
            fputcsv($out, [$c['level']??'', $c['name'], $i++, $s['last_name'].' '.$s['first_name'], $s['gender']??'', $g['note_interro']??'', $g['note_devoir']??'', $g['note_compo']??''], ';');
        }
    }
    fclose($out);
    exit;
}

// ── Import CSV (multi-classes) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_grades']) && $schoolFilter && $subject_id) {
    verifyCsrf();
    $periodCheck = checkGradingPeriod($pdo, $schoolFilter, $academic_year, $trimestre);
    if (!$periodCheck['allowed']) {
        $_SESSION['flash_toast'] = ['message' => 'Import bloqué : ' . $periodCheck['message'], 'type' => 'error'];
        header('Location: grades.php?subject_id=' . $subject_id); exit;
    }
    $allSt = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, c.name AS class_name FROM students s JOIN classes c ON s.class_id=c.id WHERE s.school_id=? ORDER BY c.name, s.last_name");
    $allSt->execute([$schoolFilter]);
    $studentMap = [];
    foreach ($allSt->fetchAll() as $s) $studentMap[strtolower($s['last_name'].' '.$s['first_name'].'|'.$s['class_name'])] = $s['id'];
    if (empty($_FILES['csv_file']['tmp_name'])) {
        $_SESSION['flash_toast'] = ['message' => 'Veuillez sélectionner un fichier CSV.', 'type' => 'error'];
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $header = fgetcsv($handle, 0, ';');
        if (!$header || count($header) < 3) {
            $_SESSION['flash_toast'] = ['message' => 'Format CSV invalide. Utilisez le séparateur ";"', 'type' => 'error'];
        } else {
            $pdo->beginTransaction();
            try {
                $rowNum = 0; $imported = 0; $errs = [];
                while (($row = fgetcsv($handle, 0, ';')) !== false) {
                    $rowNum++;
                    if (count($row) < 3) continue;
                    list($niv, $classe, $num, $nom, $sexe, $interro, $devoir, $compo) = array_pad($row, 8, '');
                    $nom = trim($nom); $classe = trim($classe);
                    if (empty($nom) || empty($classe)) continue;
                    $key = strtolower($nom.'|'.$classe);
                    $studentId = $studentMap[$key] ?? null;
                    if (!$studentId) { $errs[] = "Ligne $rowNum : '$nom' introuvable dans '$classe'"; continue; }
                    $clsSt = $pdo->prepare("SELECT class_id FROM students WHERE id=?");
                    $clsSt->execute([$studentId]); $stClassId = $clsSt->fetchColumn();
                    $ni = $interro !== '' ? (float)str_replace(',', '.', $interro) : null;
                    $nd = $devoir !== '' ? (float)str_replace(',', '.', $devoir) : null;
                    $nc = $compo !== '' ? (float)str_replace(',', '.', $compo) : null;
                    if ($ni !== null && ($ni < 0 || $ni > 20)) { $errs[] = "Ligne $rowNum : interro invalide"; continue; }
                    if ($nd !== null && ($nd < 0 || $nd > 20)) { $errs[] = "Ligne $rowNum : devoir invalide"; continue; }
                    if ($nc !== null && ($nc < 0 || $nc > 20)) { $errs[] = "Ligne $rowNum : compo invalide"; continue; }
                    $pdo->prepare("INSERT INTO grades (student_id,subject_id,class_id,school_id,trimestre,academic_year,note_interro,note_devoir,note_compo) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE note_interro=VALUES(note_interro),note_devoir=VALUES(note_devoir),note_compo=VALUES(note_compo)")
                        ->execute([$studentId, $subject_id, $stClassId, $schoolFilter, $trimestre, $academic_year, $ni, $nd, $nc]);
                    $imported++;
                }
                $pdo->commit();
                $msg = "$imported notes importées.";
                if (!empty($errs)) $msg .= ' ' . implode('. ', array_slice($errs, 0, 20));
                $_SESSION['flash_toast'] = ['message' => $msg, 'type' => 'success'];
            } catch (Exception $e) {
                $pdo->rollBack();
                $_SESSION['flash_toast'] = ['message' => 'Erreur import : ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        fclose($handle);
    }
    header('Location: grades.php?subject_id=' . $subject_id); exit;
}

// ── Sauvegarde des notes (multi-classes) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_grades'])) {
    verifyCsrf();
    $rows  = $_POST['grades']  ?? [];
    $apprs = $_POST['apprs']   ?? [];
    $saved = 0; $errors = [];
    $pdo->beginTransaction();
    $stmtInsert = $pdo->prepare("INSERT INTO grades (student_id,subject_id,class_id,school_id,trimestre,academic_year,note_interro,note_devoir,note_compo,appreciation) VALUES(?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE note_interro=VALUES(note_interro),note_devoir=VALUES(note_devoir),note_compo=VALUES(note_compo),appreciation=VALUES(appreciation)");
    $stmtUpdateMoy = $pdo->prepare("UPDATE grades SET moy_classe=? WHERE class_id=? AND subject_id=? AND trimestre=? AND academic_year=?");
    try {
        foreach ($rows as $class_id => $students) {
            $class_id = (int)$class_id;
            if (!$pdo->query("SELECT 1 FROM classes WHERE id=$class_id")->fetchColumn()) continue;
            $schoolId = $schoolFilter;
            if (!$schoolId) $schoolId = (int)$pdo->query("SELECT school_id FROM students WHERE class_id=$class_id LIMIT 1")->fetchColumn();
            $periodCheck = checkGradingPeriod($pdo, $schoolId, $academic_year, $trimestre);
            if (!$periodCheck['allowed']) continue;
            $validStudentIds = array_column($pdo->query("SELECT id FROM students WHERE class_id=$class_id")->fetchAll(), 'id');
            foreach ($students as $student_id => $subjects) {
                $student_id = (int)$student_id;
                if (!in_array($student_id, $validStudentIds, true)) continue;
                foreach ($subjects as $subj_id => $notes) {
                    $subj_id = (int)$subj_id;
                    $ni = $notes['interro'] !== '' ? (float)$notes['interro'] : null;
                    $nd = $notes['devoir']  !== '' ? (float)$notes['devoir']  : null;
                    $nc = $notes['compo']   !== '' ? (float)$notes['compo']   : null;
                    if (($ni !== null && ($ni < 0 || $ni > 20)) || ($nd !== null && ($nd < 0 || $nd > 20)) || ($nc !== null && ($nc < 0 || $nc > 20))) continue;
                    $ap = trim($apprs[$class_id][$student_id][$subj_id] ?? '');
                    $ap = $ap ?: autoAppreciation(calcMoyMatiere($ni, $nd, $nc));
                    $stmtInsert->execute([$student_id, $subj_id, $class_id, $schoolId, $trimestre, $academic_year, $ni, $nd, $nc, $ap]);
                    $saved++;
                }
            }
            // moy_classe
            $subjMoys = []; $subjCnts = [];
            foreach ($students as $student_id => $subjects) {
                foreach ($subjects as $subj_id => $notes) {
                    $m = calcMoyMatiere(
                        $notes['interro'] !== '' ? (float)$notes['interro'] : null,
                        $notes['devoir']  !== '' ? (float)$notes['devoir']  : null,
                        $notes['compo']   !== '' ? (float)$notes['compo']   : null
                    );
                    if ($m !== null) { $subjMoys[$subj_id] = ($subjMoys[$subj_id] ?? 0) + $m; $subjCnts[$subj_id] = ($subjCnts[$subj_id] ?? 0) + 1; }
                }
            }
            foreach ($subjMoys as $subj_id => $sum) {
                $stmtUpdateMoy->execute([round($sum / $subjCnts[$subj_id], 2), $class_id, $subj_id, $trimestre, $academic_year]);
            }
        }
        $pdo->commit();
        $msg = "$saved notes enregistrées.";
        if (!empty($errors)) $msg .= ' ' . implode('. ', $errors);
        $_SESSION['flash_toast'] = ['message' => $msg, 'type' => 'success'];
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['flash_toast'] = ['message' => 'Erreur : ' . $e->getMessage(), 'type' => 'error'];
    }
    header('Location: grades.php?subject_id=' . $subject_id . '&trimestre=' . $trimestre . '&academic_year=' . urlencode($academic_year));
    exit;
}

// ── Charger données ──
$allSchools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// Matières disponibles (filtrées par teacher si applicable)
$availableSubjects = [];
if ($schoolFilter) {
    if ($teacherId) {
        $sbSt = $pdo->prepare("SELECT DISTINCT s.id, s.name, s.code FROM subjects s JOIN teacher_assignments ta ON ta.subject_id=s.id AND ta.teacher_id=? ORDER BY s.name");
        $sbSt->execute([$teacherId]);
    } else {
        $sbSt = $pdo->query("SELECT s.id, s.name, s.code FROM subjects s ORDER BY s.name");
        $sbSt = $sbSt->fetchAll();
    }
    $availableSubjects = $sbSt->fetchAll();
}

// Enseignants disponibles
$availableTeachers = [];
if ($schoolFilter && !$teacherId) {
    $tSt = $pdo->prepare("SELECT t.id, t.first_name, t.last_name FROM teachers t WHERE t.school_id=? ORDER BY t.last_name, t.first_name");
    $tSt->execute([$schoolFilter]);
    $availableTeachers = $tSt->fetchAll();
}

// Classes groupées par niveau
$groupedClasses = [];
$allStudents = []; $allExistingGrades = [];

if ($schoolFilter && $subject_id && $academic_year) {
    $teacherJoin = ''; $params = [$subject_id];
    $effId = $teacherId ?: $teacher_filter;
    if ($effId) {
        $teacherJoin = " JOIN teacher_assignments ta ON ta.class_id=c.id AND ta.subject_id=? AND ta.teacher_id=?";
        $params[] = $subject_id; $params[] = $effId;
    }
    $clSt = $pdo->prepare("
        SELECT DISTINCT c.id, c.name, c.level
        FROM classes c
        JOIN class_subjects cs ON cs.class_id=c.id AND cs.subject_id=?
        $teacherJoin
        ORDER BY " . getClassSortSQL('c'));
    $clSt->execute($params);
    $allClasses = $clSt->fetchAll();
    foreach ($allClasses as $cl) {
        $level = $cl['level'] ?: 'Autres';
        $groupedClasses[$level][] = $cl;
    }
    if (!empty($allClasses)) {
        $cids = array_column($allClasses, 'id');
        $ph = implode(',', array_fill(0, count($cids), '?'));
        $stSt = $pdo->prepare("SELECT id, class_id, first_name, last_name FROM students WHERE class_id IN ($ph) ORDER BY last_name, first_name");
        $stSt->execute($cids);
        foreach ($stSt->fetchAll() as $s) $allStudents[$s['class_id']][] = $s;
        $grSt = $pdo->prepare("SELECT * FROM grades WHERE class_id IN ($ph) AND subject_id=? AND trimestre=? AND academic_year=?");
        $grSt->execute(array_merge($cids, [$subject_id, $trimestre, $academic_year]));
        foreach ($grSt->fetchAll() as $g) $allExistingGrades[$g['class_id']][$g['student_id']] = $g;
    }
}

$years = $pdo->prepare("SELECT DISTINCT year FROM academic_years WHERE school_id=? ORDER BY year DESC");
$years->execute([$schoolFilter ?: 0]);
$years = $years->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)]));

$__flash = $_SESSION['flash_toast'] ?? null;
unset($_SESSION['flash_toast']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Saisie 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; }
.header-section { display:flex; justify-content:space-between; align-items:center; margin-bottom:1.5rem; flex-wrap:wrap; gap:1rem; }
.header-section h1 { font-family:Georgia,serif; color:var(--primary); font-size:1.6rem; }
.header-section p { color:#666; font-size:.9rem; }
.filters-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.25rem 1.5rem; margin-bottom:1.5rem; }
.filters-row { display:flex; gap:1.25rem; align-items:flex-end; flex-wrap:wrap; }
.filter-group { display:flex; flex-direction:column; gap:6px; flex:1; min-width:150px; }
.filter-group label { font-weight:600; color:var(--primary); font-size:.8rem; }
.filter-group select { padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; cursor:pointer; }
.filter-group select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.table-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); overflow:hidden; margin-bottom:1.5rem; }
.table-card .tc-header { padding:1rem 1.5rem; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; }
.table-card .tc-title { font-family:Georgia,serif; color:var(--primary); font-size:1.05rem; }
.prog-table { width:100%; border-collapse:collapse; }
.prog-table thead { background:var(--primary); color:white; }
.prog-table th { padding:.6rem .8rem; text-align:left; font-weight:600; font-size:.74rem; text-transform:uppercase; letter-spacing:.4px; white-space:nowrap; }
.prog-table td { padding:.55rem .8rem; border-bottom:1px solid #E5E7EB; font-size:.82rem; vertical-align:middle; }
.prog-table tbody tr:hover { background:#F9FAFB; }
.grade-input { width:56px; padding:.3rem .3rem; border:1px solid #D1D5DB; border-radius:4px; text-align:center; font-size:.82rem; }
.grade-input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 2px rgba(46,117,182,0.12); }
.appr-select { padding:.25rem .35rem; border:1px solid #D1D5DB; border-radius:4px; font-size:.75rem; background:white; }
.btn { display:inline-flex; align-items:center; gap:6px; padding:.5rem 1.1rem; border:none; border-radius:6px; font-size:.82rem; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; }
.btn-primary { background:var(--primary); color:white; }
.btn-primary:hover { background:#163a5c; }
.btn-light { background:#E5E7EB; color:#374151; }
.btn-light:hover { background:#D1D5DB; }
.btn-success { background:#10B981; color:white; }
.btn-success:hover { background:#059669; }
.btn-warning { background:#F59E0B; color:white; }
.level-accordion { border:1px solid #E5E7EB; border-radius:8px; margin-bottom:.85rem; overflow:hidden; }
.level-header { display:flex; align-items:center; gap:.75rem; padding:.7rem 1.1rem; background:#F3F6FA; cursor:pointer; border-bottom:1px solid #E5E7EB; user-select:none; }
.level-header:hover { background:#E8EDF4; }
.level-header .level-icon { width:30px; height:30px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:.8rem; font-weight:700; flex-shrink:0; }
.level-header .level-name { font-weight:700; color:var(--primary); font-size:.9rem; flex:1; }
.level-header .level-count { color:#718096; font-size:.76rem; }
.level-header .level-arrow { color:#9CA3AF; transition:transform .2s; }
.level-header.collapsed .level-arrow { transform:rotate(-90deg); }
.level-body { transition:max-height .3s ease; overflow:hidden; }
.level-body.collapsed { max-height:0 !important; }
.class-card { border-bottom:1px solid #E5E7EB; }
.class-card:last-child { border-bottom:none; }
.class-header { display:flex; align-items:center; gap:.5rem; padding:.55rem 1.1rem; background:white; cursor:pointer; font-size:.83rem; }
.class-header:hover { background:#FAFBFC; }
.class-header .class-name { font-weight:600; color:#374151; flex:1; }
.class-header .class-arrow { color:#9CA3AF; font-size:.75rem; transition:transform .2s; }
.class-header.collapsed .class-arrow { transform:rotate(-90deg); }
.class-body { overflow:hidden; transition:max-height .3s ease; }
.class-body.collapsed { max-height:0 !important; }
.toast-container { position:fixed; bottom:30px; right:30px; z-index:2000; display:flex; flex-direction:column; gap:10px; }
.toast { background:white; padding:12px 18px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.15); display:flex; align-items:center; gap:10px; animation:slideIn .3s ease; border-left:4px solid var(--primary); font-size:.9rem; }
.toast-success { border-left-color:#10B981; }
.toast-error { border-left-color:#EF4444; }
@keyframes slideIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
.modal-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.4); z-index:1500; align-items:center; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:white; border-radius:12px; padding:2rem; width:90%; max-width:480px; max-height:90vh; overflow-y:auto; box-shadow:0 10px 40px rgba(0,0,0,0.2); }
.modal-box h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.15rem; margin-bottom:1.25rem; display:flex; align-items:center; gap:.5rem; }
.modal-box .modal-actions { display:flex; gap:.75rem; margin-top:1.25rem; justify-content:flex-end; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.toolbar { display:flex; gap:.75rem; margin-bottom:1rem; flex-wrap:wrap; align-items:center; }
.level-colors { --l6:#3B82F6; --l5:#10B981; --l4:#F59E0B; --l3:#EF4444; }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .toolbar { flex-direction:column; align-items:stretch; }
  .modal-box { padding:1.25rem; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-pen-alt"></i> Saisie des notes'; include '../includes/topbar.php'; ?>

        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>

        <!-- ═══ Header ═══ -->
        <div class="header-section">
            <div>
                <h1><i class="fas fa-pen-alt" style="color:var(--primary);"></i> Saisie des notes</h1>
                <p>Saisissez les notes par niveau, classe et mati�?re</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <?php if ($schoolFilter && $subject_id): ?>
                <a href="?subject_id=<?= $subject_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&export=1&csrf_token=<?= csrfToken() ?>" class="btn btn-success" style="font-size:.76rem;padding:.4rem .9rem;">
                    <i class="fas fa-download"></i> Export CSV
                </a>
                <button onclick="openImportModal()" class="btn btn-warning" style="font-size:.76rem;padding:.4rem .9rem;color:white;">
                    <i class="fas fa-upload"></i> Import CSV
                </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="GET" class="filters-card" id="filterForm">
            <div class="filters-row">
                <?php if (!$schoolFilter): ?>
                <div class="filter-group">
                    <label><i class="fas fa-school"></i> �?cole</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($allSchools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= (($_GET['school_id']??$sessionSchool)==$sc['id'])?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="filter-group">
                    <label><i class="fas fa-calendar"></i> Ann�?e scolaire</label>
                    <select name="academic_year" onchange="this.form.submit()">
                        <?php foreach ($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$academic_year?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-layer-group"></i> P�?riode</label>
                    <select name="trimestre" 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="filter-group">
                    <label><i class="fas fa-chalkboard-teacher"></i> Enseignant</label>
                    <select name="teacher_filter" onchange="this.form.submit()">
                        <option value="">-- Tous --</option>
                        <?php foreach ($availableTeachers as $t): ?>
                        <option value="<?= $t['id'] ?>" <?= $teacher_filter===(int)$t['id']?'selected':'' ?>><?= e($t['last_name'].' '.$t['first_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-book"></i> Mati�?re <span style="color:red;">*</span></label>
                    <select name="subject_id" required onchange="this.form.submit()">
                        <option value="">-- Choisir --</option>
                        <?php foreach ($availableSubjects as $sb): ?>
                        <option value="<?= $sb['id'] ?>" <?= $subject_id===(int)$sb['id']?'selected':'' ?>><?= e($sb['code']?:$sb['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </form>

        <?php if (!$subject_id): ?>
        <div class="table-card">
            <div class="empty-state">
                <i class="fas fa-hand-pointer" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">S�?lectionnez une mati�?re pour commencer la saisie.</p>
                <p style="font-size:.85rem;color:#B0BEC5;margin-top:.3rem;">Les notes seront organis�?es par niveau et par classe.</p>
            </div>
        </div>
        <?php elseif (empty($groupedClasses)): ?>
        <div class="table-card">
            <div class="empty-state">
                <i class="fas fa-exclamation-triangle" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p>Aucune classe trouv�?e pour cette mati�?re.</p>
            </div>
        </div>
        <?php else:
            $periodCheck = checkGradingPeriod($pdo, $schoolFilter, $academic_year, $trimestre);
            $totalStudents = array_sum(array_map('count', $allStudents));
        ?>
        <!-- ═══ P�?riode info ═══ -->
        <div style="display:flex;align-items:center;gap:.75rem;padding:.55rem 1rem;margin-bottom:1rem;font-size:.8rem;border-radius:8px;<?= $periodCheck['allowed']?'background:#F0FFF4;border:1px solid #C6F6D5;':'background:#FFF5F5;border:1px solid #FED7D7;' ?>">
            <i class="fas fa-<?= $periodCheck['allowed']?'check-circle':'exclamation-circle' ?>" style="color:<?= $periodCheck['allowed']?'#38A169':'#E53E3E' ?>;"></i>
            <span style="flex:1;">
                <?php if ($periodCheck['period']): ?>
                <strong><?= e($periodCheck['period']['label']) ?></strong> — du <?= formatDate($periodCheck['period']['start_date']) ?> au <?= formatDate($periodCheck['period']['end_date']) ?>
                <?php else: ?>
                <span style="color:#856404;">Aucune p�?riode d�?finie — saisie libre.</span>
                <?php endif; ?>
            </span>
            <span style="font-weight:600;color:<?= $periodCheck['allowed']?'#22543D':'#9B2C2C' ?>;">
                <i class="fas fa-<?= $periodCheck['allowed']?'lock-open':'lock' ?>"></i>
                <?= $periodCheck['allowed']?'Saisie autoris�?e':'Saisie ferm�?e' ?>
            </span>
        </div>

        <!-- ═══ Toolbar ═══ -->
        <div class="toolbar">
            <span style="font-size:.83rem;color:#4B5563;">
                <i class="fas fa-users"></i>
                <strong><?= count($groupedClasses) ?> niveau(x)</strong> —
                <strong><?= array_sum(array_map('count',$groupedClasses)) ?> classe(s)</strong> —
                <strong><?= $totalStudents ?> �?l�?ve(s)</strong>
            </span>
            <div style="flex:1;"></div>
            <button type="button" class="btn btn-light" onclick="expandAll()" style="font-size:.76rem;padding:.35rem .8rem;"><i class="fas fa-expand-alt"></i> Tout d�?plier</button>
            <button type="button" class="btn btn-light" onclick="collapseAll()" style="font-size:.76rem;padding:.35rem .8rem;"><i class="fas fa-compress-alt"></i> Tout replier</button>
            <button type="submit" form="gradesForm" class="btn btn-primary" style="padding:.5rem 1.5rem;"><i class="fas fa-save"></i> Enregistrer</button>
        </div>

        <!-- ═══ Formulaire ═══ -->
        <form method="POST" id="gradesForm">
            <?= csrfField() ?>
            <input type="hidden" name="save_grades" value="1">
            <input type="hidden" name="trimestre" value="<?= $trimestre ?>">
            <input type="hidden" name="academic_year" value="<?= e($academic_year) ?>">

            <?php
            $levelColors = ['6ème'=>'#3B82F6','5ème'=>'#10B981','4ème'=>'#F59E0B','3ème'=>'#EF4444','2nde'=>'#8B5CF6','1ère'=>'#EC4899','Tle'=>'#6366F1'];
            foreach ($groupedClasses as $level => $classes):
                $lc = $levelColors[$level] ?? '#1F4E79';
            ?>
            <div class="level-accordion">
                <div class="level-header" onclick="toggleLevel(this)">
                    <div class="level-icon" style="background:<?= $lc ?>;"><?= e(mb_substr($level,0,2)) ?></div>
                    <span class="level-name"><?= e($level) ?></span>
                    <span class="level-count"><?= count($classes) ?> classe(s) — <?= array_sum(array_map(fn($c)=>count($allStudents[$c['id']]??[]),$classes)) ?> �?l�?ve(s)</span>
                    <span class="level-arrow"><i class="fas fa-chevron-down"></i></span>
                </div>
                <div class="level-body">
                    <?php foreach ($classes as $cl):
                        $students = $allStudents[$cl['id']] ?? [];
                    ?>
                    <div class="class-card">
                        <div class="class-header" onclick="toggleClass(this)">
                            <span class="class-name"><i class="fas fa-users" style="color:var(--accent);"></i> <?= e($cl['name']) ?></span>
                            <span style="color:#718096;font-size:.75rem;"><?= count($students) ?> �?l�?ve(s)</span>
                            <span class="class-arrow"><i class="fas fa-chevron-down"></i></span>
                        </div>
                        <div class="class-body">
                            <?php if (empty($students)): ?>
                            <div style="padding:1.25rem;text-align:center;color:#9CA3AF;font-size:.82rem;">Aucun �?l�?ve dans cette classe.</div>
                            <?php else: ?>
                            <div style="overflow-x:auto;">
                            <table class="prog-table" style="font-size:.8rem;">
                                <thead>
                                    <tr>
                                        <th style="width:32px;text-align:center;">N°</th>
                                        <th style="min-width:160px;">�?l�?ve</th>
                                        <th style="text-align:center;width:76px;">Interro <small>(×1)</small></th>
                                        <th style="text-align:center;width:76px;">Devoir <small>(×2)</small></th>
                                        <th style="text-align:center;width:76px;">Compo <small>(×3)</small></th>
                                        <th style="text-align:center;width:54px;">Moy.</th>
                                        <th style="min-width:120px;">Appr�?ciation</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $i=1; foreach ($students as $st):
                                        $g = $allExistingGrades[$cl['id']][$st['id']] ?? [];
                                        $ni = $g['note_interro']??null; $nd = $g['note_devoir']??null; $nc = $g['note_compo']??null;
                                        $moy = calcMoyMatiere($ni, $nd, $nc);
                                        $autoAp = autoAppreciation($moy);
                                        if ($moy===null) { $abg='#E2E8F0'; $afg='#A0AEC0'; }
                                        elseif ($moy>=18) { $abg='#805AD5'; $afg='white'; }
                                        elseif ($moy>=16) { $abg='#2B6CB0'; $afg='white'; }
                                        elseif ($moy>=14) { $abg='#38A169'; $afg='white'; }
                                        elseif ($moy>=12) { $abg='#D69E2E'; $afg='white'; }
                                        elseif ($moy>=10) { $abg='#ED8936'; $afg='white'; }
                                        elseif ($moy>=6) { $abg='#E53E3E'; $afg='white'; }
                                        else { $abg='#9B2C2C'; $afg='white'; }
                                    ?>
                                    <tr>
                                        <td style="text-align:center;color:#718096;"><?= $i++ ?></td>
                                        <td><?= e($st['last_name'].' '.$st['first_name']) ?></td>
                                        <td><input type="number" name="grades[<?= $cl['id'] ?>][<?= $st['id'] ?>][<?= $subject_id ?>][interro]" value="<?= e($ni??'') ?>" min="0" max="20" step="0.25" class="grade-input" data-class="<?= $cl['id'] ?>" data-student="<?= $st['id'] ?>"></td>
                                        <td><input type="number" name="grades[<?= $cl['id'] ?>][<?= $st['id'] ?>][<?= $subject_id ?>][devoir]" value="<?= e($nd??'') ?>" min="0" max="20" step="0.25" class="grade-input" data-class="<?= $cl['id'] ?>" data-student="<?= $st['id'] ?>"></td>
                                        <td><input type="number" name="grades[<?= $cl['id'] ?>][<?= $st['id'] ?>][<?= $subject_id ?>][compo]" value="<?= e($nc??'') ?>" min="0" max="20" step="0.25" class="grade-input" data-class="<?= $cl['id'] ?>" data-student="<?= $st['id'] ?>"></td>
                                        <td style="text-align:center;font-weight:600;font-size:.85rem;color:<?= $moy!==null?($moy>=10?'#22543D':'#C53030'):'#A0AEC0' ?>;"><?= $moy!==null?e($moy):'—' ?></td>
                                        <td>
                                            <div style="display:flex;gap:.3rem;align-items:center;">
                                                <span style="display:inline-block;padding:.1rem .4rem;border-radius:4px;font-size:.68rem;font-weight:700;white-space:nowrap;background:<?= $abg ?>;color:<?= $afg ?>;"><?= $autoAp?:'—' ?></span>
                                                <select name="apprs[<?= $cl['id'] ?>][<?= $st['id'] ?>][<?= $subject_id ?>]" class="appr-select" style="flex:1;min-width:70px;">
                                                    <option value="">Auto</option>
                                                    <?php foreach(['Excellent','Très Bien','Bien','Assez Bien','Passable','A Peine Passable','Insuffisant','Très Insuffisant','Blâme'] as $ap): ?>
                                                    <option value="<?= $ap ?>" <?= (!empty($g['appreciation'])&&$g['appreciation']===$ap)?'selected':'' ?>><?= $ap ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>

            <div style="text-align:right;margin-top:1.25rem;">
                <button type="submit" class="btn btn-primary" style="padding:.7rem 2.25rem;font-size:.95rem;"><i class="fas fa-save"></i> Enregistrer toutes les notes</button>
            </div>
        </form>

        <!-- ═══ Classement général ═══ -->
        <?php
        $rankSubj = $pdo->query("SELECT DISTINCT s.id, s.name, s.code, COALESCE(cs.coefficient,1) AS coeff FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id IN (SELECT id FROM classes) ORDER BY s.name")->fetchAll();
        $rankAll = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, c.name AS cname, c.level FROM students s JOIN classes c ON s.class_id=c.id WHERE s.school_id=? ORDER BY c.level, s.last_name");
        $rankAll->execute([$schoolFilter]); $rankAll = $rankAll->fetchAll();
        $rankG = []; $rgSt = $pdo->prepare("SELECT g.*, s2.class_id FROM grades g JOIN students s2 ON g.student_id=s2.id WHERE s2.school_id=? AND g.trimestre=? AND g.academic_year=?");
        $rgSt->execute([$schoolFilter, $trimestre, $academic_year]);
        foreach ($rgSt->fetchAll() as $r) $rankG[$r['student_id']][$r['subject_id']] = $r;
        $rd = [];
        foreach ($rankAll as $st) {
            $tp=0; $tc=0;
            foreach ($rankSubj as $rs) {
                $rg = $rankG[$st['id']][$rs['id']] ?? [];
                $m = calcMoyMatiere($rg['note_interro']??null, $rg['note_devoir']??null, $rg['note_compo']??null);
                if ($m!==null) { $tp+=$m*(float)$rs['coeff']; $tc+=(float)$rs['coeff']; }
            }
            $mg = $tc>0 ? round($tp/$tc,2) : null;
            $rd[] = ['id'=>$st['id'], 'name'=>$st['last_name'].' '.$st['first_name'], 'class'=>$st['cname'], 'level'=>$st['level'], 'moy'=>$mg];
        }
        usort($rd, fn($a,$b)=>($b['moy']??-1)<=>($a['moy']??-1));
        $r=1; $pm=null; $sk=0;
        foreach ($rd as &$d) {
            if ($d['moy']===null) { $d['rank']=null; continue; }
            if ($pm!==null && $d['moy']<$pm) { $r+=$sk; $sk=0; }
            elseif ($pm!==null && $d['moy']===$pm) $sk++;
            else $sk=0;
            $d['rank']=$r; $pm=$d['moy']; $sk++;
        }
        unset($d);
        ?>
        <?php if (!empty($rd)): ?>
        <div class="table-card" style="margin-top:1.5rem;border-left:4px solid var(--accent);">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-trophy"></i> Classement g�?n�?ral</div>
                <span style="font-size:.8rem;color:#718096;">Toutes mati�?res confondues — 50 premiers</span>
            </div>
            <div style="overflow-x:auto;">
            <table class="prog-table" style="font-size:.78rem;">
                <thead><tr>
                    <th style="text-align:center;width:36px;">Rang</th><th>�?l�?ve</th><th>Niv.</th><th>Classe</th>
                    <?php foreach ($rankSubj as $rs): ?>
                    <th style="text-align:center;" title="<?= e($rs['name']) ?>"><?= e($rs['code']?:$rs['name']) ?></th>
                    <?php endforeach; ?>
                    <th style="text-align:center;min-width:70px;">Moy.G�?n.</th><th style="text-align:center;">Mention</th>
                </tr></thead>
                <tbody>
                    <?php foreach (array_slice($rd,0,50) as $d):
                        $mc = $d['moy']!==null ? ($d['moy']>=16?'#22543D':($d['moy']>=12?'#2B6CB0':($d['moy']>=10?'#975A16':'#C53030'))) : '#A0AEC0';
                    ?>
                    <tr>
                        <td style="text-align:center;font-weight:700;"><?= $d['rank']!==null ? $d['rank'] : '—' ?></td>
                        <td><?= e($d['name']) ?></td>
                        <td><?= e($d['level']??'—') ?></td>
                        <td><?= e($d['class']??'—') ?></td>
                        <?php foreach ($rankSubj as $rs):
                            $rg = $rankG[$d['id']][$rs['id']] ?? [];
                            $sm = calcMoyMatiere($rg['note_interro']??null, $rg['note_devoir']??null, $rg['note_compo']??null);
                        ?>
                        <td style="text-align:center;color:<?= $sm!==null?($sm>=10?'#22543D':'#C53030'):'#CCC' ?>;"><?= $sm!==null?$sm:'—' ?></td>
                        <?php endforeach; ?>
                        <td style="text-align:center;font-weight:700;color:<?= $mc ?>;"><?= $d['moy']!==null?$d['moy']:'—' ?></td>
                        <td style="text-align:center;color:<?= $mc ?>;"><?= $d['moy']!==null?autoAppreciation($d['moy']):'—' ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ Modal Import CSV ═══ -->
<div class="modal-overlay" id="importModal">
    <div class="modal-box">
        <h2><i class="fas fa-upload"></i> Importer des notes (CSV)</h2>
        <form method="POST" enctype="multipart/form-data">
            <?= csrfField() ?>
            <input type="hidden" name="import_grades" value="1">
            <div style="background:#EBF8FF;border:1px solid #BEE3F8;border-radius:8px;padding:1rem;margin-bottom:1.25rem;font-size:.8rem;">
                <strong><i class="fas fa-info-circle"></i> Format attendu (s�?parateur ;)</strong><br>
                <code style="font-size:.72rem;">Niveau;Classe;N°;NOM & PRENOMS;SEXE;Interro;Devoir;Compo</code><br>
                <small>Notes entre 0 et 20.</small><br>
                <a href="?subject_id=<?= $subject_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&template=1&csrf_token=<?= csrfToken() ?>" style="display:inline-flex;align-items:center;gap:.35rem;margin-top:.5rem;color:#2563EB;font-size:.78rem;"><i class="fas fa-download"></i> T�?l�?charger le mod�?le vierge</a>
            </div>
            <div style="margin-bottom:1rem;">
                <label style="font-weight:600;font-size:.8rem;color:var(--primary);">Fichier CSV <span style="color:red;">*</span></label>
                <input type="file" name="csv_file" accept=".csv" required style="width:100%;padding:.5rem;border:1px solid #D1D5DB;border-radius:6px;">
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-light" onclick="closeImportModal()">Annuler</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-upload"></i> Importer</button>
            </div>
        </form>
    </div>
</div>

<!-- ═══ Toast Container ═══ -->
<div class="toast-container" id="toastContainer"></div>

<script>
function toggleLevel(h) { h.classList.toggle('collapsed'); var b=h.nextElementSibling; b.classList.toggle('collapsed'); if(!b.classList.contains('collapsed')) b.style.maxHeight=b.scrollHeight+'px'; else b.style.maxHeight='0'; }
function toggleClass(h) { h.classList.toggle('collapsed'); var b=h.nextElementSibling; b.classList.toggle('collapsed'); if(!b.classList.contains('collapsed')) b.style.maxHeight=b.scrollHeight+'px'; else b.style.maxHeight='0'; }
function expandAll() { document.querySelectorAll('.level-body.collapsed,.class-body.collapsed').forEach(function(e){e.classList.remove('collapsed');e.style.maxHeight=e.scrollHeight+'px';}); document.querySelectorAll('.level-header.collapsed,.class-header.collapsed').forEach(function(e){e.classList.remove('collapsed');}); }
function collapseAll() { document.querySelectorAll('.level-body:not(.collapsed),.class-body:not(.collapsed)').forEach(function(e){e.classList.add('collapsed');e.style.maxHeight='0';}); document.querySelectorAll('.level-header:not(.collapsed),.class-header:not(.collapsed)').forEach(function(e){e.classList.add('collapsed');}); }
document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.level-body').forEach(function(e){e.style.maxHeight=e.scrollHeight+'px';});});
function openImportModal(){document.getElementById('importModal').classList.add('open');}
function closeImportModal(){document.getElementById('importModal').classList.remove('open');}
document.getElementById('importModal')?.addEventListener('click',function(e){if(e.target===this)closeImportModal();});
function showToast(msg,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type==='success'?'success':'error');t.innerHTML='<span>'+(type==='success'?'&#x2705;':'&#x274C;')+'</span><span>'+msg+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
</script>
</body>
</html>
