<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config'   . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'flash.php';
requireRol(ROL_COORDINADOR);

$user      = currentUser();
$db        = getDB();
$idInst = (int)($user['id_instituto'] ?? 0);
$iCond  = $idInst ? "AND pr.id_instituto = $idInst" : '';
$pageTitle = 'Evaluaciones de Satisfacción';

// ── Detalle de una práctica ───────────────────────────────────
$idVer = (int)($_GET['ver'] ?? 0);
$detalle = null;
$evals   = [];

if ($idVer) {
    $stD = $db->prepare("
        SELECT pr.id_practica, pr.estado, pr.nota_final,
               pr.nota_tutor_academico, pr.nota_tutor_empresa,
               pr.nota_bitacoras, pr.nota_informe,
               CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
               u.cedula, c.nombre AS carrera,
               per.nombre AS periodo,
               COALESCE(em.razon_social, pr.emp_nueva_nombre) AS empresa,
               pr.area_practica
        FROM practicas pr
        JOIN estudiantes e   ON e.id_estudiante = pr.id_estudiante
        JOIN usuarios u      ON u.id_usuario    = e.id_usuario
        JOIN carreras c      ON c.id_carrera    = e.id_carrera
        JOIN periodos_academicos per ON per.id_periodo = pr.id_periodo
        LEFT JOIN empresas em ON em.id_empresa  = pr.id_empresa
        WHERE pr.id_practica = :ip LIMIT 1
    ");
    $stD->execute([':ip' => $idVer]);
    $detalle = $stD->fetch();

    if ($detalle) {
        $stE = $db->prepare("SELECT * FROM evaluaciones_satisfaccion WHERE id_practica = :ip ORDER BY tipo_evaluador");
        $stE->execute([':ip' => $idVer]);
        foreach ($stE->fetchAll() as $ev) {
            $evals[$ev['tipo_evaluador']] = $ev;
        }
    }
}

// ── Filtros ──────────────────────────────────────────────────
$filtro    = $_GET['filtro']   ?? '';
$filPer    = (int)($_GET['periodo']  ?? 0);
$filCar    = (int)($_GET['carrera']  ?? 0);
$perPage   = in_array((int)($_GET['pp'] ?? 25), [10,25,100,200]) ? (int)($_GET['pp'] ?? 25) : 25;
$page      = max(1, (int)($_GET['page'] ?? 1));
$offset    = ($page - 1) * $perPage;

$where  = match($filtro) {
    'completo'   => "AND (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica) >= 3",
    'incompleto' => "AND (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica) < 3",
    default      => ""
};
if ($filPer) $where .= " AND pr.id_periodo = $filPer";
if ($filCar) $where .= " AND c.id_carrera  = $filCar";

// Total para paginación
$stTotal = $db->query("
    SELECT COUNT(*) FROM practicas pr
    JOIN estudiantes e   ON e.id_estudiante = pr.id_estudiante
    JOIN usuarios u      ON u.id_usuario    = e.id_usuario
    JOIN carreras c      ON c.id_carrera    = e.id_carrera
    JOIN periodos_academicos per ON per.id_periodo = pr.id_periodo
    LEFT JOIN empresas em ON em.id_empresa  = pr.id_empresa
    WHERE pr.estado NOT IN ('borrador','rechazado') $where {$iCond}
");
$totalRows = (int)$stTotal->fetchColumn();
$totalPages = $perPage > 0 && $totalRows > 0 ? max(1, (int)ceil($totalRows / $perPage)) : 1;

$stList = $db->query("
    SELECT pr.id_practica, pr.estado, pr.nota_final,
           CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
           u.cedula,
           c.nombre AS carrera,
           COALESCE(em.razon_social, pr.emp_nueva_nombre) AS empresa,
           per.nombre AS periodo,
           (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica) AS total_evals,
           (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica AND tipo_evaluador='estudiante')     AS eval_est,
           (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica AND tipo_evaluador='tutor_academico') AS eval_tut_ac,
           (SELECT COUNT(*) FROM evaluaciones_satisfaccion ev WHERE ev.id_practica=pr.id_practica AND tipo_evaluador='tutor_empresa')   AS eval_tut_em
    FROM practicas pr
    JOIN estudiantes e   ON e.id_estudiante = pr.id_estudiante
    JOIN usuarios u      ON u.id_usuario    = e.id_usuario
    JOIN carreras c      ON c.id_carrera    = e.id_carrera
    JOIN periodos_academicos per ON per.id_periodo = pr.id_periodo
    LEFT JOIN empresas em ON em.id_empresa  = pr.id_empresa
    WHERE pr.estado NOT IN ('borrador','rechazado') $where {$iCond}
    ORDER BY pr.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$practicas = $stList->fetchAll();

// Períodos y carreras para los filtros
$periodos = $db->query("SELECT id_periodo, nombre FROM periodos_academicos " . ($idInst ? "WHERE id_instituto=$idInst" : "") . " ORDER BY fecha_inicio DESC")->fetchAll();
$carreras  = $db->query("SELECT id_carrera, nombre FROM carreras " . ($idInst ? "WHERE id_instituto=$idInst AND activa=1" : "WHERE activa=1") . " ORDER BY nombre")->fetchAll();

// Stats
$stStats = $db->query("
    SELECT
        COUNT(DISTINCT id_practica) AS total,
        SUM(CASE WHEN (SELECT COUNT(*) FROM evaluaciones_satisfaccion e2 WHERE e2.id_practica=ev.id_practica)>=3 THEN 1 ELSE 0 END) AS completas
    FROM practicas ev
    WHERE estado NOT IN ('borrador','rechazado')" . ($idInst ? " AND id_instituto = $idInst" : '') . "
");
$stats = $stStats->fetch() ?: ['total'=>0,'completas'=>0];

// Helper: promedio de una evaluación
function promedioEval(?array $ev): ?float {
    if (!$ev) return null;
    return round(($ev['p1_satisfaccion'] + $ev['p2_aprendizaje'] + $ev['p3_infraestructura'] + $ev['p4_tutoria']) / 4, 1);
}

function barEstrellas(int $val): string {
    $out = '';
    for ($i = 1; $i <= 5; $i++) {
        $out .= $i <= $val
            ? '<span style="color:#ffb74d;font-size:15px;">★</span>'
            : '<span style="color:#d0d0d0;font-size:15px;">★</span>';
    }
    return $out;
}
?>
<?php $paginaActual = 'evaluaciones'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar.css">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-coordinador.css">
<style>
/* Stats */
.ev-stat { background:#ffffff; border:1px solid #e2e8f0; border-radius:10px; padding:14px 18px; text-align:center; }
.ev-stat .num { font-size:26px; font-weight:700; }
.ev-stat .lbl { font-size:11px; color:#64748b; margin-top:3px; }

/* Tabla */
.tbl-ev { width:100%; border-collapse:collapse; font-size:13px; }
.tbl-ev th { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px;
  color:#475569; border-bottom:2px solid #e8edf5; padding:8px 10px; text-align:left; background:#f8fafc; }
.tbl-ev td { padding:10px; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
.tbl-ev tr:hover td { background:#f8fafc; }

/* Chips */
.chip { font-size:10px; font-weight:700; padding:2px 9px; border-radius:20px;
  text-transform:uppercase; letter-spacing:.4px; white-space:nowrap; }
.chip-ok   { background:#dcfce7; color:#16a34a; border:1px solid #86efac; }
.chip-pend { background:#fef9c3; color:#ca8a04; border:1px solid #fde047; }
.chip-no   { background:#fee2e2; color:#dc2626; border:1px solid #fca5a5; }

/* Íconos check/cross */
.ic-ok  { color:#16a34a; font-size:14px; }
.ic-no  { color:#dc2626; font-size:14px; }
.ic-pend{ color:#ca8a04; font-size:14px; }

/* Panel de detalle */
.det-panel { background:#ffffff; border:1px solid #e2e8f0; border-radius:12px; padding:20px 24px; margin-bottom:16px; }
.det-section { font-size:10px; font-weight:700; color:#64748b; text-transform:uppercase;
  letter-spacing:.7px; border-bottom:1px solid #f1f5f9; padding-bottom:6px; margin:18px 0 14px; }

/* Tarjeta de evaluación por actor */
.eval-actor-card { border:1px solid #e2e8f0; border-radius:10px; overflow:hidden; margin-bottom:12px; }
.eval-actor-head { display:flex; align-items:center; justify-content:space-between;
  padding:12px 16px; background:#f1f5f9; border-bottom:1px solid #e2e8f0; }
.eval-actor-body { padding:16px; }
.eval-row { display:flex; align-items:center; justify-content:space-between;
  padding:8px 0; border-bottom:1px solid #f1f5f9; font-size:13px; }
.eval-row:last-child { border-bottom:none; }
.eval-row-lbl { color:#64748b; flex:1; }
.eval-row-val { display:flex; align-items:center; gap:8px; }
.promedio-big { font-size:22px; font-weight:700; }

/* Notas de práctica */
.nota-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:10px; }
.nota-item { background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:10px 14px; }
.nota-item .val { font-size:20px; font-weight:700; color:#2ea8ff; }
.nota-item .lbl { font-size:11px; color:#64748b; margin-top:2px; }

/* Botones */
.btn-ver { padding:5px 12px; border-radius:7px; font-size:11px; font-weight:600;
  background:#2ea8ff18; color:#2ea8ff; border:1px solid #2ea8ff40; text-decoration:none;
  display:inline-flex; align-items:center; gap:5px; }
.btn-ver:hover { background:#2ea8ff28; color:#2ea8ff; }
</style>
</head>

<body>
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'navbar.php'; ?>
<div class="app-shell">
  <?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'sidebar-coordinador.php'; ?>

  <main class="main-area">
    <?= flashHtml() ?>

    <?php if ($idVer && $detalle): ?>
    <!-- ══════════════════════════════════════════════════════
         DETALLE DE EVALUACIONES DE UNA PRÁCTICA
    ══════════════════════════════════════════════════════ -->
    <div class="mb-3">
      <a href="evaluaciones.php" style="font-size:12px;color:#8b949e;text-decoration:none;">
        <i class="fa fa-arrow-left me-1"></i> Volver a Evaluaciones
      </a>
    </div>

    <!-- Cabecera -->
    <div class="det-panel mb-4">
      <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
        <div>
          <div style="font-size:18px;font-weight:700;color:#0f172a;"><?= htmlspecialchars($detalle['estudiante']) ?></div>
          <div style="font-size:12px;color:#8b949e;margin-top:4px;">
            CI: <?= htmlspecialchars($detalle['cedula']) ?> &nbsp;·&nbsp;
            <?= htmlspecialchars($detalle['carrera']) ?> &nbsp;·&nbsp;
            <?= htmlspecialchars($detalle['periodo']) ?>
          </div>
          <div style="font-size:12px;color:#8b949e;margin-top:2px;">
            Empresa: <?= htmlspecialchars($detalle['empresa'] ?? '—') ?>
            <?php if ($detalle['area_practica']): ?> &nbsp;·&nbsp; <?= htmlspecialchars($detalle['area_practica']) ?><?php endif; ?>
          </div>
        </div>
        <?php if ($detalle['nota_final'] !== null): ?>
        <div style="text-align:center;">
          <div style="font-size:28px;font-weight:700;color:<?= $detalle['nota_final']>=70?'#16a34a':'#dc2626' ?>;">
            <?= number_format($detalle['nota_final'], 1) ?>
          </div>
          <div style="font-size:10px;color:#64748b;">Nota final</div>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Notas por componente -->
    <?php if ($detalle['nota_tutor_academico'] || $detalle['nota_tutor_empresa'] || $detalle['nota_bitacoras'] || $detalle['nota_informe']): ?>
    <div class="det-section"><i class="fa fa-chart-bar me-2" style="color:#2ea8ff;"></i>Notas por componente</div>
    <div class="nota-grid mb-4">
      <div class="nota-item">
        <div class="val"><?= $detalle['nota_tutor_academico'] !== null ? number_format($detalle['nota_tutor_academico'],1) : '—' ?></div>
        <div class="lbl">Tutor Académico <span style="color:#484f58;">(25%)</span></div>
      </div>
      <div class="nota-item">
        <div class="val"><?= $detalle['nota_tutor_empresa'] !== null ? number_format($detalle['nota_tutor_empresa'],1) : '—' ?></div>
        <div class="lbl">Tutor Empresa <span style="color:#484f58;">(30%)</span></div>
      </div>
      <div class="nota-item">
        <div class="val"><?= $detalle['nota_bitacoras'] !== null ? number_format($detalle['nota_bitacoras'],1) : '—' ?></div>
        <div class="lbl">Bitácoras <span style="color:#484f58;">(20%)</span></div>
      </div>
      <div class="nota-item">
        <div class="val"><?= $detalle['nota_informe'] !== null ? number_format($detalle['nota_informe'],1) : '—' ?></div>
        <div class="lbl">Informe Final <span style="color:#484f58;">(25%)</span></div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Evaluaciones de satisfacción por actor -->
    <div class="det-section"><i class="fa fa-star me-2" style="color:#ffb74d;"></i>Evaluaciones de satisfacción</div>

    <?php
    $actores = [
        'estudiante'     => ['label' => 'Estudiante',        'icon' => 'fa-user-graduate', 'color' => '#2ea8ff'],
        'tutor_academico'=> ['label' => 'Tutor Académico',   'icon' => 'fa-chalkboard-user','color' => '#a78bfa'],
        'tutor_empresa'  => ['label' => 'Tutor Empresa',     'icon' => 'fa-building',       'color' => '#3dffa0'],
    ];
    $preguntas = [
        'p1_satisfaccion'    => 'Satisfacción general',
        'p2_aprendizaje'     => 'Aprendizaje en relación con la carrera',
        'p3_infraestructura' => 'Infraestructura y ambiente de trabajo',
        'p4_tutoria'         => 'Calidad de la tutoría académica',
    ];
    foreach ($actores as $tipo => $actor):
        $ev = $evals[$tipo] ?? null;
        $prom = promedioEval($ev);
    ?>
    <div class="eval-actor-card">
      <div class="eval-actor-head">
        <div style="display:flex;align-items:center;gap:10px;">
          <i class="fa <?= $actor['icon'] ?>" style="color:<?= $actor['color'] ?>;font-size:16px;"></i>
          <span style="font-weight:600;font-size:14px;color:#0f172a;"><?= $actor['label'] ?></span>
        </div>
        <?php if ($ev): ?>
        <div style="display:flex;align-items:center;gap:10px;">
          <span class="promedio-big" style="color:<?= $prom>=4?'#16a34a':($prom>=3?'#d97706':'#dc2626') ?>;"><?= $prom ?></span>
          <span style="font-size:11px;color:#64748b;">/ 5</span>
          <span class="chip chip-ok">Completada</span>
        </div>
        <?php else: ?>
        <span class="chip chip-pend">Pendiente</span>
        <?php endif; ?>
      </div>

      <?php if ($ev): ?>
      <div class="eval-actor-body">
        <?php foreach ($preguntas as $campo => $lbl): ?>
        <div class="eval-row">
          <div class="eval-row-lbl"><?= $lbl ?></div>
          <div class="eval-row-val">
            <?= barEstrellas((int)$ev[$campo]) ?>
            <span style="font-size:13px;font-weight:600;color:#0f172a;min-width:16px;"><?= $ev[$campo] ?></span>
          </div>
        </div>
        <?php endforeach; ?>
        <div class="eval-row">
          <div class="eval-row-lbl">¿Recomienda la empresa?</div>
          <div class="eval-row-val">
            <?php if ($ev['p5_recomendaria']): ?>
              <i class="fa fa-thumbs-up ic-ok"></i>
              <span style="font-size:12px;color:#3dffa0;">Sí la recomienda</span>
            <?php else: ?>
              <i class="fa fa-thumbs-down ic-no"></i>
              <span style="font-size:12px;color:#dc2626;">No la recomienda</span>
            <?php endif; ?>
          </div>
        </div>
        <?php if ($ev['comentarios']): ?>
        <div style="background:#f1f5f9;border-radius:7px;padding:10px 12px;margin-top:10px;font-size:12px;color:#64748b;">
          <i class="fa fa-comment me-2" style="color:#2ea8ff;"></i>
          <?= htmlspecialchars($ev['comentarios']) ?>
        </div>
        <?php endif; ?>
        <div style="font-size:11px;color:#94a3b8;margin-top:8px;">
          Registrada el <?= date('d/m/Y H:i', strtotime($ev['created_at'])) ?>
        </div>
      </div>
      <?php else: ?>
      <div style="padding:14px 16px;font-size:12px;color:#64748b;">
        <i class="fa fa-hourglass-half me-2"></i>Este actor aún no ha completado su evaluación.
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>

    <?php else: ?>
    <!-- ══════════════════════════════════════════════════════
         LISTADO GENERAL
    ══════════════════════════════════════════════════════ -->

    <!-- Stats -->
    <div class="row g-3 mb-4">
      <div class="col-6 col-md-3">
        <div class="ev-stat">
          <div class="num" style="color:#2ea8ff;"><?= $stats['total'] ?></div>
          <div class="lbl">Prácticas activas</div>
        </div>
      </div>
      <div class="col-6 col-md-3">
        <div class="ev-stat">
          <div class="num" style="color:#3dffa0;"><?= $stats['completas'] ?></div>
          <div class="lbl">Evaluaciones completas</div>
        </div>
      </div>
      <div class="col-6 col-md-3">
        <div class="ev-stat">
          <div class="num" style="color:#e5a50a;"><?= $stats['total'] - $stats['completas'] ?></div>
          <div class="lbl">Pendientes</div>
        </div>
      </div>
      <div class="col-6 col-md-3">
        <div class="ev-stat">
          <div class="num" style="color:#a78bfa;"><?= $stats['total'] > 0 ? round(($stats['completas']/$stats['total'])*100) : 0 ?>%</div>
          <div class="lbl">Cobertura</div>
        </div>
      </div>
    </div>

    <!-- Filtros -->
    <div class="d-flex gap-2 mb-3 flex-wrap align-items-center"
         style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:12px 16px;">

      <!-- Estado -->
      <div class="d-flex gap-1">
        <?php foreach (['' => 'Todas', 'completo' => 'Completas', 'incompleto' => 'Pendientes'] as $f => $lbl): ?>
        <a href="?filtro=<?= $f ?>&periodo=<?= $filPer ?>&carrera=<?= $filCar ?>&pp=<?= $perPage ?>"
           class="btn btn-sm <?= $filtro === $f ? 'btn-primary' : 'btn-outline-secondary' ?>"
           style="font-size:12px;">
          <?= $lbl ?>
        </a>
        <?php endforeach; ?>
      </div>

      <div class="vr d-none d-md-block" style="height:28px;margin:0 4px;"></div>

      <!-- Período -->
      <select onchange="applyFilter()" id="selPer"
              style="font-size:12px;padding:5px 10px;border:1px solid #cbd5e1;border-radius:7px;color:#475569;background:#fff;">
        <option value="0">— Todos los períodos —</option>
        <?php foreach ($periodos as $per): ?>
        <option value="<?= $per['id_periodo'] ?>" <?= $filPer==$per['id_periodo']?'selected':'' ?>>
          <?= htmlspecialchars($per['nombre']) ?>
        </option>
        <?php endforeach; ?>
      </select>

      <!-- Carrera -->
      <select onchange="applyFilter()" id="selCar"
              style="font-size:12px;padding:5px 10px;border:1px solid #cbd5e1;border-radius:7px;color:#475569;background:#fff;">
        <option value="0">— Todas las carreras —</option>
        <?php foreach ($carreras as $car): ?>
        <option value="<?= $car['id_carrera'] ?>" <?= $filCar==$car['id_carrera']?'selected':'' ?>>
          <?= htmlspecialchars($car['nombre']) ?>
        </option>
        <?php endforeach; ?>
      </select>

      <!-- Por página -->
      <div class="ms-auto d-flex align-items-center gap-2">
        <span style="font-size:12px;color:#64748b;">Mostrar</span>
        <?php foreach ([10,25,100,200] as $pp): ?>
        <a href="?filtro=<?= $filtro ?>&periodo=<?= $filPer ?>&carrera=<?= $filCar ?>&pp=<?= $pp ?>&page=1"
           class="btn btn-sm <?= $perPage==$pp?'btn-primary':'btn-outline-secondary' ?>"
           style="font-size:12px;min-width:36px;">
          <?= $pp ?>
        </a>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Info resultados -->
    <div style="font-size:12px;color:#64748b;margin-bottom:8px;">
      Mostrando <?= min($offset+1,$totalRows) ?>–<?= min($offset+$perPage,$totalRows) ?> de <?= $totalRows ?> registros
    </div>

    <!-- Tabla -->
    <div style="background:#ffffff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.06);">
      <?php if (empty($practicas)): ?>
      <div style="padding:40px;text-align:center;color:#94a3b8;background:#f8fafc;font-size:13px;">
        <i class="fa fa-star" style="font-size:28px;display:block;margin-bottom:10px;color:#30363d;"></i>
        No hay prácticas con evaluaciones registradas.
      </div>
      <?php else: ?>
      <table class="tbl-ev">
        <thead>
          <tr>
            <th>#</th>
            <th>Estudiante</th>
            <th>Carrera</th>
            <th>Período</th>
            <th style="text-align:center;">Est.</th>
            <th style="text-align:center;">Tut.Ac.</th>
            <th style="text-align:center;">Tut.Emp.</th>
            <th style="text-align:center;">Estado</th>
            <th>Nota</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($practicas as $loop => $p):
          $completa = $p['total_evals'] >= 3;
        ?>
        <tr>
          <td style="font-size:11px;color:#94a3b8;"><?= $offset + ($loop ?? 0) + 1 ?></td>
          <td>
            <div style="font-weight:600;color:#0f172a;"><?= htmlspecialchars($p['estudiante']) ?></div>
            <div style="font-size:11px;color:#64748b;">CI: <?= htmlspecialchars($p['cedula'] ?? '—') ?></div>
          </td>
          <td style="font-size:12px;color:#475569;"><?= htmlspecialchars($p['carrera']) ?></td>
          <td style="font-size:12px;color:#64748b;"><?= htmlspecialchars($p['periodo']) ?></td>
          <td style="text-align:center;">
            <?= $p['eval_est']    ? '<i class="fa fa-circle-check ic-ok"></i>' : '<i class="fa fa-circle-xmark ic-no"></i>' ?>
          </td>
          <td style="text-align:center;">
            <?= $p['eval_tut_ac'] ? '<i class="fa fa-circle-check ic-ok"></i>' : '<i class="fa fa-circle-xmark ic-no"></i>' ?>
          </td>
          <td style="text-align:center;">
            <?= $p['eval_tut_em'] ? '<i class="fa fa-circle-check ic-ok"></i>' : '<i class="fa fa-circle-xmark ic-no"></i>' ?>
          </td>
          <td>
            <span class="chip <?= $completa ? 'chip-ok' : 'chip-pend' ?>">
              <?= $completa ? '✓ Completa' : $p['total_evals'].'/3' ?>
            </span>
          </td>
          <td>
            <?php if ($p['nota_final'] !== null): ?>
            <span style="font-weight:700;color:<?= $p['nota_final']>=70?'#16a34a':'#dc2626' ?>;">
              <?= number_format($p['nota_final'],1) ?>
            </span>
            <?php else: ?>
            <span style="color:#94a3b8;font-size:12px;">Sin calificar</span>
            <?php endif; ?>
          </td>
          <td>
            <a href="?ver=<?= $p['id_practica'] ?>" class="btn-ver">
              <i class="fa fa-eye"></i> Ver
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>

    <!-- Paginación -->
    <?php if ($totalPages > 1): ?>
    <div class="d-flex justify-content-center align-items-center gap-1 mt-3 flex-wrap">
      <?php if ($page > 1): ?>
      <a href="?filtro=<?=$filtro?>&periodo=<?=$filPer?>&carrera=<?=$filCar?>&pp=<?=$perPage?>&page=<?=$page-1?>"
         class="btn btn-sm btn-outline-secondary" style="font-size:12px;">
        <i class="fa fa-chevron-left"></i>
      </a>
      <?php endif; ?>
      <?php for ($pg = max(1,$page-2); $pg <= min($totalPages,$page+2); $pg++): ?>
      <a href="?filtro=<?=$filtro?>&periodo=<?=$filPer?>&carrera=<?=$filCar?>&pp=<?=$perPage?>&page=<?=$pg?>"
         class="btn btn-sm <?= $pg==$page?'btn-primary':'btn-outline-secondary' ?>" style="font-size:12px;min-width:36px;">
        <?= $pg ?>
      </a>
      <?php endfor; ?>
      <?php if ($page < $totalPages): ?>
      <a href="?filtro=<?=$filtro?>&periodo=<?=$filPer?>&carrera=<?=$filCar?>&pp=<?=$perPage?>&page=<?=$page+1?>"
         class="btn btn-sm btn-outline-secondary" style="font-size:12px;">
        <i class="fa fa-chevron-right"></i>
      </a>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php endif; ?>
  </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>
function applyFilter() {
    var filtro  = '<?= $filtro ?>';
    var pp      = '<?= $perPage ?>';
    var periodo = document.getElementById('selPer').value;
    var carrera = document.getElementById('selCar').value;
    window.location.href = '?filtro=' + filtro + '&periodo=' + periodo + '&carrera=' + carrera + '&pp=' + pp + '&page=1';
}
</script>
</body>
</html>