<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/functions.php';
requireRol(ROL_SECRETARIA);
$idInst = instId();

$db        = getDB();
$user      = currentUser();
$pageTitle = 'Mediciones — Notas y Calificaciones';

// ── AJAX: guardar nota_trabajo del complexivo ──────────────
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['action'] ?? '') === 'guardar_nota_complexivo') {
    header('Content-Type: application/json; charset=utf-8');
    $idTit = (int)($_POST['id_titulacion'] ?? 0);
    $nota  = $_POST['nota'] === '' ? null : (float)$_POST['nota'];

    // Validaciones
    if (!$idTit) { echo json_encode(['ok'=>false,'msg'=>'ID inválido']); exit; }
    if ($nota !== null && ($nota < 0 || $nota > 100)) {
        echo json_encode(['ok'=>false,'msg'=>'La nota debe estar entre 0 y 100']); exit;
    }

    try {
        // Verificar que la titulación pertenece al instituto (seguridad multi-tenant)
        $chk = $db->prepare("SELECT id_titulacion FROM titulaciones WHERE id_titulacion=:id" . ($idInst ? " AND id_instituto=:inst" : ""));
        $chk->bindValue(':id', $idTit);
        if ($idInst) $chk->bindValue(':inst', $idInst);
        $chk->execute();
        if (!$chk->fetch()) { echo json_encode(['ok'=>false,'msg'=>'Registro no encontrado']); exit; }

        $st = $db->prepare("UPDATE titulaciones SET nota_trabajo=:nota, updated_at=NOW() WHERE id_titulacion=:id");
        $st->bindValue(':nota', $nota, $nota === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
        $st->bindValue(':id', $idTit);
        $st->execute();
        echo json_encode(['ok'=>true,'nota'=>$nota]);
    } catch (Exception $ex) {
        echo json_encode(['ok'=>false,'msg'=>'Error BD: '.$ex->getMessage()]);
    }
    exit;
}

// ── Filtros ────────────────────────────────────────────────
$modulo = $_GET['modulo'] ?? 'practicas';   // practicas | vinculacion | tit_complexivo | tit_investigacion
$idPer  = (int)($_GET['periodo'] ?? 0);
$idCar  = (int)($_GET['carrera'] ?? 0);
$buscar = trim($_GET['q'] ?? '');
$export = $_GET['export'] ?? '';

$periodos = $db->query("SELECT id_periodo, nombre, activo FROM periodos_academicos WHERE 1=1" . instCond() . " ORDER BY id_periodo DESC")->fetchAll();
$carreras = $db->query("SELECT id_carrera,nombre FROM carreras WHERE 1=1" . instCond() . " AND activa=1 ORDER BY nombre")->fetchAll();

// Período activo por defecto — solo si no viene explícito en la URL
if (!$idPer && !isset($_GET['periodo'])) {
    $pa = $db->query("SELECT id_periodo FROM periodos_academicos WHERE activo=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " LIMIT 1")->fetch();
    $idPer = $pa ? (int)$pa['id_periodo'] : ($periodos[0]['id_periodo'] ?? 0);
} elseif (!$idPer) {
    $pa = $db->query("SELECT id_periodo FROM periodos_academicos WHERE activo=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " LIMIT 1")->fetch();
    $idPer = $pa ? (int)$pa['id_periodo'] : ($periodos[0]['id_periodo'] ?? 0);
}

// Nombres para indicador
$idPerActivo = 0;
foreach ($periodos as $p) { if ($p['activo']) { $idPerActivo = $p['id_periodo']; break; } }
$perNom = ''; foreach ($periodos as $p) { if ($p['id_periodo']==$idPer) { $perNom=$p['nombre']; break; } }
$carNom = ''; foreach ($carreras as $c) { if ($c['id_carrera']==$idCar) { $carNom=$c['nombre']; break; } }

// ════════════════════════════════════════════════════════════
//  DATOS: PRÁCTICAS PPP
// ════════════════════════════════════════════════════════════
$datosPract = [];
$statsPract  = ['total'=>0,'aprobados'=>0,'reprobados'=>0,'sin_nota'=>0,'prom_nota'=>null];

if ($modulo === 'practicas') {
    $where  = ['1=1'];
    $params = [];
    if ($idInst) { $where[] = 'c.id_instituto = :inst'; $params[':inst'] = $idInst; }
    if ($idPer) { $where[] = 'p.id_periodo=:per'; $params[':per'] = $idPer; }
    if ($idCar) { $where[] = 'c.id_carrera=:car';  $params[':car'] = $idCar; }
    if ($buscar){ $where[] = "(u.nombres LIKE :q OR u.apellidos LIKE :q OR u.cedula LIKE :q OR e.codigo_estudiante LIKE :q)";
                  $params[':q'] = '%'.$buscar.'%'; }
    $wStr = implode(' AND ', $where);

    $st = $db->prepare("
        SELECT CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
               u.cedula, e.codigo_estudiante,
               c.nombre AS carrera,
               COALESCE(em.razon_social, p.emp_nueva_nombre, '—') AS empresa,
               pa.nombre AS periodo,
               p.id_practica, p.estado, p.modalidad,
               p.horas_requeridas, p.horas_cumplidas,
               p.nota_tutor_academico   AS n1,
               p.nota_tutor_empresa     AS n2,
               p.nota_bitacoras         AS n3,
               p.nota_informe           AS n4,
               p.nota_final,
               p.observaciones_gestor,
               CONCAT(ut.apellidos,' ',ut.nombres) AS tutor,
               p.updated_at
        FROM practicas p
        JOIN estudiantes e   ON e.id_estudiante  = p.id_estudiante
        JOIN usuarios u      ON u.id_usuario     = e.id_usuario
        JOIN carreras c      ON c.id_carrera     = e.id_carrera
        LEFT JOIN empresas em ON em.id_empresa   = p.id_empresa
        JOIN periodos_academicos pa ON pa.id_periodo = p.id_periodo
        LEFT JOIN tutores t  ON t.id_tutor       = p.id_tutor
        LEFT JOIN usuarios ut ON ut.id_usuario   = t.id_usuario
        WHERE $wStr
        ORDER BY u.apellidos, u.nombres
    ");
    $st->execute($params);
    $datosPract = $st->fetchAll();

    // Stats
    $statsPract['total'] = count($datosPract);
    $notas = [];
    foreach ($datosPract as $r) {
        if ($r['nota_final'] !== null) {
            $notas[] = (float)$r['nota_final'];
            if ((float)$r['nota_final'] >= 7) $statsPract['aprobados']++;
            else $statsPract['reprobados']++;
        } else {
            $statsPract['sin_nota']++;
        }
    }
    $statsPract['prom_nota'] = count($notas) ? round(array_sum($notas)/count($notas),2) : null;

    // CSV export
    if ($export === 'csv' && !empty($datosPract)) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="mediciones_practicas_'.date('Ymd_His').'.csv"');
        $out = fopen('php://output','w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out,['Estudiante','Cédula','Código','Carrera','Empresa','Período',
                      'Hs.Req.','Hs.Cum.',
                      'N1-TutorAcad(25%)','N2-TutorEmp(30%)',
                      'N3-Bitácoras(20%)','N4-Informe(25%)',
                      'Nota Final /100','Estado','Tutor','Obs. Gestor'],';');
        foreach ($datosPract as $r) {
            $nf = $r['nota_final'];
            $est = $nf !== null ? ($nf >= 70 ? 'APROBADO' : 'REPROBADO') : 'SIN NOTA';
            fputcsv($out,[$r['estudiante'],$r['cedula'],$r['codigo_estudiante'],
                          $r['carrera'],$r['empresa'],$r['periodo'],
                          $r['horas_requeridas'],$r['horas_cumplidas'],
                          $r['n1']??'',$r['n2']??'',$r['n3']??'',$r['n4']??'',
                          $nf??'',$est,$r['tutor']??'',$r['observaciones_gestor']??''],';');
        }
        fclose($out); exit;
    }
}

// ════════════════════════════════════════════════════════════
//  DATOS: VINCULACIÓN
// ════════════════════════════════════════════════════════════
$datosVinc = [];
$statsVinc  = ['total'=>0,'aprobados'=>0,'reprobados'=>0,'sin_nota'=>0,'prom_nota'=>null];

if ($modulo === 'vinculacion') {
    $where  = ['1=1'];
    $params = [];
    if ($idInst) { $where[] = 'c.id_instituto = :inst'; $params[':inst'] = $idInst; }
    if ($idInst) { $where[] = 'c.id_instituto = :inst'; $params[':inst'] = $idInst; }
    if ($idPer) { $where[] = 'g.id_periodo=:per'; $params[':per'] = $idPer; }
    if ($idCar) { $where[] = 'c.id_carrera=:car';  $params[':car'] = $idCar; }
    if ($buscar){ $where[] = "(u.nombres LIKE :q OR u.apellidos LIKE :q OR u.cedula LIKE :q OR e.codigo_estudiante LIKE :q)";
                  $params[':q'] = '%'.$buscar.'%'; }
    $wStr = implode(' AND ', $where);

    try {
        $st = $db->prepare("
            SELECT CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
                   u.cedula, e.codigo_estudiante,
                   c.nombre AS carrera,
                   COALESCE(ob.nombre,g.org_nueva_nombre) AS organizacion,
                   pa.nombre AS periodo,
                   g.id_grupo, g.nombre_proyecto, g.estado AS estado_grupo,
                   m.rol,
                   cv.nota_informe_pdf     AS n1,
                   cv.nota_trabajo_individual AS n2,
                   cv.nota_promedio        AS nota_final,
                   cv.estado               AS estado_calif,
                   CONCAT(ut.apellidos,' ',ut.nombres) AS tutor
            FROM miembros_grupo_vinculacion m
            JOIN grupos_vinculacion g        ON g.id_grupo       = m.id_grupo
            JOIN periodos_academicos pa      ON pa.id_periodo    = g.id_periodo
            LEFT JOIN organizaciones_beneficiarias ob ON ob.id_organizacion = g.id_organizacion
            JOIN estudiantes e               ON e.id_estudiante  = m.id_estudiante
            JOIN usuarios u                  ON u.id_usuario     = e.id_usuario
            JOIN carreras c                  ON c.id_carrera     = e.id_carrera
            LEFT JOIN calificaciones_vinculacion cv ON cv.id_grupo=g.id_grupo AND cv.id_estudiante=m.id_estudiante
            LEFT JOIN tutores t              ON t.id_tutor       = g.id_tutor
            LEFT JOIN usuarios ut            ON ut.id_usuario    = t.id_usuario
            WHERE m.estado='activo' AND $wStr
            ORDER BY u.apellidos, u.nombres
        ");
        $st->execute($params);
        $datosVinc = $st->fetchAll();
    } catch (Exception $ex) { $datosVinc = []; }

    // Stats
    $statsVinc['total'] = count($datosVinc);
    $notas = [];
    foreach ($datosVinc as $r) {
        if ($r['nota_final'] !== null) {
            $notas[] = (float)$r['nota_final'];
            if ((float)$r['nota_final'] >= 70) $statsVinc['aprobados']++;
            else $statsVinc['reprobados']++;
        } else {
            $statsVinc['sin_nota']++;
        }
    }
    $statsVinc['prom_nota'] = count($notas) ? round(array_sum($notas)/count($notas),2) : null;

    // CSV export
    if ($export === 'csv' && !empty($datosVinc)) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="mediciones_vinculacion_'.date('Ymd_His').'.csv"');
        $out = fopen('php://output','w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out,['Estudiante','Cédula','Código','Carrera','Organización','Período',
                      'Proyecto','Rol','N1-Informe','N2-Trabajo','Promedio','Estado','Tutor'],';');
        foreach ($datosVinc as $r) {
            $nf  = $r['nota_final'];
            $est = $nf !== null ? ($nf >= 70 ? 'APROBADO' : 'REPROBADO') : 'SIN NOTA';
            fputcsv($out,[$r['estudiante'],$r['cedula'],$r['codigo_estudiante'],
                          $r['carrera'],$r['organizacion'],$r['periodo'],
                          $r['nombre_proyecto'],strtoupper($r['rol']),
                          $r['n1']??'',$r['n2']??'',$nf??'',$est,$r['tutor']??''],';');
        }
        fclose($out); exit;
    }
}

// ════════════════════════════════════════════════════════════
//  DATOS: TITULACIÓN — EXAMEN COMPLEXIVO
// ════════════════════════════════════════════════════════════
$datosCompl = [];
$statsCompl = ['total'=>0,'aprobados'=>0,'en_proceso'=>0,'rechazados'=>0,'pendientes'=>0];

if ($modulo === 'tit_complexivo') {
    $where  = ["t.modalidad = 'examen_complexivo'"];
    $params = [];
    if ($idInst) { $where[] = 't.id_instituto = :inst'; $params[':inst'] = $idInst; }
    if ($idCar)  { $where[] = 'est.id_carrera = :car';  $params[':car']  = $idCar; }
    if ($buscar) { $where[] = "(u.nombres LIKE :q OR u.apellidos LIKE :q OR u.cedula LIKE :q)";
                   $params[':q'] = '%'.$buscar.'%'; }
    $wStr = implode(' AND ', $where);
    try {
        $st = $db->prepare("
            SELECT t.id_titulacion, t.estado, t.fecha_envio, t.fecha_habilitacion,
                   t.nota_trabajo,
                   CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
                   u.cedula, est.codigo_estudiante,
                   car.nombre AS carrera
            FROM titulaciones t
            JOIN estudiantes est ON est.id_estudiante = t.id_estudiante
            JOIN usuarios u      ON u.id_usuario      = est.id_usuario
            JOIN carreras car    ON car.id_carrera     = est.id_carrera
            WHERE $wStr
            ORDER BY car.nombre, u.apellidos, u.nombres
        ");
        $st->execute($params);
        $datosCompl = $st->fetchAll();
    } catch (Exception $ex) { $datosCompl = []; }

    $statsCompl['total'] = count($datosCompl);
    foreach ($datosCompl as $r) {
        if ($r['estado'] === 'aprobado')  $statsCompl['aprobados']++;
        elseif ($r['estado'] === 'enviada')  $statsCompl['en_proceso']++;
        elseif ($r['estado'] === 'rechazado') $statsCompl['rechazados']++;
        else $statsCompl['pendientes']++;
    }
    // CSV
    if ($export === 'csv' && !empty($datosCompl)) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="mediciones_complexivo_'.date('Ymd_His').'.csv"');
        $out = fopen('php://output','w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out,['Estudiante','Cédula','Código','Carrera','Estado','Fecha Envío'],';');
        foreach ($datosCompl as $r) {
            fputcsv($out,[$r['estudiante'],$r['cedula'],$r['codigo_estudiante'],
                          $r['carrera'],strtoupper($r['estado']),$r['fecha_envio']??''],';');
        }
        fclose($out); exit;
    }
}

// ════════════════════════════════════════════════════════════
//  DATOS: TITULACIÓN — TRABAJO DE INVESTIGACIÓN
// ════════════════════════════════════════════════════════════
$datosInvest = [];
$statsInvest = ['total'=>0,'aprobados'=>0,'en_proceso'=>0,'rechazados'=>0,'sin_nota'=>0,'prom_nota'=>null];

if ($modulo === 'tit_investigacion') {
    $where  = ["t.modalidad = 'trabajo_investigacion'"];
    $params = [];
    if ($idInst) { $where[] = 't.id_instituto = :inst'; $params[':inst'] = $idInst; }
    if ($idCar)  { $where[] = 'est.id_carrera = :car';  $params[':car']  = $idCar; }
    if ($buscar) { $where[] = "(u.nombres LIKE :q OR u.apellidos LIKE :q OR u.cedula LIKE :q)";
                   $params[':q'] = '%'.$buscar.'%'; }
    $wStr = implode(' AND ', $where);
    try {
        $st = $db->prepare("
            SELECT t.id_titulacion, t.estado, t.tema,
                   t.nota_trabajo,
                   t.nota_director, t.nota_lector, t.nota_tribunal,
                   t.nota_final, t.nota_global,
                   CONCAT(u.apellidos,' ',u.nombres)   AS estudiante,
                   u.cedula, est.codigo_estudiante,
                   car.nombre                          AS carrera,
                   CONCAT(ut.apellidos,' ',ut.nombres) AS tutor_nombre,
                   CONCAT(ud.apellidos,' ',ud.nombres) AS director_nombre
            FROM titulaciones t
            JOIN estudiantes est ON est.id_estudiante = t.id_estudiante
            JOIN usuarios u      ON u.id_usuario      = est.id_usuario
            JOIN carreras car    ON car.id_carrera     = est.id_carrera
            LEFT JOIN tutores tut ON tut.id_tutor      = t.id_tutor
            LEFT JOIN usuarios ut ON ut.id_usuario     = tut.id_usuario
            LEFT JOIN tutores td  ON td.id_tutor       = t.id_director
            LEFT JOIN usuarios ud ON ud.id_usuario     = td.id_usuario
            WHERE $wStr
            ORDER BY car.nombre, u.apellidos, u.nombres
        ");
        $st->execute($params);
        $datosInvest = $st->fetchAll();
    } catch (Exception $ex) { $datosInvest = []; }

    $statsInvest['total'] = count($datosInvest);
    $notas = [];
    foreach ($datosInvest as $r) {
        if ($r['estado'] === 'aprobado') $statsInvest['aprobados']++;
        elseif ($r['estado'] === 'enviada') $statsInvest['en_proceso']++;
        elseif ($r['estado'] === 'rechazado') $statsInvest['rechazados']++;
        if ($r['nota_global'] !== null) $notas[] = (float)$r['nota_global'];
        else $statsInvest['sin_nota']++;
    }
    $statsInvest['prom_nota'] = count($notas) ? round(array_sum($notas)/count($notas),2) : null;

    // CSV
    if ($export === 'csv' && !empty($datosInvest)) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="mediciones_investigacion_'.date('Ymd_His').'.csv"');
        $out = fopen('php://output','w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out,['Estudiante','Cédula','Código','Carrera','Tema','Estado',
                      'N.Trabajo(10)','N.Director(100)','N.Lector(100)','N.Tribunal(100)','Nota Global(100)','Tutor','Director'],';');
        foreach ($datosInvest as $r) {
            fputcsv($out,[$r['estudiante'],$r['cedula'],$r['codigo_estudiante'],
                          $r['carrera'],$r['tema']??'',strtoupper($r['estado']),
                          $r['nota_trabajo']??'',$r['nota_director']??'',$r['nota_lector']??'',
                          $r['nota_tribunal']??'',$r['nota_global']??'',
                          $r['tutor_nombre']??'',$r['director_nombre']??''],';');
        }
        fclose($out); exit;
    }
}

// ── KPIs globales rápidos (sidebar badge) ──────────────────
$totalSinNota = 0;
try {
    $totalSinNota = (int)$db->query("
        SELECT COUNT(*) FROM practicas
        WHERE estado IN ('completado','calificado') AND nota_final IS NULL
    ")->fetchColumn();
} catch (Exception $ex) {}
?>
<?php $paginaActual = 'mediciones'; ?>
<!DOCTYPE html><html lang="es"><head>
<?php include __DIR__.'/../../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar.css">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-secretaria.css">
<style>
/* ── Módulo tabs ─────────────────── */
.mod-tabs{display:flex;gap:0;border-bottom:2px solid #e2e8f0;margin-bottom:24px}
.mod-tab{padding:10px 24px;font-size:13px;font-weight:600;color:#64748b;text-decoration:none;border-bottom:3px solid transparent;margin-bottom:-2px;transition:.15s;display:flex;align-items:center;gap:6px}
.mod-tab.active{color:#0f172a;border-bottom-color:#3b82f6}
.mod-tab:hover:not(.active){color:#334155;border-bottom-color:#cbd5e1}
/* ── Stats row ───────────────────── */
.med-stats{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:20px}
.med-stat{flex:1;min-width:110px;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:14px 16px;text-align:center;box-shadow:0 1px 3px rgba(0,0,0,.05)}
.med-stat .n{font-size:26px;font-weight:800;line-height:1}
.med-stat .l{font-size:11px;color:#64748b;margin-top:4px;font-weight:600;text-transform:uppercase;letter-spacing:.5px}
/* ── Table rows ──────────────────── */
.med-tbl{background:#fff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden}
.med-tbl table{font-size:12.5px;margin:0}
.med-tbl th{background:#f8fafc;font-size:10.5px;text-transform:uppercase;color:#64748b;font-weight:700;padding:10px 12px;border-bottom:1px solid #e2e8f0;white-space:nowrap}
.med-tbl td{padding:9px 12px;vertical-align:middle;border-bottom:1px solid #f1f5f9}
.med-tbl tr:last-child td{border-bottom:none}
.med-tbl tr:hover td{background:#f8fafc}
/* ── Note bars ───────────────────── */
.nota-bar{display:flex;align-items:center;gap:6px}
.nota-bar .bar{flex:1;height:5px;background:#e2e8f0;border-radius:4px;overflow:hidden;min-width:36px}
.nota-bar .fill{height:5px;border-radius:4px}
/* ── Badges ──────────────────────── */
.badge-ap{background:#f0fdf4;color:#16a34a;border:1px solid #bbf7d0;font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700;white-space:nowrap}
.badge-rp{background:#fff1f0;color:#ef4444;border:1px solid #fecaca;font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700;white-space:nowrap}
.badge-pend{background:#f8fafc;color:#94a3b8;border:1px solid #e2e8f0;font-size:10px;padding:2px 8px;border-radius:20px;font-weight:600;white-space:nowrap}
/* ── Search box ──────────────────── */
.search-bar{display:flex;gap:10px;flex-wrap:wrap;align-items:center;background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:12px 16px;margin-bottom:16px}
.search-bar input,.search-bar select{font-size:13px;border:1px solid #e2e8f0;border-radius:8px;padding:6px 10px;color:#0f172a;background:#fff}
.search-bar input:focus,.search-bar select:focus{outline:none;border-color:#3b82f6}
/* ── Escala vinc ─────────────────── */
.escala-strip{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px}
.escala-strip span{font-size:10px;padding:2px 9px;border-radius:20px;font-weight:600}
</style>
</head><body>
<?php include __DIR__.'/../../includes/navbar.php'; ?>
<div class="app-shell">
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'sidebar-secretaria.php'; ?>

<main class="main-area">
  <!-- Header -->
  <div class="page-header d-flex justify-content-between align-items-start flex-wrap gap-2">
    <div>
      <h4><i class="fa fa-chart-column me-2" style="color:#3b82f6"></i>Mediciones — Notas y Calificaciones</h4>
      <p>Registro de notas por estudiante · Prácticas PPP · Vinculación · Titulación</p>
    </div>
    <div style="display:flex;gap:6px">
      <span style="font-size:10px;padding:3px 10px;border-radius:20px;font-weight:700;background:#3b82f622;color:#3b82f6;border:1px solid #3b82f644">CES 2022</span>
      <span style="font-size:10px;padding:3px 10px;border-radius:20px;font-weight:700;background:#8b5cf622;color:#8b5cf6;border:1px solid #8b5cf644">CACES</span>
    </div>
  </div>

  <!-- Tabs módulo -->
  <div class="mod-tabs">
    <a href="?modulo=practicas&periodo=<?=$idPer?>&carrera=<?=$idCar?>&q=<?=urlencode($buscar)?>"
       class="mod-tab <?=$modulo==='practicas'?'active':''?>">
      <i class="fa fa-briefcase"></i> Prácticas PPP
    </a>
    <a href="?modulo=vinculacion&periodo=<?=$idPer?>&carrera=<?=$idCar?>&q=<?=urlencode($buscar)?>"
       class="mod-tab <?=$modulo==='vinculacion'?'active':''?>">
      <i class="fa fa-handshake"></i> Vinculación
    </a>
    <!-- Sub-tabs Titulación -->
    <a href="?modulo=tit_complexivo&periodo=<?=$idPer?>&carrera=<?=$idCar?>&q=<?=urlencode($buscar)?>"
       class="mod-tab <?=$modulo==='tit_complexivo'?'active':''?>"
       style="<?=in_array($modulo,['tit_complexivo','tit_investigacion'])?'border-bottom-color:#f59e0b;color:#92400e':''; ?>">
      <i class="fa fa-file-pen" style="color:#8b5cf6"></i> Complexivo
    </a>
    <a href="?modulo=tit_investigacion&periodo=<?=$idPer?>&carrera=<?=$idCar?>&q=<?=urlencode($buscar)?>"
       class="mod-tab <?=$modulo==='tit_investigacion'?'active':''?>"
       style="<?=in_array($modulo,['tit_complexivo','tit_investigacion'])?'border-bottom-color:#f59e0b;color:#92400e':''; ?>">
      <i class="fa fa-microscope" style="color:#ec4899"></i> Investigación
    </a>
  </div>
  <!-- Etiqueta de grupo Titulación -->
  <?php if(in_array($modulo,['tit_complexivo','tit_investigacion'])): ?>
  <div style="font-size:11px;font-weight:700;color:#92400e;background:#fffbeb;border:1px solid #fde68a;
              border-radius:8px;padding:4px 12px;display:inline-flex;align-items:center;gap:6px;margin-bottom:12px;">
    <i class="fa fa-graduation-cap" style="color:#f59e0b;"></i>
    TITULACIÓN —
    <?=$modulo==='tit_complexivo'?'Examen Complexivo':'Trabajo de Investigación'?>
  </div>
  <?php endif; ?>

  <?php
  // ════ Escala activa ════
  $isTit = in_array($modulo, ['tit_complexivo','tit_investigacion']);
  $escalaMax = $modulo==='practicas' ? 10  : 100;
  $escalaMin = $modulo==='practicas' ? 7   : 70;
  $datos = $modulo==='practicas' ? $datosPract
         : ($modulo==='vinculacion' ? $datosVinc
         : ($modulo==='tit_complexivo' ? $datosCompl : $datosInvest));
  $stats = $modulo==='practicas' ? $statsPract
         : ($modulo==='vinculacion' ? $statsVinc
         : ($modulo==='tit_complexivo'
             ? ['total'=>$statsCompl['total'],'aprobados'=>$statsCompl['aprobados'],
                'reprobados'=>$statsCompl['rechazados'],'sin_nota'=>$statsCompl['pendientes']+$statsCompl['en_proceso'],'prom_nota'=>null]
             : ['total'=>$statsInvest['total'],'aprobados'=>$statsInvest['aprobados'],
                'reprobados'=>$statsInvest['rechazados'],'sin_nota'=>$statsInvest['sin_nota'],'prom_nota'=>$statsInvest['prom_nota']]));
  $exportUrl = '?modulo='.$modulo.'&periodo='.$idPer.'&carrera='.$idCar.'&q='.urlencode($buscar).'&export=csv';
  ?>

  <!-- Escala de referencia -->
  <div class="escala-strip">
    <?php if($modulo==='practicas'):?>
    <span style="background:#f0fdf4;color:#16a34a">≥ 90 Excelente</span>
    <span style="background:#f0fdf4;color:#22c55e">80–89 Muy Bueno</span>
    <span style="background:#e0f2fe;color:#0369a1">70–79 Bueno</span>
    <span style="background:#fff1f0;color:#ef4444">< 70 Reprobado</span>
    <span style="background:#fef3c7;color:#d97706">Escala /100 · Mín. aprobatorio: 70 · N1(25%)+N2(30%)+N3(20%)+N4(25%)</span>
    <?php elseif($modulo==='vinculacion'):?>
    <span style="background:#f0fdf4;color:#16a34a">90–100 Excelente</span>
    <span style="background:#f0fdf4;color:#22c55e">80–89 Muy Bueno</span>
    <span style="background:#e0f2fe;color:#0369a1">70–79 Bueno</span>
    <span style="background:#fff1f0;color:#ef4444">0–69 Reprobado</span>
    <span style="background:#fef3c7;color:#d97706">Escala /100 · Mín.: 70 (CACES)</span>
    <?php elseif($modulo==='tit_complexivo'):?>
    <span style="background:#f5f3ff;color:#7c3aed">Pendiente · Esperando · Aprobado · Rechazado</span>
    <span style="background:#fef3c7;color:#d97706">Nota examen /100 · Mín. aprobatorio: 70</span>
    <?php else:?>
    <span style="background:#f0fdf4;color:#16a34a">90–100 Excelente</span>
    <span style="background:#f0fdf4;color:#22c55e">80–89 Muy Bueno</span>
    <span style="background:#e0f2fe;color:#0369a1">70–79 Bueno</span>
    <span style="background:#fff1f0;color:#ef4444">0–69 Reprobado</span>
    <span style="background:#fdf2f8;color:#be185d">Nota Global /100 · Mín. aprobatorio: 70</span>
    <?php endif;?>
  </div>

  <!-- Stats cards -->
  <div class="med-stats">
    <div class="med-stat">
      <div class="n" style="color:#3b82f6"><?=$stats['total']?></div>
      <div class="l">Total registros</div>
    </div>
    <div class="med-stat">
      <div class="n" style="color:#16a34a"><?=$stats['aprobados']?></div>
      <div class="l"><?=$modulo==='tit_complexivo'?'Aprobados':'Aprobados'?></div>
    </div>
    <div class="med-stat">
      <div class="n" style="color:#ef4444"><?=$stats['reprobados']?></div>
      <div class="l"><?=$modulo==='tit_complexivo'?'Rechazados':'Reprobados'?></div>
    </div>
    <div class="med-stat">
      <div class="n" style="color:#94a3b8"><?=$stats['sin_nota']?></div>
      <div class="l"><?=$modulo==='tit_complexivo'?'Pendientes/Proceso':'Sin nota'?></div>
    </div>
    <?php if($modulo!=='tit_complexivo'):?>
    <div class="med-stat">
      <div class="n" style="color:<?=$stats['prom_nota']!==null?($stats['prom_nota']>=$escalaMin?'#16a34a':'#ef4444'):'#94a3b8'?>">
        <?=$stats['prom_nota']!==null?number_format($stats['prom_nota'],2):'—'?>
      </div>
      <div class="l">Promedio general</div>
    </div>
    <?php if($stats['total']>0&&$stats['aprobados']+$stats['reprobados']>0):
      $pctAp=round($stats['aprobados']/($stats['aprobados']+$stats['reprobados'])*100);
    ?>
    <div class="med-stat">
      <div class="n" style="color:<?=$pctAp>=70?'#16a34a':'#ef4444'?>"><?=$pctAp?>%</div>
      <div class="l">Tasa aprobación</div>
    </div>
    <?php endif;?>
    <?php else:?>
    <?php if($statsCompl['total']>0&&$statsCompl['aprobados']+$statsCompl['rechazados']>0):
      $pctAp=round($statsCompl['aprobados']/($statsCompl['aprobados']+$statsCompl['rechazados'])*100);?>
    <div class="med-stat">
      <div class="n" style="color:<?=$pctAp>=70?'#16a34a':'#ef4444'?>"><?=$pctAp?>%</div>
      <div class="l">Tasa aprobación</div>
    </div>
    <?php endif;?>
    <?php endif;?>
  </div>

  <!-- ── FILTROS ── -->
  <div style="background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:14px 18px;margin-bottom:16px;">
    <form method="GET" class="row g-2 align-items-end">
      <input type="hidden" name="modulo" value="<?=htmlspecialchars($modulo)?>">

      <!-- Búsqueda -->
      <div class="col-sm-6 col-md-3">
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#64748b;display:block;margin-bottom:4px;">Buscar</label>
        <input type="text" name="q" class="form-control form-control-sm"
               placeholder="Estudiante, cédula, código..." value="<?=htmlspecialchars($buscar)?>" style="font-size:13px;">
      </div>

      <!-- Período -->
      <div class="col-sm-6 col-md-3">
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#64748b;display:block;margin-bottom:4px;">Período</label>
        <select name="periodo" class="form-select form-select-sm" style="font-size:13px;">
          <option value="0">— Todos los períodos —</option>
          <?php foreach($periodos as $p):?>
          <option value="<?=$p['id_periodo']?>" <?=$idPer==$p['id_periodo']?'selected':''?>>
            <?=htmlspecialchars($p['nombre'])?><?=$p['activo']?' ★':''?>
          </option>
          <?php endforeach;?>
        </select>
      </div>

      <!-- Carrera -->
      <div class="col-sm-6 col-md-3">
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#64748b;display:block;margin-bottom:4px;">Carrera</label>
        <select name="carrera" class="form-select form-select-sm" style="font-size:13px;">
          <option value="0">— Todas las carreras —</option>
          <?php foreach($carreras as $c):?>
          <option value="<?=$c['id_carrera']?>" <?=$idCar==$c['id_carrera']?'selected':''?>><?=htmlspecialchars($c['nombre'])?></option>
          <?php endforeach;?>
        </select>
      </div>

      <!-- Botones acción -->
      <div class="col-auto d-flex gap-2 flex-wrap">
        <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-filter me-1"></i>Filtrar</button>
        <a href="?modulo=<?=$modulo?>" class="btn btn-sm btn-outline-secondary"><i class="fa fa-xmark me-1"></i>Limpiar</a>
        <a href="<?=$exportUrl?>" class="btn btn-sm btn-outline-secondary"><i class="fa fa-download me-1"></i>CSV</a>
        <button type="button" onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="fa fa-print me-1"></i>Imprimir</button>
      </div>
    </form>

    <!-- Indicador filtros activos + contador -->
    <div style="display:flex;align-items:center;gap:10px;margin-top:10px;padding-top:10px;border-top:1px solid #f1f5f9;flex-wrap:wrap;">
      <?php if($idPer||$idCar||$buscar):?>
      <span style="font-size:11px;color:#64748b;">
        <i class="fa fa-filter" style="color:#3b82f6;margin-right:4px;"></i>
        <?php if($idPer):?><strong style="color:#0f172a;"><?=htmlspecialchars($perNom)?></strong><?php if($idPer==$idPerActivo):?> <span style="font-size:9px;background:#f0fdf4;color:#16a34a;padding:1px 5px;border-radius:8px;font-weight:700;border:1px solid #bbf7d0;">★ activo</span><?php endif;?><?php endif;?>
        <?php if($idCar):?> · <strong style="color:#0f172a;"><?=htmlspecialchars($carNom)?></strong><?php endif;?>
        <?php if($buscar):?> · "<strong style="color:#0f172a;"><?=htmlspecialchars($buscar)?></strong>"<?php endif;?>
      </span>
      <?php endif;?>
      <span style="margin-left:auto;font-size:12px;color:#64748b;">
        <i class="fa fa-list me-1"></i><strong><?=count($datos)?></strong> registro(s)
      </span>
    </div>
  </div>

  <!-- ════════ TABLA PRÁCTICAS ════════ -->
  <?php if($modulo==='practicas'):?>

  <!-- Ponderación visual -->
  <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px;align-items:center;">
    <span style="font-size:10px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.05em;">Ponderación:</span>
    <span style="font-size:11px;padding:3px 10px;border-radius:20px;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;font-weight:700;">N1 Tutor Acad. 25%</span>
    <span style="font-size:11px;padding:3px 10px;border-radius:20px;background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;font-weight:700;">N2 Tutor Emp. 30%</span>
    <span style="font-size:11px;padding:3px 10px;border-radius:20px;background:#fef3c7;color:#d97706;border:1px solid #fde68a;font-weight:700;">N3 Bitácoras 20%</span>
    <span style="font-size:11px;padding:3px 10px;border-radius:20px;background:#f5f3ff;color:#7c3aed;border:1px solid #ddd6fe;font-weight:700;">N4 Informe 25%</span>
    <span style="font-size:10px;color:#94a3b8;margin-left:4px;">Escala /100 · Mín. aprobatorio: 70</span>
  </div>

  <div class="med-tbl">
    <table class="table table-borderless mb-0">
      <thead>
        <tr>
          <th style="width:30px">#</th>
          <th>Estudiante</th>
          <th>Carrera</th>
          <th class="text-center">Tipo</th>
          <th>Empresa</th>
          <th class="text-center">Horas</th>
          <th class="text-center" style="background:#eff6ff;color:#1d4ed8;">N1<br><small style="font-weight:400;font-size:9px;">Tutor Acad. · 25%</small></th>
          <th class="text-center" style="background:#f0fdf4;color:#15803d;">N2<br><small style="font-weight:400;font-size:9px;">Tutor Emp. · 30%</small></th>
          <th class="text-center" style="background:#fef9c3;color:#d97706;">N3<br><small style="font-weight:400;font-size:9px;">Bitácoras · 20%</small></th>
          <th class="text-center" style="background:#f5f3ff;color:#7c3aed;">N4<br><small style="font-weight:400;font-size:9px;">Informe · 25%</small></th>
          <th class="text-center" style="background:#0f172a;color:#fff;">Nota Final<br><small style="font-weight:400;font-size:9px;color:#94a3b8;">/100</small></th>
          <th class="text-center" style="min-width:90px">Estado</th>
          <th>Tutor</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($datosPract)):?>
        <tr><td colspan="13" class="text-center py-5" style="color:#94a3b8"><i class="fa fa-info-circle me-1"></i>Sin datos para el filtro seleccionado.</td></tr>
        <?php else: foreach($datosPract as $i=>$r):
          $nf = $r['nota_final']!==null ? (float)$r['nota_final'] : null;
          $n1 = $r['n1']!==null ? (float)$r['n1'] : null;
          $n2 = $r['n2']!==null ? (float)$r['n2'] : null;
          $n3 = $r['n3']!==null ? (float)$r['n3'] : null;
          $n4 = $r['n4']!==null ? (float)$r['n4'] : null;
          $aprobado = $nf!==null ? ($nf>=70) : null;
          $colorNF = $nf===null?'#94a3b8':($nf>=70?'#16a34a':'#ef4444');
          $bgNF    = $nf===null?'transparent':($nf>=90?'#f0fdf4':($nf>=70?'#f0fdf4':'#fff1f0'));
          $pctHoras = $r['horas_requeridas']>0 ? min(100,round($r['horas_cumplidas']/$r['horas_requeridas']*100)) : 0;
          // Helper: render nota bar /100
          $notaBar100 = function($nota, $color) {
            if ($nota === null) return '<span style="color:#94a3b8;font-size:12px;">—</span>';
            $pct = min(100, round($nota));
            $ok  = $nota >= 70;
            $clr = $ok ? '#16a34a' : '#ef4444';
            return '<div class="nota-bar" style="justify-content:center;gap:4px;">
                      <div class="bar" style="min-width:32px;"><div class="fill" style="width:'.$pct.'%;background:'.$clr.';"></div></div>
                      <span style="font-weight:700;font-size:12px;color:'.$clr.';">' . number_format($nota,1) . '</span>
                    </div>';
          };
        ?>
        <tr>
          <td style="color:#94a3b8;font-size:11px;"><?=$i+1?></td>
          <td>
            <div style="font-weight:700;color:#0f172a;font-size:13px;"><?=htmlspecialchars($r['estudiante'])?></div>
            <div style="font-size:10px;color:#94a3b8;font-family:monospace;margin-top:1px;"><?=htmlspecialchars($r['cedula'])?> · <?=htmlspecialchars($r['codigo_estudiante'])?></div>
            <?php if(!empty($r['observaciones_gestor'])):?>
            <div style="font-size:10px;color:#7c3aed;margin-top:3px;background:#f5f3ff;padding:2px 6px;border-radius:4px;border-left:2px solid #7c3aed;">
              <i class="fa fa-comment-dots me-1"></i><?=htmlspecialchars(mb_substr($r['observaciones_gestor'],0,60)).(mb_strlen($r['observaciones_gestor'])>60?'…':'')?>
            </div>
            <?php endif;?>
          </td>
          <td style="font-size:11px;color:#64748b;max-width:130px;"><?=htmlspecialchars($r['carrera'])?></td>
          <td class="text-center">
            <?php $modPract = $r['modalidad'] ?? 'practica_laboral';
              if ($modPract === 'convalidacion'):?>
            <span style="font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;white-space:nowrap;">
              <i class="fa fa-rotate me-1" style="font-size:9px;"></i>Conv.
            </span>
            <?php else:?>
            <span style="font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700;background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;white-space:nowrap;">
              <i class="fa fa-briefcase me-1" style="font-size:9px;"></i>PPP
            </span>
            <?php endif;?>
          </td>
          <td style="font-size:11px;max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#334155;" title="<?=htmlspecialchars($r['empresa'])?>">
            <?=htmlspecialchars($r['empresa'])?>
          </td>
          <td class="text-center">
            <div class="nota-bar">
              <div class="bar"><div class="fill" style="width:<?=$pctHoras?>%;background:<?=$pctHoras>=100?'#16a34a':'#3b82f6'?>"></div></div>
              <span style="font-size:11px;font-weight:600;color:<?=$pctHoras>=100?'#16a34a':'#64748b'?>;white-space:nowrap;"><?=$r['horas_cumplidas']?>/<?=$r['horas_requeridas']?>h</span>
            </div>
          </td>
          <!-- N1 Tutor Académico 25% -->
          <td class="text-center" style="background:#fafbff;"><?=$notaBar100($n1,'#1d4ed8')?></td>
          <!-- N2 Tutor Empresa 30% -->
          <td class="text-center" style="background:#fafffa;"><?=$notaBar100($n2,'#15803d')?></td>
          <!-- N3 Bitácoras 20% -->
          <td class="text-center" style="background:#fffdf0;"><?=$notaBar100($n3,'#d97706')?></td>
          <!-- N4 Informe Final 25% -->
          <td class="text-center" style="background:#fdf8ff;"><?=$notaBar100($n4,'#7c3aed')?></td>
          <!-- Nota Final -->
          <td class="text-center" style="background:<?=$bgNF?>;">
            <div style="font-size:18px;font-weight:900;color:<?=$colorNF?>;line-height:1;">
              <?=$nf!==null?number_format($nf,2):'—'?>
            </div>
            <?php if($nf!==null):?>
            <div style="font-size:9px;color:#94a3b8;margin-top:1px;">/100</div>
            <?php endif;?>
          </td>
          <td class="text-center">
            <?php if($aprobado===null):?>
              <span class="badge-pend">Sin nota</span>
            <?php elseif($aprobado):?>
              <span class="badge-ap"><i class="fa fa-check me-1"></i>Aprobado</span>
            <?php else:?>
              <span class="badge-rp"><i class="fa fa-xmark me-1"></i>Reprobado</span>
            <?php endif;?>
          </td>
          <td style="font-size:11px;color:#64748b;"><?=htmlspecialchars($r['tutor']??'—')?></td>
        </tr>
        <?php endforeach; endif;?>
      </tbody>
    </table>
  </div>

  <!-- ════════ TABLA VINCULACIÓN ════════ -->
  <?php elseif($modulo==='vinculacion'):?>
  <?php if(empty($datosVinc)&&!empty($buscar)||empty($datosVinc)):?>
  <div class="med-tbl">
    <table class="table mb-0"><tbody>
      <tr><td class="text-center py-5" style="color:#94a3b8">
        <?php if(empty($datosVinc)&&empty($buscar)):?>
        <i class="fa fa-info-circle me-1"></i>No hay datos de calificaciones de vinculación registrados aún. El tutor debe completar grupos y asignar notas.
        <?php else:?><i class="fa fa-search me-1"></i>Sin resultados para "<?=htmlspecialchars($buscar)?>"<?php endif;?>
      </td></tr>
    </tbody></table>
  </div>
  <?php else:?>
  <div class="med-tbl">
    <table class="table table-borderless mb-0">
      <thead>
        <tr>
          <th>#</th>
          <th>Estudiante</th>
          <th>Carrera</th>
          <th>Organización / Proyecto</th>
          <th>Período</th>
          <th class="text-center">Rol</th>
          <th class="text-center">N1 — Informe PDF</th>
          <th class="text-center">N2 — Trabajo Indiv.</th>
          <th class="text-center">Promedio</th>
          <th class="text-center" style="min-width:100px">Estado</th>
          <th>Tutor</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($datosVinc as $i=>$r):
          $nf  = $r['nota_final']!==null ? (float)$r['nota_final'] : null;
          $n1  = $r['n1']!==null ? (float)$r['n1'] : null;
          $n2  = $r['n2']!==null ? (float)$r['n2'] : null;
          $ap  = $nf!==null ? ($nf>=70) : null;
          $cNF = $nf===null?'#94a3b8':($nf>=70?'#16a34a':'#ef4444');
          $esLider = $r['rol']==='lider';
          // Etiqueta cualitativa
          $etiq='';
          if($nf!==null){ $etiq=$nf>=90?'Excelente':($nf>=80?'Muy Bueno':($nf>=70?'Bueno':'Reprobado')); }
        ?>
        <tr>
          <td style="color:#94a3b8;font-size:11px"><?=$i+1?></td>
          <td>
            <div style="font-weight:600;color:#0f172a"><?=htmlspecialchars($r['estudiante'])?></div>
            <div style="font-size:10px;color:#94a3b8;font-family:monospace"><?=htmlspecialchars($r['cedula'])?> · <?=htmlspecialchars($r['codigo_estudiante'])?></div>
          </td>
          <td style="font-size:11px;color:#64748b"><?=htmlspecialchars($r['carrera'])?></td>
          <td>
            <div style="font-size:11px;font-weight:600;color:#0f172a;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?=htmlspecialchars($r['nombre_proyecto'])?>">
              <?=htmlspecialchars($r['nombre_proyecto'])?>
            </div>
            <div style="font-size:10px;color:#94a3b8"><?=htmlspecialchars($r['organizacion']??'')?></div>
          </td>
          <td style="font-size:11px;color:#64748b;white-space:nowrap"><?=htmlspecialchars($r['periodo'])?></td>
          <td class="text-center">
            <?php if($esLider):?>
            <span style="font-size:9px;padding:1px 7px;border-radius:20px;background:#fffbeb;color:#92400e;border:1px solid #fde68a;font-weight:700"><i class="fa fa-crown me-1" style="font-size:8px"></i>Líder</span>
            <?php else:?>
            <span style="font-size:10px;color:#64748b">Miembro</span>
            <?php endif;?>
          </td>
          <td class="text-center">
            <?php if($n1!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$n1)?>%;background:<?=$n1>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$n1>=70?'#16a34a':'#ef4444'?>"><?=number_format($n1,1)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <td class="text-center">
            <?php if($n2!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$n2)?>%;background:<?=$n2>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$n2>=70?'#16a34a':'#ef4444'?>"><?=number_format($n2,1)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <td class="text-center">
            <span style="font-size:18px;font-weight:800;color:<?=$cNF?>">
              <?=$nf!==null?number_format($nf,1):'—'?>
            </span>
            <?php if($nf!==null):?><div style="font-size:9px;color:#94a3b8"><?=$etiq?></div><?php endif;?>
          </td>
          <td class="text-center">
            <?php if($ap===null):?>
              <span class="badge-pend">Sin nota</span>
            <?php elseif($ap):?>
              <span class="badge-ap"><i class="fa fa-check me-1"></i>Aprobado</span>
            <?php else:?>
              <span class="badge-rp"><i class="fa fa-xmark me-1"></i>Reprobado</span>
            <?php endif;?>
          </td>
          <td style="font-size:11px;color:#64748b"><?=htmlspecialchars($r['tutor']??'—')?></td>
        </tr>
        <?php endforeach;?>
      </tbody>
    </table>
  </div>
  <?php endif;?>
  <?php endif;?>

  <!-- ════════ TABLA COMPLEXIVO ════════ -->
  <?php if($modulo==='tit_complexivo'):?>
  <div class="med-tbl">
    <table class="table table-borderless mb-0">
      <thead>
        <tr>
          <th>#</th>
          <th>Estudiante</th>
          <th>Carrera</th>
          <th class="text-center" style="min-width:110px">Estado</th>
          <th class="text-center">Nota Examen<br><span style="font-weight:400;font-size:9px">/100</span></th>
          <th class="text-center">Fecha envío</th>
          <th class="text-center">Habilitación</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($datosCompl)):?>
        <tr><td colspan="7" class="text-center py-5" style="color:#94a3b8">
          <i class="fa fa-graduation-cap me-1"></i>
          Sin registros de examen complexivo<?=$idCar?' para esta carrera':''?>.
        </td></tr>
        <?php else:
          $estadoColors = [
            'pendiente' => ['#94a3b8','Pendiente','fa-clock'],
            'enviada'   => ['#3b82f6','Esperando aprobación','fa-hourglass-half'],
            'aprobado'  => ['#16a34a','Aprobado','fa-circle-check'],
            'rechazado' => ['#ef4444','Rechazado','fa-circle-xmark'],
          ];
          $currentCar = '';
          foreach($datosCompl as $i=>$r):
            $ec = $estadoColors[$r['estado']] ?? ['#94a3b8','?','fa-question'];
            // Separador por carrera
            if($r['carrera'] !== $currentCar):
              $currentCar = $r['carrera'];
        ?>
        <tr style="background:#f8fafc;">
          <td colspan="7" style="font-weight:700;font-size:11px;text-transform:uppercase;
                                  letter-spacing:.07em;color:#64748b;padding:8px 12px;border-bottom:2px solid #e2e8f0;">
            <i class="fa fa-graduation-cap me-1" style="color:#8b5cf6"></i>
            <?=htmlspecialchars($currentCar)?>
          </td>
        </tr>
        <?php endif;?>
        <tr>
          <td style="color:#94a3b8;font-size:11px"><?=$i+1?></td>
          <td>
            <div style="font-weight:600;color:#0f172a"><?=htmlspecialchars($r['estudiante'])?></div>
            <div style="font-size:10px;color:#94a3b8;font-family:monospace">
              <?=htmlspecialchars($r['cedula'])?> · <?=htmlspecialchars($r['codigo_estudiante'])?>
            </div>
          </td>
          <td style="font-size:11px;color:#64748b"><?=htmlspecialchars($r['carrera'])?></td>
          <td class="text-center">
            <span style="font-size:11px;padding:3px 10px;border-radius:20px;font-weight:700;
                         background:<?=$ec[0]?>18;color:<?=$ec[0]?>;border:1px solid <?=$ec[0]?>33;">
              <i class="fa <?=$ec[2]?> me-1"></i><?=$ec[1]?>
            </span>
          </td>
          <td class="text-center nota-compl-cell" data-id="<?=$r['id_titulacion']?>">
            <?php
              $notaExamen = $r['nota_trabajo'] !== null ? (float)$r['nota_trabajo'] : null;
              $colorNE    = ($notaExamen !== null) ? ($notaExamen >= 70 ? '#16a34a' : '#ef4444') : '#94a3b8';
            ?>
            <!-- Vista -->
            <div class="nota-compl-view" style="cursor:pointer" title="Clic para editar nota">
              <?php if ($notaExamen !== null): ?>
              <span class="nota-compl-valor" style="font-size:18px;font-weight:800;color:<?=$colorNE?>">
                <?=number_format($notaExamen,2)?>
              </span>
              <div style="font-size:9px;color:#94a3b8">/ 100</div>
              <?php else: ?>
              <span class="nota-compl-valor nota-compl-empty"
                    style="font-size:10px;padding:2px 8px;border-radius:20px;font-weight:600;
                           background:#f8fafc;color:#94a3b8;border:1px solid #e2e8f0;">
                <i class="fa fa-pen me-1" style="font-size:9px"></i>Ingresar nota
              </span>
              <?php endif; ?>
            </div>
            <!-- Editor inline (oculto por defecto) -->
            <div class="nota-compl-edit" style="display:none;align-items:center;gap:4px;justify-content:center">
              <input type="number" min="0" max="100" step="0.01"
                     value="<?=$notaExamen!==null?number_format($notaExamen,2,'.',''): ''?>"
                     placeholder="0–100"
                     style="width:72px;font-size:13px;font-weight:700;text-align:center;
                            border:2px solid #3b82f6;border-radius:6px;padding:2px 4px;color:#0f172a">
              <button class="btn-guardar-nota" title="Guardar"
                      style="background:#16a34a;color:#fff;border:none;border-radius:6px;
                             padding:3px 7px;font-size:12px;cursor:pointer;line-height:1">
                <i class="fa fa-check"></i>
              </button>
              <button class="btn-cancelar-nota" title="Cancelar"
                      style="background:#e2e8f0;color:#64748b;border:none;border-radius:6px;
                             padding:3px 7px;font-size:12px;cursor:pointer;line-height:1">
                <i class="fa fa-xmark"></i>
              </button>
            </div>
            <!-- Spinner -->
            <div class="nota-compl-saving" style="display:none;color:#3b82f6;font-size:11px">
              <i class="fa fa-spinner fa-spin me-1"></i>Guardando…
            </div>
          </td>
          <td class="text-center" style="font-size:11px;color:#64748b">
            <?=$r['fecha_envio'] ? date('d/m/Y H:i', strtotime($r['fecha_envio'])) : '—'?>
          </td>
          <td class="text-center" style="font-size:11px;color:#64748b">
            <?=$r['fecha_habilitacion'] ? date('d/m/Y H:i', strtotime($r['fecha_habilitacion'])) : '—'?>
          </td>
        </tr>
        <?php endforeach; endif;?>
      </tbody>
    </table>
  </div>
  <?php endif;?>

  <!-- ════════ TABLA INVESTIGACIÓN ════════ -->
  <?php if($modulo==='tit_investigacion'):?>
  <div class="med-tbl">
    <table class="table table-borderless mb-0">
      <thead>
        <tr>
          <th>#</th>
          <th>Estudiante</th>
          <th>Carrera</th>
          <th>Tema</th>
          <th class="text-center" style="min-width:100px">Estado</th>
          <th>Docente</th>
          <th class="text-center">N. Trabajo<br><span style="font-weight:400;font-size:9px">/100</span></th>
          <th class="text-center">Director<br><span style="font-weight:400;font-size:9px">/100</span></th>
          <th class="text-center">Lector<br><span style="font-weight:400;font-size:9px">/100</span></th>
          <th class="text-center">Tribunal<br><span style="font-weight:400;font-size:9px">/100</span></th>
          <th class="text-center">Nota Global</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($datosInvest)):?>
        <tr><td colspan="11" class="text-center py-5" style="color:#94a3b8">
          <i class="fa fa-microscope me-1"></i>
          Sin registros de trabajo de investigación<?=$idCar?' para esta carrera':''?>.
        </td></tr>
        <?php else:
          $estadoColors = [
            'pendiente' => ['#94a3b8','Pendiente'],
            'enviada'   => ['#3b82f6','Esperando'],
            'aprobado'  => ['#16a34a','Aprobado'],
            'rechazado' => ['#ef4444','Rechazado'],
          ];
          $currentCar = '';
          foreach($datosInvest as $i=>$r):
            $ec  = $estadoColors[$r['estado']] ?? ['#94a3b8','?'];
            $ng  = $r['nota_global'] !== null ? (float)$r['nota_global'] : null;
            $nt  = $r['nota_trabajo'] !== null ? (float)$r['nota_trabajo'] : null;
            $nd  = $r['nota_director'] !== null ? (float)$r['nota_director'] : null;
            $nl  = $r['nota_lector']   !== null ? (float)$r['nota_lector']   : null;
            $ntr = $r['nota_tribunal'] !== null ? (float)$r['nota_tribunal'] : null;
            // Separador por carrera
            if($r['carrera'] !== $currentCar):
              $currentCar = $r['carrera'];
        ?>
        <tr style="background:#fdf2f8;">
          <td colspan="11" style="font-weight:700;font-size:11px;text-transform:uppercase;
                                   letter-spacing:.07em;color:#be185d;padding:8px 12px;border-bottom:2px solid #fce7f3;">
            <i class="fa fa-microscope me-1" style="color:#ec4899"></i>
            <?=htmlspecialchars($currentCar)?>
          </td>
        </tr>
        <?php endif;?>
        <tr>
          <td style="color:#94a3b8;font-size:11px"><?=$i+1?></td>
          <td>
            <div style="font-weight:600;color:#0f172a"><?=htmlspecialchars($r['estudiante'])?></div>
            <div style="font-size:10px;color:#94a3b8;font-family:monospace">
              <?=htmlspecialchars($r['cedula'])?>
            </div>
          </td>
          <td style="font-size:11px;color:#64748b"><?=htmlspecialchars($r['carrera'])?></td>
          <td style="max-width:160px;">
            <div style="font-size:11px;color:#0f172a;overflow:hidden;text-overflow:ellipsis;
                        white-space:nowrap;" title="<?=htmlspecialchars($r['tema']??'')?>">
              <?=htmlspecialchars($r['tema'] ?: '—')?>
            </div>
          </td>
          <td class="text-center">
            <span style="font-size:10px;padding:2px 8px;border-radius:20px;font-weight:700;
                         background:<?=$ec[0]?>18;color:<?=$ec[0]?>;border:1px solid <?=$ec[0]?>33;">
              <?=$ec[1]?>
            </span>
          </td>
          <td style="font-size:11px;">
            <?php if($r['tutor_nombre'] && trim($r['tutor_nombre'])!==' '):?>
            <div style="color:#64748b">
              <i class="fa fa-user-tie me-1" style="color:#3b82f6;font-size:10px;"></i><?=htmlspecialchars($r['tutor_nombre'])?>
            </div>
            <?php endif;?>
            <?php if($r['director_nombre'] && trim($r['director_nombre'])!==' '):?>
            <div style="color:#64748b;margin-top:2px;">
              <i class="fa fa-star me-1" style="color:#f59e0b;font-size:10px;"></i><?=htmlspecialchars($r['director_nombre'])?>
            </div>
            <?php endif;?>
          </td>
          <!-- N. Trabajo /100 -->
          <td class="text-center">
            <?php if($nt!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$nt)?>%;background:<?=$nt>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$nt>=70?'#16a34a':'#ef4444'?>"><?=number_format($nt,2)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <!-- N. Director /100 -->
          <td class="text-center">
            <?php if($nd!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$nd)?>%;background:<?=$nd>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$nd>=70?'#16a34a':'#ef4444'?>"><?=number_format($nd,0)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <!-- N. Lector /100 -->
          <td class="text-center">
            <?php if($nl!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$nl)?>%;background:<?=$nl>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$nl>=70?'#16a34a':'#ef4444'?>"><?=number_format($nl,0)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <!-- N. Tribunal /100 -->
          <td class="text-center">
            <?php if($ntr!==null):?>
            <div class="nota-bar" style="justify-content:center">
              <div class="bar"><div class="fill" style="width:<?=min(100,$ntr)?>%;background:<?=$ntr>=70?'#16a34a':'#ef4444'?>"></div></div>
              <span style="font-weight:700;font-size:12px;color:<?=$ntr>=70?'#16a34a':'#ef4444'?>"><?=number_format($ntr,0)?></span>
            </div>
            <?php else:?><span style="color:#94a3b8">—</span><?php endif;?>
          </td>
          <!-- Nota Global /100 — la más importante -->
          <td class="text-center">
            <?php if($ng!==null):?>
            <span style="font-size:18px;font-weight:800;color:<?=$ng>=70?'#16a34a':'#ef4444'?>">
              <?=number_format($ng,2)?>
            </span>
            <div style="font-size:9px;color:#94a3b8">/ 100</div>
            <?php else:?><span class="badge-pend">Pendiente</span><?php endif;?>
          </td>
        </tr>
        <?php endforeach; endif;?>
      </tbody>
    </table>
  </div>
  <?php endif;?>

  <!-- Nota al pie -->
  <div style="font-size:11px;color:#94a3b8;margin-top:16px;text-align:right">
    <i class="fa fa-info-circle me-1"></i>
    <?php if($modulo==='practicas'):?>
    N1 = Nota Tutor Académico · N2 = Nota Tutor Empresa · Mínimo aprobatorio: <strong>7.0 / 10</strong>
    <?php elseif($modulo==='vinculacion'):?>
    N1 = Informe Final PDF · N2 = Trabajo Individual · Mínimo aprobatorio: <strong>70 / 100</strong> (Norma CES/CACES)
    <?php elseif($modulo==='tit_complexivo'):?>
    Examen complexivo — Nota registrada por el coordinador (escala /100) · Mín. aprobatorio: <strong>70 / 100</strong>
    <?php else:?>
    N. Trabajo /100 · N. Director, Lector, Tribunal en escala /100 · Nota Global /100 · Mín. aprobatorio: <strong>70 / 100</strong>
    <?php endif;?>
  </div>

</main>
</div>

<style>
@media print {
  .sidebar,.navbar,form,.mod-tabs,.escala-strip,.filter-panel .btn{display:none!important}
  .main-area{padding:0!important}
  body{background:#fff!important;color:#000!important}
  .med-tbl{border:1px solid #ccc!important}
  .med-tbl th{background:#eee!important;color:#000!important}
  .med-tbl td{color:#000!important}
  .badge-ap,.badge-rp,.badge-pend{border:1px solid #999!important;color:#000!important;background:#eee!important}
}
</style>

<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(){
  // ── Abrir editor al hacer clic en la celda ──
  $(document).on('click', '.nota-compl-view', function(){
    var $cell = $(this).closest('.nota-compl-cell');
    $(this).hide();
    $cell.find('.nota-compl-edit').css('display','flex');
    $cell.find('input[type=number]').focus().select();
  });

  // ── Cancelar ──
  $(document).on('click', '.btn-cancelar-nota', function(){
    var $cell = $(this).closest('.nota-compl-cell');
    $cell.find('.nota-compl-edit').hide();
    $cell.find('.nota-compl-view').show();
  });

  // ── Guardar con Enter ──
  $(document).on('keydown', '.nota-compl-cell input', function(e){
    if (e.key === 'Enter')  $(this).closest('.nota-compl-cell').find('.btn-guardar-nota').click();
    if (e.key === 'Escape') $(this).closest('.nota-compl-cell').find('.btn-cancelar-nota').click();
  });

  // ── Guardar via AJAX ──
  $(document).on('click', '.btn-guardar-nota', function(){
    var $cell  = $(this).closest('.nota-compl-cell');
    var idTit  = $cell.data('id');
    var valor  = $cell.find('input[type=number]').val().trim();

    // Validar rango
    if (valor !== '' && (parseFloat(valor) < 0 || parseFloat(valor) > 100)) {
      alert('La nota debe estar entre 0 y 100');
      return;
    }

    $cell.find('.nota-compl-edit').hide();
    $cell.find('.nota-compl-saving').show();

    $.post('', { action:'guardar_nota_complexivo', id_titulacion: idTit, nota: valor })
      .done(function(res){
        $cell.find('.nota-compl-saving').hide();
        if (res.ok) {
          // Actualizar la vista
          var $view = $cell.find('.nota-compl-view');
          if (res.nota !== null && res.nota !== undefined) {
            var n    = parseFloat(res.nota);
            var color = n >= 70 ? '#16a34a' : '#ef4444';
            var fmt   = n.toFixed(2);
            $view.html(
              '<span class="nota-compl-valor" style="font-size:18px;font-weight:800;color:'+color+'">'+fmt+'</span>'+
              '<div style="font-size:9px;color:#94a3b8">/ 100</div>'
            );
          } else {
            $view.html(
              '<span class="nota-compl-valor nota-compl-empty" '+
              'style="font-size:10px;padding:2px 8px;border-radius:20px;font-weight:600;'+
              'background:#f8fafc;color:#94a3b8;border:1px solid #e2e8f0;">'+
              '<i class="fa fa-pen me-1" style="font-size:9px"></i>Ingresar nota</span>'
            );
          }
          $view.show();
          // Feedback visual breve
          $view.css('transition','background .3s').css('background','#f0fdf4');
          setTimeout(function(){ $view.css('background',''); }, 800);
        } else {
          alert('Error: ' + (res.msg || 'No se pudo guardar'));
          $cell.find('.nota-compl-view').show();
        }
      })
      .fail(function(){
        $cell.find('.nota-compl-saving').hide();
        $cell.find('.nota-compl-view').show();
        alert('Error de conexión al guardar la nota.');
      });
  });
});
</script>
</body></html>