<?php
// modules/admin/dashboard.php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../includes/auth.php';
requireRol(ROL_ADMIN);

$user        = currentUser();
$db          = getDB();
$pageTitle   = 'Dashboard Administrador';
$idInst      = (int)($user['id_instituto'] ?? 1);

// ── Instituto ────────────────────────────────────────────────
$inst = $db->prepare("SELECT * FROM institutos WHERE id_instituto = :id LIMIT 1");
$inst->execute([':id' => $idInst]);
$inst = $inst->fetch() ?: [];

$stCfg = $db->prepare("SELECT clave, valor FROM configuracion_institucional WHERE id_instituto = :id");
$stCfg->execute([':id' => $idInst]);
$cfg = array_column($stCfg->fetchAll(), 'valor', 'clave');

$logoInst   = $inst['logo']   ?? '';
$nombreInst = $inst['nombre'] ?? 'SIGVP';
$siglasInst = $cfg['siglas_institucion'] ?? '';
$logoUrl    = $logoInst ? BASE_URL . '/uploads/institutos/' . $logoInst : '';

// ── KPIs globales ────────────────────────────────────────────
$kpi = [];

// Estudiantes activos
$kpi['estudiantes'] = (int)$db->prepare("
    SELECT COUNT(*) FROM estudiantes e
    JOIN usuarios u ON u.id_usuario = e.id_usuario
    WHERE e.id_instituto = :i AND u.activo = 1
")->execute([':i'=>$idInst]) ? $db->prepare("
    SELECT COUNT(*) FROM estudiantes e
    JOIN usuarios u ON u.id_usuario = e.id_usuario
    WHERE e.id_instituto = :i AND u.activo = 1
")->execute([':i'=>$idInst]) : 0;

// Reutilizable: helper de count
function dbCount($db, $sql, $params = []) {
    $st = $db->prepare($sql);
    $st->execute($params);
    return (int)$st->fetchColumn();
}

$kpi['estudiantes']    = dbCount($db, "SELECT COUNT(*) FROM estudiantes e JOIN usuarios u ON u.id_usuario=e.id_usuario WHERE e.id_instituto=:i AND u.activo=1", [':i'=>$idInst]);
$kpi['ppp_completadas']= dbCount($db, "SELECT COUNT(*) FROM practicas p JOIN estudiantes e ON e.id_estudiante=p.id_estudiante WHERE e.id_instituto=:i AND p.estado='completado'", [':i'=>$idInst]);
$kpi['ppp_curso']      = dbCount($db, "SELECT COUNT(*) FROM practicas p JOIN estudiantes e ON e.id_estudiante=p.id_estudiante WHERE e.id_instituto=:i AND p.estado IN('aprobado','en_progreso')", [':i'=>$idInst]);
$kpi['conv_aprobadas'] = dbCount($db, "SELECT COUNT(*) FROM convalidaciones cv JOIN estudiantes e ON e.id_estudiante=cv.id_estudiante WHERE e.id_instituto=:i AND cv.estado='aprobada'", [':i'=>$idInst]);
$kpi['vinc_completada']= dbCount($db, "SELECT COUNT(*) FROM participaciones_vinculacion pv JOIN estudiantes e ON e.id_estudiante=pv.id_estudiante WHERE e.id_instituto=:i AND pv.estado='completado'", [':i'=>$idInst]);
$kpi['tit_complexivo'] = dbCount($db, "SELECT COUNT(*) FROM titulaciones t JOIN estudiantes e ON e.id_estudiante=t.id_estudiante WHERE e.id_instituto=:i AND t.modalidad='examen_complexivo' AND t.estado='aprobado'", [':i'=>$idInst]);
$kpi['tit_trabajo']    = dbCount($db, "SELECT COUNT(*) FROM titulaciones t JOIN estudiantes e ON e.id_estudiante=t.id_estudiante WHERE e.id_instituto=:i AND t.modalidad='trabajo_investigacion' AND t.estado='aprobado'", [':i'=>$idInst]);
$kpi['tit_proceso']    = dbCount($db, "SELECT COUNT(*) FROM titulaciones t JOIN estudiantes e ON e.id_estudiante=t.id_estudiante WHERE e.id_instituto=:i AND t.estado IN('pendiente','enviada')", [':i'=>$idInst]);

// ── Filtro periodo ───────────────────────────────────────────
$periodos = $db->prepare("SELECT id_periodo, nombre, activo FROM periodos_academicos WHERE id_instituto=:i ORDER BY id_periodo DESC");
$periodos->execute([':i'=>$idInst]);
$periodos = $periodos->fetchAll();

$filtPer = isset($_GET['periodo']) && $_GET['periodo'] !== '' ? (int)$_GET['periodo'] : null;
$perWhere = $filtPer ? "AND p.id_periodo = $filtPer" : "";
$perWhereVinc = $filtPer ? "AND proy.id_periodo = $filtPer" : "";
$perWhereTit  = $filtPer ? "AND t.id_periodo = $filtPer" : "";  // titulaciones no tiene id_periodo directo

// ── Tabla por carrera ────────────────────────────────────────
$resumenCarreras = $db->prepare("
    SELECT
        c.id_carrera,
        c.nombre AS carrera,
        c.codigo,
        -- Total estudiantes
        COUNT(DISTINCT e.id_estudiante) AS total_estudiantes,
        -- PPP
        SUM(CASE WHEN p.estado = 'completado' THEN 1 ELSE 0 END)                                AS ppp_completadas,
        SUM(CASE WHEN p.estado IN('aprobado','en_progreso') THEN 1 ELSE 0 END)                  AS ppp_curso,
        SUM(CASE WHEN p.estado IN('borrador','postulado') THEN 1 ELSE 0 END)                    AS ppp_pendientes,
        -- Convalidaciones
        SUM(CASE WHEN cv.estado = 'aprobada' THEN 1 ELSE 0 END)                                 AS conv_aprobadas,
        SUM(CASE WHEN cv.estado IN('pendiente','en_revision') THEN 1 ELSE 0 END)                AS conv_pendientes,
        -- Vinculación
        SUM(CASE WHEN pv.estado = 'completado' THEN 1 ELSE 0 END)                               AS vinc_completada,
        SUM(CASE WHEN pv.estado IN('inscrito','en_progreso') THEN 1 ELSE 0 END)                 AS vinc_curso,
        -- Titulación
        SUM(CASE WHEN t.modalidad='examen_complexivo'  AND t.estado='aprobado' THEN 1 ELSE 0 END) AS tit_complexivo,
        SUM(CASE WHEN t.modalidad='trabajo_investigacion' AND t.estado='aprobado' THEN 1 ELSE 0 END) AS tit_trabajo,
        SUM(CASE WHEN t.estado IN('pendiente','enviada') THEN 1 ELSE 0 END)                     AS tit_proceso
    FROM carreras c
    LEFT JOIN estudiantes e  ON e.id_carrera = c.id_carrera AND e.id_instituto = :i
    LEFT JOIN practicas p    ON p.id_estudiante = e.id_estudiante $perWhere
    LEFT JOIN convalidaciones cv ON cv.id_estudiante = e.id_estudiante
    LEFT JOIN participaciones_vinculacion pv ON pv.id_estudiante = e.id_estudiante
    LEFT JOIN titulaciones t  ON t.id_estudiante = e.id_estudiante
    WHERE c.id_instituto = :i2 AND c.activa = 1
    GROUP BY c.id_carrera, c.nombre, c.codigo
    ORDER BY c.nombre
")->execute([':i'=>$idInst, ':i2'=>$idInst]) ? [] : [];

$stR = $db->prepare("
    SELECT
        c.id_carrera, c.nombre AS carrera, c.codigo,
        COUNT(DISTINCT e.id_estudiante) AS total_estudiantes,
        SUM(CASE WHEN p.estado = 'completado' THEN 1 ELSE 0 END)                                  AS ppp_completadas,
        SUM(CASE WHEN p.estado IN('aprobado','en_progreso') THEN 1 ELSE 0 END)                    AS ppp_curso,
        SUM(CASE WHEN p.estado IN('borrador','postulado') THEN 1 ELSE 0 END)                      AS ppp_pendientes,
        SUM(CASE WHEN cv.estado = 'aprobada' THEN 1 ELSE 0 END)                                   AS conv_aprobadas,
        SUM(CASE WHEN cv.estado IN('pendiente','en_revision') THEN 1 ELSE 0 END)                  AS conv_pendientes,
        SUM(CASE WHEN pv.estado = 'completado' THEN 1 ELSE 0 END)                                 AS vinc_completada,
        SUM(CASE WHEN pv.estado IN('inscrito','en_progreso') THEN 1 ELSE 0 END)                   AS vinc_curso,
        SUM(CASE WHEN t.modalidad='examen_complexivo'   AND t.estado='aprobado' THEN 1 ELSE 0 END) AS tit_complexivo,
        SUM(CASE WHEN t.modalidad='trabajo_investigacion' AND t.estado='aprobado' THEN 1 ELSE 0 END) AS tit_trabajo,
        SUM(CASE WHEN t.estado IN('pendiente','enviada') THEN 1 ELSE 0 END)                       AS tit_proceso
    FROM carreras c
    LEFT JOIN estudiantes e   ON e.id_carrera = c.id_carrera AND e.id_instituto = :i
    LEFT JOIN practicas p     ON p.id_estudiante = e.id_estudiante $perWhere
    LEFT JOIN convalidaciones cv ON cv.id_estudiante = e.id_estudiante
    LEFT JOIN participaciones_vinculacion pv ON pv.id_estudiante = e.id_estudiante
    LEFT JOIN titulaciones t   ON t.id_estudiante = e.id_estudiante
    WHERE c.id_instituto = :i2 AND c.activa = 1
    GROUP BY c.id_carrera, c.nombre, c.codigo
    ORDER BY c.nombre
");
$stR->execute([':i'=>$idInst, ':i2'=>$idInst]);
$resumenCarreras = $stR->fetchAll();

// ── Últimos usuarios ─────────────────────────────────────────
$ultimosUsuarios = $db->query("
    SELECT u.apellidos, u.nombres, u.email, u.activo, u.created_at, r.nombre AS rol_nombre
    FROM   usuarios u JOIN roles r ON r.id_rol = u.id_rol
    ORDER  BY u.created_at DESC LIMIT 8
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php include __DIR__ . '/../../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-admin.css">
<style>
/* ── KPI Cards ── */
.kpi-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
  gap: 14px;
  margin-bottom: 24px;
}
.kpi-card {
  background: #fff;
  border-radius: 14px;
  padding: 18px 20px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 4px rgba(0,0,0,.04);
  display: flex;
  flex-direction: column;
  gap: 6px;
  transition: box-shadow .2s;
}
.kpi-card:hover { box-shadow: 0 4px 16px rgba(0,0,0,.09); }
.kpi-icon {
  width: 38px; height: 38px; border-radius: 10px;
  display: flex; align-items: center; justify-content: center;
  font-size: 18px; margin-bottom: 4px;
}
.kpi-num  { font-size: 28px; font-weight: 900; line-height: 1; }
.kpi-lbl  { font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: .05em; }
.kpi-sub  { font-size: 11px; color: #94a3b8; margin-top: 2px; }

/* colores por módulo */
.kpi-blue   { background: #eff6ff; } .kpi-blue   .kpi-icon { background: #dbeafe; }
.kpi-green  { background: #f0fdf4; } .kpi-green  .kpi-icon { background: #dcfce7; }
.kpi-violet { background: #f5f3ff; } .kpi-violet .kpi-icon { background: #ede9fe; }
.kpi-teal   { background: #f0fdfa; } .kpi-teal   .kpi-icon { background: #ccfbf1; }
.kpi-orange { background: #fff7ed; } .kpi-orange .kpi-icon { background: #fed7aa; }
.kpi-rose   { background: #fff1f2; } .kpi-rose   .kpi-icon { background: #ffe4e6; }
.kpi-indigo { background: #eef2ff; } .kpi-indigo .kpi-icon { background: #e0e7ff; }
.kpi-amber  { background: #fffbeb; } .kpi-amber  .kpi-icon { background: #fef3c7; }
.kpi-blue   .kpi-num { color: #1d4ed8; }
.kpi-green  .kpi-num { color: #15803d; }
.kpi-violet .kpi-num { color: #6d28d9; }
.kpi-teal   .kpi-num { color: #0d9488; }
.kpi-orange .kpi-num { color: #c2410c; }
.kpi-rose   .kpi-num { color: #be123c; }
.kpi-indigo .kpi-num { color: #4338ca; }
.kpi-amber  .kpi-num { color: #b45309; }

/* ── Sección headers ── */
.sec-header {
  display: flex; align-items: center; justify-content: space-between;
  margin: 28px 0 14px; gap: 12px; flex-wrap: wrap;
}
.sec-title {
  font-size: 15px; font-weight: 800; color: #0f172a;
  display: flex; align-items: center; gap: 8px;
}
.sec-title i { font-size: 14px; }

/* ── Tabla resumen por carrera ── */
.tbl-resumen { width: 100%; border-collapse: separate; border-spacing: 0 5px; }
.tbl-resumen thead th {
  font-size: 10px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .07em; color: #94a3b8; padding: 8px 12px;
  background: #f8fafc; border-bottom: 2px solid #e2e8f0;
  white-space: nowrap;
}
.tbl-resumen thead th:first-child { border-radius: 8px 0 0 0; }
.tbl-resumen thead th:last-child  { border-radius: 0 8px 0 0; }

.tbl-resumen tbody tr {
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,.04);
  transition: box-shadow .15s;
}
.tbl-resumen tbody tr:hover { box-shadow: 0 3px 12px rgba(0,0,0,.09); }
.tbl-resumen tbody td {
  padding: 12px 12px; font-size: 13px; color: #1e293b;
  border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9;
  vertical-align: middle;
}
.tbl-resumen tbody td:first-child { border-left:1px solid #f1f5f9; border-radius:8px 0 0 8px; }
.tbl-resumen tbody td:last-child  { border-right:1px solid #f1f5f9; border-radius:0 8px 8px 0; }

/* Mini badges de estado */
.mini-badge {
  display: inline-flex; align-items: center; justify-content: center;
  min-width: 26px; height: 22px; border-radius: 20px; padding: 0 8px;
  font-size: 12px; font-weight: 800; line-height: 1;
}
.mb-green  { background: #dcfce7; color: #15803d; }
.mb-blue   { background: #dbeafe; color: #1d4ed8; }
.mb-yellow { background: #fef9c3; color: #854d0e; }
.mb-red    { background: #fee2e2; color: #991b1b; }
.mb-violet { background: #ede9fe; color: #6d28d9; }
.mb-teal   { background: #ccfbf1; color: #0d9488; }
.mb-gray   { background: #f1f5f9; color: #475569; }
.mb-orange { background: #fed7aa; color: #c2410c; }
.mb-0      { background: #f1f5f9; color: #cbd5e1; }

/* Barra de progreso mini */
.prog-wrap { width: 80px; background: #f1f5f9; border-radius: 20px; height: 6px; }
.prog-bar  { height: 6px; border-radius: 20px; }

/* ── Tabla usuarios recientes ── */
.tbl-usuarios { width:100%; border-collapse:separate; border-spacing:0 4px; }
.tbl-usuarios thead th {
  background:#1e293b; color:#94a3b8; font-size:10px; font-weight:700;
  letter-spacing:.07em; text-transform:uppercase; padding:9px 12px; border:none;
}
.tbl-usuarios thead th:first-child { border-radius:8px 0 0 8px; }
.tbl-usuarios thead th:last-child  { border-radius:0 8px 8px 0; }
.tbl-usuarios tbody tr { background:#fff; }
.tbl-usuarios tbody tr:hover { background:#f8fafc; }
.tbl-usuarios tbody td {
  padding:10px 12px; font-size:12.5px; color:#1e293b;
  border-top:1px solid #f1f5f9; border-bottom:1px solid #f1f5f9; vertical-align:middle;
}
.tbl-usuarios tbody td:first-child { border-left:1px solid #f1f5f9; border-radius:8px 0 0 8px; }
.tbl-usuarios tbody td:last-child  { border-right:1px solid #f1f5f9; border-radius:0 8px 8px 0; }
.usr-av {
  width:30px; height:30px; border-radius:50%;
  display:inline-flex; align-items:center; justify-content:center;
  font-size:12px; font-weight:800; background:linear-gradient(135deg,#dbeafe,#ede9fe);
  color:#2563eb; border:1.5px solid #bfdbfe; flex-shrink:0;
}
.rol-chip {
  font-size:10px; font-weight:700; border-radius:20px; padding:2px 8px;
  text-transform:uppercase; letter-spacing:.04em;
}
</style>
</head>
<body>
<?php include __DIR__ . '/../../includes/navbar.php'; ?>
<div class="app-shell">
  <?php $sbActivo = 'dashboard'; include __DIR__ . '/../../includes/sidebar_admin.php'; ?>
  <main class="main-area">

    <!-- ══ ENCABEZADO INSTITUTO ══ -->
    <div style="display:flex;align-items:center;justify-content:space-between;
                background:#fff;border:1px solid #e2e8f0;border-radius:14px;
                padding:16px 24px;margin-bottom:24px;box-shadow:0 1px 4px rgba(0,0,0,.05);">
      <div style="flex-shrink:0;">
        <?php if ($logoUrl): ?>
          <img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo"
               style="height:68px;width:68px;object-fit:contain;border-radius:10px;border:1px solid #e2e8f0;padding:4px;background:#f8fafc;">
        <?php else: ?>
          <div style="height:68px;width:68px;background:#1a3a6b;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:28px;">🏫</div>
        <?php endif; ?>
      </div>
      <div style="flex:1;text-align:center;padding:0 20px;">
        <div style="font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:#94a3b8;margin-bottom:4px;">Panel de Administración</div>
        <div style="font-size:19px;font-weight:900;color:#0f172a;"><?= htmlspecialchars($nombreInst) ?></div>
        <?php if ($siglasInst): ?>
          <div style="font-size:12px;color:#64748b;margin-top:3px;font-weight:600;"><?= htmlspecialchars($siglasInst) ?></div>
        <?php endif; ?>
      </div>
      <div style="flex-shrink:0;text-align:center;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:12px 18px;min-width:120px;">
        <div style="font-size:22px;font-weight:800;color:#0f172a;line-height:1;" id="reloj-hora"><?= date('H:i:s') ?></div>
        <div style="font-size:11px;color:#94a3b8;margin-top:4px;font-weight:600;"><?= date('d/m/Y') ?></div>
        <div style="font-size:10px;color:#cbd5e1;margin-top:2px;" id="reloj-dia"></div>
      </div>
    </div>

    <!-- ══ KPIs GLOBALES ══ -->
    <div class="kpi-grid">
      <div class="kpi-card kpi-blue">
        <div class="kpi-icon">🎓</div>
        <div class="kpi-num"><?= $kpi['estudiantes'] ?></div>
        <div class="kpi-lbl">Estudiantes activos</div>
      </div>
      <div class="kpi-card kpi-green">
        <div class="kpi-icon">✅</div>
        <div class="kpi-num"><?= $kpi['ppp_completadas'] ?></div>
        <div class="kpi-lbl">PPP Completadas</div>
        <div class="kpi-sub"><?= $kpi['ppp_curso'] ?> en curso</div>
      </div>
      <div class="kpi-card kpi-teal">
        <div class="kpi-icon">🔄</div>
        <div class="kpi-num"><?= $kpi['conv_aprobadas'] ?></div>
        <div class="kpi-lbl">Convalidaciones</div>
        <div class="kpi-sub">aprobadas</div>
      </div>
      <div class="kpi-card kpi-violet">
        <div class="kpi-icon">🤝</div>
        <div class="kpi-num"><?= $kpi['vinc_completada'] ?></div>
        <div class="kpi-lbl">Vinculación</div>
        <div class="kpi-sub">completada</div>
      </div>
      <div class="kpi-card kpi-indigo">
        <div class="kpi-icon">📝</div>
        <div class="kpi-num"><?= $kpi['tit_complexivo'] ?></div>
        <div class="kpi-lbl">Examen Complexivo</div>
        <div class="kpi-sub">aprobado</div>
      </div>
      <div class="kpi-card kpi-orange">
        <div class="kpi-icon">📄</div>
        <div class="kpi-num"><?= $kpi['tit_trabajo'] ?></div>
        <div class="kpi-lbl">Trabajo Investigación</div>
        <div class="kpi-sub">aprobado</div>
      </div>
      <div class="kpi-card kpi-amber">
        <div class="kpi-icon">⏳</div>
        <div class="kpi-num"><?= $kpi['tit_proceso'] ?></div>
        <div class="kpi-lbl">Titulación en proceso</div>
      </div>
    </div>

    <!-- ══ RESUMEN POR CARRERA Y CICLO ══ -->
    <div class="sec-header">
      <div class="sec-title">
        <i class="fa fa-chart-bar" style="color:#2ea8ff;"></i>
        Resumen por Carrera
      </div>
      <!-- Filtro periodo -->
      <form method="GET" style="display:flex;align-items:center;gap:8px;">
        <label style="font-size:12px;color:#64748b;font-weight:600;white-space:nowrap;">
          <i class="fa fa-calendar me-1"></i>Ciclo:
        </label>
        <select name="periodo" class="form-select form-select-sm" style="width:160px;" onchange="this.form.submit()">
          <option value="">Todos los ciclos</option>
          <?php foreach ($periodos as $per): ?>
            <option value="<?= $per['id_periodo'] ?>" <?= $filtPer===$per['id_periodo']?'selected':'' ?>>
              <?= htmlspecialchars($per['nombre']) ?><?= $per['activo'] ? ' ★' : '' ?>
            </option>
          <?php endforeach; ?>
        </select>
      </form>
    </div>

    <!-- Leyenda de columnas -->
    <div style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:12px;">
      <?php
        $leyenda = [
          ['mb-green','PPP completadas'],['mb-blue','PPP en curso'],
          ['mb-teal','Convalidaciones aprobadas'],['mb-violet','Vinculación completada'],
          ['mb-indigo','Examen complexivo'],['mb-orange','Trabajo investigación'],
          ['mb-yellow','En proceso / pendiente'],
        ];
        foreach($leyenda as [$cls,$lbl]):
      ?>
        <span style="display:inline-flex;align-items:center;gap:5px;font-size:11px;color:#64748b;">
          <span class="mini-badge <?= $cls ?>" style="width:14px;height:14px;min-width:14px;padding:0;border-radius:50%;"></span>
          <?= $lbl ?>
        </span>
      <?php endforeach; ?>
    </div>

    <div style="background:#fff;border-radius:14px;border:1px solid #e2e8f0;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.04);overflow-x:auto;">
      <table class="tbl-resumen">
        <thead>
          <tr>
            <th>Carrera</th>
            <th style="text-align:center;">Estudiantes</th>
            <th colspan="3" style="text-align:center;border-left:2px solid #e2e8f0;">
              <span style="color:#15803d;">PPP</span>
            </th>
            <th colspan="2" style="text-align:center;border-left:2px solid #e2e8f0;">
              <span style="color:#0d9488;">Convalidación</span>
            </th>
            <th colspan="2" style="text-align:center;border-left:2px solid #e2e8f0;">
              <span style="color:#6d28d9;">Vinculación</span>
            </th>
            <th colspan="3" style="text-align:center;border-left:2px solid #e2e8f0;">
              <span style="color:#4338ca;">Titulación</span>
            </th>
          </tr>
          <tr>
            <th></th>
            <th style="text-align:center;">Total</th>
            <th style="text-align:center;border-left:2px solid #e2e8f0;">✅ Complet.</th>
            <th style="text-align:center;">🔄 Curso</th>
            <th style="text-align:center;">⏳ Pend.</th>
            <th style="text-align:center;border-left:2px solid #e2e8f0;">✅ Aprob.</th>
            <th style="text-align:center;">⏳ Pend.</th>
            <th style="text-align:center;border-left:2px solid #e2e8f0;">✅ Complet.</th>
            <th style="text-align:center;">🔄 Curso</th>
            <th style="text-align:center;border-left:2px solid #e2e8f0;">📝 Complex.</th>
            <th style="text-align:center;">📄 Trab.</th>
            <th style="text-align:center;">⏳ Proceso</th>
          </tr>
        </thead>
        <tbody>
        <?php if (empty($resumenCarreras)): ?>
          <tr><td colspan="12" style="text-align:center;padding:32px;color:#94a3b8;">Sin datos para mostrar</td></tr>
        <?php else: foreach($resumenCarreras as $row):
          $tot = max(1, (int)$row['total_estudiantes']);
          $pctPpp = round(($row['ppp_completadas']/$tot)*100);
        ?>
          <tr>
            <td>
              <div style="font-weight:700;font-size:13px;"><?= htmlspecialchars($row['carrera']) ?></div>
              <div style="font-size:10px;color:#94a3b8;margin-top:2px;"><?= htmlspecialchars($row['codigo']) ?></div>
              <!-- Barra progreso PPP -->
              <div style="margin-top:5px;display:flex;align-items:center;gap:6px;">
                <div class="prog-wrap">
                  <div class="prog-bar" style="width:<?= $pctPpp ?>%;background:#22c55e;"></div>
                </div>
                <span style="font-size:10px;color:#64748b;"><?= $pctPpp ?>% PPP</span>
              </div>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge mb-blue"><?= (int)$row['total_estudiantes'] ?></span>
            </td>
            <!-- PPP -->
            <td style="text-align:center;border-left:2px solid #f1f5f9;">
              <span class="mini-badge <?= $row['ppp_completadas']>0?'mb-green':'mb-0' ?>"><?= (int)$row['ppp_completadas'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['ppp_curso']>0?'mb-blue':'mb-0' ?>"><?= (int)$row['ppp_curso'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['ppp_pendientes']>0?'mb-yellow':'mb-0' ?>"><?= (int)$row['ppp_pendientes'] ?></span>
            </td>
            <!-- Convalidación -->
            <td style="text-align:center;border-left:2px solid #f1f5f9;">
              <span class="mini-badge <?= $row['conv_aprobadas']>0?'mb-teal':'mb-0' ?>"><?= (int)$row['conv_aprobadas'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['conv_pendientes']>0?'mb-yellow':'mb-0' ?>"><?= (int)$row['conv_pendientes'] ?></span>
            </td>
            <!-- Vinculación -->
            <td style="text-align:center;border-left:2px solid #f1f5f9;">
              <span class="mini-badge <?= $row['vinc_completada']>0?'mb-violet':'mb-0' ?>"><?= (int)$row['vinc_completada'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['vinc_curso']>0?'mb-blue':'mb-0' ?>"><?= (int)$row['vinc_curso'] ?></span>
            </td>
            <!-- Titulación -->
            <td style="text-align:center;border-left:2px solid #f1f5f9;">
              <span class="mini-badge <?= $row['tit_complexivo']>0?'mb-indigo':'mb-0' ?>"><?= (int)$row['tit_complexivo'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['tit_trabajo']>0?'mb-orange':'mb-0' ?>"><?= (int)$row['tit_trabajo'] ?></span>
            </td>
            <td style="text-align:center;">
              <span class="mini-badge <?= $row['tit_proceso']>0?'mb-yellow':'mb-0' ?>"><?= (int)$row['tit_proceso'] ?></span>
            </td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

    <!-- ══ ÚLTIMOS USUARIOS ══ -->
    <div class="sec-header" style="margin-top:30px;">
      <div class="sec-title">
        <i class="fa fa-users" style="color:#2ea8ff;"></i>
        Últimos usuarios registrados
      </div>
      <a href="usuarios.php" style="font-size:12px;color:#2ea8ff;text-decoration:none;font-weight:600;">
        Ver todos <i class="fa fa-arrow-right fa-xs"></i>
      </a>
    </div>

    <div style="background:#fff;border-radius:14px;border:1px solid #e2e8f0;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.04);">
      <table class="tbl-usuarios">
        <thead><tr>
          <th>Nombre</th><th>Email</th><th>Rol</th><th>Estado</th><th>Registrado</th>
        </tr></thead>
        <tbody>
        <?php if (empty($ultimosUsuarios)): ?>
          <tr><td colspan="5" style="text-align:center;padding:28px;color:#94a3b8;">Sin usuarios</td></tr>
        <?php else: foreach($ultimosUsuarios as $u):
          $ini = mb_strtoupper(mb_substr($u['nombres'],0,1,'UTF-8'),'UTF-8');
          $rolColors = [
            'administrador'=>['#ede9fe','#5b21b6'],'coordinador'=>['#dbeafe','#1d4ed8'],
            'estudiante'=>['#dcfce7','#166534'],'tutor'=>['#fef9c3','#854d0e'],
            'secretaria'=>['#fce7f3','#9d174d'],'facturacion'=>['#e0f2fe','#075985'],
          ];
          $rc = $rolColors[$u['rol_nombre']] ?? ['#f1f5f9','#475569'];
        ?>
          <tr>
            <td>
              <div style="display:flex;align-items:center;gap:9px;">
                <span class="usr-av"><?= $ini ?></span>
                <span style="font-weight:600;"><?= htmlspecialchars($u['apellidos'].' '.$u['nombres']) ?></span>
              </div>
            </td>
            <td style="font-size:11.5px;color:#475569;font-family:monospace;"><?= htmlspecialchars($u['email']) ?></td>
            <td>
              <span class="rol-chip" style="background:<?= $rc[0] ?>;color:<?= $rc[1] ?>;">
                <?= htmlspecialchars($u['rol_nombre']) ?>
              </span>
            </td>
            <td>
              <?= $u['activo']
                ? '<span style="background:#dcfce7;color:#15803d;font-size:11px;font-weight:700;border-radius:20px;padding:2px 10px;">Activo</span>'
                : '<span style="background:#fee2e2;color:#991b1b;font-size:11px;font-weight:700;border-radius:20px;padding:2px 10px;">Inactivo</span>'
              ?>
            </td>
            <td style="font-size:11px;color:#94a3b8;"><?= date('d/m/Y H:i', strtotime($u['created_at'])) ?></td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

  </main>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
<script>
var BASE_URL = '<?= BASE_URL ?>';
// Reloj
(function tick(){
  const d=new Date();
  const pad=n=>String(n).padStart(2,'0');
  const dias=['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'];
  document.getElementById('reloj-hora').textContent=pad(d.getHours())+':'+pad(d.getMinutes())+':'+pad(d.getSeconds());
  document.getElementById('reloj-dia').textContent=dias[d.getDay()];
  setTimeout(tick,1000);
})();
</script>
</body>
</html>