<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'flash.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'OneDriveStorage.php';
requireRol(ROL_TUTOR);
$idInst = instId();

$user      = currentUser();
$db        = getDB();
$pageTitle = 'Bitácoras PPP';

// ── Tutor ────────────────────────────────────────────────────
$stTutor = $db->prepare("SELECT id_tutor FROM tutores WHERE id_usuario = :uid");
$stTutor->execute([':uid' => $user['id']]);
$tutor = $stTutor->fetch();

// ── Variables inicializadas SIEMPRE ─────────────────────────
$bitPendientes = [];
$totalEst      = 0;
$totalVal      = 0;
$totalObs      = 0;
$periodos      = [];
$carreras      = [];
$totalRegistros = 0;
$totalPaginas   = 1;

// ── Filtros GET ──────────────────────────────────────────────
$filtroPeriodo = trim($_GET['periodo'] ?? '');
$filtroCarrera = trim($_GET['carrera'] ?? '');
$filtroEstado  = trim($_GET['estado']  ?? '');
$_pp           = (int)($_GET['pp']  ?? 25);
$porPagina     = in_array($_pp, [25,50,100,200]) ? $_pp : 25;
$pagina        = max(1, (int)($_GET['pag'] ?? 1));

if ($tutor) {
    $tid = $tutor['id_tutor'];

    // ── Combos de filtro (desde practicas, no bitacoras) ────
    $stPer = $db->prepare("
        SELECT DISTINCT pe.id_periodo, pe.nombre
        FROM practicas pr
        JOIN periodos_academicos pe ON pe.id_periodo = pr.id_periodo
        WHERE pr.id_tutor = :tid
        ORDER BY pe.nombre DESC
    ");
    $stPer->execute([':tid' => $tid]);
    $periodos = $stPer->fetchAll();

    $stCar = $db->prepare("
        SELECT DISTINCT c.id_carrera, c.nombre
        FROM practicas pr
        JOIN estudiantes e ON e.id_estudiante = pr.id_estudiante
        JOIN carreras c    ON c.id_carrera    = e.id_carrera
        WHERE pr.id_tutor = :tid
        ORDER BY c.nombre ASC
    ");
    $stCar->execute([':tid' => $tid]);
    $carreras = $stCar->fetchAll();

    // ── WHERE dinámico ───────────────────────────────────────
    $where  = "WHERE pr.id_tutor = :tid";
    $params = [':tid' => $tid];

    if ($filtroPeriodo !== '') {
        $where .= " AND pe.id_periodo = :pid";
        $params[':pid'] = $filtroPeriodo;
    } else {
        $where .= " AND pe.activo = 1";
    }
    if ($filtroCarrera !== '') {
        $where .= " AND c.id_carrera = :cid";
        $params[':cid'] = $filtroCarrera;
    }
    if ($filtroEstado !== '') {
        $where .= " AND b.estado = :est";
        $params[':est'] = $filtroEstado;
    }

    $sqlBase = "
        FROM   bitacoras b
        JOIN   practicas pr  ON pr.id_practica  = b.id_practica
        JOIN   estudiantes e ON e.id_estudiante = pr.id_estudiante
        JOIN   usuarios uu   ON uu.id_usuario   = e.id_usuario
        JOIN   carreras c    ON c.id_carrera    = e.id_carrera
        LEFT JOIN empresas em ON em.id_empresa  = pr.id_empresa
        JOIN   periodos_academicos pe ON pe.id_periodo = pr.id_periodo
        $where
    ";

    // Total
    $stCount = $db->prepare("SELECT COUNT(*) $sqlBase");
    $stCount->execute($params);
    $totalRegistros = (int)$stCount->fetchColumn();
    $totalPaginas   = $totalRegistros > 0 ? max(1, (int)ceil($totalRegistros / $porPagina)) : 1;
    $pagina         = min($pagina, $totalPaginas);
    $offset         = ($pagina - 1) * $porPagina;

    // Bitácoras paginadas
    $paramsPag = $params;
    $paramsPag[':lim'] = $porPagina;
    $paramsPag[':off'] = $offset;
    $stPend = $db->prepare("
        SELECT b.id_bitacora, b.semana_numero, b.horas_semana, b.estado,
               b.actividades, b.logros, b.dificultades, b.created_at,
               CONCAT(uu.nombres,' ',uu.apellidos) AS estudiante,
               c.nombre AS carrera,
               COALESCE(em.razon_social, pr.emp_nueva_nombre) AS empresa,
               pe.nombre AS periodo
        $sqlBase
        ORDER  BY b.created_at DESC
        LIMIT  :lim OFFSET :off
    ");
    $stPend->execute($paramsPag);
    $bitPendientes = $stPend->fetchAll();

    // ── Resolver URLs de fotos OneDrive en cada bitácora ──────────────────
    foreach ($bitPendientes as &$b) {
        if (empty($b['actividades'])) continue;
        $dias = json_decode($b['actividades'], true);
        if (!is_array($dias)) continue;
        $cambiado = false;
        foreach ($dias as &$dia) {
            $fotoRaw = trim($dia['foto'] ?? '');
            if ($fotoRaw === '') continue;
            if (OneDriveStorage::esOneDrive($fotoRaw)) {
                try {
                    $dia['foto'] = OneDriveStorage::getDownloadUrl($fotoRaw);
                    $cambiado = true;
                } catch (Throwable) {}
            } else {
                // ruta local — construir URL completa
                $dia['foto'] = BASE_URL . '/assets/uploads/' . ltrim($fotoRaw, '/');
                $cambiado = true;
            }
        }
        unset($dia);
        if ($cambiado) $b['actividades'] = json_encode($dias, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    unset($b);

    // Contadores globales
    $stStats = $db->prepare("
        SELECT b.estado, COUNT(*) AS total
        FROM   bitacoras b
        JOIN   practicas pr ON pr.id_practica = b.id_practica
        WHERE  pr.id_tutor = :tid
        GROUP  BY b.estado
    ");
    $stStats->execute([':tid' => $tid]);
    $stats    = array_column($stStats->fetchAll(), 'total', 'estado');
    $totalVal = (int)($stats['validada']  ?? 0);
    $totalObs = (int)($stats['observada'] ?? 0);

    $stEst = $db->prepare("
        SELECT COUNT(DISTINCT pr.id_estudiante) AS total
        FROM   practicas pr
        WHERE  pr.id_tutor = :tid
          AND  pr.estado IN ('aprobado','en_progreso','informe_enviado')
    ");
    $stEst->execute([':tid' => $tid]);
    $totalEst = (int)$stEst->fetchColumn();
}

// Acción validar/observar
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $tutor) {
    $id     = (int)($_POST['id_bitacora'] ?? 0);
    $accion = in_array($_POST['accion'] ?? '', ['validada','observada']) ? $_POST['accion'] : null;
    $coment = trim($_POST['comentario'] ?? '');
    if ($id && $accion) {
        $db->prepare("UPDATE bitacoras SET estado=:e, comentario_tutor=:c, fecha_validacion=NOW() WHERE id_bitacora=:id")
           ->execute([':e' => $accion, ':c' => $coment, ':id' => $id]);
        registrarAudit($user['id'], $accion.'_bitacora', 'bitacoras', $id);
        flashSet('ok', $accion === 'validada' ? 'Bitácora validada.' : 'Observación enviada al estudiante.');
    }
    header('Location: bitacoras.php?' . http_build_query([
        'periodo'=>$filtroPeriodo,'carrera'=>$filtroCarrera,'estado'=>$filtroEstado,'pp'=>$porPagina,'pag'=>$pagina
    ]));
    exit;
}

function urlBit(array $extra = []): string {
    global $filtroPeriodo, $filtroCarrera, $filtroEstado, $porPagina, $pagina;
    $base = ['periodo'=>$filtroPeriodo,'carrera'=>$filtroCarrera,'estado'=>$filtroEstado,'pp'=>$porPagina,'pag'=>$pagina];
    return 'bitacoras.php?' . http_build_query(array_merge($base, $extra));
}
?>
<?php $paginaActual = 'bitacoras'; ?>
<!DOCTYPE html>
<html lang="es">
<head><?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar.css">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-tutor.css">
<style>
.filtros-bar {
  display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end;
  background:#fff; border:1px solid #e2e8f0; border-radius:12px;
  padding:14px 16px; margin-bottom:20px;
}
.filtros-bar label { font-size:11px; font-weight:700; text-transform:uppercase;
  letter-spacing:.5px; color:#64748b; margin-bottom:3px; display:block; }
.filtros-bar select {
  border:1.5px solid #e2e8f0; border-radius:8px; padding:6px 10px;
  font-size:13px; background:#f8fafc; color:#1e293b; min-width:150px; cursor:pointer;
}
.filtros-bar select:focus { outline:none; border-color:#2ea8ff; box-shadow:0 0 0 3px rgba(46,168,255,.12); }
.btn-filtrar {
  background:linear-gradient(135deg,#0f1f3d,#2ea8ff); border:none;
  border-radius:8px; color:#fff; font-size:13px; font-weight:600;
  padding:7px 18px; cursor:pointer; transition:opacity .2s;
}
.btn-filtrar:hover { opacity:.88; }
.btn-limpiar {
  background:none; border:1.5px solid #e2e8f0; border-radius:8px;
  color:#64748b; font-size:13px; padding:6px 14px; cursor:pointer;
  text-decoration:none; display:inline-flex; align-items:center; transition:all .2s;
}
.btn-limpiar:hover { border-color:#94a3b8; color:#334155; }
.paginacion {
  display:flex; align-items:center; justify-content:space-between;
  flex-wrap:wrap; gap:10px; margin-top:12px; padding:8px 4px;
}
.pag-info { font-size:12px; color:#64748b; }
.pag-btns { display:flex; gap:4px; flex-wrap:wrap; }
.pag-btn {
  min-width:34px; height:34px; border-radius:7px; border:1.5px solid #e2e8f0;
  background:#fff; color:#374151; font-size:13px; font-weight:500;
  display:flex; align-items:center; justify-content:center;
  cursor:pointer; text-decoration:none; transition:all .15s;
}
.pag-btn:hover { border-color:#2ea8ff; color:#2ea8ff; }
.pag-btn.active { background:#2ea8ff; border-color:#2ea8ff; color:#fff; font-weight:700; }
.pag-btn.disabled { opacity:.4; pointer-events:none; }
.pp-sel { border:1.5px solid #e2e8f0; border-radius:7px; padding:5px 8px;
  font-size:12px; background:#f8fafc; color:#374151; cursor:pointer; }
</style>
</head>
<body>
<?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'navbar.php'; ?>

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

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

    <div class="page-header">
      <h4>Bitácoras PPP</h4>
      <p>Revisa, valida u observa las bitácoras de tus estudiantes</p>
    </div>

    <?php if (!$tutor): ?>
    <div class="alert-dark-danger p-3 mb-4">
      <i class="fa fa-circle-exclamation me-2"></i>
      Tu cuenta no tiene un perfil de tutor configurado. Contacta al administrador.
    </div>
    <?php else: ?>

    <!-- Stat cards -->
    <div class="row g-3 mb-4">
      <div class="col-6 col-lg-3">
        <div class="stat-card"><div><div class="stat-num" style="color:#2ea8ff;"><?= $totalEst ?></div><div class="stat-label">Estudiantes activos</div></div><div class="stat-icon">🎓</div></div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="stat-card"><div><div class="stat-num" style="color:#f7b93e;"><?= count(array_filter($bitPendientes, fn($b) => $b['estado']==='enviada')) ?></div><div class="stat-label">Pendientes de validar</div></div><div class="stat-icon">📬</div></div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="stat-card"><div><div class="stat-num" style="color:#3dffa0;"><?= $totalVal ?></div><div class="stat-label">Validadas (total)</div></div><div class="stat-icon">✅</div></div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="stat-card"><div><div class="stat-num" style="color:#ff9d93;"><?= $totalObs ?></div><div class="stat-label">Con observaciones</div></div><div class="stat-icon">💬</div></div>
      </div>
    </div>

    <!-- Filtros -->
    <form method="GET" action="bitacoras.php" class="filtros-bar">
      <div>
        <label>Ciclo / Período</label>
        <select name="periodo">
          <option value="">Período activo</option>
          <?php foreach ($periodos as $p): ?>
            <option value="<?= $p['id_periodo'] ?>" <?= $filtroPeriodo == $p['id_periodo'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($p['nombre']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Carrera</label>
        <select name="carrera">
          <option value="">Todas las carreras</option>
          <?php foreach ($carreras as $c): ?>
            <option value="<?= $c['id_carrera'] ?>" <?= $filtroCarrera == $c['id_carrera'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($c['nombre']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Estado</label>
        <select name="estado">
          <option value="">Todos</option>
          <option value="enviada"   <?= $filtroEstado==='enviada'  ?'selected':'' ?>>Pendientes</option>
          <option value="validada"  <?= $filtroEstado==='validada' ?'selected':'' ?>>Validadas</option>
          <option value="observada" <?= $filtroEstado==='observada'?'selected':'' ?>>Observadas</option>
          <option value="borrador"  <?= $filtroEstado==='borrador' ?'selected':'' ?>>Borrador</option>
        </select>
      </div>
      <div>
        <label>Mostrar</label>
        <select name="pp">
          <?php foreach ([25,50,100,200] as $n): ?>
            <option value="<?=$n?>" <?= $porPagina==$n?'selected':'' ?>><?=$n?> por página</option>
          <?php endforeach; ?>
        </select>
      </div>
      <input type="hidden" name="pag" value="1">
      <button type="submit" class="btn-filtrar"><i class="fa fa-filter me-1"></i>Filtrar</button>
      <a href="bitacoras.php" class="btn-limpiar"><i class="fa fa-xmark me-1"></i>Limpiar</a>
    </form>

    <!-- Tabla -->
    <div class="tbl-wrap mb-3">
      <table class="table table-borderless mb-0">
        <thead>
          <tr>
            <th>#</th>
            <th>Estudiante</th>
            <th>Carrera</th>
            <th>Empresa</th>
            <th>Período</th>
            <th>Semana</th>
            <th>Horas</th>
            <th>Estado</th>
            <th>Enviada</th>
            <th>Acciones</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($bitPendientes)): ?>
          <tr>
            <td colspan="10" class="text-center py-5">
              <div style="font-size:28px;margin-bottom:8px;">🎉</div>
              <div style="color:#8b949e;font-size:13px;">Sin bitácoras con los filtros seleccionados.</div>
            </td>
          </tr>
          <?php else: foreach ($bitPendientes as $i => $b):
            $num = ($pagina - 1) * $porPagina + $i + 1;
          ?>
          <tr>
            <td style="color:#8b949e;font-size:12px;"><?= $num ?></td>
            <td><strong style="font-size:13px;"><?= htmlspecialchars($b['estudiante']) ?></strong></td>
            <td style="font-size:12px;color:#8b949e;"><?= htmlspecialchars($b['carrera']) ?></td>
            <td style="font-size:12px;color:#8b949e;"><?= htmlspecialchars($b['empresa'] ?? '—') ?></td>
            <td style="font-size:12px;color:#8b949e;"><?= htmlspecialchars($b['periodo']) ?></td>
            <td><strong>Sem. <?= $b['semana_numero'] ?></strong></td>
            <td style="font-weight:600;"><?= $b['horas_semana'] ?>h</td>
            <td><?= badgeEstado($b['estado']) ?></td>
            <td style="font-size:12px;color:#8b949e;"><?= date('d/m/Y H:i', strtotime($b['created_at'])) ?></td>
            <td>
              <div class="d-flex gap-1">
                <button class="btn btn-sm btn-outline-secondary btn-ver"
                  data-id="<?= $b['id_bitacora'] ?>"
                  data-estudiante="<?= htmlspecialchars($b['estudiante']) ?>"
                  data-semana="<?= $b['semana_numero'] ?>"
                  data-horas="<?= $b['horas_semana'] ?>"
                  data-actividades="<?= htmlspecialchars($b['actividades']) ?>"
                  data-logros="<?= htmlspecialchars($b['logros'] ?? '') ?>"
                  data-dificultades="<?= htmlspecialchars($b['dificultades'] ?? '') ?>">
                  <i class="fa fa-eye me-1"></i>Ver
                </button>
                <?php if ($b['estado'] === 'enviada'): ?>
                <button class="btn btn-sm btn-success btn-validar-rapido"
                  data-id="<?= $b['id_bitacora'] ?>" title="Validar sin comentario">
                  <i class="fa fa-check"></i>
                </button>
                <?php endif; ?>
              </div>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

    <!-- Paginación -->
    <?php if ($totalRegistros > 0): ?>
    <div class="paginacion">
      <div class="pag-info">
        Mostrando <?= (($pagina-1)*$porPagina)+1 ?>–<?= min($pagina*$porPagina, $totalRegistros) ?>
        de <?= $totalRegistros ?> bitácoras &nbsp;|&nbsp;
        <select class="pp-sel" onchange="cambiarPP(this.value)">
          <?php foreach ([25,50,100,200] as $n): ?>
            <option value="<?=$n?>" <?= $porPagina==$n?'selected':'' ?>><?=$n?>/pág</option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="pag-btns">
        <a class="pag-btn <?= $pagina<=1?'disabled':'' ?>" href="<?= urlBit(['pag'=>$pagina-1]) ?>">
          <i class="fa fa-chevron-left fa-xs"></i>
        </a>
        <?php
          $ini = max(1, $pagina-2); $fin = min($totalPaginas, $pagina+2);
          if ($ini>1) echo '<a class="pag-btn" href="'.urlBit(['pag'=>1]).'">1</a>';
          if ($ini>2) echo '<span class="pag-btn disabled">…</span>';
          for ($p=$ini; $p<=$fin; $p++)
            echo '<a class="pag-btn'.($p==$pagina?' active':'').'" href="'.urlBit(['pag'=>$p]).'">'.$p.'</a>';
          if ($fin<$totalPaginas-1) echo '<span class="pag-btn disabled">…</span>';
          if ($fin<$totalPaginas)   echo '<a class="pag-btn" href="'.urlBit(['pag'=>$totalPaginas]).'">'.$totalPaginas.'</a>';
        ?>
        <a class="pag-btn <?= $pagina>=$totalPaginas?'disabled':'' ?>" href="<?= urlBit(['pag'=>$pagina+1]) ?>">
          <i class="fa fa-chevron-right fa-xs"></i>
        </a>
      </div>
    </div>
    <?php endif; ?>

    <?php endif; // fin if($tutor) ?>
  </main>
</div>

<!-- Modal Ver Bitácora -->
<div class="modal fade" id="modalBit" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="m-titulo">Bitácora</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-2 mb-3" style="font-size:13px;">
          <div class="col-4">
            <div style="font-size:10px;color:#8b949e;text-transform:uppercase;">Estudiante</div>
            <div id="m-est" style="font-weight:600;"></div>
          </div>
          <div class="col-4">
            <div style="font-size:10px;color:#8b949e;text-transform:uppercase;">Semana</div>
            <div id="m-sem"></div>
          </div>
          <div class="col-4">
            <div style="font-size:10px;color:#8b949e;text-transform:uppercase;">Horas</div>
            <div id="m-hrs" style="font-weight:700;"></div>
          </div>
        </div>
        <hr style="border-color:#30363d;">
        <div class="mb-3">
          <div class="form-label">Actividades</div>
          <div id="m-act" style="background:#0d1117;border:1px solid #30363d;border-radius:8px;
                                  padding:12px;font-size:13px;white-space:pre-wrap;line-height:1.7;"></div>
        </div>
        <div class="mb-3" id="blk-log">
          <div class="form-label">Logros</div>
          <div id="m-log" style="background:#0d1117;border:1px solid #30363d;border-radius:8px;
                                  padding:12px;font-size:13px;white-space:pre-wrap;line-height:1.7;"></div>
        </div>
        <div class="mb-3" id="blk-dif">
          <div class="form-label">Dificultades</div>
          <div id="m-dif" style="background:#0d1117;border:1px solid #30363d;border-radius:8px;
                                  padding:12px;font-size:13px;white-space:pre-wrap;line-height:1.7;"></div>
        </div>
        <hr style="border-color:#30363d;">
        <form method="POST" id="formAcc">
          <input type="hidden" name="id_bitacora" id="f-bid">
          <div class="mb-3">
            <label class="form-label">Comentario para el estudiante <small style="color:#8b949e;">(opcional)</small></label>
            <textarea name="comentario" id="f-com" class="form-control" rows="3"
                      placeholder="Retroalimentación, observaciones..."></textarea>
          </div>
          <div class="d-flex gap-2">
            <button type="submit" name="accion" value="validada" class="btn btn-success flex-fill">
              <i class="fa fa-circle-check me-2"></i>Validar
            </button>
            <button type="submit" name="accion" value="observada" class="btn btn-outline-secondary flex-fill">
              <i class="fa fa-message me-2"></i>Observar
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Modal Foto Evidencia -->
<div class="modal fade" id="modalFotoEvidencia" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content" style="background:#0d1117;border:1px solid #30363d;">
      <div class="modal-header" style="border-bottom:1px solid #30363d;padding:12px 16px;">
        <h6 class="modal-title" style="color:#f0f6fc;"><i class="fa fa-camera me-2" style="color:#2ea8ff;"></i>Foto de evidencia</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center" style="padding:16px;">
        <img id="fotoEvidenciaGrande" src="" alt="Evidencia" style="max-width:100%;max-height:75vh;border-radius:10px;object-fit:contain;">
      </div>
      <div class="modal-footer" style="border-top:1px solid #30363d;padding:10px 16px;">
        <a id="fotoEvidenciaDescarga" href="#" download target="_blank" class="btn btn-sm btn-outline-secondary">
          <i class="fa fa-download me-1"></i>Descargar
        </a>
        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</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 ?>';

function cambiarPP(val) {
  var url = new URL(window.location.href);
  url.searchParams.set('pp', val);
  url.searchParams.set('pag', '1');
  window.location.href = url.toString();
}

function verFotoEvidencia(url) {
  document.getElementById('fotoEvidenciaGrande').src = url;
  document.getElementById('fotoEvidenciaDescarga').href = url;
  new bootstrap.Modal(document.getElementById('modalFotoEvidencia')).show();
}

$(function () {

  $(document).on('click', '.btn-ver', function () {
    var d = $(this).data();
    $('#m-titulo').text('Bitácora — Semana ' + d.semana);
    $('#m-est').text(d.estudiante);
    $('#m-sem').text('Semana ' + d.semana);
    $('#m-hrs').text(d.horas + ' h');

    var act = d.actividades;
    var parsed = null;
    try { parsed = typeof act === 'string' ? JSON.parse(act) : act; } catch(e) {}

    if (Array.isArray(parsed) && parsed.length) {
      var diasNom = ['','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado','Domingo'];
      var thStyle = 'padding:6px 10px;border-bottom:2px solid #e2e8f0;color:#64748b;font-size:10px;font-weight:700;letter-spacing:.6px;text-transform:uppercase;background:#f8fafc;';
      var tbl = '<table style="width:100%;border-collapse:collapse;font-size:12.5px;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;">'
              + '<thead><tr>'
              + '<th style="'+thStyle+'">Fecha</th>'
              + '<th style="'+thStyle+'text-align:center;">Horas</th>'
              + '<th style="'+thStyle+'">Actividades</th>'
              + '<th style="'+thStyle+'">Logros</th>'
              + '<th style="'+thStyle+'">Dificultades</th>'
              + '<th style="'+thStyle+'text-align:center;">Evidencia</th>'
              + '</tr></thead><tbody>';
      $.each(parsed, function(i, dia) {
        var feriado  = parseInt(dia.horas) === 0;
        var dt       = new Date(dia.fecha + 'T12:00:00');
        var diaNom   = diasNom[dt.getDay() === 0 ? 7 : dt.getDay()];
        var fechaStr = dia.fecha.split('-').reverse().join('/');
        var rowBg    = feriado ? 'background:#fffbeb;' : (i%2===0 ? 'background:#fff;' : 'background:#f8fafc;');
        var tdB      = 'border-bottom:1px solid #e2e8f0;';
        tbl += '<tr style="'+rowBg+'">'
          + '<td style="padding:8px 10px;'+tdB+'">'
          +   '<strong style="color:#0f172a;">'+fechaStr+'</strong>'
          +   '<div style="font-size:10px;color:#94a3b8;">'+diaNom+'</div>'
          +   (feriado ? '<span style="font-size:9px;padding:1px 6px;border-radius:4px;background:#fef3c7;color:#d97706;font-weight:700;border:1px solid #fde68a;">FERIADO</span>' : '')
          + '</td>'
          + '<td style="padding:8px 10px;'+tdB+'text-align:center;font-weight:700;color:'+(feriado?'#d97706':'#2563eb')+';">'+(feriado?'—':dia.horas+'h')+'</td>'
          + '<td style="padding:8px 10px;'+tdB+'color:#1e293b;">'+(dia.descripcion||'<span style="color:#94a3b8;">—</span>')+'</td>'
          + '<td style="padding:8px 10px;'+tdB+'color:#059669;">'+(dia.logros||'<span style="color:#94a3b8;">—</span>')+'</td>'
          + '<td style="padding:8px 10px;'+tdB+'color:#d97706;">'+(dia.dificultades||'<span style="color:#94a3b8;">—</span>')+'</td>'
          + (dia.foto
            ? '<td style="padding:6px 10px;'+tdB+'text-align:center;"><img src="'+dia.foto+'" onclick="verFotoEvidencia(\'\'+dia.foto+\'\')" style="width:40px;height:40px;object-fit:cover;border-radius:6px;border:1px solid #e2e8f0;cursor:zoom-in;" title="Ver evidencia"></td>'
            : '<td style="padding:6px 10px;'+tdB+'text-align:center;"><span style="color:#94a3b8;font-size:11px;">—</span></td>')
          + '</tr>';
      });
      tbl += '</tbody></table>';
      $('#m-act').html(tbl);
      $('#blk-log,#blk-dif').hide();
    } else {
      $('#m-act').text(typeof act === 'string' ? act : '—');
      $('#m-log').text(d.logros || '—');
      $('#m-dif').text(d.dificultades || '—');
      $('#blk-log,#blk-dif').show();
    }

    $('#f-bid').val(d.id);
    $('#f-com').val('');
    new bootstrap.Modal('#modalBit').show();
  });

  $(document).on('click', '.btn-validar-rapido', function () {
    var $btn = $(this);
    if (!confirm('¿Validar esta bitácora sin comentario?')) return;
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    var $form = $('<form method="POST">');
    $form.append('<input name="id_bitacora" value="' + $btn.data('id') + '">');
    $form.append('<input name="accion" value="validada">');
    $form.append('<input name="comentario" value="">');
    $('body').append($form);
    $form.submit();
  });

});
</script>
</body>