<?php
declare(strict_types=1);

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

if (!(has_role('ADMIN') || has_role('DIRECTOR') || has_role('SECRETARIA') || has_role('ALUMNO') || has_role('TUTOR'))) {
  http_response_code(403);
  die("Acceso no permitido");
}

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

$boletinId = (int)($_GET['boletin'] ?? 0);
if ($boletinId <= 0) { http_response_code(400); die("Boletín inválido"); }

// Traer boletín + alumno + matrícula
$st = $pdo->prepare("
  SELECT
    b.*,
    m.estudiante_id, m.anio_lectivo, m.nivel, m.curso, COALESCE(m.seccion,'') AS seccion, m.turno,
    e.ci, e.apellidos, e.nombres
  FROM boletines b
  JOIN matriculas m ON m.id=b.matricula_id
  JOIN estudiantes e ON e.id=m.estudiante_id
  WHERE b.id=?
  LIMIT 1
");
$st->execute([$boletinId]);
$bol = $st->fetch(PDO::FETCH_ASSOC);
if (!$bol) { http_response_code(404); die("Boletín no encontrado"); }

$det = $pdo->prepare("
  SELECT bd.materia_id, ma.nombre AS materia, bd.promedio, bd.condicion, bd.observacion
  FROM boletin_detalle bd
  JOIN materias ma ON ma.id=bd.materia_id
  WHERE bd.boletin_id=?
  ORDER BY ma.nombre
");
$det->execute([$boletinId]);
$detalle = $det->fetchAll(PDO::FETCH_ASSOC) ?: [];

// Etapa label
$etapaNombre = null;
try {
  $stE = $pdo->prepare("SELECT nombre FROM etapas WHERE id=? LIMIT 1");
  $stE->execute([(int)$bol['etapa_id']]);
  $etapaNombre = $stE->fetchColumn() ?: null;
} catch(Throwable $e){}

?><!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Boletín #<?= (int)$boletinId ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial; margin:0; background:#f6f7fb;}
    .page{max-width:900px; margin:24px auto; background:#fff; padding:22px; border:1px solid #e9ecef; border-radius:14px;}
    .top{display:flex; justify-content:space-between; gap:14px; align-items:flex-start;}
    .h1{font-size:18px; font-weight:900; margin:0;}
    .muted{color:#6c757d; font-size:12px;}
    .box{border:1px solid #e9ecef; border-radius:12px; padding:12px;}
    table{width:100%; border-collapse:collapse; margin-top:12px;}
    th,td{border-bottom:1px solid #eee; padding:10px 8px; font-size:13px;}
    th{background:#f8f9fa; text-align:left; font-size:12px; color:#6c757d;}
    .right{text-align:right;}
    .badge{display:inline-block; padding:4px 10px; border-radius:999px; font-size:12px; border:1px solid #e9ecef;}
    .ok{background:#e7f7ef; border-color:#b7ebcf;}
    .bad{background:#fff0f1; border-color:#ffd0d6;}
    .printbar{display:flex; gap:10px; justify-content:flex-end; margin-top:12px;}
    .btn{border:1px solid #d0d7de; background:#fff; padding:8px 12px; border-radius:10px; cursor:pointer; font-weight:700;}
    @media print{
      body{background:#fff;}
      .page{margin:0; border:none; border-radius:0;}
      .printbar{display:none;}
    }
  </style>
</head>
<body>
  <div class="page">
    <div class="top">
      <div>
        <p class="h1">Boletín de calificaciones</p>
        <p class="muted">
          Año lectivo <?= (int)$bol['anio_lectivo'] ?> ·
          <?= h($etapaNombre ?: ('Etapa '.$bol['etapa_id'])) ?> ·
          Estado: <b><?= h($bol['estado'] ?? '-') ?></b>
        </p>
      </div>
      <div class="box">
        <div class="muted">Boletín #<?= (int)$boletinId ?></div>
        <div style="font-weight:900; font-size:14px;">
          <?= h(($bol['apellidos'] ?? '').' '.($bol['nombres'] ?? '')) ?>
        </div>
        <div class="muted">CI: <?= h($bol['ci'] ?? '-') ?></div>
        <div class="muted">
          <?= h(($bol['nivel'] ?? '').' '.($bol['curso'] ?? '').' '.($bol['seccion'] ?? '')) ?> · Turno <?= h($bol['turno'] ?? '-') ?>
        </div>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th>Materia</th>
          <th class="right">Promedio (%)</th>
          <th class="right">Condición</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($detalle)): ?>
          <tr><td colspan="3" class="muted">Sin detalle todavía (no se generó o no hay evaluaciones).</td></tr>
        <?php else: foreach($detalle as $d):
          $prom = $d['promedio']!==null ? (float)$d['promedio'] : null;
          $cond = (string)($d['condicion'] ?? '');
        ?>
          <tr>
            <td><b><?= h($d['materia']) ?></b></td>
            <td class="right"><?= $prom===null ? '-' : number_format($prom,2).'%' ?></td>
            <td class="right">
              <?php if ($cond==='APROBADO'): ?>
                <span class="badge ok">APROBADO</span>
              <?php elseif ($cond==='REPROBADO'): ?>
                <span class="badge bad">REPROBADO</span>
              <?php else: ?>
                <span class="badge">-</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>

    <div class="box" style="margin-top:12px;">
      <div class="muted">Resumen</div>
      <div style="display:flex; gap: