<?php
session_start();
// AJAX handlers run before any HTML to keep JSON response clean
if (isset($_POST['ajax_delete']) || isset($_POST['ajax_update']) || isset($_POST['ajax_delete_all'])) {
    error_reporting(0);
    include '_serveur_json1.php';
    $teacherUserID = intval(
        $_SESSION['id'] ??
        $_SESSION['userID'] ??
        $_SESSION['user_id'] ??
        $_SESSION['userId'] ?? 0
    );
    function _teacherOwns($link, $uid, $ssid, $cid) {
        $q = 'SELECT COUNT(*) FROM teachersSubsubjects WHERE userID="' . intval($uid)
           . '" AND subsubjectID="' . intval($ssid)
           . '" AND classID="'     . intval($cid)  . '"';
        $r = mysqli_query($link, $q);
        if (!$r) return false;
        $row = mysqli_fetch_row($r);
        return $row[0] > 0;
    }
    header('Content-Type: application/json');

    if (isset($_POST['ajax_delete'])) {
        $gid  = intval($_POST['grade_id']);
        $ssid = intval($_POST['sub_subject_id']);
        $cid  = intval($_POST['class_id']);
        if (!_teacherOwns($link, $teacherUserID, $ssid, $cid)) {
            echo json_encode(['ok' => false, 'msg' => 'Acces refuse']); exit;
        }
        $ok = mysqli_query($link, 'DELETE FROM grades WHERE id="' . $gid . '"');
        echo json_encode(['ok' => (bool)$ok]); exit;
    }

    if (isset($_POST['ajax_delete_all'])) {
        $ssid = intval($_POST['sub_subject_id']);
        $cid  = intval($_POST['class_id']);
        $sid  = intval($_POST['semester_id']);
        if (!_teacherOwns($link, $teacherUserID, $ssid, $cid)) {
            echo json_encode(['ok' => false, 'msg' => 'Acces refuse']); exit;
        }
        $ok = mysqli_query($link,
            'DELETE FROM grades WHERE classID="' . $cid
            . '" AND subSubjectID="' . $ssid
            . '" AND semesterID="'  . $sid . '"');
        echo json_encode(['ok' => (bool)$ok, 'deleted' => mysqli_affected_rows($link)]); exit;
    }

    if (isset($_POST['ajax_update'])) {
        $gid  = intval($_POST['grade_id']);
        $nv   = floatval($_POST['new_grade']);
        $coef = floatval($_POST['coef']);
        $ssid = intval($_POST['sub_subject_id']);
        $cid  = intval($_POST['class_id']);
        if (!_teacherOwns($link, $teacherUserID, $ssid, $cid)) {
            echo json_encode(['ok' => false, 'msg' => 'Acces refuse']); exit;
        }
        // -1 means absent — allowed; otherwise 0..coef
        if ($nv != -1.0 && ($nv < 0 || $nv > $coef)) {
            echo json_encode(['ok' => false, 'msg' => 'Valeur hors limites']); exit;
        }
        $ok = mysqli_query($link, 'UPDATE grades SET grade="' . $nv . '" WHERE id="' . $gid . '"');
        echo json_encode(['ok' => (bool)$ok]); exit;
    }
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<title>Saisie des Notes — Enseignant</title>
<link rel="stylesheet" href="w3.css">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
  :root {
    --bg:            #f0f4f8;
    --surface:       #ffffff;
    --primary:       #1a56db;
    --primary-light: #e8eeff;
    --accent:        #0e9f6e;
    --danger:        #e02424;
    --warn:          #e3a008;
    --text:          #111928;
    --muted:         #6b7280;
    --border:        #e5e7eb;
    --radius:        12px;
    --shadow:        0 2px 12px rgba(0,0,0,.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'DM Sans', sans-serif;
    background: var(--bg);
    color: var(--text);
    min-height: 100vh;
  }

  .page-header {
    background: linear-gradient(135deg, #1a56db 0%, #0e9f6e 100%);
    padding: 18px 32px;
    display: flex; align-items: center; gap: 14px;
    box-shadow: 0 2px 16px rgba(26,86,219,.25);
  }
  .page-header h1 { color:#fff; font-size:1.3rem; font-weight:600; letter-spacing:-.3px; }
  .page-header .icon {
    width:38px; height:38px;
    background:rgba(255,255,255,.2); border-radius:10px;
    display:flex; align-items:center; justify-content:center; font-size:1.2rem;
  }

  .container { max-width:980px; margin:32px auto; padding:0 20px 80px; }

  .card {
    background:var(--surface); border-radius:var(--radius);
    box-shadow:var(--shadow); padding:28px 32px;
    margin-bottom:24px; border:1px solid var(--border);
  }
  .card-title {
    font-size:.7rem; font-weight:700; letter-spacing:1.2px;
    text-transform:uppercase; color:var(--primary);
    margin-bottom:18px; display:flex; align-items:center; gap:8px;
  }
  .card-title::after { content:''; flex:1; height:1px; background:var(--border); }

  .form-grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; align-items:end; }
  @media(max-width:640px){ .form-grid{grid-template-columns:1fr;} }

  .field label {
    display:block; font-size:.8rem; font-weight:600;
    color:var(--muted); margin-bottom:6px; letter-spacing:.3px;
  }
  .field select {
    width:100%; padding:10px 14px;
    border:1.5px solid var(--border); border-radius:8px;
    font-family:'DM Sans',sans-serif; font-size:.9rem;
    color:var(--text); background:#fafafa;
    appearance:none;
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='%236b7280' d='M6 8L0 0h12z'/%3E%3C/svg%3E");
    background-repeat:no-repeat; background-position:right 14px center;
    transition:border-color .2s;
  }
  .field select:focus { outline:none; border-color:var(--primary); background-color:var(--primary-light); }

  .btn {
    display:inline-flex; align-items:center; gap:7px;
    padding:9px 20px; border:none; border-radius:8px;
    font-family:'DM Sans',sans-serif; font-size:.88rem; font-weight:600;
    cursor:pointer; transition:all .18s ease; white-space:nowrap;
  }
  .btn-primary { background:var(--primary); color:#fff; }
  .btn-primary:hover { background:#1648c0; transform:translateY(-1px); box-shadow:0 4px 14px rgba(26,86,219,.35); }
  .btn-success { background:var(--accent); color:#fff; }
  .btn-success:hover { background:#0a8a5e; transform:translateY(-1px); box-shadow:0 4px 14px rgba(14,159,110,.35); }
  .btn-danger  { background:var(--danger); color:#fff; }
  .btn-danger:hover  { background:#c31c1c; transform:translateY(-1px); box-shadow:0 4px 14px rgba(224,36,36,.35); }
  .btn-warn    { background:var(--warn); color:#fff; }
  .btn-warn:hover    { background:#c48900; transform:translateY(-1px); }
  .btn-ghost   { background:transparent; color:var(--muted); border:1.5px solid var(--border); }
  .btn-ghost:hover   { border-color:var(--primary); color:var(--primary); }
  .btn-sm { padding:5px 13px; font-size:.78rem; border-radius:6px; gap:5px; }
  .btn:disabled { opacity:.55; cursor:not-allowed; transform:none !important; box-shadow:none !important; }

  .mode-tabs { display:flex; gap:10px; margin-bottom:22px; flex-wrap:wrap; }
  .mode-tab {
    padding:9px 22px; border-radius:999px; font-weight:600; font-size:.85rem;
    cursor:pointer; border:1.5px solid var(--border); background:#fafafa; color:var(--muted);
    transition:all .2s; user-select:none;
  }
  .mode-tab.active-edit   { background:var(--warn);   color:#fff; border-color:var(--warn);   }
  .mode-tab.active-delete { background:var(--danger);  color:#fff; border-color:var(--danger);  }

  .info-badge {
    display:inline-flex; align-items:center; gap:8px;
    background:linear-gradient(90deg,var(--primary-light),#e8f8f3);
    border:1px solid #c3ddfd; border-radius:999px;
    padding:7px 18px; font-weight:600; font-size:.92rem; color:var(--primary);
    margin-bottom:22px;
  }

  .grades-table { width:100%; border-collapse:collapse; font-size:.9rem; }
  .grades-table th {
    background:var(--primary); color:#fff;
    padding:11px 16px; text-align:left;
    font-weight:600; font-size:.78rem; letter-spacing:.5px; text-transform:uppercase;
  }
  .grades-table th:first-child { border-radius:8px 0 0 0; }
  .grades-table th:last-child  { border-radius:0 8px 0 0; }
  .grades-table td {
    padding:9px 16px; border-bottom:1px solid var(--border); vertical-align:middle;
  }
  .grades-table tr:last-child td { border-bottom:none; }
  .grades-table tbody tr:hover   { background:#f8faff; }
  .grades-table .num { font-family:'DM Mono',monospace; color:var(--muted); font-size:.8rem; width:38px; }
  .grades-table .name { font-weight:500; }

  .coef-badge {
    display:inline-block; background:var(--primary-light); color:var(--primary);
    border-radius:6px; padding:2px 10px;
    font-family:'DM Mono',monospace; font-size:.82rem; font-weight:600;
  }

  .grade-display {
    display:inline-block; min-width:54px; text-align:center;
    font-family:'DM Mono',monospace; font-size:1rem; font-weight:700;
    padding:4px 12px; border-radius:7px;
  }
  .grade-display.ok   { background:#f0fdf4; color:var(--accent); border:1.5px solid #86efac; }
  .grade-display.fail { background:#fef2f2; color:var(--danger); border:1.5px solid #fca5a5; }
  .grade-display.none { background:#f3f4f6; color:var(--muted);  border:1.5px solid var(--border); font-style:italic; }
  .grade-display.absent { background:#fef9c3; color:#854d0e; border:1.5px solid #fde047; }
  .grade-input.absent { border-color:#854d0e; background:#fef9c3; color:#854d0e; }

  .grade-input {
    width:90px; padding:7px 10px;
    border:1.5px solid var(--border); border-radius:7px;
    font-family:'DM Mono',monospace; font-size:1rem; font-weight:600;
    color:var(--text); text-align:center; transition:all .18s;
  }
  .grade-input:focus { outline:none; border-color:var(--primary); background:var(--primary-light); }
  .grade-input.ok   { border-color:var(--accent); background:#f0fdf4; color:var(--accent); }
  .grade-input.fail { border-color:var(--danger); background:#fef2f2; color:var(--danger); }
  .grade-input.warn { border-color:var(--warn);   background:#fffbeb; color:var(--warn); }
  .grade-input:disabled { background:#f3f4f6; color:var(--muted); cursor:not-allowed; border-style:dashed; }

  .stats-panel { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; margin-bottom:24px; }
  @media(max-width:640px){ .stats-panel{grid-template-columns:1fr 1fr;} }

  .stat-card {
    background:var(--surface); border:1.5px solid var(--border);
    border-radius:var(--radius); padding:18px 20px; text-align:center;
    transition:transform .15s;
  }
  .stat-card:hover { transform:translateY(-2px); }
  .stat-card .val { font-family:'DM Mono',monospace; font-size:2rem; font-weight:700; line-height:1; margin-bottom:4px; }
  .stat-card .lbl { font-size:.75rem; font-weight:600; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; }
  .stat-avg  .val { color:var(--primary); }
  .stat-pass .val { color:var(--accent); }
  .stat-fail .val { color:var(--danger); }
  .stat-tot  .val { color:var(--text); }

  .progress-wrap { margin-bottom:6px; }
  .progress-label { display:flex; justify-content:space-between; font-size:.78rem; color:var(--muted); margin-bottom:4px; }
  .progress-bar { height:8px; border-radius:99px; background:var(--border); overflow:hidden; }
  .progress-fill { height:100%; border-radius:99px; background:linear-gradient(90deg,var(--accent),var(--primary)); transition:width .4s cubic-bezier(.4,0,.2,1); }

  .alert { padding:14px 18px; border-radius:8px; font-weight:500; margin-bottom:18px; display:flex; align-items:center; gap:10px; }
  .alert-danger  { background:#fef2f2; border:1px solid #fca5a5; color:var(--danger); }
  .alert-success { background:#f0fdf4; border:1px solid #86efac; color:#166534; }

  .action-row {
    display:flex; align-items:center; gap:12px; flex-wrap:wrap;
    padding-top:16px; border-top:1px solid var(--border); margin-top:16px;
  }

  .modal-overlay {
    display:none; position:fixed; inset:0;
    background:rgba(0,0,0,.48); z-index:1000;
    align-items:center; justify-content:center;
  }
  .modal-overlay.show { display:flex; }
  .modal-box {
    background:#fff; border-radius:16px; padding:36px 40px;
    max-width:420px; width:90%;
    box-shadow:0 20px 60px rgba(0,0,0,.22);
    text-align:center; animation:popIn .2s ease;
  }
  @keyframes popIn { from{transform:scale(.88);opacity:0} to{transform:scale(1);opacity:1} }
  .modal-icon { font-size:3rem; margin-bottom:12px; }
  .modal-box h3 { font-size:1.15rem; margin-bottom:8px; color:var(--text); }
  .modal-box p  { color:var(--muted); font-size:.9rem; margin-bottom:26px; }
  .modal-actions { display:flex; gap:12px; justify-content:center; }

  #toast {
    position:fixed; bottom:28px; right:28px;
    padding:13px 24px; border-radius:10px;
    font-weight:600; font-size:.9rem; color:#fff;
    box-shadow:0 4px 20px rgba(0,0,0,.2);
    display:none; z-index:2000;
    animation:slideUp .25s ease;
  }
  @keyframes slideUp { from{transform:translateY(12px);opacity:0} to{transform:translateY(0);opacity:1} }

  .row-deleted td { background:#fef2f2 !important; opacity:.5; transition:opacity .4s; }
</style>
</head>
<body>

<div class="page-header">
  <div class="icon">📝</div>
  <h1>Gestion des Notes — Enseignant</h1>
</div>

<div class="container">
<?php
error_reporting(E_ALL & ~E_WARNING & ~E_DEPRECATED);
ini_set('log_errors', '0');

include '_serveur_json1.php';
//include 'header.php';

// Teacher's user ID from session
// Try common session key names
$teacherUserID = intval(
    $_SESSION['id'] ??
    $_SESSION['userID'] ??
    $_SESSION['user_id'] ??
    $_SESSION['userId'] ??
    0
);

// ── DEBUG BLOCK (remove after fixing) ──────────────────────────────
if (isset($_GET['debug'])) {
    echo '<div style="background:#1e1e2e;color:#cdd6f4;font-family:monospace;font-size:.85rem;padding:18px 24px;border-radius:10px;margin-bottom:20px;white-space:pre-wrap;">';
    echo '<b style="color:#cba6f7">🔍 DEBUG INFO</b>' . "\n\n";
    echo '<b style="color:#89b4fa">Session keys:</b> ' . implode(', ', array_keys($_SESSION)) . "\n";
    echo '<b style="color:#89b4fa">teacherUserID resolved:</b> ' . $teacherUserID . "\n\n";

    // Test query without teachersActive filter
    $testSql = 'SELECT DISTINCT
        classes.id, classes.name AS className,
        semesters.id AS semID, semesters.name AS semName,
        subjects.name AS subjectName,
        subSubjects.id AS ssID, subSubjects.name AS ssName,
        classesSemesters.teachersActive
    FROM teachersSubsubjects
    JOIN subSubjects  ON teachersSubsubjects.subsubjectID = subSubjects.id
    JOIN subjects     ON teachersSubsubjects.subjectID    = subjects.id
    JOIN classes      ON teachersSubsubjects.classID      = classes.id
    JOIN gradesSubjects ON gradesSubjects.classID = classes.id AND gradesSubjects.subSubjectID = subSubjects.id
    JOIN classesSemesters ON classesSemesters.classID = classes.id
    JOIN semesters    ON classesSemesters.semesterID  = semesters.id
    WHERE teachersSubsubjects.userID = "' . $teacherUserID . '"
    ORDER BY semesters.id, classes.id LIMIT 20';

    $testRes = mysqli_query($link, $testSql);
    if (!$testRes) {
        echo '<b style="color:#f38ba8">SQL Error:</b> ' . mysqli_error($link) . "\n";
    } else {
        $count = mysqli_num_rows($testRes);
        echo '<b style="color:#89b4fa">Rows (without teachersActive filter):</b> ' . $count . "\n\n";
        if ($count > 0) {
            echo '<b style="color:#a6e3a1">Results preview:</b>' . "\n";
            while ($r = mysqli_fetch_assoc($testRes)) {
                echo '  Class: ' . $r['className']
                    . ' | Sem: ' . $r['semName']
                    . ' | Subject: ' . $r['subjectName']
                    . ' / ' . $r['ssName']
                    . ' | teachersActive: ' . $r['teachersActive'] . "\n";
            }
        } else {
            // Check if teacher exists at all
            $chkSql = 'SELECT COUNT(*) FROM teachersSubsubjects WHERE userID="' . $teacherUserID . '"';
            $chkRes = mysqli_query($link, $chkSql);
            $chkRow = mysqli_fetch_row($chkRes);
            echo '<b style="color:#fab387">teachersSubsubjects rows for this userID:</b> ' . $chkRow[0] . "\n";

            // Show all session data
            echo "\n" . '<b style="color:#fab387">Full $_SESSION dump:</b>' . "\n";
            foreach ($_SESSION as $k => $v) {
                echo '  ' . $k . ' = ' . (is_array($v) ? json_encode($v) : $v) . "\n";
            }
        }
    }
    echo '</div>';
}
// ── END DEBUG BLOCK ─────────────────────────────────────────────────

// ════════════════════════════════════════════════════════════════════
// SECURITY HELPER — verify this teacher owns the given subSubjectID + classID combo
// ════════════════════════════════════════════════════════════════════
function teacherOwns($link, $teacherUserID, $subSubjectID, $classID) {
    $sql = 'SELECT COUNT(*) FROM teachersSubsubjects
            WHERE userID="' . intval($teacherUserID) . '"
              AND subsubjectID="' . intval($subSubjectID) . '"
              AND classID="' . intval($classID) . '"';
    $res = mysqli_query($link, $sql);
    if (!$res) return false;
    $row = mysqli_fetch_row($res);
    return ($row[0] > 0);
}

// ════════════════════════════════════════════════════════════════════
// SELECTOR CARD — teacher sees only their assigned classes/subjects/semesters
// ════════════════════════════════════════════════════════════════════
$saved_cont = $_POST['cont'] ?? '';

// Build the options list: each option = classID;semesterID;subSubjectID
$sql = 'SELECT DISTINCT
            classes.id          AS classID,
            classes.name        AS className,
            semesters.id        AS semesterID,
            semesters.name      AS semesterName,
            subjects.name       AS subjectName,
            subSubjects.id      AS subSubjectID,
            subSubjects.name    AS subSubjectName,
            gradesSubjects.ordering AS gsOrdering
        FROM teachersSubsubjects
        JOIN subSubjects    ON teachersSubsubjects.subsubjectID = subSubjects.id
        JOIN subjects       ON teachersSubsubjects.subjectID    = subjects.id
        JOIN classes        ON teachersSubsubjects.classID      = classes.id
        JOIN gradesSubjects ON gradesSubjects.classID           = classes.id
                           AND gradesSubjects.subSubjectID      = subSubjects.id
        JOIN classesSemesters ON classesSemesters.classID       = classes.id
        JOIN semesters      ON classesSemesters.semesterID      = semesters.id
        WHERE teachersSubsubjects.userID = "' . $teacherUserID . '"
          AND classesSemesters.teachersActive = 1
        ORDER BY semesters.id, classes.id, gradesSubjects.ordering, subSubjects.id';

$req = mysqli_query($link, $sql);
if (!$req) {
    echo '<div class="alert alert-danger">⚠️ Erreur SQL sélecteur: ' . htmlspecialchars(mysqli_error($link)) . '</div>';
}

echo '<div class="card">';
echo '<div class="card-title">📋 Sélectionner la Classe / Contrôle / Matière</div>';
echo '<form method="post" action="_ecrirenoteparmatiereprof.php" name="selector">';
echo '<div class="form-grid">';

echo '<div class="field"><label>📚 Classe — Contrôle — Matière</label>';
echo '<select name="cont">';
if ($req && mysqli_num_rows($req) > 0) {
    while ($data = mysqli_fetch_assoc($req)) {
        $val = $data['classID'] . ';' . $data['semesterID'] . ';' . $data['subSubjectID'];
        $sel = ($saved_cont === $val) ? 'selected' : '';
        $label = htmlspecialchars($data['className'])
               . ' — ' . htmlspecialchars($data['semesterName'])
               . ' — ' . htmlspecialchars($data['subjectName'])
               . ' / ' . htmlspecialchars($data['subSubjectName']);
        echo '<option value="' . htmlspecialchars($val) . '" ' . $sel . '>' . $label . '</option>';
    }
} else {
    echo '<option value="">Aucune matière assignée</option>';
}
echo '</select></div>';

echo '<div class="field"><label>&nbsp;</label>';
echo '<button type="submit" name="chercher" class="btn btn-primary" style="width:100%">🔍 Chercher</button>';
echo '</div>';
echo '</div></form></div>';

// ════════════════════════════════════════════════════════════════════
// MAIN CONTENT
// ════════════════════════════════════════════════════════════════════
if (isset($_POST['chercher']) || isset($_POST['publish'])) {

    $cont_raw     = $_POST['cont'];
    $cellm        = explode(';', $cont_raw);
    $classeID     = intval($cellm[0]);
    $ctrlID       = intval($cellm[1]);
    $subSubjectID = intval($cellm[2]);

    // ── SECURITY: verify teacher owns this assignment ─────────────
    if (!teacherOwns($link, $teacherUserID, $subSubjectID, $classeID)) {
        echo '<div class="alert alert-danger">🚫 Accès refusé : vous n\'êtes pas autorisé à gérer cette matière.</div>';
    } else {

        // Semester name
        $res = mysqli_query($link, 'SELECT name FROM semesters WHERE id="' . $ctrlID . '"');
        $ctrlRow  = mysqli_fetch_array($res);
        $ctrlName = $ctrlRow[0] ?? '';

        // Class name
        $res = mysqli_query($link, 'SELECT name FROM classes WHERE id="' . $classeID . '"');
        $classeRow = mysqli_fetch_array($res);
        $className = $classeRow[0] ?? '';

        // SubSubject + coef
        $res = mysqli_query($link, 'SELECT subSubjects.name, gradesSubjects.coeficient
                                     FROM subSubjects
                                     JOIN gradesSubjects ON subSubjects.id = gradesSubjects.subSubjectID
                                     WHERE subSubjects.id="' . $subSubjectID . '" AND gradesSubjects.classID="' . $classeID . '"');
        $ssRow          = mysqli_fetch_array($res);
        $subSubjectName = $ssRow[0] ?? '';
        $coef           = floatval($ssRow[1] ?? 20);
        $passMark       = $coef / 2;

        // Load existing grades keyed by studentID
        $res = mysqli_query($link, 'SELECT * FROM grades
                                     WHERE classID="' . $classeID . '" AND semesterID="' . $ctrlID . '" AND subSubjectID="' . $subSubjectID . '"');
        $existingGrades = [];
        while ($g = mysqli_fetch_assoc($res)) {
            $existingGrades[$g['studentID']] = ['id' => $g['id'], 'grade' => $g['grade']];
        }
        $hasExisting = count($existingGrades) > 0;

        // Info badge
        echo '<div class="info-badge">🏫 ' . htmlspecialchars($className)
             . '&nbsp;&nbsp;|&nbsp;&nbsp;📅 ' . htmlspecialchars($ctrlName)
             . '&nbsp;&nbsp;|&nbsp;&nbsp;📚 ' . htmlspecialchars($subSubjectName)
             . '&nbsp;&nbsp;|&nbsp;&nbsp;⚖️ /' . $coef . '</div>';

        // ── Handle INSERT ─────────────────────────────────────────
        $publishError   = '';
        $publishSuccess = false;
        if (isset($_POST['publish']) && !$hasExisting) {
            $notes_post = $_POST['note']       ?? [];
            $studentIDs = $_POST['student_id'] ?? [];
            $hasError   = false;
            foreach ($notes_post as $n) {
                if ($n === '') continue;
                $nf = floatval($n);
                if ($nf == -1) continue; // absent is valid
                if ($nf > $coef || $nf < 0) { $hasError = true; break; }
            }
            if ($hasError) {
                $publishError = "⚠️ Valeur inacceptable ! Les notes doivent être entre 0 et " . $coef . ".";
            } else {
                foreach ($notes_post as $k => $n) {
                    if ($n !== '') {
                        $nf  = floatval($n);
                        $sid = intval($studentIDs[$k]);
                        mysqli_query($link, 'INSERT INTO grades VALUES(DEFAULT,"' . $sid . '","' . $classeID . '","' . $ctrlID . '","' . $subSubjectID . '","' . $nf . '")');
                    }
                }
                $publishSuccess = true;
                $res2 = mysqli_query($link, 'SELECT * FROM grades WHERE classID="' . $classeID . '" AND semesterID="' . $ctrlID . '" AND subSubjectID="' . $subSubjectID . '"');
                $existingGrades = [];
                while ($g = mysqli_fetch_assoc($res2)) {
                    $existingGrades[$g['studentID']] = ['id' => $g['id'], 'grade' => $g['grade']];
                }
                $hasExisting = count($existingGrades) > 0;
            }
        }

        if ($publishSuccess) echo '<div class="alert alert-success">✅ Notes publiées avec succès !</div>';
        if ($publishError)   echo '<div class="alert alert-danger">' . $publishError . '</div>';

        // Load students
        $res = mysqli_query($link, 'SELECT students.id, students.firstName, students.lastName, users.firstName AS middleName
                                     FROM students INNER JOIN users ON students.userID = users.id
                                     WHERE students.classID="' . $classeID . '"
                                     ORDER BY students.firstName, students.lastName, users.firstName');
        $students = [];
        while ($d = mysqli_fetch_assoc($res)) { $students[] = $d; }

        // Pre-compute stats
        $preSum=0; $preCount=0; $prePass=0; $preFail=0;
        foreach ($existingGrades as $eg) {
            $v = floatval($eg['grade']); $preSum+=$v; $preCount++;
            if ($v >= $passMark) $prePass++; else $preFail++;
        }
        $preAvg  = $preCount > 0 ? number_format($preSum/$preCount,2) : '—';
        $preRate = $preCount > 0 ? round(($prePass/$preCount)*100)    : 0;

        // Stats panel
        echo '<div class="stats-panel">';
        echo '  <div class="stat-card stat-tot"><div class="val" id="statTotal">' . count($students) . '</div><div class="lbl">Élèves</div></div>';
        echo '  <div class="stat-card stat-avg"><div class="val" id="statAvg">'  . ($preCount ? $preAvg  : '—') . '</div><div class="lbl">Moyenne</div></div>';
        echo '  <div class="stat-card stat-pass"><div class="val" id="statPass">' . ($preCount ? $prePass : '—') . '</div><div class="lbl">Réussis ✅</div></div>';
        echo '  <div class="stat-card stat-fail"><div class="val" id="statFail">' . ($preCount ? $preFail : '—') . '</div><div class="lbl">Échoués ❌</div></div>';
        echo '</div>';

        echo '<div class="card" style="padding:16px 28px;margin-bottom:24px;">';
        echo '<div class="progress-wrap"><div class="progress-label"><span>Taux de réussite</span><span id="rateLabel">' . ($preCount ? $preRate.'%' : '—') . '</span></div>';
        echo '<div class="progress-bar"><div class="progress-fill" id="progressFill" style="width:' . $preRate . '%"></div></div></div></div>';

        // ════════════════════════════════════════════════════════
        // CASE A — EXISTING GRADES → Edit / Delete table
        // ════════════════════════════════════════════════════════
        if ($hasExisting) {

            echo '<div class="mode-tabs">';
            echo '  <span class="mode-tab active-edit" id="tab-edit"   onclick="switchMode(\'edit\')">✏️ Modifier les Notes</span>';
            echo '  <span class="mode-tab"             id="tab-delete" onclick="switchMode(\'delete\')">🗑️ Effacer une Note</span>';
            echo '  <button type="button" class="btn btn-danger btn-sm" style="margin-left:auto" onclick="confirmDeleteAll()">⚠️ Effacer TOUTES les Notes</button>';
            echo '</div>';

            echo '<div class="card">';
            echo '<div class="card-title" id="tableTitle">✏️ Modifier les Notes &nbsp;'
                 . '<small style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--muted)">Note sur ' . $coef . ' — Seuil : ' . $passMark . '</small></div>';

            echo '<table class="grades-table">';
            echo '<thead><tr><th>#</th><th>Prénom</th><th>Nom</th><th>Note actuelle</th><th>Nouvelle note</th><th>Action</th></tr></thead>';
            echo '<tbody id="gradesTbody">';

            foreach ($students as $i => $s) {
                $sid      = $s['id'];
                $eg       = $existingGrades[$sid] ?? null;
                $gradeID  = $eg ? $eg['id']    : null;
                $gradeVal = $eg ? $eg['grade'] : null;
                $hasGrade = ($eg !== null);
                $num      = $i + 1;
                $dispClass = !$hasGrade ? 'none' : (floatval($gradeVal) == -1 ? 'absent' : (floatval($gradeVal) >= $passMark ? 'ok' : 'fail'));

                echo '<tr id="row_' . $sid . '" data-sid="' . $sid . '" data-grade-id="' . ($gradeID ?? '') . '">';
                echo '  <td class="num">' . $num . '</td>';
                echo '  <td class="name">' . htmlspecialchars($s['firstName']) . '</td>';
                echo '  <td>' . htmlspecialchars($s['lastName']) . '</td>';
                echo '  <td><span class="grade-display ' . $dispClass . '" id="disp_' . $sid . '">'
                     . (!$hasGrade ? '—' : (floatval($gradeVal) == -1 ? 'Absent' : $gradeVal)) . '</span></td>';
                echo '  <td><input type="number" class="grade-input edit-input" id="inp_' . $sid . '"'
                     . ' step="0.25" min="-1" max="' . $coef . '" placeholder="— (-1=Absent)"'
                     . ($hasGrade ? ' value="' . $gradeVal . '"' : '')
                     . ' oninput="liveStats(' . $coef . ',' . $passMark . ')"'
                     . ' data-original="' . ($hasGrade ? $gradeVal : '') . '"></td>';
                echo '  <td id="acts_' . $sid . '" style="white-space:nowrap">';
                echo '    <button class="btn btn-warn btn-sm edit-btn"'
                     . ' onclick="saveGrade(' . $sid . ',' . ($gradeID ?? 'null') . ',' . $coef . ',' . $subSubjectID . ',' . $classeID . ')"'
                     . ' title="Enregistrer la modification">💾 Enregistrer</button>';
                if ($hasGrade) {
                    echo '    <button class="btn btn-danger btn-sm delete-btn" style="display:none"'
                         . ' onclick="confirmDelete(' . $sid . ',' . $gradeID . ',\'' . addslashes($s['firstName'].' '.$s['lastName']) . '\',' . $subSubjectID . ',' . $classeID . ')"'
                         . ' title="Effacer la note">🗑️ Effacer</button>';
                } else {
                    echo '    <span style="color:var(--muted);font-size:.8rem" class="delete-btn" style="display:none">—</span>';
                }
                echo '  </td>';
                echo '</tr>';
            }

            echo '</tbody></table>';
            echo '</div>';

        // ════════════════════════════════════════════════════════
        // CASE B — NO EXISTING GRADES → Insert form
        // ════════════════════════════════════════════════════════
        } else {

            echo '<div class="card">';
            echo '<div class="card-title">✏️ Saisie des Notes &nbsp;'
                 . '<small style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--muted)">Note sur ' . $coef . ' — Seuil de réussite : ' . $passMark . '</small></div>';
            echo '<form method="post" action="_ecrirenoteparmatiereprof.php" id="gradesForm">';
            echo '<input type="hidden" name="cont" value="' . htmlspecialchars($cont_raw) . '">';

            echo '<table class="grades-table">';
            echo '<thead><tr><th>#</th><th>Prénom</th><th>Nom</th><th>Note / ' . $coef . '</th><th>Coef.</th></tr></thead>';
            echo '<tbody>';
            foreach ($students as $i => $s) {
                $num = $i + 1;
                echo '<tr>';
                echo '  <td class="num">' . $num . '</td>';
                echo '  <td class="name">' . htmlspecialchars($s['firstName']) . '</td>';
                echo '  <td>' . htmlspecialchars($s['lastName']) . '</td>';
                echo '  <td>';
                echo '    <input type="hidden" name="student_id[]" value="' . $s['id'] . '">';
                echo '    <input type="number" name="note[]" class="grade-input"'
                     . ' step="0.25" min="-1" max="' . $coef . '" placeholder="— (-1=Absent)"'
                     . ' oninput="liveStats(' . $coef . ',' . $passMark . ')">';
                echo '  </td>';
                echo '  <td><span class="coef-badge">' . $coef . '</span></td>';
                echo '</tr>';
            }
            echo '</tbody></table>';

            echo '<div class="action-row">';
            echo '  <button type="submit" name="publish" class="btn btn-success">📤 Publier les Notes</button>';
            echo '  <a href="javascript:history.go(-1)"><button type="button" class="btn btn-ghost">↩ Retour</button></a>';
            echo '</div>';
            echo '</form>';
            echo '</div>';
        }

    } // end security check
}
?>
</div><!-- /container -->

<!-- DELETE CONFIRM MODAL -->
<div class="modal-overlay" id="deleteModal">
  <div class="modal-box">
    <div class="modal-icon">🗑️</div>
    <h3>Effacer cette note ?</h3>
    <p id="deleteModalMsg">Cette action est irréversible.</p>
    <div class="modal-actions">
      <button class="btn btn-ghost" onclick="closeModal()">Annuler</button>
      <button class="btn btn-danger" id="confirmDeleteBtn">Effacer définitivement</button>
    </div>
  </div>
</div>

<!-- DELETE ALL MODAL -->
<div class="modal-overlay" id="deleteAllModal">
  <div class="modal-box">
    <div class="modal-icon">⚠️</div>
    <h3>Effacer TOUTES les notes ?</h3>
    <p>Cette action supprimera définitivement <strong>toutes les notes</strong> de cette matière pour ce contrôle. Elle est irréversible.</p>
    <div class="modal-actions">
      <button class="btn btn-ghost" onclick="closeDeleteAllModal()">Annuler</button>
      <button class="btn btn-danger" id="confirmDeleteAllBtn">Effacer définitivement</button>
    </div>
  </div>
</div>

<!-- TOAST -->
<div id="toast"></div>

<script>
const COEF     = <?php echo json_encode(isset($coef)     ? $coef     : 20); ?>;
const PASSMARK = <?php echo json_encode(isset($passMark) ? $passMark : 10); ?>;
const PAGE_URL   = '_ecrirenoteparmatiereprof.php';
const SEMESTER_ID   = <?php echo json_encode(isset($ctrlID)       ? $ctrlID       : 0); ?>;
const SUB_SUBJECT_ID = <?php echo json_encode(isset($subSubjectID) ? $subSubjectID : 0); ?>;
const CLASS_ID      = <?php echo json_encode(isset($classeID)      ? $classeID     : 0); ?>;

// ── TOAST ──────────────────────────────────────────────────────────
function showToast(msg, type = 'success') {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.style.background = type === 'success' ? '#0e9f6e'
                     : type === 'warn'    ? '#e3a008'
                     :                      '#e02424';
  t.style.display = 'block';
  clearTimeout(t._timer);
  t._timer = setTimeout(() => { t.style.display = 'none'; }, 3400);
}

// ── LIVE STATS ─────────────────────────────────────────────────────
function liveStats(coef, passMark) {
  const inputs = document.querySelectorAll('.grade-input:not(:disabled)');
  let sum = 0, count = 0, pass = 0, fail = 0;

  inputs.forEach(inp => {
    const raw = inp.value.trim();
    inp.classList.remove('ok', 'fail', 'warn', 'absent');
    if (raw === '') return;
    const v = parseFloat(raw);
    if (v === -1) { inp.classList.add('absent'); return; } // absent — skip from stats
    if (isNaN(v) || v < 0 || v > coef) { inp.classList.add('warn'); return; }
    sum += v; count++;
    if (v >= passMark) { pass++; inp.classList.add('ok'); }
    else               { fail++; inp.classList.add('fail'); }
  });

  if (count === 0) {
    ['statAvg','statPass','statFail'].forEach(id => {
      const el = document.getElementById(id);
      if (el) el.textContent = '—';
    });
    const rl = document.getElementById('rateLabel');
    const pf = document.getElementById('progressFill');
    if (rl) rl.textContent = '—';
    if (pf) pf.style.width = '0%';
    return;
  }

  const avg  = (sum / count).toFixed(2);
  const rate = Math.round((pass / count) * 100);
  document.getElementById('statAvg').textContent  = avg;
  document.getElementById('statPass').textContent = pass;
  document.getElementById('statFail').textContent = fail;
  document.getElementById('rateLabel').textContent = rate + '%';
  document.getElementById('progressFill').style.width = rate + '%';
}

// ── MODE SWITCH ────────────────────────────────────────────────────
let currentMode = 'edit';

function switchMode(mode) {
  currentMode = mode;
  const tabEdit   = document.getElementById('tab-edit');
  const tabDelete = document.getElementById('tab-delete');
  if (tabEdit && tabDelete) {
    tabEdit.className   = 'mode-tab' + (mode === 'edit'   ? ' active-edit'   : '');
    tabDelete.className = 'mode-tab' + (mode === 'delete' ? ' active-delete' : '');
  }
  document.querySelectorAll('.edit-btn').forEach(b   => b.style.display = mode === 'edit'   ? '' : 'none');
  document.querySelectorAll('.delete-btn').forEach(b => b.style.display = mode === 'delete' ? '' : 'none');
  document.querySelectorAll('.edit-input').forEach(i => i.disabled = (mode === 'delete'));

  const title = document.getElementById('tableTitle');
  if (title) {
    title.innerHTML = mode === 'edit'
      ? '✏️ Modifier les Notes &nbsp;<small style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--muted)">Note sur '+COEF+' — Seuil : '+PASSMARK+'</small>'
      : '🗑️ Effacer les Notes &nbsp;<small style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--muted)">Cliquez sur Effacer pour supprimer la note d\'un élève</small>';
  }
  if (mode === 'edit') liveStats(COEF, PASSMARK);
}

// ── SAVE (UPDATE) — AJAX ───────────────────────────────────────────
function saveGrade(sid, gradeID, coef, subSubjectID, classID) {
  const inp = document.getElementById('inp_' + sid);
  if (!inp) return;
  const newVal = inp.value.trim();

  if (newVal === '') { showToast('Entrez une valeur avant d\'enregistrer', 'warn'); return; }
  const nf = parseFloat(newVal);
  const isAbsent = (nf === -1);
  if (isNaN(nf) || (!isAbsent && (nf < 0 || nf > coef))) {
    showToast('Valeur hors limites (0 – ' + coef + ', ou -1 pour Absent)', 'error'); return;
  }
  if (inp.dataset.original !== '' && parseFloat(inp.dataset.original) === nf) {
    showToast('La note n\'a pas changé', 'warn'); return;
  }

  const btn = document.querySelector('#acts_' + sid + ' .edit-btn');
  if (btn) { btn.disabled = true; btn.textContent = '⏳'; }

  const fd = new FormData();
  fd.append('ajax_update',    '1');
  fd.append('grade_id',       gradeID);
  fd.append('new_grade',      nf);
  fd.append('coef',           coef);
  fd.append('sub_subject_id', subSubjectID);
  fd.append('class_id',       classID);

  fetch(PAGE_URL, { method: 'POST', body: fd })
    .then(r => r.text())
    .then(txt => { try { return JSON.parse(txt); } catch(e) { throw new Error(txt.substring(0,200)); } })
    .then(data => {
      if (data.ok) {
        const disp = document.getElementById('disp_' + sid);
        if (disp) {
          if (nf === -1) {
            disp.textContent = 'Absent';
            disp.className = 'grade-display absent';
          } else {
            disp.textContent = nf;
            disp.className = 'grade-display ' + (nf >= PASSMARK ? 'ok' : 'fail');
          }
        }
        inp.dataset.original = nf;
        showToast('✅ Note modifiée avec succès');
        liveStats(COEF, PASSMARK);
      } else {
        showToast('❌ ' + (data.msg || 'Erreur lors de la mise à jour'), 'error');
      }
      if (btn) { btn.disabled = false; btn.textContent = '💾 Enregistrer'; }
    })
    .catch(err => {
      showToast('❌ ' + (err && err.message ? err.message : 'Erreur réseau'), 'error');
      if (btn) { btn.disabled = false; btn.textContent = '💾 Enregistrer'; }
    });
}

// ── DELETE MODAL ───────────────────────────────────────────────────
let _pendingSid = null, _pendingGradeID = null, _pendingSubSubjectID = null, _pendingClassID = null;

function confirmDelete(sid, gradeID, studentName, subSubjectID, classID) {
  _pendingSid          = sid;
  _pendingGradeID      = gradeID;
  _pendingSubSubjectID = subSubjectID;
  _pendingClassID      = classID;
  document.getElementById('deleteModalMsg').textContent =
    'Effacer la note de ' + studentName + ' ? Cette action est irréversible.';
  document.getElementById('deleteModal').classList.add('show');
}

function confirmDeleteAll() {
  document.getElementById('deleteAllModal').classList.add('show');
}
function closeDeleteAllModal() {
  document.getElementById('deleteAllModal').classList.remove('show');
}

document.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('confirmDeleteAllBtn');
  if (btn) {
    btn.addEventListener('click', () => {
      btn.disabled = true; btn.textContent = '⏳';
      const fd = new FormData();
      fd.append('ajax_delete_all', '1');
      fd.append('sub_subject_id',  SUB_SUBJECT_ID);
      fd.append('class_id',        CLASS_ID);
      fd.append('semester_id',     SEMESTER_ID);
      closeDeleteAllModal();
      fetch(PAGE_URL, { method: 'POST', body: fd })
        .then(r => r.text())
        .then(txt => { try { return JSON.parse(txt); } catch(e) { throw new Error(txt.substring(0,200)); } })
        .then(data => {
          btn.disabled = false; btn.textContent = 'Effacer définitivement';
          if (data.ok) {
            showToast('🗑️ ' + data.deleted + ' note(s) effacée(s)');
            setTimeout(() => location.reload(), 1200);
          } else {
            showToast('❌ ' + (data.msg || 'Erreur'), 'error');
          }
        })
        .catch(err => {
          btn.disabled = false; btn.textContent = 'Effacer définitivement';
          showToast('❌ ' + (err && err.message ? err.message : 'Erreur réseau'), 'error');
        });
    });
  }
  document.getElementById('deleteAllModal').addEventListener('click', e => {
    if (e.target === e.currentTarget) closeDeleteAllModal();
  });
});

function closeModal() {
  document.getElementById('deleteModal').classList.remove('show');
  _pendingSid = null; _pendingGradeID = null; _pendingSubSubjectID = null; _pendingClassID = null;
}

document.getElementById('confirmDeleteBtn').addEventListener('click', () => {
  if (!_pendingGradeID) { closeModal(); return; }
  const btn = document.getElementById('confirmDeleteBtn');
  btn.disabled = true; btn.textContent = '⏳';

  const fd = new FormData();
  fd.append('ajax_delete',    '1');
  fd.append('grade_id',       _pendingGradeID);
  fd.append('sub_subject_id', _pendingSubSubjectID);
  fd.append('class_id',       _pendingClassID);

  const sidSnap = _pendingSid;
  closeModal();

  fetch(PAGE_URL, { method: 'POST', body: fd })
    .then(r => r.text())
    .then(txt => { try { return JSON.parse(txt); } catch(e) { throw new Error(txt.substring(0,200)); } })
    .then(data => {
      btn.disabled = false; btn.textContent = 'Effacer définitivement';
      if (data.ok) {
        const row = document.getElementById('row_' + sidSnap);
        if (row) {
          const disp = document.getElementById('disp_' + sidSnap);
          if (disp) { disp.textContent = '—'; disp.className = 'grade-display none'; }
          const inp = document.getElementById('inp_' + sidSnap);
          if (inp) { inp.value = ''; inp.dataset.original = ''; inp.className = 'grade-input edit-input'; }
          row.querySelectorAll('.delete-btn').forEach(b => b.remove());
          row.classList.add('row-deleted');
          setTimeout(() => row.classList.remove('row-deleted'), 600);
        }
        showToast('🗑️ Note effacée');
        liveStats(COEF, PASSMARK);
      } else {
        showToast('❌ ' + (data.msg || 'Erreur lors de la suppression'), 'error');
      }
    })
    .catch(err => {
      btn.disabled = false; btn.textContent = 'Effacer définitivement';
      showToast('❌ ' + (err && err.message ? err.message : 'Erreur réseau'), 'error');
    });
});

document.getElementById('deleteModal').addEventListener('click', e => {
  if (e.target === e.currentTarget) closeModal();
});

// ── INSERT FORM — client-side validation ───────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('gradesForm');
  if (form) {
    form.addEventListener('submit', e => {
      let bad = false;
      form.querySelectorAll('.grade-input').forEach(inp => {
        if (inp.value.trim() === '') return;
        const v = parseFloat(inp.value);
        if (v === -1) return; // absent is valid
        if (isNaN(v) || v < 0 || v > COEF) bad = true;
      });
      if (bad) {
        e.preventDefault();
        showToast('⚠️ Certaines notes sont hors limites (0 – ' + COEF + ')', 'error');
      }
    });
  }
  liveStats(COEF, PASSMARK);
});
</script>
</body>
</html>
