<?php
declare(strict_types=1);
require_once __DIR__.'/../app/layout.php';
require_once __DIR__.'/../app/config_system.php';
require_once __DIR__.'/../app/notifications.php';
$u   = require_role('ADMIN');
$pdo = app_pdo();
$year = (int)sys_cfg('school_year_active', date('Y'));

/* ══════════════════════════════════════════════════════════
   Detectar tablas y columnas disponibles
   ══════════════════════════════════════════════════════════ */
$_tables    = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
$has_sa     = in_array('student_assignments', $_tables);
$has_levels = in_array('levels', $_tables) && in_array('grades', $_tables);
$has_tasks  = in_array('task_submissions', $_tables) && in_array('tasks', $_tables);

$_ucols    = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
$has_bday  = in_array('birth_date',   $_ucols);
$has_parent= in_array('parent_name',  $_ucols);
$has_pphone= in_array('parent_phone', $_ucols);
$has_phone = in_array('phone',        $_ucols);

/* ══════════════════════════════════════════════════════════
   Helper — obtener alumno
   ══════════════════════════════════════════════════════════ */
function fetch_alumno(PDO $pdo, int $id, int $year,
    bool $has_sa, bool $has_levels): array
{
    if ($has_sa && $has_levels) {
        return $pdo->query("
            SELECT u.*,
                sa.level_id, sa.grade_id,
                l.name AS lv, g.name AS gr
            FROM users u
            LEFT JOIN student_assignments sa
                ON sa.student_id=u.id AND sa.school_year=$year AND sa.is_active=1
            LEFT JOIN levels l ON l.id=sa.level_id
            LEFT JOIN grades g ON g.id=sa.grade_id
            WHERE u.id=$id
        ")->fetch() ?: [];
    }
    return $pdo->query("SELECT * FROM users WHERE id=$id")->fetch() ?: [];
}

/* ══════════════════════════════════════════════════════════
   POST — acciones AJAX
   ══════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $act = $_POST['act'] ?? '';

    /* ── Crear alumno ──────────────────────────────────── */
    if ($act === 'create') {
        $dni    = preg_replace('/\D/', '', $_POST['dni']       ?? '');
        $name   = trim($_POST['full_name']                     ?? '');
        $email  = trim($_POST['email']                         ?? '');
        $phone  = trim($_POST['phone']                         ?? '');
        $pass   = trim($_POST['password']                      ?? $dni);
        $bday   = ($has_bday   ? ($_POST['birth_date']   ?? null) : null);
        $parent = ($has_parent ? trim($_POST['parent_name']  ?? '') : '');
        $pphone = ($has_pphone ? trim($_POST['parent_phone'] ?? '') : '');
        $lid    = (int)($_POST['level_id'] ?? 0);
        $gid    = (int)($_POST['grade_id'] ?? 0);

        if (!preg_match('/^\d{7,12}$/', $dni)) json_err('DNI inválido (7-12 dígitos).');
        if (strlen($name) < 3)                  json_err('Nombre muy corto.');
        if (strlen($pass) < 4)                  json_err('Contraseña mínimo 4 caracteres.');

        $dup = $pdo->prepare('SELECT id FROM users WHERE dni=?');
        $dup->execute([$dni]);
        if ($dup->fetchColumn()) json_err("El DNI $dni ya está registrado.");

        $ins_cols = 'dni,full_name,email,phone,role,password_hash';
        $ins_vals = '?,?,?,?,?,?';
        $ins_data = [$dni,$name,$email?:null,$phone?:null,'ALUMNO',
                     password_hash($pass, PASSWORD_DEFAULT)];
        if ($has_bday)   { $ins_cols .= ',birth_date';   $ins_vals .= ',?'; $ins_data[] = $bday   ?: null; }
        if ($has_parent) { $ins_cols .= ',parent_name';  $ins_vals .= ',?'; $ins_data[] = $parent ?: null; }
        if ($has_pphone) { $ins_cols .= ',parent_phone'; $ins_vals .= ',?'; $ins_data[] = $pphone ?: null; }

        $pdo->prepare("INSERT INTO users ($ins_cols) VALUES($ins_vals)")->execute($ins_data);
        $new_uid = (int)$pdo->lastInsertId();

        if ($has_sa && $lid && $gid) {
            $chk = $pdo->prepare("SELECT id FROM student_assignments
                WHERE student_id=? AND school_year=?");
            $chk->execute([$new_uid, $year]);
            if (!$chk->fetchColumn()) {
                $pdo->prepare("INSERT INTO student_assignments
                    (student_id,level_id,grade_id,school_year) VALUES(?,?,?,?)")
                    ->execute([$new_uid,$lid,$gid,$year]);
            }
        }

        $row = fetch_alumno($pdo, $new_uid, $year, $has_sa, $has_levels);
        json_ok("Alumno $name registrado.", ['alumno' => $row]);
    }

    /* ── Editar alumno ─────────────────────────────────── */
    if ($act === 'edit') {
        $id     = (int)($_POST['id']          ?? 0);
        $dni    = preg_replace('/\D/', '', $_POST['dni'] ?? '');
        $name   = trim($_POST['full_name']    ?? '');
        $email  = trim($_POST['email']        ?? '');
        $phone  = trim($_POST['phone']        ?? '');
        $pass   = trim($_POST['password']     ?? '');
        $bday   = ($has_bday   ? ($_POST['birth_date']   ?? null) : null);
        $parent = ($has_parent ? trim($_POST['parent_name']  ?? '') : '');
        $pphone = ($has_pphone ? trim($_POST['parent_phone'] ?? '') : '');

        if (!$id)                              json_err('ID inválido.');
        if (!preg_match('/^\d{7,12}$/', $dni)) json_err('DNI inválido.');
        if (strlen($name) < 3)                 json_err('Nombre muy corto.');

        $dup = $pdo->prepare('SELECT id FROM users WHERE dni=? AND id<>?');
        $dup->execute([$dni, $id]);
        if ($dup->fetchColumn()) json_err("El DNI $dni pertenece a otro usuario.");

        $set_cols = 'dni=?,full_name=?,email=?,phone=?';
        $set_data = [$dni,$name,$email?:null,$phone?:null];
        if ($has_bday)   { $set_cols .= ',birth_date=?';   $set_data[] = $bday   ?: null; }
        if ($has_parent) { $set_cols .= ',parent_name=?';  $set_data[] = $parent ?: null; }
        if ($has_pphone) { $set_cols .= ',parent_phone=?'; $set_data[] = $pphone ?: null; }
        if ($pass) {
            $set_cols .= ',password_hash=?';
            $set_data[] = password_hash($pass, PASSWORD_DEFAULT);
        }
        $set_data[] = $id;
        $pdo->prepare("UPDATE users SET $set_cols WHERE id=?")->execute($set_data);

        $row = fetch_alumno($pdo, $id, $year, $has_sa, $has_levels);
        json_ok('Alumno actualizado.', ['alumno' => $row]);
    }

    /* ── Toggle activo/inactivo ────────────────────────── */
    if ($act === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE users SET is_active=1-is_active WHERE id=? AND role='ALUMNO'")
            ->execute([$id]);
        $is = (int)$pdo->query("SELECT is_active FROM users WHERE id=$id")->fetchColumn();
        json_ok($is ? 'Alumno activado.' : 'Alumno desactivado.', ['is_active' => $is]);
    }

    /* ── Resetear contraseña ───────────────────────────── */
    if ($act === 'reset_pass') {
        $id  = (int)($_POST['id']  ?? 0);
        $new = trim($_POST['pass'] ?? '');
        if (strlen($new) < 4) json_err('Mínimo 4 caracteres.');
        $pdo->prepare("UPDATE users SET password_hash=? WHERE id=? AND role='ALUMNO'")
            ->execute([password_hash($new, PASSWORD_DEFAULT), $id]);
        json_ok('Contraseña restablecida.');
    }

    /* ── Asignar / Cambiar grado ───────────────────────── */
    if ($act === 'set_grade' && $has_sa) {
        $sid = (int)($_POST['student_id'] ?? 0);
        $lid = (int)($_POST['level_id']   ?? 0);
        $gid = (int)($_POST['grade_id']   ?? 0);
        if (!$sid || !$lid || !$gid) json_err('Completa todos los campos.');

        $exist = $pdo->prepare("SELECT id FROM student_assignments
            WHERE student_id=? AND school_year=?");
        $exist->execute([$sid, $year]);
        $eid = $exist->fetchColumn();
        if ($eid) {
            $pdo->prepare("UPDATE student_assignments
                SET level_id=?,grade_id=?,is_active=1 WHERE id=?")
                ->execute([$lid,$gid,$eid]);
        } else {
            $pdo->prepare("INSERT INTO student_assignments
                (student_id,level_id,grade_id,school_year) VALUES(?,?,?,?)")
                ->execute([$sid,$lid,$gid,$year]);
        }
        $info = ['lv' => '', 'gr' => ''];
        if ($has_levels) {
            $info = $pdo->query("SELECT l.name AS lv, g.name AS gr
                FROM levels l, grades g WHERE l.id=$lid AND g.id=$gid")->fetch() ?: $info;
        }
        json_ok('Grado asignado.', ['level' => $info['lv']??'', 'grade' => $info['gr']??'']);
    }

    /* ── Quitar asignación de grado ────────────────────── */
    if ($act === 'remove_grade' && $has_sa) {
        $sid = (int)($_POST['student_id'] ?? 0);
        $pdo->prepare("UPDATE student_assignments SET is_active=0
            WHERE student_id=? AND school_year=?")
            ->execute([$sid, $year]);
        json_ok('Asignación removida.', ['level' => '', 'grade' => '']);
    }

    /* ── Enviar notificación ───────────────────────────── */
    if ($act === 'send_notif') {
        $sid   = (int)($_POST['student_id'] ?? 0);
        $title = trim($_POST['title']       ?? '');
        $body  = trim($_POST['body']        ?? '');
        if (!$sid || !$title) json_err('Faltan datos.');
        notif_create($sid, 'announcement', $title, $body, '', (int)$u['id']);
        json_ok('Notificación enviada al alumno.');
    }

    /* ── Eliminar alumno (soft) ────────────────────────── */
    if ($act === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE users SET is_active=0 WHERE id=? AND role='ALUMNO'")
            ->execute([$id]);
        json_ok('Alumno desactivado permanentemente.');
    }
}

/* ══════════════════════════════════════════════════════════
   GET — cargar datos
   ══════════════════════════════════════════════════════════ */
$q_search = trim($_GET['q']      ?? '');
$f_level  = (int)($_GET['level'] ?? 0);
$f_grade  = (int)($_GET['grade'] ?? 0);
$f_status = $_GET['status']      ?? 'active';
$f_assign = $_GET['assign']      ?? '';
$page     = max(1, (int)($_GET['page'] ?? 1));
$per_page = (int)sys_cfg('admin_per_page', 25);

/* ── WHERE dinámico ── */
$where  = ["u.role='ALUMNO'"];
$params = [];

if ($q_search) {
    $like    = "%$q_search%";
    $extra   = '';
    if ($has_parent) $extra = " OR u.parent_name LIKE ?";
    $where[] = "(u.full_name LIKE ? OR u.dni LIKE ? OR u.email LIKE ?$extra)";
    $params  = array_merge($params, [$like,$like,$like]);
    if ($has_parent) $params[] = $like;
}
if ($f_status === 'active')   $where[] = 'u.is_active=1';
if ($f_status === 'inactive') $where[] = 'u.is_active=0';
if ($has_sa) {
    if ($f_level) {
        $where[]  = "EXISTS(SELECT 1 FROM student_assignments sa
                    WHERE sa.student_id=u.id AND sa.level_id=?
                      AND sa.school_year=? AND sa.is_active=1)";
        $params[] = $f_level; $params[] = $year;
    }
    if ($f_grade) {
        $where[]  = "EXISTS(SELECT 1 FROM student_assignments sa
                    WHERE sa.student_id=u.id AND sa.grade_id=?
                      AND sa.school_year=? AND sa.is_active=1)";
        $params[] = $f_grade; $params[] = $year;
    }
    if ($f_assign === 'yes') {
        $where[]  = "EXISTS(SELECT 1 FROM student_assignments sa
                    WHERE sa.student_id=u.id AND sa.school_year=? AND sa.is_active=1)";
        $params[] = $year;
    }
    if ($f_assign === 'no') {
        $where[]  = "NOT EXISTS(SELECT 1 FROM student_assignments sa
                    WHERE sa.student_id=u.id AND sa.school_year=? AND sa.is_active=1)";
        $params[] = $year;
    }
}
$whereSQL = 'WHERE ' . implode(' AND ', $where);

/* ── Query 1: Total ── */
try {
    $total_q = $pdo->prepare("SELECT COUNT(*) FROM users u $whereSQL");
    $total_q->execute($params);
    $total = (int)$total_q->fetchColumn();
} catch (Throwable $e) {
    die('<pre style="background:#ffebee;color:#c62828;padding:20px;border-radius:8px">
❌ ERROR COUNT: ' . $e->getMessage() . '
SQL: SELECT COUNT(*) FROM users u ' . $whereSQL . '
Params: ' . print_r($params, true) . '</pre>');
}

$pages  = max(1, (int)ceil($total / $per_page));
$offset = ($page - 1) * $per_page;

/* ── Query 2: Alumnos paginados (adaptativa) ── */
$max_grade = (int)sys_cfg('tasks_max_grade', 20);

if ($has_sa && $has_levels && $has_tasks) {
    /* ✅ FIX: tasks tiene level_id y grade_id directos, sin JOIN a teacher_assignments
              y sin t.max_points — se usa AVG(ts.grade) directo */
    $sql_alumnos = "
        SELECT u.*,
            sa.level_id, sa.grade_id,
            l.name AS lv, g.name AS gr,
            l.id AS lvl_id, g.id AS gr_id,
            sa.id AS sa_id,
            (SELECT COUNT(*)
               FROM task_submissions ts
               JOIN tasks t ON t.id = ts.task_id
               WHERE ts.student_id = u.id
                 AND t.level_id  = sa.level_id
                 AND t.grade_id  = sa.grade_id
                 AND t.school_year = $year
                 AND t.is_active = 1
            ) AS n_submissions,
            (SELECT ROUND(AVG(ts.grade), 1)
               FROM task_submissions ts
               JOIN tasks t ON t.id = ts.task_id
               WHERE ts.student_id = u.id
                 AND ts.grade IS NOT NULL
                 AND t.school_year = $year
            ) AS avg_grade,
            (SELECT COUNT(*)
               FROM task_submissions ts2
               JOIN tasks t2 ON t2.id = ts2.task_id
               WHERE ts2.student_id = u.id
                 AND ts2.grade IS NULL
                 AND t2.school_year = $year
            ) AS n_pending_grade
        FROM users u
        LEFT JOIN student_assignments sa
            ON sa.student_id = u.id AND sa.school_year = $year AND sa.is_active = 1
        LEFT JOIN levels l ON l.id = sa.level_id
        LEFT JOIN grades g ON g.id = sa.grade_id
        $whereSQL
        GROUP BY u.id
        ORDER BY l.sort_order, g.sort_order, u.full_name
        LIMIT $per_page OFFSET $offset
    ";
} elseif ($has_sa && $has_levels) {
    $sql_alumnos = "
        SELECT u.*,
            sa.level_id, sa.grade_id,
            l.name AS lv, g.name AS gr,
            l.id AS lvl_id, g.id AS gr_id,
            sa.id AS sa_id,
            0 AS n_submissions, NULL AS avg_grade, 0 AS n_pending_grade
        FROM users u
        LEFT JOIN student_assignments sa
            ON sa.student_id=u.id AND sa.school_year=$year AND sa.is_active=1
        LEFT JOIN levels l ON l.id=sa.level_id
        LEFT JOIN grades g ON g.id=sa.grade_id
        $whereSQL
        GROUP BY u.id
        ORDER BY u.full_name
        LIMIT $per_page OFFSET $offset
    ";
} else {
    $sql_alumnos = "
        SELECT u.*,
            NULL AS level_id, NULL AS grade_id,
            NULL AS lv, NULL AS gr,
            NULL AS lvl_id, NULL AS gr_id, NULL AS sa_id,
            0 AS n_submissions, NULL AS avg_grade, 0 AS n_pending_grade
        FROM users u
        $whereSQL
        ORDER BY u.full_name
        LIMIT $per_page OFFSET $offset
    ";
}

try {
    $stmt = $pdo->prepare($sql_alumnos);
    $stmt->execute($params);
    $alumnos = $stmt->fetchAll();
} catch (Throwable $e) {
    die('<pre style="background:#ffebee;color:#c62828;padding:20px;border-radius:8px">
❌ ERROR ALUMNOS: ' . $e->getMessage() . '</pre>');
}

/* ── Catálogos ── */
$levels     = $has_levels ? $pdo->query("SELECT * FROM levels  WHERE is_active=1 ORDER BY sort_order")->fetchAll() : [];
$grades_all = $has_levels ? $pdo->query("SELECT * FROM grades  WHERE is_active=1 ORDER BY level_id,sort_order")->fetchAll() : [];

/* ── Stats ── */
try {
    $sel_asignados = $has_sa
        ? "(SELECT COUNT(DISTINCT sa.student_id) FROM student_assignments sa
           WHERE sa.school_year=$year AND sa.is_active=1)" : '0';
    $sel_sin_grado = $has_sa
        ? "(SELECT COUNT(*) FROM users u2
           WHERE u2.role='ALUMNO' AND u2.is_active=1
             AND NOT EXISTS(SELECT 1 FROM student_assignments sa2
               WHERE sa2.student_id=u2.id AND sa2.school_year=$year AND sa2.is_active=1))" : '0';

    $stats = $pdo->query("
        SELECT
            COUNT(*)         AS total,
            SUM(is_active=1) AS activos,
            SUM(is_active=0) AS inactivos,
            $sel_asignados   AS asignados,
            $sel_sin_grado   AS sin_grado
        FROM users WHERE role='ALUMNO'
    ")->fetch();
} catch (Throwable $e) {
    $stats = ['total'=>0,'activos'=>0,'inactivos'=>0,'asignados'=>0,'sin_grado'=>0];
}

layout_start('Gestión de Alumnos', $u);
$csrf = htmlspecialchars(csrf_token());
?>

<!-- CABECERA -->
<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:12px;margin-bottom:20px">
  <div>
    <h2 style="font-size:18px;font-weight:800;color:var(--navy)">🎓 Gestión de Alumnos</h2>
    <p class="txt-muted">Administra alumnos, grados y seguimiento académico</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <button class="btn btn-outline btn-sm" onclick="exportAlumnos()">📊 Exportar CSV</button>
    <?php if ($has_sa && $has_levels): ?>
    <button class="btn btn-outline btn-sm" onclick="openModal('m-masivo')">📥 Asignación masiva</button>
    <?php endif; ?>
    <button class="btn btn-navy" onclick="openModal('m-alum')">➕ Nuevo Alumno</button>
  </div>
</div>

<!-- STATS -->
<div class="stats-row" style="margin-bottom:18px">
  <div class="stat-card">
    <div class="sv"><?= (int)$stats['total'] ?></div>
    <div class="sl">Total alumnos</div>
  </div>
  <div class="stat-card" style="border-top-color:var(--green)">
    <div class="sv" style="color:var(--green)"><?= (int)$stats['activos'] ?></div>
    <div class="sl">Activos</div>
  </div>
  <?php if ($has_sa): ?>
  <div class="stat-card" style="border-top-color:var(--teal)">
    <div class="sv" style="color:var(--teal)"><?= (int)$stats['asignados'] ?></div>
    <div class="sl">Con grado <?= $year ?></div>
  </div>
  <div class="stat-card" style="border-top-color:var(--orange)">
    <div class="sv" style="color:var(--orange)"><?= (int)$stats['sin_grado'] ?></div>
    <div class="sl">Sin grado</div>
  </div>
  <?php endif; ?>
  <div class="stat-card" style="border-top-color:var(--red)">
    <div class="sv" style="color:var(--red)"><?= (int)$stats['inactivos'] ?></div>
    <div class="sl">Inactivos</div>
  </div>
</div>

<!-- FILTROS -->
<div class="card" style="padding:12px 16px;margin-bottom:14px">
  <form method="get" id="f-filter"
        style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
    <div class="tbl-search" style="flex:1;min-width:200px">
      <span class="tbl-sico">🔍</span>
      <input name="q" value="<?= htmlspecialchars($q_search) ?>"
             placeholder="Nombre, DNI<?= $has_parent?', apoderado':'' ?>..."
             style="width:100%">
    </div>
    <?php if ($has_levels): ?>
    <div class="fg" style="min-width:140px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Nivel</label>
      <select name="level" id="flt-level"
              onchange="loadGrades(this.value,'flt-grade'); this.form.submit()">
        <option value="">Todos los niveles</option>
        <?php foreach ($levels as $lv): ?>
          <option value="<?= (int)$lv['id'] ?>"
            <?= $f_level===(int)$lv['id']?'selected':'' ?>>
            <?= htmlspecialchars($lv['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fg" style="min-width:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Grado</label>
      <select name="grade" id="flt-grade">
        <option value="">Todos los grados</option>
        <?php foreach ($grades_all as $gr):
          if ($f_level && (int)$gr['level_id'] !== $f_level) continue; ?>
          <option value="<?= (int)$gr['id'] ?>"
            <?= $f_grade===(int)$gr['id']?'selected':'' ?>>
            <?= htmlspecialchars($gr['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php endif; ?>
    <div class="fg" style="min-width:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Estado</label>
      <select name="status">
        <option value=""         <?= $f_status===''        ?'selected':'' ?>>Todos</option>
        <option value="active"   <?= $f_status==='active'  ?'selected':'' ?>>Activos</option>
        <option value="inactive" <?= $f_status==='inactive'?'selected':'' ?>>Inactivos</option>
      </select>
    </div>
    <?php if ($has_sa): ?>
    <div class="fg" style="min-width:140px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Asignación</label>
      <select name="assign">
        <option value=""    <?= $f_assign===''   ?'selected':'' ?>>Todos</option>
        <option value="yes" <?= $f_assign==='yes'?'selected':'' ?>>Con grado</option>
        <option value="no"  <?= $f_assign==='no' ?'selected':'' ?>>Sin grado</option>
      </select>
    </div>
    <?php endif; ?>
    <div style="display:flex;gap:6px;align-items:flex-end">
      <button type="submit" class="btn btn-navy btn-sm">🔍 Filtrar</button>
      <a href="?" class="btn btn-outline btn-sm">✕ Limpiar</a>
    </div>
  </form>
</div>

<!-- INFO + VISTA TOGGLE -->
<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:8px;margin-bottom:10px">
  <div class="txt-muted">
    <?= $total ?> alumno(s) · Página <?= $page ?> de <?= $pages ?>
    <?php if ($f_level || $f_grade): ?>
      <span style="background:var(--navy);color:#fff;
            border-radius:20px;padding:2px 8px;font-size:10px;margin-left:6px">
        Filtrado
      </span>
    <?php endif; ?>
  </div>
  <div style="display:flex;gap:6px">
    <button class="btn btn-outline btn-xs" id="btn-grid2"
            onclick="setView2('grid')">⊞ Tarjetas</button>
    <button class="btn btn-outline btn-xs" id="btn-list2"
            onclick="setView2('list')">☰ Lista</button>
  </div>
</div>

<!-- ════ VISTA TARJETAS ════ -->
<div id="view2-grid">
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));
    gap:12px;margin-bottom:16px" id="alum-grid">
  <?php foreach ($alumnos as $al):
    $active  = (int)$al['is_active'];
    $has_gr  = !empty($al['lv']);
    $avg     = isset($al['avg_grade']) && $al['avg_grade'] !== null ? (float)$al['avg_grade'] : null;
    $max_g   = $max_grade;
    $avg_cls = $avg === null ? '' : ($avg < 11 ? 'fail' : ($avg < 14 ? 'warn' : ''));
  ?>
  <div class="alum-card <?= $active?'':'inactive' ?>" id="ac-<?= (int)$al['id'] ?>">
    <!-- Cabecera -->
    <div class="alum-head">
      <div class="alum-avatar">
        <?= mb_strtoupper(mb_substr($al['full_name'],0,2)) ?>
      </div>
      <div style="flex:1;min-width:0">
        <div class="alum-name"><?= htmlspecialchars($al['full_name']) ?></div>
        <div class="alum-dni">🪪 <?= htmlspecialchars($al['dni']) ?></div>
        <?php if ($has_sa): ?>
        <div style="margin-top:4px">
          <?php if ($has_gr): ?>
            <span class="bdg bdg-info" style="font-size:10px" id="ag-<?= (int)$al['id'] ?>">
              🏫 <?= htmlspecialchars($al['lv'].' · '.$al['gr']) ?>
            </span>
          <?php else: ?>
            <span class="bdg" style="background:#fff3e0;color:var(--orange);font-size:10px"
                  id="ag-<?= (int)$al['id'] ?>">
              ⚠️ Sin grado
            </span>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
      <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>"
            id="as-<?= (int)$al['id'] ?>"
            style="align-self:flex-start;flex-shrink:0">
        <?= $active?'Activo':'Inactivo' ?>
      </span>
    </div>
    <!-- Info -->
    <div class="alum-body">
      <?php if ($has_parent && !empty($al['parent_name'])): ?>
        <div class="al-info">
          👨‍👩‍👦 <?= htmlspecialchars($al['parent_name']) ?>
          <?= ($has_pphone && !empty($al['parent_phone']))
              ? ' · 📞 '.htmlspecialchars($al['parent_phone']) : '' ?>
        </div>
      <?php endif; ?>
      <?php if (!empty($al['email'])): ?>
        <div class="al-info">✉️ <?= htmlspecialchars($al['email']) ?></div>
      <?php endif; ?>
      <?php if ($has_bday && !empty($al['birth_date'])): ?>
        <div class="al-info">🎂 <?= date('d/m/Y', strtotime($al['birth_date'])) ?></div>
      <?php endif; ?>
      <?php if ($has_tasks): ?>
      <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:10px">
        <span class="mini-chip">📬 <?= (int)$al['n_submissions'] ?> entregas</span>
        <?php if ($avg !== null): ?>
          <span class="mini-chip grade-badge <?= $avg_cls ?>"
                style="font-size:11px;padding:3px 8px">
            ⭐ <?= number_format($avg,1) ?>/<?= $max_g ?>
          </span>
        <?php endif; ?>
        <?php if ((int)($al['n_pending_grade']??0) > 0): ?>
          <span class="mini-chip" style="background:#fff3e0;color:var(--orange)">
            ⏳ <?= (int)$al['n_pending_grade'] ?> por calif.
          </span>
        <?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
    <!-- Acciones -->
    <div class="alum-foot">
      <button class="btn btn-outline btn-xs"
              onclick='openEditAlum(<?= htmlspecialchars(json_encode([
                "id"           => (int)$al["id"],
                "dni"          => $al["dni"],
                "full_name"    => $al["full_name"],
                "email"        => $al["email"]        ?? "",
                "phone"        => $al["phone"]        ?? "",
                "birth_date"   => $al["birth_date"]   ?? "",
                "parent_name"  => $al["parent_name"]  ?? "",
                "parent_phone" => $al["parent_phone"] ?? "",
              ], JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>✏️ Editar</button>
      <?php if ($has_sa && $has_levels): ?>
      <button class="btn btn-teal btn-xs"
              onclick="openSetGrade(<?= (int)$al['id'] ?>,
              '<?= addslashes($al['full_name']) ?>',
              <?= (int)($al['level_id']??0) ?>,
              <?= (int)($al['grade_id']??0) ?>)">🏫 Grado</button>
      <?php endif; ?>
      <?php if ($has_tasks): ?>
      <button class="btn btn-outline btn-xs"
              onclick="openAlumDetail(<?= (int)$al['id'] ?>,'<?= addslashes($al['full_name']) ?>')">
        📊 Notas</button>
      <?php endif; ?>
      <button class="btn btn-outline btn-xs"
              onclick="openNotifAlum(<?= (int)$al['id'] ?>,'<?= addslashes($al['full_name']) ?>')">📢</button>
      <button class="btn btn-orange btn-xs" id="atb-<?= (int)$al['id'] ?>"
              onclick="togAlum(<?= (int)$al['id'] ?>,this)">
        <?= $active?'Desact.':'Activar' ?></button>
      <button class="btn btn-outline btn-xs"
              onclick="openResetPassAlum(<?= (int)$al['id'] ?>,'<?= addslashes($al['full_name']) ?>')">🔑</button>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (!$alumnos): ?>
  <div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--muted)">
    <div style="font-size:40px;margin-bottom:10px">🎓</div>
    No se encontraron alumnos con los filtros aplicados.
  </div>
  <?php endif; ?>
  </div>
</div>

<!-- ════ VISTA LISTA ════ -->
<div id="view2-list" style="display:none">
  <div class="card" style="padding:0;overflow:hidden;margin-bottom:16px">
    <div class="table-wrap">
      <table id="t-alumnos">
        <thead>
          <tr>
            <th>#</th><th>Alumno</th><th>DNI</th>
            <?php if ($has_sa && $has_levels): ?><th>Grado</th><?php endif; ?>
            <?php if ($has_parent): ?><th>Apoderado</th><?php endif; ?>
            <?php if ($has_tasks): ?><th>Entregas</th><th>Promedio</th><?php endif; ?>
            <th>Estado</th><th style="text-align:center">Acciones</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($alumnos as $i => $al):
          $active  = (int)$al['is_active'];
          $avg     = isset($al['avg_grade']) && $al['avg_grade'] !== null ? (float)$al['avg_grade'] : null;
          $avg_cls = $avg===null?'':($avg<$max_grade*0.55?'fail':($avg<$max_grade*0.7?'warn':''));
        ?>
        <tr id="atr-<?= (int)$al['id'] ?>" <?= $active?'':'style="opacity:.6"' ?>>
          <td class="txt-muted"><?= $offset+$i+1 ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <div style="width:30px;height:30px;border-radius:50%;
                   background:var(--navy);display:flex;align-items:center;
                   justify-content:center;font-size:11px;font-weight:800;
                   color:#fff;flex-shrink:0">
                <?= mb_strtoupper(mb_substr($al['full_name'],0,1)) ?>
              </div>
              <div>
                <div style="font-size:13px;font-weight:700;color:var(--navy)">
                  <?= htmlspecialchars($al['full_name']) ?>
                </div>
                <?php if (!empty($al['email'])): ?>
                  <div class="txt-muted"><?= htmlspecialchars($al['email']) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td class="txt-muted"><?= htmlspecialchars($al['dni']) ?></td>
          <?php if ($has_sa && $has_levels): ?>
          <td>
            <?php if (!empty($al['lv'])): ?>
              <span class="bdg bdg-info" style="font-size:10px" id="alg-<?= (int)$al['id'] ?>">
                <?= htmlspecialchars($al['lv'].' · '.$al['gr']) ?>
              </span>
            <?php else: ?>
              <span class="bdg" style="background:#fff3e0;color:var(--orange);font-size:10px"
                    id="alg-<?= (int)$al['id'] ?>">Sin grado</span>
            <?php endif; ?>
          </td>
          <?php endif; ?>
          <?php if ($has_parent): ?>
          <td class="txt-muted">
            <?= htmlspecialchars($al['parent_name'] ?? '—') ?>
            <?= ($has_pphone && !empty($al['parent_phone']))
                ? '<br><span style="font-size:11px">📞 '.htmlspecialchars($al['parent_phone']).'</span>'
                : '' ?>
          </td>
          <?php endif; ?>
          <?php if ($has_tasks): ?>
          <td style="text-align:center;font-weight:700"><?= (int)$al['n_submissions'] ?></td>
          <td style="text-align:center">
            <?php if ($avg !== null): ?>
              <span class="grade-badge <?= $avg_cls ?>" style="font-size:12px;padding:4px 10px">
                <?= number_format($avg,1) ?>/<?= $max_grade ?>
              </span>
            <?php else: ?>
              <span class="txt-muted">—</span>
            <?php endif; ?>
          </td>
          <?php endif; ?>
          <td>
            <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>" id="als-<?= (int)$al['id'] ?>">
              <?= $active?'Activo':'Inactivo' ?>
            </span>
          </td>
          <td>
            <div style="display:flex;gap:4px;justify-content:center;flex-wrap:wrap">
              <button class="btn btn-outline btn-xs"
                      onclick='openEditAlum(<?= htmlspecialchars(json_encode([
                        "id"=>(int)$al["id"],"dni"=>$al["dni"],
                        "full_name"=>$al["full_name"],
                        "email"=>$al["email"]??"",
                        "phone"=>$al["phone"]??"",
                        "birth_date"=>$al["birth_date"]??"",
                        "parent_name"=>$al["parent_name"]??"",
                        "parent_phone"=>$al["parent_phone"]??"",
                      ],JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>✏️</button>
              <?php if ($has_sa && $has_levels): ?>
              <button class="btn btn-teal btn-xs"
                      onclick="openSetGrade(<?= (int)$al['id'] ?>,
                      '<?= addslashes($al['full_name']) ?>',
                      <?= (int)($al['level_id']??0) ?>,
                      <?= (int)($al['grade_id']??0) ?>)">🏫</button>
              <?php endif; ?>
              <?php if ($has_tasks): ?>
              <button class="btn btn-outline btn-xs"
                      onclick="openAlumDetail(<?= (int)$al['id'] ?>,'<?= addslashes($al['full_name']) ?>')">📊</button>
              <?php endif; ?>
              <button class="btn btn-orange btn-xs"
                      id="altb-<?= (int)$al['id'] ?>"
                      onclick="togAlum(<?= (int)$al['id'] ?>,this)">
                <?= $active?'↓':'↑' ?>
              </button>
              <button class="btn btn-outline btn-xs"
                      onclick="openResetPassAlum(<?= (int)$al['id'] ?>,'<?= addslashes($al['full_name']) ?>')">🔑</button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- PAGINACIÓN -->
<?php if ($pages > 1): ?>
<div style="display:flex;gap:6px;justify-content:center;
     flex-wrap:wrap;margin-top:4px;margin-bottom:20px">
  <?php $rs=max(1,$page-3); $re=min($pages,$page+3); ?>
  <?php if ($rs>1): ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>1])) ?>"
       class="btn btn-outline btn-sm">1</a>
    <?php if ($rs>2): ?><span style="padding:8px;color:var(--muted)">…</span><?php endif; ?>
  <?php endif; ?>
  <?php for ($p=$rs; $p<=$re; $p++): ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>"
       class="btn <?= $p===$page?'btn-navy':'btn-outline' ?> btn-sm"><?= $p ?></a>
  <?php endfor; ?>
  <?php if ($re<$pages): ?>
    <?php if ($re<$pages-1): ?><span style="padding:8px;color:var(--muted)">…</span><?php endif; ?>
    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$pages])) ?>"
       class="btn btn-outline btn-sm"><?= $pages ?></a>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- ════ MODALES ════ -->

<!-- Crear/Editar Alumno -->
<div class="modal-ov" id="m-alum">
  <div class="modal" style="max-width:580px">
    <h3 id="malum-title">➕ Nuevo Alumno</h3>
    <form id="f-alum" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="create" id="falum-act">
      <input type="hidden" name="id"   id="falum-id">
      <div style="font-size:12px;font-weight:700;color:var(--navy);
           margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid var(--bg)">
        👤 Datos del alumno
      </div>
      <div class="form-grid" style="margin-bottom:14px">
        <div class="fg">
          <label>DNI *</label>
          <input name="dni" id="falum-dni" required maxlength="12" placeholder="Ej: 78901234">
        </div>
        <?php if ($has_bday): ?>
        <div class="fg">
          <label>Fecha de nacimiento</label>
          <input name="birth_date" id="falum-bday" type="date">
        </div>
        <?php endif; ?>
        <div class="fg" style="grid-column:1/-1">
          <label>Nombre completo *</label>
          <input name="full_name" id="falum-name" required placeholder="Apellidos y nombres">
        </div>
        <div class="fg">
          <label>Email</label>
          <input name="email" id="falum-email" type="email" placeholder="correo@ejemplo.com">
        </div>
        <?php if ($has_phone): ?>
        <div class="fg">
          <label>Teléfono</label>
          <input name="phone" id="falum-phone" type="tel" placeholder="Ej: 987654321">
        </div>
        <?php endif; ?>
        <div class="fg">
          <label>Contraseña</label>
          <input name="password" id="falum-pass" type="text"
                 placeholder="Vacío = DNI como contraseña">
        </div>
      </div>
      <?php if ($has_parent || $has_pphone): ?>
      <div style="font-size:12px;font-weight:700;color:var(--navy);
           margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid var(--bg)">
        👨‍👩‍👦 Datos del apoderado
      </div>
      <div class="form-grid" style="margin-bottom:14px">
        <?php if ($has_parent): ?>
        <div class="fg">
          <label>Nombre del apoderado</label>
          <input name="parent_name" id="falum-pname" placeholder="Padre/madre/tutor">
        </div>
        <?php endif; ?>
        <?php if ($has_pphone): ?>
        <div class="fg">
          <label>Teléfono del apoderado</label>
          <input name="parent_phone" id="falum-pphone" type="tel" placeholder="Ej: 987000123">
        </div>
        <?php endif; ?>
      </div>
      <?php endif; ?>
      <?php if ($has_sa && $has_levels): ?>
      <div style="font-size:12px;font-weight:700;color:var(--navy);
           margin-bottom:8px;padding-bottom:6px;border-bottom:2px solid var(--bg)">
        🏫 Asignación de grado (opcional)
      </div>
      <div class="form-grid" style="margin-bottom:0" id="grade-section-form">
        <div class="fg">
          <label>Nivel</label>
          <select name="level_id" id="falum-level" onchange="loadGradesModal(this.value)">
            <option value="">— Sin asignar —</option>
            <?php foreach ($levels as $lv): ?>
              <option value="<?= (int)$lv['id'] ?>"><?= htmlspecialchars($lv['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <label>Grado</label>
          <select name="grade_id" id="falum-grade">
            <option value="">— Selecciona nivel primero —</option>
          </select>
        </div>
      </div>
      <?php endif; ?>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-alum');resetAlumForm()">Cancelar</button>
        <button type="submit" class="btn btn-navy">💾 Guardar</button>
      </div>
    </form>
  </div>
</div>

<!-- Asignar Grado -->
<?php if ($has_sa && $has_levels): ?>
<div class="modal-ov" id="m-setgrade">
  <div class="modal" style="max-width:420px">
    <h3 id="msg-title">🏫 Asignar Grado</h3>
    <p class="txt-muted" id="msg-name" style="margin-bottom:14px"></p>
    <form id="f-setgrade" method="post">
      <input type="hidden" name="csrf"       value="<?= $csrf ?>">
      <input type="hidden" name="act"        value="set_grade" id="sg-act">
      <input type="hidden" name="student_id" id="sg-sid">
      <div class="form-grid" id="sg-fields">
        <div class="fg">
          <label>Nivel *</label>
          <select name="level_id" id="sg-level" required
                  onchange="loadGrades(this.value,'sg-grade')">
            <option value="">— Nivel —</option>
            <?php foreach ($levels as $lv): ?>
              <option value="<?= (int)$lv['id'] ?>"><?= htmlspecialchars($lv['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <label>Grado *</label>
          <select name="grade_id" id="sg-grade" required>
            <option value="">— Selecciona nivel —</option>
          </select>
        </div>
      </div>
      <div style="margin-top:12px">
        <label style="display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer">
          <input type="checkbox" id="sg-remove" style="width:auto">
          Quitar asignación de grado (<?= $year ?>)
        </label>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-setgrade')">Cancelar</button>
        <button type="submit" class="btn btn-teal" id="sg-submit">🏫 Guardar</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Detalle Académico -->
<?php if ($has_tasks): ?>
<div class="modal-ov" id="m-alum-detail">
  <div class="modal" style="max-width:620px">
    <h3 id="mad-title">📊 Resumen académico</h3>
    <div id="mad-body">
      <div style="text-align:center;padding:24px">
        <span class="spinner" style="border-color:var(--border);
          border-top-color:var(--navy);width:26px;height:26px;display:inline-block"></span>
      </div>
    </div>
    <div class="modal-actions">
      <button class="btn btn-outline" onclick="closeModal('m-alum-detail')">Cerrar</button>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Reset Contraseña -->
<div class="modal-ov" id="m-pass-a">
  <div class="modal" style="max-width:360px">
    <h3>🔑 Restablecer Contraseña</h3>
    <p class="txt-muted" id="pasa-name" style="margin-bottom:14px"></p>
    <form id="f-pass-a" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="reset_pass">
      <input type="hidden" name="id"   id="pasa-id">
      <div class="fg" style="margin-bottom:14px">
        <label>Nueva contraseña</label>
        <input name="pass" type="text" required minlength="4" placeholder="Mínimo 4 caracteres">
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-pass-a')">Cancelar</button>
        <button type="submit" class="btn btn-navy">🔑 Restablecer</button>
      </div>
    </form>
  </div>
</div>

<!-- Notificación a alumno -->
<div class="modal-ov" id="m-notif-a">
  <div class="modal" style="max-width:420px">
    <h3>📢 Enviar Notificación</h3>
    <p class="txt-muted" id="na-name" style="margin-bottom:14px"></p>
    <form id="f-notif-a" method="post">
      <input type="hidden" name="csrf"       value="<?= $csrf ?>">
      <input type="hidden" name="act"        value="send_notif">
      <input type="hidden" name="student_id" id="na-sid">
      <div class="fg" style="margin-bottom:12px">
        <label>Título</label>
        <input name="title" type="text" required placeholder="Asunto">
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Mensaje</label>
        <textarea name="body" rows="3" placeholder="Detalle..."></textarea>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-notif-a')">Cancelar</button>
        <button type="submit" class="btn btn-navy">📤 Enviar</button>
      </div>
    </form>
  </div>
</div>

<!-- Asignación masiva -->
<?php if ($has_sa && $has_levels): ?>
<div class="modal-ov" id="m-masivo">
  <div class="modal" style="max-width:480px">
    <h3>📥 Asignación Masiva de Grado</h3>
    <p class="txt-muted" style="margin-bottom:14px">
      Asigna un grado a todos los alumnos activos sin grado en <?= $year ?>.
    </p>
    <form id="f-masivo" method="post"
          action="/sistemaescolar/admin/asignacion_masiva.php">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="year" value="<?= $year ?>">
      <input type="hidden" name="q"    value="<?= htmlspecialchars($q_search) ?>">
      <div class="form-grid">
        <div class="fg">
          <label>Nivel *</label>
          <select name="level_id" id="mas-level" required
                  onchange="loadGrades(this.value,'mas-grade')">
            <option value="">— Nivel —</option>
            <?php foreach ($levels as $lv): ?>
              <option value="<?= (int)$lv['id'] ?>"><?= htmlspecialchars($lv['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <label>Grado *</label>
          <select name="grade_id" id="mas-grade" required>
            <option value="">— Selecciona nivel —</option>
          </select>
        </div>
      </div>
      <div style="background:#fff3e0;border-radius:8px;padding:10px 14px;
           margin-top:12px;font-size:12px;color:var(--orange)">
        ⚠️ Solo se asignarán alumnos activos sin grado en <?= $year ?>.
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-masivo')">Cancelar</button>
        <button type="submit" class="btn btn-teal">📥 Asignar masivamente</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- ESTILOS -->
<style>
.alum-card {
  background:var(--card);border-radius:var(--r);
  box-shadow:var(--sh);overflow:hidden;
  transition:var(--tr);border:1.5px solid var(--border)
}
.alum-card:hover { transform:translateY(-3px);box-shadow:0 8px 22px rgba(0,0,0,.11) }
.alum-card.inactive { opacity:.6 }
.alum-head {
  display:flex;align-items:flex-start;gap:10px;padding:13px 14px;
  background:linear-gradient(135deg,var(--navy) 0%,#1a2d9e 100%)
}
.alum-avatar {
  width:40px;height:40px;border-radius:50%;flex-shrink:0;
  background:rgba(255,255,255,.22);color:#fff;
  display:flex;align-items:center;justify-content:center;
  font-size:15px;font-weight:800
}
.alum-name {
  font-size:13px;font-weight:800;color:#fff;line-height:1.2;
  overflow:hidden;display:-webkit-box;
  -webkit-line-clamp:2;-webkit-box-orient:vertical
}
.alum-dni  { font-size:11px;color:rgba(255,255,255,.75);margin-top:2px }
.alum-body { padding:10px 13px }
.al-info   { font-size:11px;color:var(--muted);margin-bottom:4px;
             white-space:nowrap;overflow:hidden;text-overflow:ellipsis }
.alum-foot { padding:9px 13px;border-top:1px solid var(--bg);display:flex;gap:5px;flex-wrap:wrap }
.curso-stat-row {
  display:flex;align-items:center;justify-content:space-between;
  padding:10px 12px;border-radius:9px;background:var(--bg);
  margin-bottom:6px;flex-wrap:wrap;gap:8px
}
</style>

<script>
var CSRF  = '<?= $csrf ?>';
var _view2 = localStorage.getItem('alum_view') || 'grid';
setView2(_view2, true);

function setView2(v, silent) {
  _view2 = v;
  if (!silent) localStorage.setItem('alum_view', v);
  document.getElementById('view2-grid').style.display = v==='grid'?'':'none';
  document.getElementById('view2-list').style.display = v==='list'?'':'none';
  document.getElementById('btn-grid2').className = 'btn btn-xs '+(v==='grid'?'btn-navy':'btn-outline');
  document.getElementById('btn-list2').className = 'btn btn-xs '+(v==='list'?'btn-navy':'btn-outline');
}

function openModal(id)  { document.getElementById(id).classList.add('show'); }
function closeModal(id) { document.getElementById(id).classList.remove('show'); }
document.querySelectorAll('.modal-ov').forEach(function(ov) {
  ov.addEventListener('click', function(e){ if(e.target===this) this.classList.remove('show'); });
});

/* ── Crear/Editar alumno ── */
ajaxForm(document.getElementById('f-alum'), function(d) {
  closeModal('m-alum');
  resetAlumForm();
  toast(d.msg, 'ok');
  setTimeout(() => location.reload(), 900);
});

function openEditAlum(data) {
  document.getElementById('malum-title').textContent = '✏️ Editar Alumno';
  document.getElementById('falum-act').value    = 'edit';
  document.getElementById('falum-id').value     = data.id;
  document.getElementById('falum-dni').value    = data.dni;
  document.getElementById('falum-name').value   = data.full_name;
  document.getElementById('falum-email').value  = data.email;
  var ph = document.getElementById('falum-phone');
  if (ph) ph.value = data.phone;
  var bd = document.getElementById('falum-bday');
  if (bd) bd.value = data.birth_date;
  var pn = document.getElementById('falum-pname');
  if (pn) pn.value = data.parent_name;
  var pp = document.getElementById('falum-pphone');
  if (pp) pp.value = data.parent_phone;
  document.getElementById('falum-pass').placeholder = '(vacío = no cambiar)';
  var gs = document.getElementById('grade-section-form');
  if (gs) gs.style.display = 'none';
  openModal('m-alum');
}

function resetAlumForm() {
  document.getElementById('malum-title').textContent = '➕ Nuevo Alumno';
  document.getElementById('falum-act').value = 'create';
  document.getElementById('falum-id').value  = '';
  document.getElementById('f-alum').reset();
  var gs = document.getElementById('grade-section-form');
  if (gs) gs.style.display = '';
}

/* ── Toggle alumno ── */
function togAlum(id, btn) {
  btn.disabled = true;
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle'); fd.append('id',id);
  fetch(location.href, {method:'POST',
    headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd})
  .then(r=>r.json()).then(d=>{
    toast(d.msg, d.ok?'ok':'err');
    if (d.ok) {
      var card = document.getElementById('ac-'+id);
      if (card) card.classList.toggle('inactive', !d.is_active);
      ['as-','als-'].forEach(function(p){
        var b = document.getElementById(p+id); if(!b) return;
        b.className   = 'bdg '+(d.is_active?'bdg-on':'bdg-off');
        b.textContent = d.is_active?'Activo':'Inactivo';
      });
      btn.innerHTML = d.is_active?'Desact.':'Activar';
      var bt2 = document.getElementById('altb-'+id);
      if (bt2) bt2.innerHTML = d.is_active?'↓':'↑';
    }
    btn.disabled = false;
  });
}

/* ── Asignar grado ── */
function openSetGrade(sid, name, lid, gid) {
  document.getElementById('msg-title').textContent = '🏫 Asignar Grado — '+name;
  document.getElementById('msg-name').textContent  = '📅 Año escolar: <?= $year ?>';
  document.getElementById('sg-sid').value          = sid;
  document.getElementById('sg-act').value          = 'set_grade';
  document.getElementById('sg-level').value        = lid || '';
  document.getElementById('sg-remove').checked     = false;
  document.getElementById('sg-fields').style.display = '';
  document.getElementById('sg-submit').textContent  = '🏫 Guardar';
  document.querySelectorAll('#f-setgrade select').forEach(function(s){ s.disabled=false; });
  if (lid) {
    loadGrades(lid, 'sg-grade');
    setTimeout(function(){ document.getElementById('sg-grade').value = gid||''; }, 400);
  } else {
    document.getElementById('sg-grade').innerHTML = '<option value="">— Selecciona nivel —</option>';
  }
  openModal('m-setgrade');
}

/* ── Checkbox quitar grado ── */
var sgRemove = document.getElementById('sg-remove');
if (sgRemove) {
  sgRemove.addEventListener('change', function() {
    var removing = this.checked;
    document.getElementById('sg-act').value = removing ? 'remove_grade' : 'set_grade';
    document.querySelectorAll('#f-setgrade select[name]').forEach(function(s){
      s.disabled = removing;
    });
    document.getElementById('sg-submit').textContent = removing ? '⚠️ Quitar grado' : '🏫 Guardar';
  });
}

ajaxForm(document.getElementById('f-setgrade'), function(d) {
  closeModal('m-setgrade');
  toast(d.msg, 'ok');
  var sid = document.getElementById('sg-sid').value;
  ['ag-','alg-'].forEach(function(p) {
    var el = document.getElementById(p+sid); if (!el) return;
    if (d.level && d.grade) {
      el.className = 'bdg bdg-info'; el.style = 'font-size:10px';
      el.textContent = '🏫 '+d.level+' · '+d.grade;
    } else {
      el.className = 'bdg';
      el.style = 'background:#fff3e0;color:var(--orange);font-size:10px';
      el.textContent = 'Sin grado';
    }
  });
});

/* ── Cargar grados ── */
function loadGrades(lid, targetId) {
  var sel = document.getElementById(targetId);
  if (!lid) { sel.innerHTML='<option value="">— Selecciona nivel —</option>'; return; }
  sel.innerHTML='<option value="">Cargando...</option>';
  fetch('/sistemaescolar/api/catalog.php?act=grades&level_id='+lid,{
    headers:{'X-Requested-With':'XMLHttpRequest'}
  }).then(r=>r.json()).then(d=>{
    sel.innerHTML='<option value="">— Grado —</option>'+
      (d.data||[]).map(g=>'<option value="'+g.id+'">'+g.name+'</option>').join('');
  });
}
function loadGradesModal(lid) { loadGrades(lid,'falum-grade'); }

/* ── Detalle académico ── */
function openAlumDetail(sid, name) {
  var mad = document.getElementById('m-alum-detail');
  if (!mad) return;
  document.getElementById('mad-title').textContent = '📊 Académico — '+name;
  document.getElementById('mad-body').innerHTML =
    '<div style="text-align:center;padding:24px">'+
    '<span class="spinner" style="border-color:var(--border);'+
    'border-top-color:var(--navy);width:24px;height:24px;display:inline-block"></span></div>';
  openModal('m-alum-detail');
  fetch('/sistemaescolar/api/grades.php?act=student_summary_admin&student_id='+sid+
        '&year=<?= $year ?>',{headers:{'X-Requested-With':'XMLHttpRequest'}})
  .then(r=>r.json()).then(d=>{
    if (!d.ok || !d.data || !d.data.length) {
      document.getElementById('mad-body').innerHTML =
        '<div style="text-align:center;padding:30px;color:var(--muted)">'+
        '<div style="font-size:36px;margin-bottom:10px">📭</div>'+
        'Sin datos académicos disponibles.</div>';
      return;
    }
    var max = <?= $max_grade ?>;
    var html = d.data.map(function(r){
      var avg    = r.promedio !== null ? parseFloat(r.promedio) : null;
      var avgCls = avg===null?'':(avg<max*0.55?'fail':(avg<max*0.7?'warn':''));
      var pct    = r.total_tasks>0 ? Math.round((r.entregadas||0)/r.total_tasks*100) : 0;
      return '<div class="curso-stat-row">'+
        '<div>'+
          '<div style="font-size:13px;font-weight:700;color:var(--navy)">'+
            escH(r.curso+(r.sub?' › '+r.sub:''))+'</div>'+
          '<div class="txt-muted" style="margin-top:2px">'+
            '📋 '+r.total_tasks+' tareas · 📬 '+r.entregadas+' entregadas · ✅ '+r.calificadas+' calificadas</div>'+
          '<div style="background:#e0e0e0;border-radius:20px;height:4px;overflow:hidden;margin-top:6px;max-width:200px">'+
            '<div style="width:'+pct+'%;height:100%;background:var(--teal);border-radius:20px"></div></div>'+
        '</div>'+
        (avg!==null?
          '<div class="grade-badge '+avgCls+'" style="font-size:16px;padding:7px 14px">'+
            avg.toFixed(1)+'<span style="font-size:12px;font-weight:400">/'+max+'</span></div>'
          : '<span class="txt-muted" style="font-size:11px">Sin calificar</span>')+
      '</div>';
    }).join('');
    document.getElementById('mad-body').innerHTML = html;
  });
}

/* ── Reset contraseña ── */
function openResetPassAlum(id, name) {
  document.getElementById('pasa-id').value         = id;
  document.getElementById('pasa-name').textContent = '👤 '+name;
  openModal('m-pass-a');
}
ajaxForm(document.getElementById('f-pass-a'), function() { closeModal('m-pass-a'); });

/* ── Notificación ── */
function openNotifAlum(id, name) {
  document.getElementById('na-sid').value         = id;
  document.getElementById('na-name').textContent  = '📢 Para: '+name;
  openModal('m-notif-a');
}
ajaxForm(document.getElementById('f-notif-a'), function() { closeModal('m-notif-a'); });

/* ── Exportar CSV ── */
function exportAlumnos() {
  var rows=[['Nombre','DNI','Nivel','Grado','Apoderado','Tel.Apoderado',
             'Email','Entregas','Promedio','Estado']];
  document.querySelectorAll('#t-alumnos tbody tr').forEach(function(tr){
    var tds=tr.querySelectorAll('td');
    if(tds.length<4) return;
    rows.push([
      tds[1].querySelector('[style*="font-weight:700"]')?.textContent.trim()||'',
      tds[2].textContent.trim(),
      tds[3]?.textContent.trim()||'',
      '',
      tds[4]?.firstChild?.textContent.trim()||'',
      '','',
      tds[5]?.textContent.trim()||'',
      tds[6]?.textContent.trim()||'',
      tds[7]?.textContent.trim()||'',
    ]);
  });
  var csv = rows.map(function(r){
    return r.map(function(x){ return '"'+String(x||'').replace(/"/g,'""')+'"'; }).join(',');
  }).join('\n');
  var b = new Blob(['\uFEFF'+csv], {type:'text/csv;charset=utf-8;'});
  var a = document.createElement('a');
  a.href = URL.createObjectURL(b);
  a.download = 'alumnos_<?= $year ?>.csv';
  a.click();
}

function escH(s){
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
</script>
<?php layout_end(); ?>