<?php
/**
 * Baccalauréat — résultats des élèves de Terminale & déconnexion des comptes
 * (élèves admis et parents liés)
 */
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']);
requirePermission('students', 'edit');

// Table des résultats au bac (créée si absente)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS bac_results (
        id int NOT NULL AUTO_INCREMENT,
        school_id int NOT NULL,
        student_id int NOT NULL,
        academic_year varchar(30) NOT NULL,
        result enum('reussi','echoue','non_presente') NOT NULL,
        updated_by int DEFAULT NULL,
        updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY uniq_student_year (student_id, academic_year),
        KEY school_id (school_id),
        KEY academic_year (academic_year)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (PDOException $e) {}

// Migration : statut « abandon » (date de sortie) sur les élèves
try { $pdo->exec("ALTER TABLE students ADD COLUMN dropped_out DATE DEFAULT NULL AFTER parent_phone"); } catch (PDOException $e) {}

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

$tab = $_GET['tab'] ?? 'resultats';
$year = $_GET['academic_year'] ?? getDefaultAcademicYear($pdo, $schoolFilter);

// Années disponibles (classes de Terminale)
$years = $pdo->query("SELECT DISTINCT academic_year FROM classes WHERE academic_year IS NOT NULL AND academic_year != '' AND level LIKE 'Tle%' ORDER BY academic_year DESC")->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) { $years = []; }
$years = array_unique(array_merge($years, [date('Y') . '-' . (date('Y')+1)]));
if (!in_array($year, $years, true)) $year = $years[0];

$schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// ── Liste des élèves de Terminale (année + école) ─────────────────────────────
function getTerminaleStudents(PDO $pdo, ?int $schoolId, string $year): array {
    $sql = "SELECT s.id, s.first_name, s.last_name, s.user_id, s.school_id,
                   c.name AS class_name, c.level
            FROM students s
            JOIN classes c ON s.class_id = c.id
            WHERE c.level LIKE 'Tle%' AND c.academic_year = ?";
    $params = [$year];
    if ($schoolId) { $sql .= " AND s.school_id = ?"; $params[] = $schoolId; }
    $sql .= " ORDER BY c.name, s.last_name, s.first_name";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll();
}

// ── Carte des résultats déjà saisis ───────────────────────────────────────────
$resMap = [];
$st = $pdo->prepare("SELECT student_id, result FROM bac_results WHERE academic_year = ?" . ($schoolFilter ? " AND school_id=?" : ""));
$st->execute($schoolFilter ? [$year, $schoolFilter] : [$year]);
foreach ($st->fetchAll() as $r) { $resMap[$r['student_id']] = $r['result']; }

// ── Export Excel des résultats ────────────────────────────────────────────────
if (isset($_GET['export']) && $_GET['export'] === '1') {
    verifyCsrf();
    requirePermission('students', 'edit');
    $st = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, c.name AS class_name,
                                sc.name AS school_name, br.result
                         FROM students s
                         JOIN classes c ON s.class_id = c.id
                         LEFT JOIN schools sc ON s.school_id = sc.id
                         LEFT JOIN bac_results br ON br.student_id = s.id AND br.academic_year = ?
                         WHERE c.level LIKE 'Tle%' AND c.academic_year = ?" . ($schoolFilter ? " AND s.school_id=?" : "") . "
                         ORDER BY c.name, s.last_name, s.first_name");
    $params = [$year, $year];
    if ($schoolFilter) $params[] = $schoolFilter;
    $st->execute($params);
    $rows = $st->fetchAll();
    $labels = ['reussi' => 'Réussi', 'echoue' => 'Échoué', 'non_presente' => 'Non présenté'];
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment; filename=bac_' . date('Y-m-d') . '.xls');
    header('Cache-Control: max-age=0');
    echo "\xEF\xBB\xBF";
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">';
    echo '<head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Résultats bac</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
    echo '<body><table border="1">';
    echo '<tr>
            <th>ID</th><th>Nom</th><th>Prénom</th><th>Classe</th><th>École</th><th>Résultat</th>
          </tr>';
    foreach ($rows as $r) {
        echo '<tr><td>' . (int)$r['id'] . '</td>'
           . '<td>' . htmlspecialchars((string)$r['last_name'], ENT_QUOTES, 'UTF-8') . '</td>'
           . '<td>' . htmlspecialchars((string)$r['first_name'], ENT_QUOTES, 'UTF-8') . '</td>'
           . '<td>' . htmlspecialchars((string)$r['class_name'], ENT_QUOTES, 'UTF-8') . '</td>'
           . '<td>' . htmlspecialchars((string)($r['school_name'] ?? ''), ENT_QUOTES, 'UTF-8') . '</td>'
           . '<td>' . htmlspecialchars($labels[$r['result']] ?? '', ENT_QUOTES, 'UTF-8') . '</td></tr>';
    }
    echo '</table></body></html>';
    exit;
}

// ── Élèves admis (réussi) pour la déconnexion ────────────────────────────────
function getPassedStudents(PDO $pdo, ?int $schoolId, string $year): array {
    $sql = "SELECT s.id AS student_id, s.first_name, s.last_name,
                   c.name AS class_name, s.user_id AS student_account_id,
                   u.email AS student_email, u.active AS student_active, u.name AS student_account_name
            FROM bac_results br
            JOIN students s ON s.id = br.student_id
            JOIN classes c ON s.class_id = c.id
            LEFT JOIN users u ON u.id = s.user_id
            WHERE br.academic_year = ? AND br.result = 'reussi'";
    $params = [$year];
    if ($schoolId) { $sql .= " AND s.school_id = ?"; $params[] = $schoolId; }
    $sql .= " ORDER BY c.name, s.last_name, s.first_name";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll();
}

$passedStudents = getPassedStudents($pdo, $schoolFilter, $year);

// ── Élèves en abandon (dropped_out) pour la déconnexion ──────────────────────
function getAbandonedStudents(PDO $pdo, ?int $schoolId, string $year): array {
    $sql = "SELECT s.id AS student_id, s.first_name, s.last_name, s.dropped_out,
                   c.name AS class_name, s.user_id AS student_account_id,
                   u.email AS student_email, u.active AS student_active, u.name AS student_account_name
            FROM students s
            JOIN classes c ON s.class_id = c.id
            LEFT JOIN users u ON u.id = s.user_id
            WHERE s.dropped_out IS NOT NULL AND c.academic_year = ?";
    $params = [$year];
    if ($schoolId) { $sql .= " AND s.school_id = ?"; $params[] = $schoolId; }
    $sql .= " ORDER BY s.dropped_out DESC, c.name, s.last_name, s.first_name";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll();
}

$abandonedStudents = getAbandonedStudents($pdo, $schoolFilter, $year);

// Parents liés aux élèves en abandon
$abandonParentMap = [];
$abandonedIds = array_column($abandonedStudents, 'student_id');
if (!empty($abandonedIds)) {
    $in = implode(',', array_fill(0, count($abandonedIds), '?'));
    $st = $pdo->prepare("SELECT ps.student_id, u.id AS parent_account_id, u.active AS parent_active,
                                u.email AS parent_email, u.name AS parent_name
                         FROM parent_students ps
                         JOIN users u ON u.id = ps.user_id
                         WHERE ps.student_id IN ($in) ORDER BY u.name");
    $st->execute($abandonedIds);
    foreach ($st->fetchAll() as $p) { $abandonParentMap[$p['student_id']][] = $p; }
}

// Ensemble des comptes liés aux admis (sécurité pour les actions)
$allowedAccounts = [];
foreach ($passedStudents as $ps) {
    if (!empty($ps['student_account_id'])) $allowedAccounts[(int)$ps['student_account_id']] = true;
    foreach ($parentMap[$ps['student_id']] ?? [] as $pa) {
        $allowedAccounts[(int)$pa['parent_account_id']] = true;
    }
}

// Ensemble des comptes liés aux abandons
$abandonAccounts = [];
foreach ($abandonedStudents as $as) {
    if (!empty($as['student_account_id'])) $abandonAccounts[(int)$as['student_account_id']] = true;
    foreach ($abandonParentMap[$as['student_id']] ?? [] as $pa) {
        $abandonAccounts[(int)$pa['parent_account_id']] = true;
    }
}

// ── Traitement ────────────────────────────────────────────────────────────────

// Import CSV des résultats
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    verifyCsrf();
    requirePermission('students', 'edit');
    $imported = 0; $errors = [];
    $back = 'baccalaureat.php?' . http_build_query(array_filter(['tab'=>'resultats','academic_year'=>$year,'school_id'=>$_GET['school_id'] ?? null]));
    if (empty($_FILES['csv_file']['tmp_name'])) {
        flashMessage('error', 'Veuillez sélectionner un fichier CSV.');
        header('Location: ' . $back); exit;
    }
    // Élèves autorisés (filtre école) + index par nom
    $allowed = [];
    $byName = [];
    foreach (getTerminaleStudents($pdo, $schoolFilter, $year) as $ts) {
        $allowed[$ts['id']] = (int)$ts['school_id'];
        $byName[mb_strtolower(trim($ts['last_name'])) . '|' . mb_strtolower(trim($ts['first_name']))] = (int)$ts['id'];
    }
    // Lecture du fichier : CSV classique OU Excel (tableau HTML)
    $content = (string)file_get_contents($_FILES['csv_file']['tmp_name']);
    $content = preg_replace('/^\xEF\xBB\xBF/', '', $content); // BOM UTF-8
    $trimmed = ltrim(trim($content));
    $isHtml = $trimmed !== '' && (strpos($trimmed, '<') === 0 || stripos($content, '<table') !== false || stripos($content, '<html') !== false);

    $dataRows = [];
    if ($isHtml) {
        // Extraire les lignes du tableau HTML (export Excel)
        preg_match_all('/<tr[^>]*>(.*?)<\/tr>/is', $content, $trM);
        foreach ($trM[1] as $tr) {
            preg_match_all('/<(?:td|th)[^>]*>(.*?)<\/(?:td|th)>/is', $tr, $cM);
            $cells = array_map(function ($c) {
                return html_entity_decode(trim(strip_tags($c)), ENT_QUOTES, 'UTF-8');
            }, $cM[1]);
            $dataRows[] = $cells;
        }
        $header = !empty($dataRows) ? array_shift($dataRows) : [];
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        if (!$handle) {
            flashMessage('error', 'Impossible de lire le fichier.');
            header('Location: ' . $back); exit;
        }
        $first = fgets($handle); rewind($handle);
        $delim = substr_count((string)$first, ';') >= substr_count((string)$first, ',') ? ';' : ',';
        $header = fgetcsv($handle, 0, $delim);
        while (($row = fgetcsv($handle, 0, $delim)) !== false) { $dataRows[] = $row; }
        fclose($handle);
    }

    if (!$header || count($header) < 2) {
        flashMessage('error', 'Format de fichier invalide. En-têtes attendus : ID;Nom;Prénom;Classe;École;Résultat');
        header('Location: ' . $back); exit;
    }
    $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string)$header[0]);
    $cols = array_map(fn($h) => mb_strtolower(trim((string)$h)), $header);
    $iId = array_search('id', $cols, true);
    $iNom = array_search('nom', $cols, true);
    $iPrenom = array_search('prénom', $cols, true);
    if ($iPrenom === false) $iPrenom = array_search('prenom', $cols, true);
    $iRes = array_search('résultat', $cols, true);
    if ($iRes === false) $iRes = array_search('resultat', $cols, true);
    if ($iRes === false || ($iId === false && ($iNom === false || $iPrenom === false))) {
        flashMessage('error', 'Colonnes manquantes. Attendu : ID;Nom;Prénom;Classe;École;Résultat');
        header('Location: ' . $back); exit;
    }
    $upsert = $pdo->prepare("INSERT INTO bac_results (school_id, student_id, academic_year, result, updated_by)
                             VALUES (?,?,?,?,?)
                             ON DUPLICATE KEY UPDATE result=VALUES(result), updated_by=VALUES(updated_by)");
    $del = $pdo->prepare("DELETE FROM bac_results WHERE student_id=? AND academic_year=?");
    $rowNum = 1;
    foreach ($dataRows as $row) {
        $rowNum++;
        if (count($row) < 2) continue;
        $sid = null;
        if ($iId !== false) {
            $idv = trim((string)($row[$iId] ?? ''));
            if ($idv !== '' && ctype_digit($idv)) $sid = (int)$idv;
        }
        if ($sid === null && $iNom !== false && $iPrenom !== false) {
            $key = mb_strtolower(trim((string)($row[$iNom] ?? ''))) . '|' . mb_strtolower(trim((string)($row[$iPrenom] ?? '')));
            if (isset($byName[$key])) $sid = $byName[$key];
        }
        if ($sid === null || !isset($allowed[$sid])) {
            $errors[] = "Ligne $rowNum : élève introuvable (ID ou Nom/Prénom non reconnu).";
            continue;
        }
        $resRaw = mb_strtolower(trim((string)($row[$iRes] ?? '')));
        if (in_array($resRaw, ['reussi','réussi','admis','oui'], true)) $resVal = 'reussi';
        elseif (in_array($resRaw, ['echoue','échoué','echec','échec','non admis','nonadmise'], true)) $resVal = 'echoue';
        elseif (in_array($resRaw, ['non_presente','non presente','non présenté','nonpresente','np','abs'], true)) $resVal = 'non_presente';
        elseif ($resRaw === '' || in_array($resRaw, ['non defini','non défini','nondefini','-'], true)) $resVal = '';
        else { $errors[] = "Ligne $rowNum : résultat invalide (« " . trim((string)($row[$iRes] ?? '')) . " »)."; continue; }
        if ($resVal === '') {
            $del->execute([$sid, $year]);
        } else {
            $upsert->execute([$allowed[$sid], $sid, $year, $resVal, $_SESSION['user_id'] ?? null]);
        }
        $imported++;
    }
    $msg = "$imported résultat(s) importé(s) pour l'année $year.";
    if (!empty($errors)) {
        $msg .= ' Erreurs : ' . implode(' | ', array_slice($errors, 0, 10));
        if (count($errors) > 10) $msg .= ' …';
    }
    flashMessage($errors ? 'warning' : 'success', $msg);
    header('Location: ' . $back); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    requirePermission('students', 'edit');
    $action = $_POST['action'] ?? '';

    // 1) Enregistrer les résultats
    if ($action === 'save_results') {
        $results = $_POST['result'] ?? [];
        $updates = 0;
        // Liste des élèves autorisés (filtre école)
        $allowedStudents = [];
        foreach (getTerminaleStudents($pdo, $schoolFilter, $year) as $ts) {
            $allowedStudents[$ts['id']] = (int)$ts['school_id'];
        }
        $upsert = $pdo->prepare("INSERT INTO bac_results (school_id, student_id, academic_year, result, updated_by)
                                 VALUES (?,?,?,?,?)
                                 ON DUPLICATE KEY UPDATE result=VALUES(result), updated_by=VALUES(updated_by)");
        $del = $pdo->prepare("DELETE FROM bac_results WHERE student_id=? AND academic_year=?");
        foreach ($results as $sid => $res) {
            $sid = (int)$sid;
            if ($sid <= 0 || !isset($allowedStudents[$sid])) continue;
            if ($res === '') {
                $del->execute([$sid, $year]);
                $updates++;
            } elseif (in_array($res, ['reussi','echoue','non_presente'], true)) {
                $upsert->execute([$allowedStudents[$sid], $sid, $year, $res, $_SESSION['user_id'] ?? null]);
                $updates++;
            }
        }
        flashMessage('success', "$updates résultat(s) enregistré(s) pour l'année $year.");
        header('Location: baccalaureat.php?' . http_build_query(array_filter(['tab'=>'resultats','academic_year'=>$year,'school_id'=>$_GET['school_id'] ?? null])));
        exit;
    }

    // 2) Déconnecter / réactiver un compte (élève ou parent admis/abandon)
    if ($action === 'toggle_account') {
        $accountId = (int)($_POST['account_id'] ?? 0);
        $activate  = isset($_POST['activate']) ? 1 : 0;
        $allowed   = $allowedAccounts + $abandonAccounts;
        if ($accountId > 0 && isset($allowed[$accountId])) {
            if ($accountId !== (int)$_SESSION['user_id']) {
                $pdo->prepare("UPDATE users SET active=? WHERE id=?")->execute([$activate, $accountId]);
                flashMessage('success', $activate ? 'Compte réactivé.' : 'Compte déconnecté (désactivé).');
            } else {
                flashMessage('error', 'Vous ne pouvez pas désactiver votre propre compte.');
            }
        } else {
            flashMessage('error', 'Compte non autorisé.');
        }
        header('Location: baccalaureat.php?' . http_build_query(array_filter(['tab'=>'deconnexion','academic_year'=>$year,'school_id'=>$_GET['school_id'] ?? null])));
        exit;
    }

    // 3) Déconnecter tous les comptes actifs des admis
    if ($action === 'bulk_deactivate') {
        $targets = [];
        foreach ($allowedAccounts as $accId => $true) {
            if ($accId !== (int)$_SESSION['user_id']) $targets[] = $accId;
        }
        $count = 0;
        if (!empty($targets)) {
            $in = implode(',', array_fill(0, count($targets), '?'));
            $st = $pdo->prepare("UPDATE users SET active=0 WHERE id IN ($in) AND active=1");
            $st->execute($targets);
            $count = $st->rowCount();
        }
        flashMessage('success', "$count compte(s) déconnecté(s).");
        header('Location: baccalaureat.php?' . http_build_query(array_filter(['tab'=>'deconnexion','academic_year'=>$year,'school_id'=>$_GET['school_id'] ?? null])));
        exit;
    }

    // 4) Déconnecter tous les comptes actifs des abandons
    if ($action === 'bulk_deactivate_abandon') {
        $targets = [];
        foreach ($abandonAccounts as $accId => $true) {
            if ($accId !== (int)$_SESSION['user_id']) $targets[] = $accId;
        }
        $count = 0;
        if (!empty($targets)) {
            $in = implode(',', array_fill(0, count($targets), '?'));
            $st = $pdo->prepare("UPDATE users SET active=0 WHERE id IN ($in) AND active=1");
            $st->execute($targets);
            $count = $st->rowCount();
        }
        flashMessage('success', "$count compte(s) d'abandons déconnecté(s).");
        header('Location: baccalaureat.php?' . http_build_query(array_filter(['tab'=>'deconnexion','academic_year'=>$year,'school_id'=>$_GET['school_id'] ?? null])));
        exit;
    }
}

// Statistiques
$terminalStudents = getTerminaleStudents($pdo, $schoolFilter, $year);
$statDefined = 0; $statReussi = 0; $statEchoue = 0; $statNP = 0;
foreach ($terminalStudents as $ts) {
    $r = $resMap[$ts['id']] ?? null;
    if (!$r) continue;
    $statDefined++;
    if ($r === 'reussi') $statReussi++;
    elseif ($r === 'echoue') $statEchoue++;
    elseif ($r === 'non_presente') $statNP++;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Baccalauréat & sortants - 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>
        .bac-tabs { display:flex; gap:.5rem; margin-bottom:1rem; flex-wrap:wrap; }
        .bac-tabs a {
            padding:.55rem 1.1rem; border-radius:8px; font-size:.85rem; font-weight:600;
            background:#edf2f7; color:#4a5568; text-decoration:none; border:1px solid #e2e8f0;
        }
        .bac-tabs a.active { background:#667eea; color:#fff; border-color:#667eea; }
        .bac-summary { display:flex; gap:1rem; flex-wrap:wrap; margin-bottom:1rem; font-size:.85rem; }
        .bac-summary span { padding:.4rem .9rem; border-radius:8px; background:#edf2f7; }
        .bac-summary .ok { background:#c6f6d5; color:#22543d; }
        .bac-summary .ko { background:#fed7d7; color:#9b2c2c; }
        .bac-summary .np { background:#fefcbf; color:#744210; }
        .res-select { padding:.35rem .5rem; border:1px solid #e2e8f0; border-radius:6px; font-size:.8rem; background:#f7fafc; }
        .res-select.r-reussi { border-color:#38a169; background:#f0fff4; }
        .res-select.r-echoue { border-color:#e53e3e; background:#fff5f5; }
        .res-select.r-np { border-color:#ecc94b; background:#fffff0; }
        .account-status { font-size:.75rem; padding:.2rem .6rem; border-radius:10px; font-weight:600; }
        .account-status.actif { background:#c6f6d5; color:#22543d; }
        .account-status.inactif { background:#fed7d7; color:#9b2c2c; }
        .account-row { border:1px solid #e2e8f0; border-radius:8px; padding:.5rem .75rem; margin-top:.4rem; background:#fafbfc; }
        .account-row .email { font-size:.78rem; color:#4a5568; }
        .empty-msg { text-align:center; color:#a0aec0; padding:2rem 0; }
        td .account-row:first-child { margin-top:0; }
        @media (max-width: 768px) {
            .card-header { flex-direction: column; align-items: flex-start; gap: .5rem; }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-user-graduate"></i> Baccalauréat & sortants'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <!-- Filtres -->
        <div class="card no-print">
            <div class="card-header"><span class="card-title"><i class="fas fa-filter"></i> Période & école</span></div>
            <form method="GET" style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:end;padding:.5rem 0;">
                <input type="hidden" name="tab" value="<?= e($tab) ?>">
                <?php if (isSuperAdmin()): ?>
                <div class="form-group" style="margin:0;">
                    <label>École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">Toutes</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="form-group" style="margin:0;">
                    <label>Année scolaire</label>
                    <select name="academic_year" onchange="this.form.submit()">
                        <?php foreach ($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$year?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i> Charger</button>
            </form>
        </div>

        <!-- Onglets -->
        <div class="bac-tabs no-print">
            <a href="?<?= http_build_query(array_filter(['tab'=>'resultats','academic_year'=>$year,'school_id'=>$_GET['school_id']??null])) ?>" class="<?= $tab==='resultats'?'active':'' ?>"><i class="fas fa-clipboard-check"></i> Résultats au bac</a>
            <a href="?<?= http_build_query(array_filter(['tab'=>'deconnexion','academic_year'=>$year,'school_id'=>$_GET['school_id']??null])) ?>" class="<?= $tab==='deconnexion'?'active':'' ?>"><i class="fas fa-user-slash"></i> Déconnexion des comptes</a>
        </div>

        <?php if ($tab === 'resultats'): ?>
        <!-- ── Partie 1 : Résultats au bac ── -->
        <div class="card no-print" style="margin-bottom:1rem;">
            <div class="card-header"><span class="card-title"><i class="fas fa-exchange-alt"></i> Exportation / Importation</span></div>
            <div style="display:flex;gap:1rem;flex-wrap:wrap;align-items:end;padding:.75rem 0;">
                <a href="?<?= http_build_query(array_filter(['export'=>'1','academic_year'=>$year,'school_id'=>$_GET['school_id']??null,'csrf_token'=>csrfToken()])) ?>" class="btn-action btn-success">
                    <i class="fas fa-file-excel"></i> Exporter en Excel (tableau)
                </a>
                <form method="POST" enctype="multipart/form-data" style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:end;margin:0;">
                    <?= csrfField() ?>
                    <input type="hidden" name="academic_year" value="<?= e($year) ?>">
                    <?php if (isSuperAdmin()): ?><input type="hidden" name="school_id" value="<?= e($_GET['school_id'] ?? '') ?>"><?php endif; ?>
                    <div class="form-group" style="margin:0;">
                        <label>Fichier Excel (.xls) ou CSV</label>
                        <input type="file" name="csv_file" accept=".xls,.csv,text/csv,application/vnd.ms-excel" required>
                    </div>
                    <button type="submit" name="import_csv" class="btn-action btn-view"><i class="fas fa-upload"></i> Importer</button>
                </form>
            </div>
            <div style="font-size:.75rem;color:#718096;">
                Colonnes : <code>ID;Nom;Prénom;Classe;École;Résultat</code> — Valeurs de résultat : <code>réussi</code>, <code>échoué</code>, <code>non présenté</code> ou vide (non défini). Le fichier exporté peut être réimporté tel quel.
            </div>
        </div>

        <div class="bac-summary">
            <span><strong><?= count($terminalStudents) ?></strong> élève(s) de Terminale</span>
            <span><strong><?= $statDefined ?></strong> résultat(s) défini(s)</span>
            <span class="ok"><i class="fas fa-check-circle"></i> Admis : <?= $statReussi ?></span>
            <span class="ko"><i class="fas fa-times-circle"></i> Échoués : <?= $statEchoue ?></span>
            <span class="np"><i class="fas fa-question-circle"></i> Non présentés : <?= $statNP ?></span>
        </div>

        <div class="card">
            <div class="card-header"><span class="card-title"><i class="fas fa-clipboard-check"></i> Définir la réussite à l'examen — <?= e($year) ?></span></div>
            <form method="POST">
                <?= csrfField() ?>
                <input type="hidden" name="action" value="save_results">
                <?php if (empty($terminalStudents)): ?>
                <div class="empty-msg">
                    <i class="fas fa-users-slash" style="font-size:2.5rem;margin-bottom:.5rem;"></i><br>
                    Aucun élève de Terminale trouvé pour cette année et cette école.
                </div>
                <?php else: ?>
                <div class="data-table-wrapper">
                <table class="data-table">
                    <thead><tr><th>#</th><th>Élève</th><th>Classe</th><th>Résultat à l'examen</th><th>Compte élève</th></tr></thead>
                    <tbody>
                    <?php foreach ($terminalStudents as $i => $ts):
                        $cur = $resMap[$ts['id']] ?? '';
                    ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td><strong><?= e($ts['last_name']) ?> <?= e($ts['first_name']) ?></strong></td>
                        <td><?= e($ts['class_name']) ?></td>
                        <td>
                            <select name="result[<?= $ts['id'] ?>]" class="res-select <?= $cur?'r-'.$cur:'' ?>" onchange="this.classList.remove('r-reussi','r-echoue','r-np');if(this.value)this.classList.add('r-'+this.value);">
                                <option value="">— Non défini —</option>
                                <option value="reussi" <?= $cur==='reussi'?'selected':'' ?>>✅ Réussi</option>
                                <option value="echoue" <?= $cur==='echoue'?'selected':'' ?>>❌ Échoué</option>
                                <option value="non_presente" <?= $cur==='non_presente'?'selected':'' ?>>➖ Non présenté</option>
                            </select>
                        </td>
                        <td style="font-size:.78rem;color:#718096;">
                            <?= $ts['user_id'] ? 'Lié au compte <strong>#'.$ts['user_id'].'</strong>' : '—' ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
                <div style="display:flex;gap:.75rem;align-items:center;padding-top:1rem;" class="no-print">
                    <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Enregistrer les résultats</button>
                    <span style="color:#718096;font-size:.85rem;">Les lignes « Non défini » suppriment le résultat enregistré.</span>
                </div>
                <?php endif; ?>
            </form>
        </div>
        <?php else: ?>

        <!-- ── Partie 2 : Déconnexion des comptes des admis ── -->
        <div class="card">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-user-slash"></i> Déconnexion des admis au bac — <?= e($year) ?></span>
            </div>
            <?php if (empty($passedStudents)): ?>
            <div class="empty-msg">
                <i class="fas fa-clipboard-check" style="font-size:2.5rem;margin-bottom:.5rem;"></i><br>
                Aucun élève marqué « Réussi » pour cette année.<br>
                <span style="font-size:.8rem;">Définissez d'abord les résultats dans l'onglet « Résultats au bac ».</span>
            </div>
            <?php else: ?>
            <div style="padding:.5rem 0 1rem;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.5rem;">
                <span><strong><?= count($passedStudents) ?></strong> admis au bac — leurs comptes (élèves et parents liés) peuvent être déconnectés.</span>
                <form method="POST" style="display:inline" onsubmit="return confirm('Déconnecter tous les comptes actifs des admis ?');">
                    <?= csrfField() ?>
                    <input type="hidden" name="action" value="bulk_deactivate">
                    <button type="submit" class="btn-action btn-danger"><i class="fas fa-user-slash"></i> Tout déconnecter</button>
                </form>
            </div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>#</th><th>Élève admis</th><th>Classe</th><th>Comptes liés (élève / parents)</th></tr></thead>
                <tbody>
                <?php foreach ($passedStudents as $i => $ps): ?>
                <tr>
                    <td><?= $i+1 ?></td>
                    <td><strong><?= e($ps['last_name']) ?> <?= e($ps['first_name']) ?></strong><br><span class="account-status actif">✅ Admis</span></td>
                    <td><?= e($ps['class_name']) ?></td>
                    <td>
                        <?php
                        $accounts = [];
                        if (!empty($ps['student_account_id'])) {
                            $accounts[] = [
                                'id'     => (int)$ps['student_account_id'],
                                'label'  => 'Compte élève',
                                'name'   => $ps['student_account_name'] ?? '',
                                'email'  => $ps['student_email'] ?? '',
                                'active' => (int)($ps['student_active'] ?? 0),
                            ];
                        }
                        foreach ($parentMap[$ps['student_id']] ?? [] as $pa) {
                            $accounts[] = [
                                'id'     => (int)$pa['parent_account_id'],
                                'label'  => 'Compte parent',
                                'name'   => $pa['parent_name'] ?? '',
                                'email'  => $pa['parent_email'] ?? '',
                                'active' => (int)($pa['parent_active'] ?? 0),
                            ];
                        }
                        if (empty($accounts)): ?>
                            <span style="color:#a0aec0;font-size:.8rem;">Aucun compte lié.</span>
                        <?php else:
                            foreach ($accounts as $acc): ?>
                            <div class="account-row">
                                <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;flex-wrap:wrap;">
                                    <div>
                                        <strong style="font-size:.85rem;"><?= e($acc['label']) ?></strong>
                                        <?php if ($acc['name']): ?><span style="color:#718096;font-size:.78rem;"> — <?= e($acc['name']) ?></span><?php endif; ?><br>
                                        <span class="email"><?= e($acc['email']) ?></span>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:.5rem;">
                                        <span class="account-status <?= $acc['active'] ? 'actif' : 'inactif' ?>"><?= $acc['active'] ? 'Actif' : 'Déconnecté' ?></span>
                                        <?php if ($acc['active']): ?>
                                        <form method="POST" style="display:inline" onsubmit="return confirm('Déconnecter ce compte ?');">
                                            <?= csrfField() ?>
                                            <input type="hidden" name="action" value="toggle_account">
                                            <input type="hidden" name="account_id" value="<?= $acc['id'] ?>">
                                            <button type="submit" class="btn-action btn-danger" style="font-size:.75rem;padding:.3rem .6rem;"><i class="fas fa-user-slash"></i> Déconnecter</button>
                                        </form>
                                        <?php else: ?>
                                        <form method="POST" style="display:inline">
                                            <?= csrfField() ?>
                                            <input type="hidden" name="action" value="toggle_account">
                                            <input type="hidden" name="account_id" value="<?= $acc['id'] ?>">
                                            <input type="hidden" name="activate" value="1">
                                            <button type="submit" class="btn-action btn-success" style="font-size:.75rem;padding:.3rem .6rem;"><i class="fas fa-undo"></i> Réactiver</button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach;
                        endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <?php endif; ?>
        </div>

        <!-- ── Partie 3 : Déconnexion des comptes des abandons ── -->
        <div class="card" style="margin-top:1rem;">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-user-slash"></i> Déconnexion des abandons — <?= e($year) ?></span>
            </div>
            <div style="padding:.5rem 1rem 0;font-size:.8rem;color:#b7791f;"><i class="fas fa-info-circle"></i> Élèves marqués « En abandon » dans leur fiche (date de sortie).</div>
            <?php if (empty($abandonedStudents)): ?>
            <div class="empty-msg">
                <i class="fas fa-user-minus" style="font-size:2.5rem;margin-bottom:.5rem;"></i><br>
                Aucun élève en abandon pour cette année.<br>
                <span style="font-size:.8rem;">Marquez un élève « En abandon » dans <a href="students.php">la liste des élèves</a> pour le faire apparaître ici.</span>
            </div>
            <?php else: ?>
            <div style="padding:.5rem 0 1rem;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.5rem;">
                <span><strong><?= count($abandonedStudents) ?></strong> élève(s) en abandon — leurs comptes (élèves et parents liés) peuvent être déconnectés.</span>
                <form method="POST" style="display:inline" onsubmit="return confirm('Déconnecter tous les comptes actifs des abandons ?');">
                    <?= csrfField() ?>
                    <input type="hidden" name="action" value="bulk_deactivate_abandon">
                    <button type="submit" class="btn-action btn-danger"><i class="fas fa-user-slash"></i> Tout déconnecter (abandons)</button>
                </form>
            </div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>#</th><th>Élève en abandon</th><th>Classe</th><th>Abandon le</th><th>Comptes liés (élève / parents)</th></tr></thead>
                <tbody>
                <?php foreach ($abandonedStudents as $i => $as): ?>
                <tr>
                    <td><?= $i+1 ?></td>
                    <td><strong><?= e($as['last_name']) ?> <?= e($as['first_name']) ?></strong><br><span class="account-status inactif">✖ Abandon</span></td>
                    <td><?= e($as['class_name']) ?></td>
                    <td><?= $as['dropped_out'] ? formatDate($as['dropped_out']) : '—' ?></td>
                    <td>
                        <?php
                        $accounts = [];
                        if (!empty($as['student_account_id'])) {
                            $accounts[] = [
                                'id'     => (int)$as['student_account_id'],
                                'label'  => 'Compte élève',
                                'name'   => $as['student_account_name'] ?? '',
                                'email'  => $as['student_email'] ?? '',
                                'active' => (int)($as['student_active'] ?? 0),
                            ];
                        }
                        foreach ($abandonParentMap[$as['student_id']] ?? [] as $pa) {
                            $accounts[] = [
                                'id'     => (int)$pa['parent_account_id'],
                                'label'  => 'Compte parent',
                                'name'   => $pa['parent_name'] ?? '',
                                'email'  => $pa['parent_email'] ?? '',
                                'active' => (int)($pa['parent_active'] ?? 0),
                            ];
                        }
                        if (empty($accounts)): ?>
                            <span style="color:#a0aec0;font-size:.8rem;">Aucun compte lié.</span>
                        <?php else:
                            foreach ($accounts as $acc): ?>
                            <div class="account-row">
                                <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;flex-wrap:wrap;">
                                    <div>
                                        <strong style="font-size:.85rem;"><?= e($acc['label']) ?></strong>
                                        <?php if ($acc['name']): ?><span style="color:#718096;font-size:.78rem;"> — <?= e($acc['name']) ?></span><?php endif; ?><br>
                                        <span class="email"><?= e($acc['email']) ?></span>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:.5rem;">
                                        <span class="account-status <?= $acc['active'] ? 'actif' : 'inactif' ?>"><?= $acc['active'] ? 'Actif' : 'Déconnecté' ?></span>
                                        <?php if ($acc['active']): ?>
                                        <form method="POST" style="display:inline" onsubmit="return confirm('Déconnecter ce compte ?');">
                                            <?= csrfField() ?>
                                            <input type="hidden" name="action" value="toggle_account">
                                            <input type="hidden" name="account_id" value="<?= $acc['id'] ?>">
                                            <button type="submit" class="btn-action btn-danger" style="font-size:.75rem;padding:.3rem .6rem;"><i class="fas fa-user-slash"></i> Déconnecter</button>
                                        </form>
                                        <?php else: ?>
                                        <form method="POST" style="display:inline">
                                            <?= csrfField() ?>
                                            <input type="hidden" name="action" value="toggle_account">
                                            <input type="hidden" name="account_id" value="<?= $acc['id'] ?>">
                                            <input type="hidden" name="activate" value="1">
                                            <button type="submit" class="btn-action btn-success" style="font-size:.75rem;padding:.3rem .6rem;"><i class="fas fa-undo"></i> Réactiver</button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach;
                        endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
