<?php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/flash.php';
requireRol(ROL_GESTOR_PPP);
$idInst = instId();
$user = currentUser(); $db = getDB(); $pageTitle = 'Calificaciones — Gestor PPP';

$cfg        = getAllConfig();
$notaMinima = (float)($cfg['nota_minima_aprobacion'] ?? 60);
$horasMin   = (int)($cfg['horas_minimas_ppp'] ?? 240);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id   = (int)($_POST['id_practica'] ?? 0);

    // El gestor SOLO califica Bitacoras e Informe
    $nBit = min(100, max(0, (float)str_replace(',','.',($_POST['nota_bitacoras'] ?? 0))));
    $nInf = min(100, max(0, (float)str_replace(',','.',($_POST['nota_informe']   ?? 0))));
    $obs  = trim($_POST['observaciones_gestor'] ?? '');

    // Leer notas de empresa y tutor ya guardadas por ellos (no las toca el gestor)
    $stN = $db->prepare("SELECT nota_tutor_empresa, nota_empresa_100, nota_tutor_academico FROM practicas WHERE id_practica=:id");
    $stN->execute([':id' => $id]);
    $fila = $stN->fetch();
    // nota_empresa_100 es escala 0-100; nota_tutor_empresa es 0-10 (convertida)
    $nEmp = ($fila['nota_empresa_100'] !== null) ? (float)$fila['nota_empresa_100'] : (($fila['nota_tutor_empresa'] !== null) ? (float)$fila['nota_tutor_empresa'] * 10 : null);
    $nTut = ($fila['nota_tutor_academico'] !== null) ? (float)$fila['nota_tutor_academico'] : null;

    // Nota final solo si los 4 componentes estan disponibles
    $nFin = null;
    if ($nEmp !== null && $nTut !== null) {
        $nFin = round($nBit*0.20 + $nInf*0.25 + $nEmp*0.30 + $nTut*0.25, 2);
    }

    $db->prepare("
        UPDATE practicas SET
            nota_bitacoras       = :nb,
            nota_informe         = :ni,
            nota_final           = :nf,
            observaciones_gestor = :obs,
            calificado_por       = :uid,
            fecha_calificacion   = CURDATE(),
            estado               = IF(:nf2 IS NOT NULL, 'calificado', estado)
        WHERE id_practica = :id
    ")->execute([':nb'=>$nBit,':ni'=>$nInf,':nf'=>$nFin,':nf2'=>$nFin,':obs'=>$obs,':uid'=>$user['id'],':id'=>$id]);

    registrarAudit($user['id'], 'calificar_practica', 'practicas');

    // ── Si se calculó nota final, notificar a secretarias ─────────
    if ($nFin !== null) {
        $stNomEst = $db->prepare("
            SELECT CONCAT(u.apellidos,' ',u.nombres) AS estudiante
            FROM   practicas p
            JOIN   estudiantes est ON est.id_estudiante = p.id_estudiante
            JOIN   usuarios u      ON u.id_usuario      = est.id_usuario
            WHERE  p.id_practica = :id LIMIT 1
        ");
        $stNomEst->execute([':id' => $id]);
        $nomEst = $stNomEst->fetchColumn() ?: "Estudiante ID {$id}";
        $resultado = $nFin >= $notaMinima ? 'APROBADO' : 'REPROBADO';

        $stSecs = $db->query("SELECT id_usuario FROM usuarios WHERE id_rol = " . ROL_SECRETARIA . " AND activo = 1" . instCond() . "");
        $stNotifSec = $db->prepare("
            INSERT INTO notificaciones (id_usuario, tipo, asunto, mensaje)
            VALUES (:uid, 'sistema', :asunto, :msg)
        ");
        foreach ($stSecs->fetchAll() as $sec) {
            $stNotifSec->execute([
                ':uid'    => $sec['id_usuario'],
                ':asunto' => "Práctica calificada — {$nomEst}",
                ':msg'    => "La práctica de {$nomEst} ha sido calificada con {$nFin}/100 ({$resultado}). Puedes proceder a emitir el certificado correspondiente.",
            ]);
        }
    }

    if ($nFin !== null) {
        flashSet('ok', "Nota final: {$nFin}/100 --- ".($nFin >= $notaMinima ? 'APROBADO' : 'REPROBADO'));
    } else {
        flashSet('info', "Bitacoras e Informe guardados. La nota final se calculara cuando empresa y tutor completen su evaluacion.");
    }
    header("Location: calificaciones.php?id=$id"); exit;
}

$idPractica = (int)($_GET['id'] ?? 0);
$practica   = null;
if ($idPractica) {
    $st = $db->prepare("
        SELECT p.*,
               CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
               u.email AS estudiante_email, u.cedula,
               p.modalidad,
               CASE WHEN p.modalidad='convalidacion' OR EXISTS(SELECT 1 FROM convalidaciones cv WHERE cv.id_practica=p.id_practica) THEN 1 ELSE 0 END AS es_conval,
               c.nombre AS carrera,
               COALESCE(em.razon_social, p.emp_nueva_nombre) AS empresa,
               pa.nombre AS periodo,
               CONCAT(ut.nombres,' ',ut.apellidos) AS tutor_nombre,
               (SELECT COUNT(*) FROM bitacoras b WHERE b.id_practica=p.id_practica AND b.estado='validada') AS bit_validadas,
               (SELECT COUNT(*) FROM bitacoras b WHERE b.id_practica=p.id_practica) AS bit_total,
               (SELECT COALESCE(SUM(horas_semana),0) FROM bitacoras b WHERE b.id_practica=p.id_practica AND b.estado='validada') AS horas_validadas
        FROM   practicas p
        JOIN   estudiantes est ON est.id_estudiante = p.id_estudiante
        JOIN   usuarios u      ON u.id_usuario      = est.id_usuario
        JOIN   carreras c      ON c.id_carrera       = est.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  p.id_practica = :id
    ");
    $st->execute([':id' => $idPractica]);
    $practica = $st->fetch();
}

// Catálogos para filtros de la lista lateral
$periodos    = $db->query("SELECT id_periodo, nombre FROM periodos_academicos WHERE 1=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " ORDER BY id_periodo DESC")->fetchAll();
$pa          = $db->query("SELECT id_periodo FROM periodos_academicos WHERE activo=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " LIMIT 1")->fetch();
$idPerActivo = $pa ? $pa['id_periodo'] : ($periodos[0]['id_periodo'] ?? 0);
$carreras    = $db->query("SELECT id_carrera, nombre FROM carreras WHERE 1=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " ORDER BY nombre")->fetchAll();

// Filtros lista lateral
$filtroListaPer = (int)($_GET['lper'] ?? $idPerActivo);
$filtroListaCar = (int)($_GET['lcar'] ?? 0);

$wPend  = ["p.estado IN ('aprobado','informe_enviado','en_progreso','calificado','completado')"];
$pPend  = [];
if ($idInst) { $wPend[] = 'c.id_instituto = :inst'; $pPend[':inst'] = $idInst; }
if ($filtroListaPer) { $wPend[] = 'p.id_periodo = :lper'; $pPend[':lper'] = $filtroListaPer; }
if ($filtroListaCar) { $wPend[] = 'est.id_carrera = :lcar'; $pPend[':lcar'] = $filtroListaCar; }
$wPendStr = implode(' AND ', $wPend);

$stPend = $db->prepare("
    SELECT p.id_practica, p.estado, p.nota_final,
           p.modalidad,
           CASE WHEN p.modalidad='convalidacion' OR EXISTS(SELECT 1 FROM convalidaciones cv WHERE cv.id_practica=p.id_practica) THEN 1 ELSE 0 END AS es_conval,
           CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
           COALESCE(em.razon_social, p.emp_nueva_nombre) AS empresa,
           c.nombre AS carrera, pa.nombre AS periodo
    FROM   practicas p
    JOIN   estudiantes est ON est.id_estudiante = p.id_estudiante
    JOIN   usuarios u      ON u.id_usuario      = est.id_usuario
    JOIN   carreras c      ON c.id_carrera       = est.id_carrera
    LEFT JOIN empresas em  ON em.id_empresa      = p.id_empresa
    JOIN   periodos_academicos pa ON pa.id_periodo = p.id_periodo
    WHERE  $wPendStr
    ORDER  BY (p.nota_final IS NULL) DESC, p.updated_at DESC
");
$stPend->execute($pPend);
$pendientes = $stPend->fetchAll();
?>
<?php $paginaActual = 'calificaciones'; ?>
<!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-gestor-ppp.css">
<style>
.comp-readonly {
  background: var(--card-alt);
  border-radius: var(--r-lg);
  padding: 14px;
  position: relative;
}
.comp-readonly .comp-valor {
  font-size: 32px;
  font-weight: 900;
  text-align: center;
  margin: 8px 0 4px;
  line-height: 1;
}
.comp-readonly .comp-aporte {
  font-size: 10px;
  text-align: right;
  color: var(--text-2);
  margin-top: 4px;
}
.comp-readonly .comp-aporte span { font-weight: 700; }
.comp-pendiente .comp-valor {
  font-size: 13px !important;
  color: #d97706 !important;
  background: #fef3c7;
  border-radius: 8px;
  padding: 10px;
  text-align: center !important;
  margin: 8px 0 4px;
}
.lock-badge {
  position: absolute;
  top: 10px; right: 10px;
  font-size: 10px;
  background: #e5e7eb;
  color: #6b7280;
  border-radius: 20px;
  padding: 2px 8px;
  font-weight: 700;
}
</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-gestor-ppp.php'; ?>

  <main class="main-area">
    <?= flashHtml() ?>
    <div class="page-header">
      <h4><i class="fa fa-star me-2" style="color:#f59e0b;"></i>Calificaciones PPP</h4>
      <p>Bitacoras <strong>20</strong> &middot; Informe <strong>25</strong> &middot; Empresa <strong>30</strong> &middot; Tutor <strong>25</strong> &mdash; Total: <strong>100 pts</strong> &middot; Minimo: <strong style="color:var(--green);"><?= $notaMinima ?>/100</strong></p>
    </div>

    <div class="row g-3">
      <!-- Lista lateral -->
      <div class="col-lg-4">
        <!-- Filtros compactos -->
        <form method="GET" style="background:var(--card);border:1px solid var(--border);border-radius:var(--r-lg);padding:10px 12px;margin-bottom:10px;">
          <?php if($idPractica): ?><input type="hidden" name="id" value="<?= $idPractica ?>"><?php endif; ?>
          <div class="d-flex gap-2 flex-column">
            <select name="lper" class="form-select form-select-sm" onchange="this.form.submit()">
              <option value="0">— Todos los períodos —</option>
              <?php foreach($periodos as $p): ?>
              <option value="<?= $p['id_periodo'] ?>" <?= $filtroListaPer==$p['id_periodo']?'selected':'' ?>>
                <?= htmlspecialchars($p['nombre']) ?><?= $p['id_periodo']==$idPerActivo?' ★':'' ?>
              </option>
              <?php endforeach; ?>
            </select>
            <select name="lcar" class="form-select form-select-sm" onchange="this.form.submit()">
              <option value="0">— Todas las carreras —</option>
              <?php foreach($carreras as $c): ?>
              <option value="<?= $c['id_carrera'] ?>" <?= $filtroListaCar==$c['id_carrera']?'selected':'' ?>><?= htmlspecialchars($c['nombre']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div style="font-size:10px;color:var(--text-2);margin-top:6px;">
            <strong style="color:var(--accent);"><?= count($pendientes) ?></strong> estudiante(s) encontrado(s)
          </div>
        </form>

        <div class="tbl-wrap p-0" style="max-height:68vh;overflow-y:auto;">
          <?php if (empty($pendientes)): ?>
            <div class="p-4 text-center text-muted">Sin practicas para este filtro</div>
          <?php else: foreach ($pendientes as $p):
            $activo = $idPractica == $p['id_practica'];
            $ap     = $p['nota_final'] !== null && $p['nota_final'] >= $notaMinima;
          ?>
          <a href="calificaciones.php?id=<?= $p['id_practica'] ?>&lper=<?= $filtroListaPer ?>&lcar=<?= $filtroListaCar ?>"
             style="display:block;padding:12px 16px;border-bottom:1px solid var(--border);text-decoration:none;
                    background:<?= $activo ? 'var(--card-alt)' : 'transparent' ?>;
                    border-left:3px solid <?= $activo ? '#ec4899' : 'transparent' ?>;">
            <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
              <span style="font-size:12px;font-weight:700;color:var(--text);"><?= htmlspecialchars($p['estudiante']) ?></span>
              <?php if ($p['es_conval']): ?>
                <span style="display:inline-flex;align-items:center;gap:2px;background:#fff7ed;color:#c2410c;border:1px solid #fed7aa;border-radius:20px;font-size:9px;font-weight:700;padding:1px 6px;white-space:nowrap;"><i class="fa fa-rotate" style="font-size:8px;"></i> CONV</span>
              <?php else: ?>
                <span style="display:inline-flex;align-items:center;gap:2px;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;border-radius:20px;font-size:9px;font-weight:700;padding:1px 6px;white-space:nowrap;"><i class="fa fa-briefcase" style="font-size:8px;"></i> PPP</span>
              <?php endif; ?>
            </div>
            <div style="font-size:11px;color:var(--text-2);"><?= htmlspecialchars($p['empresa']) ?></div>
            <div style="font-size:10px;color:var(--text-2);margin-top:2px;"><?= htmlspecialchars($p['carrera']) ?></div>
            <div class="d-flex justify-content-between align-items-center mt-1">
              <?= badgeEstado($p['estado']) ?>
              <?php if ($p['nota_final'] !== null): ?>
                <span style="font-size:14px;font-weight:800;color:<?= $ap ? 'var(--green)' : 'var(--red)' ?>;">
                  <?= number_format($p['nota_final'], 2) ?>/100
                </span>
              <?php else: ?>
                <span style="font-size:10px;color:#ec4899;font-weight:700;">SIN NOTA</span>
              <?php endif; ?>
            </div>
          </a>
          <?php endforeach; endif; ?>
        </div>
      </div>

      <!-- Panel principal -->
      <div class="col-lg-8">
        <?php if (!$practica): ?>
          <div class="tbl-wrap p-5 text-center" style="color:var(--text-2);">
            <div style="font-size:48px;margin-bottom:16px;">&#128072;</div>
            <div>Selecciona un estudiante</div>
          </div>
        <?php else:
          $nota    = $practica['nota_final'];
          $aprueba = $nota !== null && $nota >= $notaMinima;
          // nota_empresa_100 es escala 0-100; nota_tutor_empresa es 0-10 (convertida)
          $nEmp    = $practica['nota_empresa_100'] !== null ? (float)$practica['nota_empresa_100'] : ($practica['nota_tutor_empresa'] !== null ? (float)$practica['nota_tutor_empresa'] * 10 : null);
          $nTut    = $practica['nota_tutor_academico'] !== null ? (float)$practica['nota_tutor_academico'] : null;
          $aEmp    = $nEmp !== null ? round($nEmp * 0.30, 2) : null;
          $aTut    = $nTut !== null ? round($nTut * 0.25, 2) : null;
        ?>

        <!-- Encabezado estudiante -->
        <div class="tbl-wrap p-3 mb-3" style="border-left:4px solid #ec4899;">
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
            <div>
              <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                <span style="font-size:16px;font-weight:800;"><?= htmlspecialchars($practica['estudiante']) ?></span>
                <?php if ($practica['es_conval']): ?>
                  <span style="display:inline-flex;align-items:center;gap:4px;background:#fff7ed;color:#c2410c;border:1px solid #fed7aa;border-radius:20px;font-size:11px;font-weight:700;padding:3px 10px;"><i class="fa fa-rotate fa-xs"></i> Convalidación PPP</span>
                <?php else: ?>
                  <span style="display:inline-flex;align-items:center;gap:4px;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;border-radius:20px;font-size:11px;font-weight:700;padding:3px 10px;"><i class="fa fa-briefcase fa-xs"></i> Práctica PPP</span>
                <?php endif; ?>
              </div>
              <div style="font-size:12px;color:var(--text-2);">
                <?= htmlspecialchars($practica['carrera']) ?> &middot; <?= htmlspecialchars($practica['empresa']) ?>
              </div>
              <div style="font-size:11px;color:var(--text-2);margin-top:4px;">
                &#128211; <?= $practica['bit_validadas'] ?>/<?= $practica['bit_total'] ?> bitacoras &middot;
                &#9201; <?= $practica['horas_validadas'] ?>/<?= $horasMin ?>h
              </div>
            </div>
            <?php if ($nota !== null): ?>
            <div style="text-align:center;">
              <div style="font-size:28px;font-weight:900;color:<?= $aprueba ? 'var(--green)' : 'var(--red)' ?>;">
                <?= number_format($nota, 2) ?>/100
              </div>
              <div style="font-size:11px;font-weight:700;color:<?= $aprueba ? 'var(--green)' : 'var(--red)' ?>;">
                <?= $aprueba ? '&#9989; APROBADO' : '&#10060; REPROBADO' ?>
              </div>
            </div>
            <?php endif; ?>
          </div>
        </div>

        <form method="POST" id="formCalif">
          <input type="hidden" name="id_practica" value="<?= $practica['id_practica'] ?>">
          <div class="tbl-wrap p-4 mb-3">

            <!-- Leyenda -->
            <div class="d-flex gap-3 mb-3 flex-wrap" style="font-size:11px;">
              <span style="background:#dbeafe;color:#1d4ed8;padding:3px 10px;border-radius:20px;font-weight:700;">
                &#9998; Gestor PPP
              </span>
              <span style="background:#e5e7eb;color:#6b7280;padding:3px 10px;border-radius:20px;font-weight:700;">
                &#128274; Evaluador externo (solo lectura)
              </span>
            </div>

            <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--text-2);margin-bottom:16px;">
              Rubrica &mdash; cada componente se califica sobre 100, el sistema aplica el porcentaje
            </div>

            <div class="row g-3">

              <!-- BITACORAS editable -->
              <div class="col-sm-6">
                <div style="background:var(--card-alt);border-radius:var(--r-lg);padding:14px;border-top:3px solid #4fc3f7;">
                  <label style="font-size:11px;font-weight:700;color:var(--text-2);text-transform:uppercase;letter-spacing:.5px;">
                    &#128211; Bitacoras semanales
                    <span style="color:#4fc3f7;">(20 pts &middot; 20%)</span>
                  </label>
                  <input type="number" name="nota_bitacoras"
                         class="form-control nota-input mt-2"
                         data-peso="20" min="0" max="100" step="0.5"
                         value="<?= htmlspecialchars($practica['nota_bitacoras'] ?? '') ?>"
                         placeholder="0 - 100"
                         style="font-size:22px;font-weight:800;text-align:center;background:var(--card);border-color:#4fc3f744;color:#4fc3f7;height:60px;">
                  <div style="font-size:10px;color:var(--text-2);text-align:right;margin-top:4px;">
                    Aporta: <span class="val-aport" style="font-weight:700;color:#4fc3f7;">--</span> pts al total
                  </div>
                </div>
              </div>

              <!-- INFORME editable -->
              <div class="col-sm-6">
                <div style="background:var(--card-alt);border-radius:var(--r-lg);padding:14px;border-top:3px solid #ab47bc;">
                  <label style="font-size:11px;font-weight:700;color:var(--text-2);text-transform:uppercase;letter-spacing:.5px;">
                    &#128196; Informe final CES
                    <span style="color:#ab47bc;">(25 pts &middot; 25%)</span>
                  </label>
                  <input type="number" name="nota_informe"
                         class="form-control nota-input mt-2"
                         data-peso="25" min="0" max="100" step="0.5"
                         value="<?= htmlspecialchars($practica['nota_informe'] ?? '') ?>"
                         placeholder="0 - 100"
                         style="font-size:22px;font-weight:800;text-align:center;background:var(--card);border-color:#ab47bc44;color:#ab47bc;height:60px;">
                  <div style="font-size:10px;color:var(--text-2);text-align:right;margin-top:4px;">
                    Aporta: <span class="val-aport" style="font-weight:700;color:#ab47bc;">--</span> pts al total
                  </div>
                </div>
              </div>

              <!-- EMPRESA solo lectura -->
              <div class="col-sm-6">
                <div class="comp-readonly <?= $nEmp === null ? 'comp-pendiente' : '' ?>" style="border-top:3px solid #ff7043;">
                  <span class="lock-badge"><i class="fa fa-lock me-1"></i>Tutor empresa</span>
                  <label style="font-size:11px;font-weight:700;color:var(--text-2);text-transform:uppercase;letter-spacing:.5px;">
                    &#127970; Evaluacion empresa
                    <span style="color:#ff7043;">(30 pts &middot; 30%)</span>
                  </label>
                  <?php if ($nEmp !== null): ?>
                    <div class="comp-valor" style="color:#ff7043;">
                      <?= number_format($nEmp, 2) ?><span style="font-size:16px;color:var(--text-2);">/100</span>
                    </div>
                    <div class="comp-aporte">
                      Aporta: <span style="color:#ff7043;"><?= number_format($aEmp, 2) ?></span> pts
                      <span style="font-weight:400;">(<?= number_format($nEmp, 2) ?> x 30%)</span>
                    </div>
                    <input type="hidden" class="nota-readonly" data-peso="30" value="<?= $nEmp ?>">
                  <?php else: ?>
                    <div class="comp-valor">&#9203; Pendiente de evaluacion</div>
                    <div class="comp-aporte">El tutor empresa aun no ha calificado</div>
                    <input type="hidden" class="nota-readonly" data-peso="30" value="">
                  <?php endif; ?>
                </div>
              </div>

              <!-- TUTOR ACADEMICO solo lectura -->
              <div class="col-sm-6">
                <div class="comp-readonly <?= $nTut === null ? 'comp-pendiente' : '' ?>" style="border-top:3px solid #66bb6a;">
                  <span class="lock-badge"><i class="fa fa-lock me-1"></i>Tutor academico</span>
                  <label style="font-size:11px;font-weight:700;color:var(--text-2);text-transform:uppercase;letter-spacing:.5px;">
                    &#128104;&#8205;&#127979; Evaluacion tutor academico
                    <span style="color:#66bb6a;">(25 pts &middot; 25%)</span>
                  </label>
                  <?php if ($nTut !== null): ?>
                    <div class="comp-valor" style="color:#66bb6a;">
                      <?= number_format($nTut, 2) ?><span style="font-size:16px;color:var(--text-2);">/100</span>
                    </div>
                    <div class="comp-aporte">
                      Aporta: <span style="color:#66bb6a;"><?= number_format($aTut, 2) ?></span> pts
                      <span style="font-weight:400;">(<?= number_format($nTut, 2) ?> x 25%)</span>
                    </div>
                    <input type="hidden" class="nota-readonly" data-peso="25" value="<?= $nTut ?>">
                  <?php else: ?>
                    <div class="comp-valor">&#9203; Pendiente de evaluacion</div>
                    <div class="comp-aporte">El tutor academico aun no ha calificado</div>
                    <input type="hidden" class="nota-readonly" data-peso="25" value="">
                  <?php endif; ?>
                </div>
              </div>

            </div><!-- /row -->

            <!-- Preview nota final -->
            <div class="mt-4 p-3" style="background:var(--card);border-radius:var(--r-lg);border:2px solid var(--border);">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <div style="font-size:11px;color:var(--text-2);text-transform:uppercase;">Nota final calculada</div>
                  <div style="font-size:10px;color:var(--text-2);">Bit x20% + Inf x25% + Emp x30% + Tut x25%</div>
                  <div id="msgPendiente" style="font-size:11px;color:#d97706;margin-top:4px;display:none;">
                    &#9888; La nota final se calculara cuando empresa y tutor completen su evaluacion
                  </div>
                </div>
                <div>
                  <span id="notaPreview" style="font-size:42px;font-weight:900;color:var(--accent);">--</span>
                  <span style="font-size:16px;color:var(--text-2);">/100</span>
                </div>
              </div>
              <div style="margin-top:10px;background:var(--border);border-radius:6px;height:10px;overflow:hidden;">
                <div id="barraPreview" style="height:10px;border-radius:6px;background:var(--accent);width:0%;transition:width .3s;"></div>
              </div>
              <div id="estadoPreview" style="font-size:13px;font-weight:700;margin-top:8px;text-align:right;"></div>
            </div>

            <div class="mt-3">
              <label class="form-label">Observaciones para el estudiante (opcional)</label>
              <textarea name="observaciones_gestor" class="form-control" rows="3"
                        placeholder="Comentarios visibles al estudiante..."><?= htmlspecialchars($practica['observaciones_gestor'] ?? '') ?></textarea>
            </div>
          </div>

          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="fa fa-save me-2"></i>Guardar calificacion
            </button>
            <a href="practicas.php" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </form>
        <?php endif; ?>
      </div>
    </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 ?>';
var NOTA_MIN = <?= $notaMinima ?>;

$(function () {
  function calc() {
    var tot = 0, allReady = true, hasReadonlyPending = false;

    // Campos editables del gestor (Bitacoras e Informe)
    $('.nota-input').each(function () {
      var v    = parseFloat($(this).val());
      var peso = parseInt($(this).data('peso'));
      var aport = isNaN(v) ? '--' : (v * peso / 100).toFixed(2);
      $(this).closest('div[style]').find('.val-aport').text(aport);
      if (isNaN(v)) { allReady = false; return; }
      tot += v * peso / 100;
    });

    // Campos de solo lectura (Empresa y Tutor)
    $('.nota-readonly').each(function () {
      var val  = $(this).val();
      var v    = parseFloat(val);
      var peso = parseInt($(this).data('peso'));
      if (val === '' || isNaN(v)) {
        allReady = false;
        hasReadonlyPending = true;
        return;
      }
      tot += v * peso / 100;
    });

    if (!allReady) {
      $('#notaPreview').text('--').css('color', 'var(--accent)');
      $('#barraPreview').css('width', '0%');
      $('#estadoPreview').text('');
      $('#msgPendiente').toggle(hasReadonlyPending);
      return;
    }

    $('#msgPendiente').hide();
    tot = Math.round(tot * 100) / 100;
    var c = tot >= NOTA_MIN ? 'var(--green)' : 'var(--red)';
    $('#notaPreview').text(tot.toFixed(2)).css('color', c);
    $('#barraPreview').css({'width': tot + '%', 'background': c});
    $('#estadoPreview')
      .text((tot >= NOTA_MIN ? 'APROBADO' : 'REPROBADO') + ' (min. ' + NOTA_MIN + '/100)')
      .css('color', c);
  }

  $('.nota-input').on('input', calc);
  calc();
});
</script>
</body></html>