<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../app/bootstrap.php';
require_login();

$pdo = db();

$anio = (int)date('Y');
$hoy  = date('Y-m-d');

$isAlumno = has_role('ALUMNO');
$isTutor  = has_role('TUTOR');
$isDoc    = has_role('DOCENTE');
$isAdmin  = (has_role('ADMIN') || has_role('DIRECTOR') || has_role('SECRETARIA'));

$uid = (int)($_SESSION['uid'] ?? 0);

function h($v): string {
  return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function badge_estado(string $s): string {
  $s = strtoupper(trim($s));
  return $s === 'ACTIVO'
    ? '<span class="badge text-bg-success">ACTIVO</span>'
    : '<span class="badge text-bg-secondary">' . h($s) . '</span>';
}

function tipo_label(string $t): string {
  return match (strtoupper(trim($t))) {
    'TP_IND'  => 'TP Individual',
    'TP_GRUP' => 'TP Grupal',
    'PARCIAL' => 'Parcial',
    default   => $t,
  };
}

function safe_int(PDO $pdo, string $sql, array $params = [], int $default = 0): int {
  try {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $v = $st->fetchColumn();
    if ($v === false || $v === null) {
      return $default;
    }
    return (int)$v;
  } catch (Throwable $e) {
    return $default;
  }
}

function safe_rows(PDO $pdo, string $sql, array $params = [], int $mode = PDO::FETCH_ASSOC): array {
  try {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll($mode) ?: [];
  } catch (Throwable $e) {
    return [];
  }
}

function safe_one(PDO $pdo, string $sql, array $params = [], int $mode = PDO::FETCH_ASSOC): ?array {
  try {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $row = $st->fetch($mode);
    return $row ?: null;
  } catch (Throwable $e) {
    return null;
  }
}

function safe_ratio(int $num, int $den): int {
  if ($den <= 0) return 0;
  return (int)round(($num / $den) * 100);
}

/**
 * Ejecuta varias consultas alternativas y devuelve la primera que funcione.
 */
function safe_int_any(PDO $pdo, array $queries, int $default = 0): int {
  foreach ($queries as $item) {
    $sql = (string)($item['sql'] ?? '');
    $params = (array)($item['params'] ?? []);
    try {
      $st = $pdo->prepare($sql);
      $st->execute($params);
      $v = $st->fetchColumn();
      if ($v !== false && $v !== null) {
        return (int)$v;
      }
    } catch (Throwable $e) {
      // probar siguiente
    }
  }
  return $default;
}

$title = 'Dashboard';
include __DIR__ . '/../app/views/header.php';
?>

<style>
  :root{
    --brand-blue:#0d6efd;
    --brand-blue-2:#0b5ed7;
    --brand-blue-3:#084298;
    --brand-ink:#0b1220;
    --brand-soft:#eff6ff;
    --brand-soft-2:rgba(13,110,253,.10);
    --brand-soft-3:rgba(13,110,253,.18);
    --ok:#198754;
    --warn:#f59f00;
    --danger:#dc3545;
    --gray-1:#f8fafc;
    --gray-2:#6c757d;
  }

  .btn-brand{
    color:#fff !important;
    border:1px solid rgba(13,110,253,.55) !important;
    background:linear-gradient(90deg,var(--brand-blue),var(--brand-blue-2)) !important;
    font-weight:900;
    box-shadow:0 14px 30px rgba(13,110,253,.22);
  }
  .btn-brand:hover{
    transform:translateY(-1px);
    box-shadow:0 18px 40px rgba(13,110,253,.28);
  }

  .hero-pro{
    position:relative;
    overflow:hidden;
    border-radius:24px;
    background:
      radial-gradient(1000px 520px at 82% 8%, rgba(13,110,253,.36), transparent 58%),
      radial-gradient(820px 480px at 10% 18%, rgba(13,110,253,.18), transparent 60%),
      linear-gradient(135deg, rgba(13,110,253,.10), rgba(13,110,253,.04)),
      linear-gradient(180deg, rgba(255,255,255,.96), rgba(255,255,255,1));
    border:1px solid rgba(13,110,253,.18);
    box-shadow:
      0 24px 58px rgba(17,24,39,.10),
      0 0 0 1px rgba(13,110,253,.08) inset;
  }
  .hero-pro:before{
    content:"";
    position:absolute;
    width:340px;height:340px;
    top:-70px;right:-90px;
    border-radius:50%;
    background:radial-gradient(circle, rgba(13,110,253,.44), transparent 66%);
  }
  .hero-pro:after{
    content:"";
    position:absolute;
    width:420px;height:420px;
    left:-130px;bottom:-140px;
    border-radius:50%;
    background:radial-gradient(circle, rgba(13,110,253,.20), transparent 68%);
  }

  .hero-title{
    font-weight:950;
    letter-spacing:-.8px;
    line-height:1.03;
    margin:0;
    color:var(--brand-ink);
  }
  .hero-accent{
    background:linear-gradient(90deg,var(--brand-blue),var(--brand-blue-2));
    -webkit-background-clip:text;
    background-clip:text;
    color:transparent;
  }

  .card-pro{
    border-radius:18px;
    border:1px solid rgba(0,0,0,.06);
    background:#fff;
    box-shadow:0 10px 26px rgba(0,0,0,.05);
  }

  .section-title{
    font-weight:900;
    letter-spacing:-.2px;
  }

  .kpi-card{
    position:relative;
    overflow:hidden;
    border-radius:18px;
    border:1px solid rgba(0,0,0,.06);
    background:#fff;
    box-shadow:0 10px 26px rgba(0,0,0,.05);
    transition:transform .12s ease, box-shadow .12s ease;
    height:100%;
  }
  .kpi-card:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 38px rgba(0,0,0,.08);
  }
  .kpi-card:before{
    content:"";
    position:absolute;
    inset:0 auto auto 0;
    width:100%;
    height:4px;
    background:linear-gradient(90deg,var(--brand-blue),var(--brand-blue-2));
  }
  .kpi-ico{
    width:48px;height:48px;
    border-radius:16px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    background:rgba(13,110,253,.14);
    border:1px solid rgba(13,110,253,.22);
    color:var(--brand-blue);
    flex:0 0 auto;
  }
  .kpi-ico.green{
    background:rgba(25,135,84,.12);
    border-color:rgba(25,135,84,.18);
    color:var(--ok);
  }
  .kpi-ico.red{
    background:rgba(220,53,69,.12);
    border-color:rgba(220,53,69,.18);
    color:var(--danger);
  }
  .kpi-ico.amber{
    background:rgba(245,159,0,.12);
    border-color:rgba(245,159,0,.18);
    color:var(--warn);
  }
  .kpi-ico.gray{
    background:rgba(108,117,125,.12);
    border-color:rgba(108,117,125,.18);
    color:#6c757d;
  }
  .kpi-value{
    font-size:2.05rem;
    line-height:1;
    font-weight:950;
    letter-spacing:-.7px;
  }
  .kpi-label{
    color:#6c757d;
    font-size:.88rem;
  }
  .kpi-sub{
    color:#6c757d;
    font-size:.8rem;
  }

  .tile-pro{
    display:block;
    position:relative;
    overflow:hidden;
    height:100%;
    text-decoration:none;
    color:inherit;
    border-radius:18px;
    border:1px solid rgba(0,0,0,.06);
    background:linear-gradient(180deg, rgba(255,255,255,.96), rgba(255,255,255,1));
    padding:18px;
    box-shadow:0 10px 26px rgba(0,0,0,.05);
    transition:transform .12s ease, box-shadow .12s ease;
  }
  .tile-pro:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 38px rgba(0,0,0,.08);
  }
  .tile-pro:before{
    content:"";
    position:absolute;
    inset:0;
    padding:1px;
    border-radius:18px;
    background:linear-gradient(90deg, rgba(13,110,253,.48), rgba(11,94,215,.30));
    -webkit-mask:
      linear-gradient(#000 0 0) content-box,
      linear-gradient(#000 0 0);
    -webkit-mask-composite:xor;
    mask-composite:exclude;
    pointer-events:none;
  }
  .tile-head{
    display:flex;
    align-items:center;
    gap:12px;
    margin-bottom:10px;
  }
  .tile-ico{
    width:48px;height:48px;
    border-radius:16px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    color:var(--brand-blue);
    border:1px solid rgba(13,110,253,.22);
    background:linear-gradient(135deg, rgba(13,110,253,.18), rgba(11,94,215,.12));
    flex:0 0 auto;
  }
  .tile-name{
    font-weight:900;
  }
  .tile-desc{
    margin:0;
    color:#6c757d;
    font-size:.9rem;
  }

  .chip{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:6px 10px;
    border-radius:999px;
    font-size:.84rem;
    border:1px solid rgba(13,110,253,.16);
    background:linear-gradient(90deg, rgba(13,110,253,.08), rgba(13,110,253,.03));
  }

  .soft-table{
    border-radius:16px;
    overflow:hidden;
    border:1px solid rgba(0,0,0,.06);
  }
  .soft-table thead th{
    background:#f8f9fa;
    color:#6c757d;
    font-size:.84rem;
    font-weight:900;
    letter-spacing:.2px;
  }

  .mini-muted{
    font-size:.86rem;
    color:#6c757d;
  }

  .progress{
    background:rgba(11,18,32,.08);
  }
  .progress-bar{
    background:linear-gradient(90deg,var(--brand-blue),var(--brand-blue-2));
    font-weight:800;
  }

  .panel-soft{
    border-radius:16px;
    border:1px dashed rgba(13,110,253,.18);
    background:linear-gradient(180deg, rgba(13,110,253,.05), rgba(13,110,253,.02));
  }

  .list-clean{
    list-style:none;
    margin:0;
    padding:0;
  }
  .list-clean li{
    display:flex;
    justify-content:space-between;
    gap:12px;
    padding:10px 0;
    border-bottom:1px solid rgba(0,0,0,.06);
  }
  .list-clean li:last-child{
    border-bottom:0;
  }
</style>

<div class="hero-pro p-4 p-lg-5 mb-4">
  <div class="row g-3 align-items-center position-relative" style="z-index:1;">
    <div class="col-12 col-lg-8">
      <div class="text-uppercase small text-muted fw-semibold">
        Escuela Nacional de Comercio · Colegio Nacional Prof. Carlos A. Ramírez F.
      </div>

      <div class="display-6 hero-title">
        Panel de Control · <span class="hero-accent">Sistema Unificado</span> · Caazapá
      </div>

      <div class="text-muted mt-2">
        Año lectivo <b><?= (int)$anio ?></b> · Hoy <b><?= h($hoy) ?></b>
        <?php if ($isAdmin): ?>
          · Perfil: <span class="badge text-bg-primary">ADMINISTRACIÓN</span>
        <?php elseif ($isDoc): ?>
          · Perfil: <span class="badge text-bg-success">DOCENTE</span>
        <?php elseif ($isAlumno): ?>
          · Perfil: <span class="badge text-bg-secondary">ALUMNO</span>
        <?php elseif ($isTutor): ?>
          · Perfil: <span class="badge text-bg-secondary">TUTOR</span>
        <?php endif; ?>
      </div>

      <div class="d-flex flex-wrap gap-2 mt-3">
        <span class="chip"><i class="bi bi-building"></i> Comercio · Caazapá</span>
        <span class="chip"><i class="bi bi-calendar3"></i> Gestión <?= (int)$anio ?></span>
        <span class="chip"><i class="bi bi-shield-check"></i> Plataforma centralizada</span>
      </div>
    </div>

    <div class="col-12 col-lg-4">
      <div class="d-flex gap-2 justify-content-lg-end flex-wrap">
        <?php if ($isAdmin): ?>
          <a class="btn btn-outline-primary" href="/Comercio/public/admin/matricular.php">
            <i class="bi bi-person-plus me-1"></i>Matricular
          </a>
          <a class="btn btn-outline-primary" href="/Comercio/public/asistencia/relojes.php">
            <i class="bi bi-hdd-network me-1"></i>Relojes
          </a>
          <a class="btn btn-brand" href="/Comercio/public/admin/asignar_clases.php">
            <i class="bi bi-diagram-3 me-1"></i>Asignar clases
          </a>
        <?php elseif ($isDoc): ?>
          <a class="btn btn-brand" href="/Comercio/public/docente/mis_clases.php">
            <i class="bi bi-journal-text me-1"></i>Mis asignaturas
          </a>
        <?php elseif ($isAlumno): ?>
          <a class="btn btn-brand" href="/Comercio/public/alumno/asistencia.php">
            <i class="bi bi-calendar-check me-1"></i>Mi asistencia
          </a>
        <?php elseif ($isTutor): ?>
          <a class="btn btn-brand" href="/Comercio/public/tutor/hijos.php">
            <i class="bi bi-people me-1"></i>Mis hijos
          </a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php
/* ============================================================
   ======================= ADMIN PANEL =========================
   ============================================================ */
if ($isAdmin):

  /* =========================
     KPIs académicos
  ========================= */
  $totalEstudiantes   = safe_int($pdo, "SELECT COUNT(*) FROM estudiantes WHERE activo=1");
  $totalDocentes      = safe_int($pdo, "SELECT COUNT(*) FROM docentes WHERE activo=1");
  $totalMatricActivos = safe_int($pdo, "SELECT COUNT(*) FROM matriculas WHERE anio_lectivo=? AND estado='ACTIVO'", [$anio]);
  $totalClases        = safe_int($pdo, "SELECT COUNT(*) FROM clases WHERE anio_lectivo=? AND activo=1", [$anio]);

  $totalEval = safe_int($pdo, "
    SELECT COUNT(*)
    FROM evaluaciones e
    JOIN clases c ON c.id = e.clase_id
    WHERE c.anio_lectivo = ? AND c.activo = 1
  ", [$anio]);

  $totalInscripciones = safe_int($pdo, "
    SELECT COUNT(*)
    FROM inscripciones_clase ic
    JOIN clases c ON c.id = ic.clase_id
    WHERE c.anio_lectivo = ? AND c.activo = 1
  ", [$anio]);

  $clasesSinDocente = safe_int($pdo, "
    SELECT COUNT(*)
    FROM clases
    WHERE anio_lectivo = ?
      AND activo = 1
      AND (docente_id IS NULL OR docente_id = 0)
  ", [$anio]);

  $clasesSinEval = safe_int($pdo, "
    SELECT COUNT(*)
    FROM (
      SELECT c.id
      FROM clases c
      LEFT JOIN evaluaciones e ON e.clase_id = c.id
      WHERE c.anio_lectivo = ? AND c.activo = 1
      GROUP BY c.id
      HAVING COUNT(e.id) = 0
    ) t
  ", [$anio]);

  $clasesSinInscriptos = safe_int($pdo, "
    SELECT COUNT(*)
    FROM (
      SELECT c.id
      FROM clases c
      LEFT JOIN inscripciones_clase ic ON ic.clase_id = c.id
      WHERE c.anio_lectivo = ? AND c.activo = 1
      GROUP BY c.id
      HAVING COUNT(ic.id) = 0
    ) t
  ", [$anio]);

  /* =========================
     Biométrico / asistencia
  ========================= */
  $relojesActivos = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM relojes_biometricos WHERE activo=1"],
    ['sql' => "SELECT COUNT(*) FROM relojes WHERE activo=1"],
    ['sql' => "SELECT COUNT(*) FROM relojes"],
  ], 0);

  $marcacionesHoy = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM marcaciones WHERE DATE(fecha_hora)=?", 'params' => [$hoy]],
    ['sql' => "SELECT COUNT(*) FROM marcaciones WHERE DATE(creado_en)=?", 'params' => [$hoy]],
  ], 0);

  $asisHoyTotal = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM asistencia_diaria WHERE anio_lectivo=? AND fecha=?", 'params' => [$anio, $hoy]],
  ], 0);

  $asisHoyPres = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM asistencia_diaria WHERE anio_lectivo=? AND fecha=? AND presente=1", 'params' => [$anio, $hoy]],
  ], 0);

  $asisHoyAus = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM asistencia_diaria WHERE anio_lectivo=? AND fecha=? AND presente=0", 'params' => [$anio, $hoy]],
  ], 0);

  $asisHoyTar = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM asistencia_diaria WHERE anio_lectivo=? AND fecha=? AND tardanza_min>0", 'params' => [$anio, $hoy]],
  ], 0);

  $nominaLocal = safe_int_any($pdo, [
    ['sql' => "SELECT COUNT(*) FROM reloj_nomina"],
  ], 0);

  $nominaCoincideEst = safe_int_any($pdo, [
    ['sql' => "
      SELECT COUNT(DISTINCT e.id)
      FROM estudiantes e
      JOIN reloj_nomina rn ON rn.device_user_id = e.ci
      WHERE e.activo = 1
    "],
  ], 0);

  $nominaPendienteMapeo = safe_int_any($pdo, [
    ['sql' => "
      SELECT COUNT(*)
      FROM reloj_nomina rn
      LEFT JOIN estudiantes e ON e.ci = rn.device_user_id
      WHERE e.id IS NULL
    "],
  ], 0);

  $ultimoReloj = safe_one($pdo, "
    SELECT id, nombre, ip, activo
    FROM relojes
    ORDER BY id DESC
    LIMIT 1
  ") ?: safe_one($pdo, "
    SELECT id, nombre, ip, activo
    FROM relojes_biometricos
    ORDER BY id DESC
    LIMIT 1
  ");

  $presPct = safe_ratio($asisHoyPres, max($asisHoyTotal, 0));
  $ausPct  = safe_ratio($asisHoyAus, max($asisHoyTotal, 0));
  $tarPct  = safe_ratio($asisHoyTar, max($asisHoyTotal, 0));

  /* =========================
     Actividad reciente
  ========================= */
  $ultMatric = safe_rows($pdo, "
    SELECT
      m.id, m.creado_en, m.nivel, m.curso, COALESCE(m.seccion,'A') AS seccion, m.turno, m.estado,
      e.ci, e.apellidos, e.nombres
    FROM matriculas m
    JOIN estudiantes e ON e.id = m.estudiante_id
    WHERE m.anio_lectivo = ?
    ORDER BY m.id DESC
    LIMIT 8
  ", [$anio]);

  $ultClases = safe_rows($pdo, "
    SELECT
      c.id, c.etapa, c.turno, c.nivel,
      cu.nombre AS curso,
      s.nombre AS seccion,
      m.nombre AS materia,
      d.apellidos AS d_apellidos,
      d.nombres AS d_nombres,
      (SELECT COUNT(*) FROM inscripciones_clase ic WHERE ic.clase_id = c.id) AS inscriptos
    FROM clases c
    JOIN cursos cu ON cu.id = c.curso_id
    JOIN secciones s ON s.id = c.seccion_id
    JOIN materias m ON m.id = c.materia_id
    LEFT JOIN docentes d ON d.id = c.docente_id
    WHERE c.anio_lectivo = ? AND c.activo = 1
    ORDER BY c.id DESC
    LIMIT 8
  ", [$anio]);

  $ultAsisHoy = safe_rows($pdo, "
    SELECT
      m.nivel, m.curso, m.seccion, m.turno,
      e.apellidos, e.nombres,
      a.hora_entrada, a.hora_salida, a.tardanza_min, a.presente
    FROM asistencia_diaria a
    JOIN estudiantes e ON e.id = a.estudiante_id
    JOIN matriculas m ON m.estudiante_id = a.estudiante_id AND m.anio_lectivo = a.anio_lectivo
    WHERE a.anio_lectivo = ? AND a.fecha = ?
    ORDER BY a.presente ASC, a.tardanza_min DESC, e.apellidos, e.nombres
    LIMIT 8
  ", [$anio, $hoy]);

  $topCursosHoy = safe_rows($pdo, "
    SELECT
      m.nivel,
      m.curso,
      COALESCE(m.seccion,'A') AS seccion,
      m.turno,
      COUNT(*) AS total,
      SUM(CASE WHEN a.presente = 1 THEN 1 ELSE 0 END) AS presentes,
      SUM(CASE WHEN a.presente = 0 THEN 1 ELSE 0 END) AS ausentes
    FROM asistencia_diaria a
    JOIN matriculas m ON m.estudiante_id = a.estudiante_id AND m.anio_lectivo = a.anio_lectivo
    WHERE a.anio_lectivo = ? AND a.fecha = ?
    GROUP BY m.nivel, m.curso, COALESCE(m.seccion,'A'), m.turno
    ORDER BY presentes DESC, total DESC
    LIMIT 6
  ", [$anio, $hoy]);

  $ultNomina = safe_rows($pdo, "
    SELECT id, reloj_id, device_user_id, nombre, empleado_no, actualizado_en
    FROM reloj_nomina
    ORDER BY id DESC
    LIMIT 8
  ");
?>

<div class="row g-3 mb-4">
  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico"><i class="bi bi-people fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$totalEstudiantes ?></div>
          <div class="kpi-label">Estudiantes activos</div>
          <div class="kpi-sub">Base estudiantil actual</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico green"><i class="bi bi-mortarboard fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$totalMatricActivos ?></div>
          <div class="kpi-label">Matrículas activas</div>
          <div class="kpi-sub">Año <?= (int)$anio ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico gray"><i class="bi bi-person-badge fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$totalDocentes ?></div>
          <div class="kpi-label">Docentes activos</div>
          <div class="kpi-sub">Plantel disponible</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico"><i class="bi bi-grid-3x3-gap fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$totalClases ?></div>
          <div class="kpi-label">Clases activas</div>
          <div class="kpi-sub">Configuradas en el año</div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-lg-4">
    <div class="card-pro p-3 h-100">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="section-title">Motor académico</div>
          <div class="mini-muted">Clases, evaluaciones e inscripciones</div>
        </div>
        <div class="kpi-value" style="font-size:1.6rem;"><?= (int)$totalEval ?></div>
      </div>

      <div class="mt-3 d-flex flex-wrap gap-2">
        <span class="chip"><i class="bi bi-ui-checks"></i> Evaluaciones: <b><?= (int)$totalEval ?></b></span>
        <span class="chip"><i class="bi bi-people"></i> Inscripciones: <b><?= (int)$totalInscripciones ?></b></span>
      </div>
    </div>
  </div>

  <div class="col-12 col-lg-4">
    <div class="card-pro p-3 h-100">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="section-title">Asignación docente</div>
          <div class="mini-muted">Seguimiento de cobertura de clases</div>
        </div>
        <div class="kpi-value" style="font-size:1.6rem;"><?= (int)$clasesSinDocente ?></div>
      </div>

      <div class="mt-3">
        <span class="chip"><i class="bi bi-exclamation-triangle"></i> Sin docente: <b><?= (int)$clasesSinDocente ?></b></span>
      </div>

      <div class="mt-3">
        <a class="btn btn-sm btn-outline-primary" href="/Comercio/public/admin/asignar_clases.php">
          <i class="bi bi-diagram-3 me-1"></i>Gestionar asignaciones
        </a>
      </div>
    </div>
  </div>

  <div class="col-12 col-lg-4">
    <div class="card-pro p-3 h-100">
      <div class="section-title mb-2">Alertas académicas</div>
      <ul class="list-clean">
        <li>
          <span>Clases sin evaluaciones</span>
          <strong><?= (int)$clasesSinEval ?></strong>
        </li>
        <li>
          <span>Clases sin inscriptos</span>
          <strong><?= (int)$clasesSinInscriptos ?></strong>
        </li>
        <li>
          <span>Docentes activos</span>
          <strong><?= (int)$totalDocentes ?></strong>
        </li>
      </ul>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico"><i class="bi bi-hdd-network fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$relojesActivos ?></div>
          <div class="kpi-label">Relojes activos</div>
          <div class="kpi-sub">Infraestructura biométrica</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico"><i class="bi bi-filetype-csv fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$marcacionesHoy ?></div>
          <div class="kpi-label">Marcaciones de hoy</div>
          <div class="kpi-sub">Datos crudos recibidos</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico green"><i class="bi bi-person-check fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$nominaCoincideEst ?></div>
          <div class="kpi-label">Nómina vinculada</div>
          <div class="kpi-sub">Coincide con estudiantes</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico amber"><i class="bi bi-person-exclamation fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$nominaPendienteMapeo ?></div>
          <div class="kpi-label">Pendientes de mapear</div>
          <div class="kpi-sub">En reloj_nomina sin alumno</div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-xl-5">
    <div class="card-pro p-3 h-100">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div>
          <div class="section-title">Presencia diaria</div>
          <div class="mini-muted">Resumen de asistencia del día</div>
        </div>
        <a class="btn btn-sm btn-outline-primary" href="/Comercio/public/asistencia/reporte_diario.php?anio=<?= (int)$anio ?>&fecha=<?= h($hoy) ?>">
          Ver reporte
        </a>
      </div>

      <div class="d-flex flex-wrap gap-2 mb-3">
        <span class="chip"><i class="bi bi-database"></i> Registros: <b><?= (int)$asisHoyTotal ?></b></span>
        <span class="chip"><i class="bi bi-check2-circle"></i> Presentes: <b><?= (int)$asisHoyPres ?></b></span>
        <span class="chip"><i class="bi bi-x-circle"></i> Ausentes: <b><?= (int)$asisHoyAus ?></b></span>
        <span class="chip"><i class="bi bi-alarm"></i> Tardanzas: <b><?= (int)$asisHoyTar ?></b></span>
      </div>

      <div class="mb-2">
        <div class="d-flex justify-content-between small mb-1">
          <span>Presencia</span>
          <strong><?= $presPct ?>%</strong>
        </div>
        <div class="progress" style="height:10px;">
          <div class="progress-bar" style="width: <?= $presPct ?>%;"></div>
        </div>
      </div>

      <div class="mb-2">
        <div class="d-flex justify-content-between small mb-1">
          <span>Ausencias</span>
          <strong><?= $ausPct ?>%</strong>
        </div>
        <div class="progress" style="height:10px;">
          <div class="progress-bar bg-danger" style="width: <?= $ausPct ?>%; background:linear-gradient(90deg,#dc3545,#bb2d3b);"></div>
        </div>
      </div>

      <div>
        <div class="d-flex justify-content-between small mb-1">
          <span>Tardanzas</span>
          <strong><?= $tarPct ?>%</strong>
        </div>
        <div class="progress" style="height:10px;">
          <div class="progress-bar" style="width: <?= $tarPct ?>%; background:linear-gradient(90deg,#f59f00,#e67700);"></div>
        </div>
      </div>

      <div class="panel-soft p-3 mt-3">
        <div class="fw-semibold mb-2">Operación recomendada</div>
        <div class="mini-muted">
          Primero sincronizá o importá marcaciones, luego generá asistencia y finalmente revisá el reporte diario.
        </div>
        <div class="d-flex flex-wrap gap-2 mt-3">
          <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/asistencia/importar_marcaciones.php">
            <i class="bi bi-upload me-1"></i>Importar CSV
          </a>
          <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/asistencia/monitor_tiempo_real.php">
            <i class="bi bi-broadcast me-1"></i>Monitor tiempo real
          </a>
          <a class="btn btn-sm btn-brand" href="/Comercio/public/asistencia/generar_asistencia.php">
            <i class="bi bi-gear-wide-connected me-1"></i>Generar asistencia
          </a>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-7">
    <div class="card-pro p-3 h-100">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div>
          <div class="section-title">Vista rápida de hoy</div>
          <div class="mini-muted">Últimos movimientos consolidados</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
          <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/asistencia/importar_marcaciones.php">
            <i class="bi bi-filetype-csv me-1"></i>Importar
          </a>
          <a class="btn btn-sm btn-brand" href="/Comercio/public/asistencia/generar_asistencia.php">
            <i class="bi bi-calendar2-check me-1"></i>Procesar
          </a>
        </div>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Alumno</th>
              <th>Curso</th>
              <th>Turno</th>
              <th>Entrada</th>
              <th>Salida</th>
              <th>Tardanza</th>
              <th>Estado</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($ultAsisHoy)): ?>
              <tr>
                <td colspan="7" class="text-muted p-3">Sin datos para hoy.</td>
              </tr>
            <?php else: ?>
              <?php foreach ($ultAsisHoy as $r): ?>
                <tr>
                  <td class="fw-semibold"><?= h(($r['apellidos'] ?? '') . ' ' . ($r['nombres'] ?? '')) ?></td>
                  <td><?= h(($r['nivel'] ?? '') . ' ' . ($r['curso'] ?? '') . ' ' . ($r['seccion'] ?? 'A')) ?></td>
                  <td><?= h($r['turno'] ?? '-') ?></td>
                  <td><?= h($r['hora_entrada'] ?? '-') ?></td>
                  <td><?= h($r['hora_salida'] ?? '-') ?></td>
                  <td><?= (int)($r['tardanza_min'] ?? 0) ?> min</td>
                  <td>
                    <?php if (!empty($r['presente'])): ?>
                      <span class="badge text-bg-success">Presente</span>
                    <?php else: ?>
                      <span class="badge text-bg-danger">Ausente</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <?php if (!empty($topCursosHoy)): ?>
        <div class="mt-3">
          <div class="fw-semibold mb-2">Cursos con más presencia hoy</div>
          <div class="row g-2">
            <?php foreach ($topCursosHoy as $tc): ?>
              <?php
                $pctCurso = safe_ratio((int)$tc['presentes'], (int)$tc['total']);
              ?>
              <div class="col-12 col-md-6">
                <div class="panel-soft p-2 h-100">
                  <div class="fw-semibold"><?= h(($tc['nivel'] ?? '') . ' ' . ($tc['curso'] ?? '') . ' ' . ($tc['seccion'] ?? 'A') . ' · ' . ($tc['turno'] ?? '-')) ?></div>
                  <div class="mini-muted mb-1">
                    <?= (int)$tc['presentes'] ?> presentes · <?= (int)$tc['ausentes'] ?> ausentes · Total <?= (int)$tc['total'] ?>
                  </div>
                  <div class="progress" style="height:8px;">
                    <div class="progress-bar" style="width: <?= $pctCurso ?>%;"></div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<div class="d-flex align-items-center justify-content-between mb-2">
  <div class="section-title">Centro biométrico y asistencia</div>
  <div class="mini-muted">Nuevos módulos integrados</div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/relojes.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-hdd-network fs-4"></i></div>
        <div>
          <div class="tile-name">Relojes biométricos</div>
          <p class="tile-desc">Alta, estado y administración de dispositivos</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/detectar_reloj.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-radar fs-4"></i></div>
        <div>
          <div class="tile-name">Detectar reloj</div>
          <p class="tile-desc">Descubrir o validar equipos en red</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/sincronizar_nomina.php<?= !empty($ultimoReloj['id']) ? '?reloj_id=' . (int)$ultimoReloj['id'] : '' ?>">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-person-vcard fs-4"></i></div>
        <div>
          <div class="tile-name">Sincronizar nómina</div>
          <p class="tile-desc">Cruce entre reloj, nómina y estudiantes</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/mapear_biometrico.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-link-45deg fs-4"></i></div>
        <div>
          <div class="tile-name">Mapear biométrico</div>
          <p class="tile-desc">Relacionar identidad del reloj con el sistema</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/importar_marcaciones.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-filetype-csv fs-4"></i></div>
        <div>
          <div class="tile-name">Importar marcaciones</div>
          <p class="tile-desc">Carga de datos desde CSV del reloj</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/monitor_tiempo_real.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-broadcast fs-4"></i></div>
        <div>
          <div class="tile-name">Monitor tiempo real</div>
          <p class="tile-desc">Seguimiento de eventos y marcaciones vivas</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/generar_asistencia.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-calendar2-check fs-4"></i></div>
        <div>
          <div class="tile-name">Generar asistencia</div>
          <p class="tile-desc">Procesar marcaciones hacia asistencia diaria</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <a class="tile-pro" href="/Comercio/public/asistencia/reporte_diario.php?anio=<?= (int)$anio ?>&fecha=<?= h($hoy) ?>">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-clipboard-data fs-4"></i></div>
        <div>
          <div class="tile-name">Reporte diario</div>
          <p class="tile-desc">Presencias, ausencias y tardanzas del día</p>
        </div>
      </div>
    </a>
  </div>
</div>

<div class="d-flex align-items-center justify-content-between mb-2">
  <div class="section-title">Gestión académica y operativa</div>
  <div class="mini-muted">Módulos principales del sistema</div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/matricular.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-person-plus fs-4"></i></div>
        <div>
          <div class="tile-name">Matricular</div>
          <p class="tile-desc">Alta por curso, turno, sección e inscripciones</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/asignar_clases.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-diagram-3 fs-4"></i></div>
        <div>
          <div class="tile-name">Asignar clases</div>
          <p class="tile-desc">Crear clases y distribuir docentes</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/plan_curso.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-journal-bookmark fs-4"></i></div>
        <div>
          <div class="tile-name">Plan de curso</div>
          <p class="tile-desc">Materias por curso y estructura anual</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/docentes.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-person-badge fs-4"></i></div>
        <div>
          <div class="tile-name">Docentes</div>
          <p class="tile-desc">Gestión del plantel y datos principales</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/usuarios.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-shield-lock fs-4"></i></div>
        <div>
          <div class="tile-name">Usuarios y roles</div>
          <p class="tile-desc">Permisos, accesos y seguridad de cuentas</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/vinculos.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-link-45deg fs-4"></i></div>
        <div>
          <div class="tile-name">Vínculos alumno/tutor</div>
          <p class="tile-desc">Relación de tutores con estudiantes</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/boletines.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-award fs-4"></i></div>
        <div>
          <div class="tile-name">Boletines</div>
          <p class="tile-desc">Consulta y generación de calificaciones</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-md-6 col-xl-4">
    <a class="tile-pro" href="/Comercio/public/admin/generar_anio.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-calendar3 fs-4"></i></div>
        <div>
          <div class="tile-name">Generar año lectivo</div>
          <p class="tile-desc">Preparar estructura anual del sistema</p>
        </div>
      </div>
    </a>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-xl-6">
    <div class="card-pro p-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="section-title">Últimas matrículas (<?= (int)$anio ?>)</div>
        <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/admin/matricular.php">Ver todo</a>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Alumno</th>
              <th>Curso</th>
              <th>Turno</th>
              <th>Estado</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($ultMatric)): ?>
              <tr><td colspan="4" class="text-muted p-3">Sin matrículas recientes.</td></tr>
            <?php else: ?>
              <?php foreach ($ultMatric as $m): ?>
                <tr>
                  <td class="fw-semibold"><?= h(($m['apellidos'] ?? '') . ' ' . ($m['nombres'] ?? '')) ?></td>
                  <td><?= h(($m['nivel'] ?? '') . ' ' . ($m['curso'] ?? '') . ' ' . ($m['seccion'] ?? 'A')) ?></td>
                  <td><?= h($m['turno'] ?? '-') ?></td>
                  <td><?= badge_estado((string)($m['estado'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-6">
    <div class="card-pro p-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="section-title">Clases recientes (<?= (int)$anio ?>)</div>
        <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/admin/asignar_clases.php">Gestionar</a>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Materia</th>
              <th>Curso</th>
              <th>Etapa</th>
              <th>Docente</th>
              <th>Inscriptos</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($ultClases)): ?>
              <tr><td colspan="5" class="text-muted p-3">Sin clases recientes.</td></tr>
            <?php else: ?>
              <?php foreach ($ultClases as $c): ?>
                <tr>
                  <td class="fw-semibold"><?= h($c['materia'] ?? '-') ?></td>
                  <td><?= h(($c['nivel'] ?? '') . ' ' . ($c['curso'] ?? '') . ' ' . ($c['seccion'] ?? '') . ' · ' . ($c['turno'] ?? '-')) ?></td>
                  <td><span class="badge text-bg-light">Etapa <?= (int)($c['etapa'] ?? 0) ?></span></td>
                  <td>
                    <?php if (!empty($c['d_apellidos'])): ?>
                      <?= h(($c['d_apellidos'] ?? '') . ' ' . ($c['d_nombres'] ?? '')) ?>
                    <?php else: ?>
                      <span class="text-danger fw-semibold">Sin asignar</span>
                    <?php endif; ?>
                  </td>
                  <td><span class="badge text-bg-light"><?= (int)($c['inscriptos'] ?? 0) ?></span></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-xl-6">
    <div class="card-pro p-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="section-title">Última nómina sincronizada</div>
        <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/asistencia/sincronizar_nomina.php<?= !empty($ultimoReloj['id']) ? '?reloj_id=' . (int)$ultimoReloj['id'] : '' ?>">Abrir módulo</a>
      </div>

      <div class="d-flex flex-wrap gap-2 mb-3">
        <span class="chip"><i class="bi bi-person-vcard"></i> Nómina local: <b><?= (int)$nominaLocal ?></b></span>
        <span class="chip"><i class="bi bi-person-check"></i> Coincide con alumnos: <b><?= (int)$nominaCoincideEst ?></b></span>
        <span class="chip"><i class="bi bi-person-exclamation"></i> Pendientes: <b><?= (int)$nominaPendienteMapeo ?></b></span>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Device User ID</th>
              <th>Nombre</th>
              <th>Empleado No</th>
              <th>Actualizado</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($ultNomina)): ?>
              <tr><td colspan="4" class="text-muted p-3">Aún no hay nómina local sincronizada.</td></tr>
            <?php else: ?>
              <?php foreach ($ultNomina as $n): ?>
                <tr>
                  <td class="fw-semibold"><?= h($n['device_user_id'] ?? '-') ?></td>
                  <td><?= h($n['nombre'] ?? '-') ?></td>
                  <td><?= h($n['empleado_no'] ?? '-') ?></td>
                  <td><?= h($n['actualizado_en'] ?? '-') ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-6">
    <div class="card-pro p-3 h-100">
      <div class="section-title mb-2">Estado operativo del biométrico</div>
      <ul class="list-clean">
        <li>
          <span>Relojes activos detectados</span>
          <strong><?= (int)$relojesActivos ?></strong>
        </li>
        <li>
          <span>Marcaciones recibidas hoy</span>
          <strong><?= (int)$marcacionesHoy ?></strong>
        </li>
        <li>
          <span>Asistencia consolidada hoy</span>
          <strong><?= (int)$asisHoyTotal ?></strong>
        </li>
        <li>
          <span>Nómina local sincronizada</span>
          <strong><?= (int)$nominaLocal ?></strong>
        </li>
      </ul>

      <?php if (!empty($ultimoReloj)): ?>
        <div class="panel-soft p-3 mt-3">
          <div class="fw-semibold mb-1">Último reloj registrado</div>
          <div class="mini-muted">
            <?= h($ultimoReloj['nombre'] ?? ('Reloj #' . ($ultimoReloj['id'] ?? ''))) ?>
            <?php if (!empty($ultimoReloj['ip'])): ?>
              · IP <?= h($ultimoReloj['ip']) ?>
            <?php endif; ?>
          </div>
          <div class="mt-2">
            <?php if (!empty($ultimoReloj['activo'])): ?>
              <span class="badge text-bg-success">ACTIVO</span>
            <?php else: ?>
              <span class="badge text-bg-secondary">INACTIVO</span>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>

      <div class="d-flex flex-wrap gap-2 mt-3">
        <a class="btn btn-sm btn-outline-primary" href="/Comercio/public/asistencia/detectar_reloj.php">
          <i class="bi bi-radar me-1"></i>Detectar
        </a>
        <a class="btn btn-sm btn-outline-primary" href="/Comercio/public/asistencia/mapear_biometrico.php">
          <i class="bi bi-link-45deg me-1"></i>Mapear
        </a>
        <a class="btn btn-sm btn-brand" href="/Comercio/public/asistencia/monitor_tiempo_real.php">
          <i class="bi bi-broadcast me-1"></i>Monitorear
        </a>
      </div>
    </div>
  </div>
</div>

<?php
/* ============================================================
   ======================= DOCENTE PANEL =======================
   ============================================================ */
elseif ($isDoc):

  $doc = safe_one($pdo, "SELECT id, apellidos, nombres FROM docentes WHERE usuario_id=? LIMIT 1", [$uid]);
  $docenteId = (int)($doc['id'] ?? 0);

  $misClases = $docenteId ? safe_int($pdo, "
    SELECT COUNT(*)
    FROM clases
    WHERE docente_id = ? AND anio_lectivo = ? AND activo = 1
  ", [$docenteId, $anio]) : 0;

  $misEval = $docenteId ? safe_int($pdo, "
    SELECT COUNT(*)
    FROM evaluaciones e
    JOIN clases c ON c.id = e.clase_id
    WHERE c.docente_id = ? AND c.anio_lectivo = ? AND c.activo = 1
  ", [$docenteId, $anio]) : 0;

  $misInscriptosDist = $docenteId ? safe_int($pdo, "
    SELECT COUNT(DISTINCT ic.matricula_id)
    FROM inscripciones_clase ic
    JOIN clases c ON c.id = ic.clase_id
    WHERE c.docente_id = ? AND c.anio_lectivo = ? AND c.activo = 1
  ", [$docenteId, $anio]) : 0;

  $misPendientes = $docenteId ? safe_int($pdo, "
    SELECT COALESCE(SUM(t.insc - t.carg), 0) AS pend
    FROM (
      SELECT
        e.id,
        (SELECT COUNT(*) FROM inscripciones_clase ic WHERE ic.clase_id = e.clase_id) AS insc,
        (SELECT COUNT(*) FROM calificaciones ca WHERE ca.evaluacion_id = e.id AND ca.estudiante_id IS NOT NULL) AS carg
      FROM evaluaciones e
      JOIN clases c ON c.id = e.clase_id
      WHERE c.docente_id = ? AND c.anio_lectivo = ? AND c.activo = 1
    ) t
  ", [$docenteId, $anio]) : 0;

  $previewClases = $docenteId ? safe_rows($pdo, "
    SELECT
      c.id, c.etapa, c.turno, c.nivel,
      cu.nombre AS curso,
      s.nombre AS seccion,
      m.nombre AS materia,
      (SELECT COUNT(*) FROM inscripciones_clase ic WHERE ic.clase_id = c.id) AS inscriptos,
      (SELECT COUNT(*) FROM evaluaciones e WHERE e.clase_id = c.id) AS evals
    FROM clases c
    JOIN cursos cu ON cu.id = c.curso_id
    JOIN secciones s ON s.id = c.seccion_id
    JOIN materias m ON m.id = c.materia_id
    WHERE c.docente_id = ? AND c.anio_lectivo = ? AND c.activo = 1
    ORDER BY c.etapa, cu.orden, cu.nombre, s.nombre, m.nombre
    LIMIT 10
  ", [$docenteId, $anio]) : [];

  $ultEval = $docenteId ? safe_rows($pdo, "
    SELECT
      e.id, e.tipo, e.titulo, e.fecha, e.puntaje_max,
      m.nombre AS materia,
      cu.nombre AS curso,
      s.nombre AS seccion,
      c.etapa,
      (SELECT COUNT(*) FROM calificaciones ca WHERE ca.evaluacion_id = e.id AND ca.estudiante_id IS NOT NULL) AS cargados,
      (SELECT COUNT(*) FROM inscripciones_clase ic WHERE ic.clase_id = c.id) AS insc
    FROM evaluaciones e
    JOIN clases c ON c.id = e.clase_id
    JOIN materias m ON m.id = c.materia_id
    JOIN cursos cu ON cu.id = c.curso_id
    JOIN secciones s ON s.id = c.seccion_id
    WHERE c.docente_id = ? AND c.anio_lectivo = ? AND c.activo = 1
    ORDER BY e.id DESC
    LIMIT 8
  ", [$docenteId, $anio]) : [];
?>

<div class="card-pro p-3 mb-3">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
    <div>
      <div class="section-title">Panel Docente</div>
      <div class="mini-muted">
        <?= ($doc && !empty($doc['apellidos'])) ? h(($doc['apellidos'] ?? '') . ' ' . ($doc['nombres'] ?? '')) : 'Docente' ?>
        · Año <?= (int)$anio ?>
      </div>
    </div>
    <a class="btn btn-brand btn-sm" href="/Comercio/public/docente/mis_clases.php">
      <i class="bi bi-journal-text me-1"></i>Mis asignaturas
    </a>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-md-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico green"><i class="bi bi-easel2 fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$misClases ?></div>
          <div class="kpi-label">Mis clases</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico"><i class="bi bi-ui-checks fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$misEval ?></div>
          <div class="kpi-label">Evaluaciones</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico gray"><i class="bi bi-people fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$misInscriptosDist ?></div>
          <div class="kpi-label">Alumnos distintos</div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-3">
    <div class="kpi-card p-3">
      <div class="d-flex align-items-center gap-3">
        <div class="kpi-ico red"><i class="bi bi-exclamation-circle fs-4"></i></div>
        <div>
          <div class="kpi-value"><?= (int)$misPendientes ?></div>
          <div class="kpi-label">Pendientes de cargar</div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-lg-6">
    <a class="tile-pro" href="/Comercio/public/docente/mis_clases.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-journal-text fs-4"></i></div>
        <div>
          <div class="tile-name">Mis asignaturas</div>
          <p class="tile-desc">Ver clases, configurar y administrar cursados</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-lg-6">
    <a class="tile-pro" href="/Comercio/public/docente/mis_clases.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-pencil-square fs-4"></i></div>
        <div>
          <div class="tile-name">Cargar puntajes</div>
          <p class="tile-desc">Clase → Evaluación → Registro de calificaciones</p>
        </div>
      </div>
    </a>
  </div>
</div>

<div class="row g-3 mb-4">
  <div class="col-12 col-xl-6">
    <div class="card-pro p-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="section-title">Mis clases</div>
        <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/docente/mis_clases.php">Ver todo</a>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Materia</th>
              <th>Curso</th>
              <th>Etapa</th>
              <th>Inscriptos</th>
              <th>Evals</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($previewClases)): ?>
              <tr><td colspan="6" class="text-muted p-3">No tenés clases asignadas todavía.</td></tr>
            <?php else: ?>
              <?php foreach ($previewClases as $c): ?>
                <tr>
                  <td class="fw-semibold"><?= h($c['materia'] ?? '-') ?></td>
                  <td><?= h(($c['nivel'] ?? '') . ' ' . ($c['curso'] ?? '') . ' ' . ($c['seccion'] ?? '') . ' · ' . ($c['turno'] ?? '-')) ?></td>
                  <td><span class="badge text-bg-light">Etapa <?= (int)($c['etapa'] ?? 0) ?></span></td>
                  <td><span class="badge text-bg-light"><?= (int)($c['inscriptos'] ?? 0) ?></span></td>
                  <td><span class="badge text-bg-light"><?= (int)($c['evals'] ?? 0) ?></span></td>
                  <td class="text-end">
                    <a class="btn btn-sm btn-brand" href="/Comercio/public/docente/clase.php?id=<?= (int)$c['id'] ?>">Entrar</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-6">
    <div class="card-pro p-3">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="section-title">Últimas evaluaciones</div>
        <a class="btn btn-sm btn-outline-secondary" href="/Comercio/public/docente/mis_clases.php">Ir a clases</a>
      </div>

      <div class="soft-table table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Tipo</th>
              <th>Materia</th>
              <th>Curso</th>
              <th>Progreso</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($ultEval)): ?>
              <tr><td colspan="5" class="text-muted p-3">Aún no hay evaluaciones creadas.</td></tr>
            <?php else: ?>
              <?php foreach ($ultEval as $e): ?>
                <?php
                  $insc = (int)($e['insc'] ?? 0);
                  $carg = (int)($e['cargados'] ?? 0);
                  $pct  = safe_ratio($carg, $insc);
                ?>
                <tr>
                  <td class="fw-semibold"><?= h(tipo_label((string)($e['tipo'] ?? ''))) ?></td>
                  <td><?= h($e['materia'] ?? '-') ?></td>
                  <td><?= h(($e['curso'] ?? '') . ' ' . ($e['seccion'] ?? '') . ' · Etapa ' . (int)($e['etapa'] ?? 0)) ?></td>
                  <td>
                    <div class="small text-muted mb-1"><?= $carg ?> / <?= $insc ?> (<?= $pct ?>%)</div>
                    <div class="progress" style="height:8px;">
                      <div class="progress-bar" style="width: <?= $pct ?>%;"></div>
                    </div>
                  </td>
                  <td class="text-end">
                    <a class="btn btn-sm btn-brand" href="/Comercio/public/docente/cargar_eval.php?eval=<?= (int)$e['id'] ?>">Cargar</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php
/* ============================================================
   ======================= ALUMNO PANEL ========================
   ============================================================ */
elseif ($isAlumno):
?>
<div class="row g-3">
  <div class="col-12 col-lg-6">
    <a class="tile-pro" href="/Comercio/public/alumno/asistencia.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-calendar-check fs-4"></i></div>
        <div>
          <div class="tile-name">Mi asistencia</div>
          <p class="tile-desc">Entradas, salidas, ausencias y tardanzas</p>
        </div>
      </div>
    </a>
  </div>
</div>

<?php
/* ============================================================
   ======================= TUTOR PANEL =========================
   ============================================================ */
elseif ($isTutor):
?>
<div class="row g-3">
  <div class="col-12 col-lg-6">
    <a class="tile-pro" href="/Comercio/public/tutor/hijos.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-people fs-4"></i></div>
        <div>
          <div class="tile-name">Mis hijos</div>
          <p class="tile-desc">Ver estudiantes vinculados y seguimiento</p>
        </div>
      </div>
    </a>
  </div>

  <div class="col-12 col-lg-6">
    <a class="tile-pro" href="/Comercio/public/tutor/asistencia.php">
      <div class="tile-head">
        <div class="tile-ico"><i class="bi bi-calendar2-week fs-4"></i></div>
        <div>
          <div class="tile-name">Asistencia</div>
          <p class="tile-desc">Consultar asistencia por alumno vinculado</p>
        </div>
      </div>
    </a>
  </div>
</div>
<?php endif; ?>

<?php include __DIR__ . '/../app/views/footer.php'; ?>