<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../../app/auth.php';
require_once __DIR__ . '/../../app/rbac.php';

start_session();
require_login();

// Solo alumnos
if (!has_role('ALUMNO')) {
  http_response_code(403);
  die("Acceso no permitido");
}

$ids = allowed_student_ids();
if (count($ids) !== 1) {
  die("Alumno no vinculado correctamente.");
}

$estudianteId = $ids[0];
$anio = date('Y');

$pdo = db();

$stmt = $pdo->prepare(
  "SELECT fecha, hora_entrada, hora_salida, tardanza_min, presente
   FROM asistencia_diaria
   WHERE estudiante_id = ? AND anio_lectivo = ?
   ORDER BY fecha DESC
   LIMIT 60"
);
$stmt->execute([$estudianteId, $anio]);
$rows = $stmt->fetchAll();

$title = "Mi asistencia";
include __DIR__ . '/../../app/views/header.php';
?>

<h1 class="h5 mb-3">Mi asistencia</h1>

<div class="table-responsive">
<table class="table table-sm table-bordered bg-white">
  <thead class="table-light">
    <tr>
      <th>Fecha</th>
      <th>Entrada</th>
      <th>Salida</th>
      <th>Tardanza</th>
      <th>Estado</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($rows as $r): ?>
      <tr>
        <td><?= htmlspecialchars($r['fecha']) ?></td>
        <td><?= htmlspecialchars($r['hora_entrada'] ?? '-') ?></td>
        <td><?= htmlspecialchars($r['hora_salida'] ?? '-') ?></td>
        <td><?= (int)$r['tardanza_min'] ?> min</td>
        <td>
          <?php if ($r['presente']): ?>
            <span class="badge bg-success">Presente</span>
          <?php else: ?>
            <span class="badge bg-danger">Ausente</span>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

<?php include __DIR__ . '/../../app/views/footer.php'; ?>
