<?php
/**
 * Gestion des élèves
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error  = '';

$schoolFilter = currentSchoolId();
requirePermission('students', 'view');

// 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) {}

// ── Suppression ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    checkDeleteAllowed();
    if ($schoolFilter) {
        $check = $pdo->prepare("SELECT id FROM students WHERE id = ? AND school_id = ?");
        $check->execute([$id, $schoolFilter]);
        if (!$check->fetch()) { flashMessage('error', 'Action non autorisée.'); header('Location: students.php'); exit; }
    }
    // Vérifier si l'élève a déjà des notes (bulletin)
    $hasGrades = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE student_id=?");
    $hasGrades->execute([$id]);
    if ($hasGrades->fetchColumn() > 0 && !isSuperAdmin()) {
        flashMessage('error', 'Cet élève a déjà un bulletin. Seul le super administrateur peut le supprimer.');
        header('Location: students.php'); exit;
    }
    $pdo->prepare("DELETE FROM students WHERE id = ?")->execute([$id]);
    flashMessage('success', 'Élève supprimé.');
    header('Location: students.php'); exit;
}

// ── Suppression multiple ──
if (isset($_POST['bulk_delete'])) {
    verifyCsrf();
    checkDeleteAllowed();
    $ids = isset($_POST['student_ids']) ? array_map('intval', (array)$_POST['student_ids']) : [];
    $deleted = 0;
    foreach ($ids as $sid) {
        if ($schoolFilter) {
            $chk = $pdo->prepare("SELECT id FROM students WHERE id=? AND school_id=?");
            $chk->execute([$sid, $schoolFilter]);
            if (!$chk->fetch()) continue;
        }
        // Vérifier si l'élève a des notes
        $hasGrades = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE student_id=?");
        $hasGrades->execute([$sid]);
        if ($hasGrades->fetchColumn() > 0 && !isSuperAdmin()) continue;
        $pdo->prepare("DELETE FROM students WHERE id=?")->execute([$sid]);
        $deleted++;
    }
    flashMessage('success', "$deleted élève(s) supprimé(s).");
    header('Location: students.php'); exit;
}

// ── Export CSV ─────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=eleves.csv');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['École','Classe','Prénom','Nom','Genre','DateNaissance','Parent','Téléphone parent'], ';');
    $expWhere = ''; $expParams = [];
    if ($schoolFilter) { $expWhere = 'WHERE s.school_id = ?'; $expParams[] = $schoolFilter; }
    $expStmt = $pdo->prepare("SELECT s.*, sc.name AS school_name, c.name AS class_name FROM students s LEFT JOIN schools sc ON s.school_id=sc.id LEFT JOIN classes c ON s.class_id=c.id $expWhere ORDER BY s.last_name, s.first_name");
    $expStmt->execute($expParams);
    foreach ($expStmt as $s) {
        fputcsv($out, [$s['school_name'], $s['class_name'], $s['first_name'], $s['last_name'], $s['gender'], $s['birth_date'], $s['parent_name'], $s['parent_phone']], ';');
    }
    fclose($out);
    exit;
}

// ── Import CSV ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    verifyCsrf();
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        flashMessage('error', 'Erreur lors du téléchargement du fichier.');
        header('Location: students.php'); exit;
    }
    $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
    $header = fgetcsv($handle, 0, ';');
    if (!$header || count($header) < 4) {
        fclose($handle);
        flashMessage('error', 'Format CSV invalide. Vérifiez le séparateur (;) et le nombre de colonnes.');
        header('Location: students.php'); exit;
    }
    $schoolMap = [];
    foreach ($pdo->query("SELECT id, name FROM schools ORDER BY name") as $sc) {
        $schoolMap[strtolower(trim($sc['name']))] = $sc['id'];
    }
    $classMap = [];
    foreach ($pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c')) as $cl) {
        $classMap[strtolower(trim($cl['name']))] = $cl;
    }
    $imported = 0; $errors = []; $rowNum = 0;
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++;
        $schoolName  = trim($row[0] ?? '');
        $className   = trim($row[1] ?? '');
        $first_name  = trim($row[2] ?? '');
        $last_name   = trim($row[3] ?? '');
        $gender      = trim($row[4] ?? '');
        $birth_date  = trim($row[5] ?? '');
        $parent_name = trim($row[6] ?? '');
        $parent_phone= trim($row[7] ?? '');
        if (empty($first_name) || empty($last_name)) continue;
        $schoolId = $schoolFilter ?: 0;
        if (!$schoolId && $schoolName) {
            $schoolId = $schoolMap[strtolower($schoolName)] ?? 0;
            if (!$schoolId) { $errors[] = "Ligne $rowNum : école '$schoolName' introuvable"; continue; }
        }
        $classId = null;
        if ($className) {
            $clEntry = $classMap[strtolower($className)] ?? null;
            if (!$clEntry) { $errors[] = "Ligne $rowNum : classe '$className' introuvable"; continue; }
            $classId = $clEntry['id'];
        }
        $gender = in_array($gender, ['M','F','Autre']) ? $gender : null;
        $bd = $birth_date ?: null;
        try {
            $pdo->prepare("INSERT INTO students (school_id, class_id, first_name, last_name, gender, birth_date, parent_name, parent_phone) VALUES (?,?,?,?,?,?,?,?)")
                ->execute([$schoolId, $classId, $first_name, $last_name, $gender, $bd, $parent_name ?: null, $parent_phone ?: null]);
            $imported++;
        } catch (PDOException $e) {
            $errors[] = "Ligne $rowNum : " . $e->getMessage();
        }
    }
    fclose($handle);
    $msg = "$imported élève(s) importé(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg);
    header('Location: students.php'); exit;
}

// ── Session : définir/réinitialiser année/période/école/classe active ──
if ($action === 'clear_session') {
    verifyCsrf();
    unset($_SESSION['active_academic_year']);
    unset($_SESSION['active_period']);
    unset($_SESSION['active_school_filter']);
    unset($_SESSION['active_class_filter']);
    flashMessage('success', 'Filtres réinitialisés.');
    header('Location: students.php'); exit;
}
if ($action === 'set_session_filters') {
    if (isset($_POST['annee_active'])) {
        $val = trim($_POST['annee_active']);
        $_SESSION['active_academic_year'] = $val ?: null;
    }
    if (isset($_POST['periode_active'])) {
        $val = (int)$_POST['periode_active'];
        setActivePeriod($val);
    }
    if (isset($_POST['ecole_active'])) {
        $val = (int)$_POST['ecole_active'];
        $_SESSION['active_school_filter'] = $val ?: null;
    }
    if (isset($_POST['classe_active'])) {
        $val = (int)$_POST['classe_active'];
        $_SESSION['active_class_filter'] = $val ?: null;
    }
    flashMessage('success', 'Filtres mis à jour.');
    header('Location: students.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $school_id    = (int)($_POST['school_id'] ?? 0);
    $class_id     = !empty($_POST['class_id']) ? (int)$_POST['class_id'] : null;
    $first_name   = trim($_POST['first_name'] ?? '');
    $last_name    = trim($_POST['last_name'] ?? '');
    $gender       = $_POST['gender'] ?? null;
    $birth_date   = !empty($_POST['birth_date']) ? $_POST['birth_date'] : null;
    $parent_name  = trim($_POST['parent_name'] ?? '');
    $parent_phone = trim($_POST['parent_phone'] ?? '');
    $abandoned    = !empty($_POST['abandoned']);
    $dropped_out  = null;
    if ($abandoned) {
        $dropped_out = !empty($_POST['dropped_out']) ? $_POST['dropped_out'] : date('Y-m-d');
    }

    if (empty($first_name) || empty($last_name)) {
        $error = 'Le prénom et le nom sont requis.';
    } elseif ($school_id <= 0) {
        $error = 'Veuillez sélectionner une école.';
    } else {
        if ($schoolFilter) $school_id = $schoolFilter;
        $sc = $pdo->prepare("SELECT id FROM schools WHERE id = ?");
        $sc->execute([$school_id]);
        if (!$sc->fetch()) $error = 'École invalide.';
    }

    if (empty($error)) {
        $fullName = trim("$last_name $first_name");
        $data = [$school_id, $class_id, $first_name, $last_name, $gender, $birth_date, $parent_name, $parent_phone, $dropped_out];
        if ($id) {
            if ($schoolFilter) {
                $check = $pdo->prepare("SELECT id FROM students WHERE id = ? AND school_id = ?");
                $check->execute([$id, $schoolFilter]);
                if (!$check->fetch()) { flashMessage('error', 'Action non autorisée.'); header('Location: students.php'); exit; }
            }
            $data[] = $id;
            $pdo->prepare("UPDATE students SET school_id=?, class_id=?, first_name=?, last_name=?, gender=?, birth_date=?, parent_name=?, parent_phone=?, dropped_out=? WHERE id=?")->execute($data);
            // Sync user account if linked
            $st = $pdo->prepare("SELECT user_id FROM students WHERE id=?");
            $st->execute([$id]);
            $uid = $st->fetchColumn();
            if ($uid) {
                $pdo->prepare("UPDATE users SET name=?, gender=?, birth_date=? WHERE id=?")
                    ->execute([$fullName, $gender, $birth_date, $uid]);
            }
            flashMessage('success', 'Élève mis à jour.');
        } else {
            $pdo->prepare("INSERT INTO students (school_id, class_id, first_name, last_name, gender, birth_date, parent_name, parent_phone, dropped_out) VALUES (?,?,?,?,?,?,?,?,?)")->execute($data);
            $newSid = $pdo->lastInsertId();
            // Auto-create user account
            $emailBase = strtolower(trim(preg_replace('/[^a-zA-Z0-9]/', '.', "$first_name $last_name"), '.'));
            $emailBase = preg_replace('/\.+/', '.', $emailBase);
            $email = $emailBase . random_int(10, 99) . '@nukunu.edu';
            $password = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 8) . '@' . random_int(10, 99);
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
            try {
                $pdo->prepare("INSERT INTO users (school_id, name, email, password, plain_password, role, gender, birth_date, active) VALUES (?,?,?,?,?,'student',?,?,1)")
                    ->execute([$school_id, $fullName, $email, $hash, $password, $gender, $birth_date]);
                $newUid = $pdo->lastInsertId();
                $pdo->prepare("UPDATE students SET user_id=? WHERE id=?")->execute([$newUid, $newSid]);
                flashMessage('success', "Élève ajouté. Compte créé : <strong>$email</strong> / mot de passe : <strong>$password</strong>");
            } catch (PDOException $e) {
                flashMessage('success', 'Élève ajouté (échec création du compte utilisateur).');
            }
        }
        header('Location: students.php'); exit;
    }
}

// ── Sync profiles ──────────────────────────────────────────────────────────────
if (isset($_GET['sync'])) {
    verifyCsrf();
    requirePermission('students', 'edit');
    $synced = 0; $errors = [];

    $where = ''; $params = [];
    if ($schoolFilter) { $where = 'WHERE s.school_id = ?'; $params[] = $schoolFilter; }
    $all = $pdo->prepare("SELECT s.* FROM students s $where ORDER BY s.last_name, s.first_name");
    $all->execute($params);

    while ($s = $all->fetch(PDO::FETCH_ASSOC)) {
        $sid = (int)$s['id'];
        $fullName = trim($s['last_name'] . ' ' . $s['first_name']);

        try {
            if ($s['user_id']) {
                $pdo->prepare("UPDATE users SET name=?, gender=?, birth_date=? WHERE id=?")
                    ->execute([$fullName, $s['gender'], $s['birth_date'], $s['user_id']]);
            } else {
                $emailBase = strtolower(trim(preg_replace('/[^a-zA-Z0-9]/', '.', $fullName), '.'));
                $emailBase = preg_replace('/\.+/', '.', $emailBase);
                $email = $emailBase . random_int(10, 99) . '@nukunu.edu';
                $password = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 8) . '@' . random_int(10, 99);
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
                $pdo->prepare("INSERT INTO users (school_id, name, email, password, plain_password, role, gender, birth_date, active) VALUES (?,?,?,?,?,'student',?,?,1)")
                    ->execute([$s['school_id'], $fullName, $email, $hash, $password, $s['gender'], $s['birth_date']]);
                $newUid = $pdo->lastInsertId();
                $pdo->prepare("UPDATE students SET user_id=? WHERE id=?")->execute([$newUid, $sid]);
            }
            $synced++;
        } catch (PDOException $e) {
            $errors[] = "Student #{$sid}: " . $e->getMessage();
        }
    }

    if ($synced > 0) {
        flashMessage('success', "$synced élève(s) synchronisé(s) avec succès.");
    }
    if (!empty($errors)) {
        flashMessage('error', 'Erreurs : ' . implode('. ', array_slice($errors, 0, 5)));
    }
    header('Location: students.php'); exit;
}

// ── Chargement pour édition ───────────────────────────────────────────────────
$student = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?" . ($schoolFilter ? " AND school_id = ?" : ""));
    $stmt->execute($schoolFilter ? [$id, $schoolFilter] : [$id]);
    $student = $stmt->fetch();
    if (!$student) { flashMessage('error', 'Élève introuvable.'); header('Location: students.php'); exit; }
}

// ── Données pour les selects ──────────────────────────────────────────────────
if ($schoolFilter) {
    $schoolsStmt = $pdo->prepare("SELECT id, name FROM schools WHERE id = ?");
    $schoolsStmt->execute([$schoolFilter]);
    $schools = $schoolsStmt->fetchAll();
    $classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
} else {
    $schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
    $classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
}

// ── Tri ───────────────────────────────────────────────────────────────────────
$sortAllowed = ['first_name', 'last_name', 'class_name', 'school_name', 'gender', 'birth_date', 'created_at'];
$sort = resolveSort($sortAllowed, 'last_name', 'asc');

// Mapping colonne triable → expression SQL
$sortMap = [
    'first_name'  => 's.first_name',
    'last_name'   => 's.last_name',
    'class_name'  => 'c.name',
    'school_name' => 'sc.name',
    'gender'      => 's.gender',
    'birth_date'  => 's.birth_date',
    'created_at'  => 's.created_at',
];
$orderExpr = ($sortMap[$sort['col']] ?? 's.last_name') . ' ' . $sort['dir'];

// ── Liste des élèves ──────────────────────────────────────────────────────────
$sessionClass = $_SESSION['active_class_filter'] ?? null;
$listSql = "
    SELECT s.*, sc.name AS school_name, c.name AS class_name
    FROM students s
    LEFT JOIN schools sc ON s.school_id = sc.id
    LEFT JOIN classes c  ON s.class_id  = c.id
";
$where = []; $params = [];
if ($schoolFilter) { $where[] = 's.school_id = ?'; $params[] = $schoolFilter; }
if ($sessionClass) { $where[] = 's.class_id = ?'; $params[] = $sessionClass; }
$listSql .= $where ? ' WHERE ' . implode(' AND ', $where) : '';
$listStmt = $pdo->prepare($listSql . " ORDER BY $orderExpr");
$listStmt->execute($params);
$students = $listStmt->fetchAll();

$sessionYear   = $_SESSION['active_academic_year'] ?? '';
$sessionPeriod = getActivePeriod();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;
$yearsList = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
$ecoles = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
$classesFilter = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Élèves - 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;
  }

  .prog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 1rem;
  }
  .prog-header h1 {
    font-family: Georgia, serif;
    color: var(--primary);
    font-size: 1.6rem;
  }
  .prog-header 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: 180px;
  }
  .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;
  }
  .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;
  }
  .table-card .tc-count {
    background: var(--light);
    color: var(--primary);
    padding: 3px 10px;
    border-radius: 20px;
    font-size: .75rem;
    font-weight: 600;
  }

  .prog-table {
    width: 100%;
    border-collapse: collapse;
  }
  .prog-table thead {
    background: var(--primary);
    color: white;
  }
  .prog-table th {
    padding: .7rem 1rem;
    text-align: left;
    font-weight: 600;
    font-size: .78rem;
    text-transform: uppercase;
    letter-spacing: .4px;
  }
  .prog-table th a {
    color: white;
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 4px;
  }
  .prog-table th a:hover { text-decoration: underline; }
  .prog-table td {
    padding: .7rem 1rem;
    border-bottom: 1px solid #E5E7EB;
    font-size: .85rem;
    vertical-align: middle;
  }
  .prog-table tbody tr:hover { background: #F9FAFB; }
  .prog-table .checkbox-wrapper { text-align: center; }

  .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: 540px;
    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.2rem;
    margin-bottom: 1.25rem;
    display: flex;
    align-items: center;
    gap: .5rem;
  }
  .modal-box .form-group { margin: 0; }
  .modal-box .form-group label { font-size: .8rem; }

  .btn { display: inline-flex; align-items: center; gap: 6px; padding: .55rem 1.25rem; 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-danger { background: #DC2626; color: white; }
  .btn-danger:hover { background: #B91C1C; }
  .btn-light { background: #E5E7EB; color: #374151; }
  .btn-light:hover { background: #D1D5DB; }

  .search-input {
    width: 100%;
    max-width: 320px;
    padding: .55rem .75rem;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: .85rem;
  }
  .search-input:focus {
    outline: none;
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(46,117,182,0.15);
  }

  .empty-state {
    text-align: center;
    padding: 3rem 1rem;
    color: #9CA3AF;
  }
  .empty-state .icon { font-size: 2.5rem; margin-bottom: .5rem; }

  .form-grid-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
  }
  .form-grid-2 .full { grid-column: 1 / -1; }

  @media (max-width: 768px) {
    .filters-row { flex-direction: column; }
    .filter-group { min-width: 100%; }
    .prog-table th, .prog-table td { padding: .5rem .6rem; font-size: .78rem; }
    .form-grid-2 { grid-template-columns: 1fr; }
  }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-user-graduate"></i> Élèves'; include '../includes/topbar.php'; ?>

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

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-user-graduate" style="color:var(--primary);"></i> Élèves</h1>
                <p>Gérez les élèves inscrits</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> Ajouter</a>
                <a href="?export=1" class="btn btn-light"><i class="fas fa-download"></i> Exporter</a>
                <button class="btn btn-light" onclick="document.getElementById('importModal').classList.add('open')"><i class="fas fa-upload"></i> Importer</button>
                <a href="#" onclick="return downloadTemplate()" class="btn btn-light"><i class="fas fa-file-export"></i> Modèle</a>
                <a href="?sync=1&csrf_token=<?= csrfToken() ?>" class="btn btn-light" onclick="return confirm('Synchroniser les comptes utilisateurs à partir des fiches élèves ?')"><i class="fas fa-sync-alt"></i> Synchroniser</a>
                <a href="id_cards.php?type=students&school_id=<?= $schoolFilter ?? '' ?>" class="btn btn-light"><i class="fas fa-id-card"></i> Cartes identité</a>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="post" action="?action=set_session_filters" class="filters-card">
            <div class="filters-row">
                <div class="filter-group">
                    <label><i class="fas fa-calendar"></i> Année</label>
                    <select name="annee_active" onchange="this.form.submit()">
                        <option value="">-- Par défaut --</option>
                        <?php foreach ($yearsList as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y === $sessionYear ? '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="periode_active" onchange="this.form.submit()">
                        <option value="">-- Par défaut --</option>
                        <?php for ($p = 1; $p <= 3; $p++): ?>
                        <option value="<?= $p ?>" <?= $p === $sessionPeriod ? 'selected' : '' ?>><?= $p ?><?= $p === 1 ? 'er' : 'ème' ?> Trimestre</option>
                        <?php endfor; ?>
                    </select>
                </div>
                <?php if (isSuperAdmin()): ?>
                <div class="filter-group">
                    <label><i class="fas fa-school"></i> École</label>
                    <select name="ecole_active" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($ecoles as $ec): ?>
                        <option value="<?= $ec['id'] ?>" <?= ($sessionSchool && $sessionSchool == $ec['id']) ? 'selected' : '' ?>><?= e($ec['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="filter-group">
                    <label><i class="fas fa-users"></i> Classe</label>
                    <select name="classe_active" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($classesFilter as $cl): ?>
                        <option value="<?= $cl['id'] ?>" <?= ($sessionClass == $cl['id']) ? 'selected' : '' ?>><?= e($cl['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div style="align-self:flex-end;">
                    <a href="?action=clear_session&csrf_token=<?= csrfToken() ?>" class="btn btn-light" onclick="return confirm('Réinitialiser les filtres ?')">
                        <i class="fas fa-undo-alt"></i>
                    </a>
                </div>
            </div>
        </form>

        <?php if ($action === 'add' || $action === 'edit'): ?>
        <!-- ═══ Ajout / Modification ═══ -->
        <div class="table-card" style="max-width:720px;">
            <div class="tc-header">
                <div class="tc-title"><?= $student ? 'Modifier' : 'Ajouter' ?> un élève</div>
            </div>
            <div style="padding:1.5rem;">
                <form method="POST">
                    <?= csrfField() ?>
                    <div class="form-grid-2">
                        <div class="form-group">
                            <label>École</label>
                            <select name="school_id" required <?= $schoolFilter ? 'disabled' : '' ?>>
                                <option value="">Choisir...</option>
                                <?php foreach ($schools as $sc): ?>
                                <option value="<?= $sc['id'] ?>" <?= ($student['school_id'] ?? '') == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?= $schoolFilter ?>"><?php endif; ?>
                        </div>
                        <div class="form-group">
                            <label>Classe</label>
                            <select name="class_id">
                                <option value="">Choisir...</option>
                                <?php foreach ($classes as $cl): ?>
                                <option value="<?= $cl['id'] ?>" <?= ($student['class_id'] ?? '') == $cl['id'] ? 'selected' : '' ?>><?= e($cl['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Prénom <span style="color:red">*</span></label>
                            <input type="text" name="first_name" required value="<?= e($student['first_name'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Nom <span style="color:red">*</span></label>
                            <input type="text" name="last_name" required value="<?= e($student['last_name'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Genre</label>
                            <select name="gender">
                                <option value="">-</option>
                                <option value="M" <?= ($student['gender'] ?? '') === 'M' ? 'selected' : '' ?>>Masculin</option>
                                <option value="F" <?= ($student['gender'] ?? '') === 'F' ? 'selected' : '' ?>>Féminin</option>
                                <option value="Autre" <?= ($student['gender'] ?? '') === 'Autre' ? 'selected' : '' ?>>Autre</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Date de naissance</label>
                            <input type="date" name="birth_date" value="<?= e($student['birth_date'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Nom du parent</label>
                            <input type="text" name="parent_name" value="<?= e($student['parent_name'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Téléphone parent</label>
                            <input type="text" name="parent_phone" value="<?= e($student['parent_phone'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Statut</label>
                            <div style="display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;">
                                <label style="display:flex;align-items:center;gap:.35rem;font-weight:400;font-size:.85rem;cursor:pointer;">
                                    <input type="checkbox" name="abandoned" id="abandonedCheck" <?= !empty($student['dropped_out']) ? 'checked' : '' ?> onchange="document.getElementById('droppedOutWrap').style.display = this.checked ? '' : 'none'">
                                    En abandon
                                </label>
                            </div>
                        </div>
                        <div class="form-group" id="droppedOutWrap" <?= empty($student['dropped_out']) ? 'style="display:none"' : '' ?>>
                            <label>Date d'abandon</label>
                            <input type="date" name="dropped_out" value="<?= e($student['dropped_out'] ?? '') ?>">
                            <div style="font-size:.72rem;color:#718096;margin-top:4px;">Laisser vide pour utiliser la date du jour.</div>
                        </div>
                    </div>
                    <div style="margin-top:1.25rem;display:flex;gap:.75rem;">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                        <a href="students.php" class="btn btn-light">Annuler</a>
                    </div>
                </form>
            </div>
        </div>

        <?php else: ?>

        <!-- ═══ Tableau ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des élèves</div>
                <span class="tc-count"><?= count($students) ?> élève(s)</span>
            </div>
            <div style="padding:1rem 1.5rem;border-bottom:1px solid #E5E7EB;">
                <input type="text" id="searchSt" class="search-input" placeholder="Rechercher un élève..." onkeyup="searchTable('searchSt','studentsTable')">
            </div>
            <?php if (empty($students)): ?>
            <div class="empty-state">
                <div class="icon"><i class="fas fa-user-graduate"></i></div>
                <p>Aucun élève enregistré.</p>
                <a href="?action=add" class="btn btn-primary" style="margin-top:1rem;"><i class="fas fa-plus"></i> Ajouter un élève</a>
            </div>
            <?php else: ?>
            <form method="POST" id="bulkFormStudents">
            <input type="hidden" name="bulk_delete" value="1">
            <?= csrfField() ?>
            <table class="prog-table" id="studentsTable">
                <thead>
                    <tr>
                        <?php if (isSuperAdmin()): ?>
                        <th style="width:36px;"><input type="checkbox" onchange="document.querySelectorAll('#bulkFormStudents .row-check').forEach(c=>c.checked=this.checked)"></th>
                        <?php endif; ?>
                        <th><?= sortTh('last_name',   'Nom',  $sort) ?></th>
                        <th><?= sortTh('class_name',  'Classe', $sort) ?></th>
                        <th><?= sortTh('school_name', 'École', $sort) ?></th>
                        <th><?= sortTh('gender',      'Genre', $sort) ?></th>
                        <th><?= sortTh('birth_date',  'Naissance', $sort) ?></th>
                        <th><?= sortTh('created_at',  'Inscrit le', $sort) ?></th>
                        <th style="width:80px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $s): ?>
                    <tr>
                        <?php if (isSuperAdmin()): ?>
                        <td class="checkbox-wrapper"><input type="checkbox" name="student_ids[]" value="<?= $s['id'] ?>" class="row-check"></td>
                        <?php endif; ?>
                        <td><strong><?= e($s['last_name'] . ' ' . $s['first_name']) ?></strong><?php if (!empty($s['dropped_out'])): ?> <span style="display:inline-block;margin-left:.35rem;background:#fed7d7;color:#9b2c2c;font-size:.68rem;font-weight:700;padding:.12rem .5rem;border-radius:10px;" title="Abandon le <?= formatDate($s['dropped_out']) ?>">Abandon</span><?php endif; ?></td>
                        <td><?= e($s['class_name']  ?? '-') ?></td>
                        <td><?= e($s['school_name'] ?? '-') ?></td>
                        <td><?php if ($s['gender']??''): ?><?php if ($s['gender']==='F'): ?><i class="fas fa-female" style="color:#d53f8c;" title="Féminin"></i><?php elseif ($s['gender']==='M'): ?><i class="fas fa-male" style="color:#3182ce;" title="Masculin"></i><?php else: ?><i class="fas fa-venus-mars" style="color:#718096;" title="<?=e($s['gender'])?>"></i><?php endif; ?><?php else: ?>—<?php endif; ?></td>
                        <td><?= formatDate($s['birth_date']) ?></td>
                        <td><?= formatDate($s['created_at']) ?></td>
                        <td>
                            <a href="?action=edit&id=<?= $s['id'] ?>" class="btn btn-light" style="padding:.3rem .6rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                            <?php if (isSuperAdmin()): ?>
                            <a href="?action=delete&id=<?= $s['id'] ?>&csrf_token=<?= csrfToken() ?>" class="btn btn-danger" style="padding:.3rem .6rem;font-size:.75rem;" title="Supprimer" onclick="return confirm('Supprimer cet élève ?')"><i class="fas fa-trash"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php if (isSuperAdmin() && count($students) > 0): ?>
            <div style="padding:.75rem 1.25rem;border-top:1px solid #E5E7EB;">
                <button type="submit" class="btn btn-danger" style="font-size:.78rem;padding:.4rem 1rem;" onclick="return confirm('Supprimer les élèves sélectionnés ?')">
                    <i class="fas fa-trash-alt"></i> Supprimer la sélection
                </button>
            </div>
            <?php endif; ?>
            </form>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ Modal Import ═══ -->
<div class="modal-overlay" id="importModal">
    <div class="modal-box">
        <h2><i class="fas fa-upload"></i> Importer des élèves</h2>
        <p style="color:#6B7280;font-size:.85rem;margin-bottom:1.25rem;">
            <strong>Format CSV</strong> (séparateur <code>;</code>)<br>
            Colonnes : <code>École;Classe;Prénom;Nom;Genre;DateNaissance;Parent;Téléphone parent</code><br>
            <a href="#" onclick="return downloadTemplate()" style="color:var(--accent);">Télécharger un modèle</a>
        </p>
        <form method="POST" enctype="multipart/form-data">
            <?= csrfField() ?>
            <div class="form-group">
                <label>Fichier CSV</label>
                <input type="file" name="csv_file" accept=".csv,.txt" required style="width:100%;">
            </div>
            <div style="margin-top:1rem;display:flex;gap:.75rem;justify-content:flex-end;">
                <button type="button" class="btn btn-light" onclick="document.getElementById('importModal').classList.remove('open')">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 src="../assets/js/main.js"></script>
<script>
function downloadTemplate() {
    const w = window.open('', '_blank');
    w.document.write('<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>td,th{border:1px solid #ccc;padding:4px 8px;font:11px Calibri,sans-serif}th{background:#4472c4;color:#fff;font-weight:700}</style></head><body><table>');
    w.document.write('<tr><th>École</th><th>Classe</th><th>Prénom</th><th>Nom</th><th>Genre</th><th>DateNaissance</th><th>Parent</th><th>Téléphone parent</th></tr>');
    w.document.write('<tr><td>École 1</td><td>CM1</td><td>Jean</td><td>Dupont</td><td>M</td><td>15/03/2012</td><td>Marie Dupont</td><td>0123456789</td></tr>');
    w.document.write('<tr><td>École 1</td><td>CM2</td><td>Marie</td><td>Martin</td><td>F</td><td>22/07/2011</td><td>Pierre Martin</td><td>0987654321</td></tr>');
    w.document.write('</table></body></html>');
    w.document.close();
    w.focus();
    w.print();
    return false;
}

function showToast(message, type) {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    const icons = { success: '&#9989;', error: '&#10060;' };
    toast.innerHTML = '<span>' + (icons[type] || '&#8505;') + '</span><span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 4000);
}

// ── Auto-show flash as toast ──
<?php if ($__flash): ?>
document.addEventListener('DOMContentLoaded', function() {
    showToast(<?= json_encode($__flash['message']) ?>, <?= json_encode($__flash['type'] === 'success' ? 'success' : 'error') ?>);
});
<?php endif; ?>
</script>
</body>
</html>
