<?php
/**
 * GET — Lista de médicos solicitantes.
 */
require_once __DIR__ . '/../../../config/config.php';
if (!isUserLoggedIn()) { http_response_code(401); echo json_encode(['ok'=>false,'error'=>'No autorizado']); exit; }

header('Content-Type: application/json');

$pdo    = Database::getInstance()->getConnection();
$buscar = trim($_GET['q'] ?? '');
$page   = max(1, (int)($_GET['page']  ?? 1));
$limit  = max(1, min(200, (int)($_GET['limit'] ?? 25)));
$offset = ($page - 1) * $limit;

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

if ($buscar !== '') {
    $like   = '%' . $buscar . '%';
    $where  = "WHERE nombres LIKE ? OR apellidos LIKE ? OR codigo LIKE ? OR docidmedico LIKE ?";
    $params = [$like, $like, $like, $like];
}

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM medicos $where");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

$dataStmt = $pdo->prepare(
    "SELECT id, codigo, nombres, apellidos, telefonos, email, cod_especialidad, docidmedico, activo
       FROM medicos $where
      ORDER BY apellidos, nombres
      LIMIT $limit OFFSET $offset"
);
$dataStmt->execute($params);

echo json_encode([
    'ok'    => true,
    'data'  => $dataStmt->fetchAll(PDO::FETCH_ASSOC),
    'total' => $total,
    'page'  => $page,
    'limit' => $limit,
]);
