<?php
/**
 * GET ?q=&categoria=&page=&limit= — Catálogo de exámenes, paginado y filtrable.
 */
require_once __DIR__ . '/_helpers.php';
requireLogin();

$q          = trim($_GET['q']         ?? '');
$cat        = trim($_GET['categoria'] ?? '');
$page       = max(1, (int)($_GET['page']  ?? 1));
$limit      = max(1, min(200, (int)($_GET['limit'] ?? 50)));
$offset     = ($page - 1) * $limit;

$where  = [];
$params = [];

if ($q !== '') {
    $like     = '%' . $q . '%';
    $where[]  = '(nombre LIKE ? OR codigo LIKE ? OR cups LIKE ?)';
    $params[] = $like; $params[] = $like; $params[] = $like;
}
if ($cat !== '') {
    $where[]  = 'categoria = ?';
    $params[] = $cat;
}
$wSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$pdo = db();

$s = $pdo->prepare("SELECT COUNT(*) FROM exam_tipos $wSql");
$s->execute($params);
$total = (int)$s->fetchColumn();

$s = $pdo->prepare(
    "SELECT id, codigo, nombre, categoria, activo, cups, seremite, cod_protocolo, tipo_muestra
     FROM exam_tipos $wSql ORDER BY categoria, nombre LIMIT $limit OFFSET $offset"
);
$s->execute($params);

jsonOk(['data' => $s->fetchAll(PDO::FETCH_ASSOC), 'total' => $total, 'page' => $page, 'limit' => $limit]);
