<?php
// api/transporte_list.php — Lista de empresas de transporte activas para <select> o Select2
declare(strict_types=1);

/* ===== Encabezados ===== */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(204); exit;
}

/* ===== Conexión ===== */
$pathConex = realpath(__DIR__ . '/../conex.php') ?: realpath(__DIR__ . '/../../conex.php') ?: realpath(__DIR__ . '/conex.php');
if (!$pathConex) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'No se encontró conex.php']); exit;
}
require_once $pathConex;

$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión a la BD']); exit;
}
mysqli_set_charset($db, 'utf8mb4');

/* ===== Parámetros =====
   q      : filtro por nombre (LIKE)
   limit  : cantidad de registros (por defecto 50)
   page   : para paginación estilo Select2 (1-based)
   select2: si =1, retorna formato {results:[{id,text}], pagination:{more}}
*/
$q       = trim((string)($_GET['q'] ?? ''));
$limit   = (int)($_GET['limit'] ?? 50);
$limit   = ($limit > 0 && $limit <= 500) ? $limit : 50;
$page    = max(1, (int)($_GET['page'] ?? 1));
$offset  = ($page - 1) * $limit;
$asSelect2 = (int)($_GET['select2'] ?? 0) === 1;

/* ===== SQL con filtros y paginación ===== */
$where = "t.condicion = 1";
$params = [];
$types  = "";

if ($q !== '') {
  $where .= " AND t.nombre LIKE ?";
  $params[] = "%{$q}%";
  $types   .= "s";
}

$sqlBase = "FROM tb_transporte t WHERE $where";

/* Total (para paginación) */
$sqlCount = "SELECT COUNT(*) ".$sqlBase;
$stmtC = $db->prepare($sqlCount);
if ($types !== "") $stmtC->bind_param($types, ...$params);
$stmtC->execute();
$stmtC->bind_result($total);
$stmtC->fetch();
$stmtC->close();

/* Página de datos */
$sql = "SELECT t.id, t.nombre, t.condicion ".$sqlBase." ORDER BY t.nombre ASC LIMIT ? OFFSET ?";
$stmt = $db->prepare($sql);

if ($types !== "") {
  $types2 = $types . "ii";
  $params2 = array_merge($params, [$limit, $offset]);
  $stmt->bind_param($types2, ...$params2);
} else {
  $stmt->bind_param("ii", $limit, $offset);
}

$stmt->execute();
$res = $stmt->get_result();

$data = [];
while ($row = $res->fetch_assoc()) {
  // Estructura base
  $data[] = [
    'id'        => (int)$row['id'],
    'nombre'    => (string)$row['nombre'],
    'condicion' => (int)$row['condicion']
  ];
}
$stmt->close();

/* ===== Salida ===== */
if ($asSelect2) {
  // Formato Select2: results [{id,text}], pagination.more
  $results = array_map(fn($r) => ['id'=>$r['id'], 'text'=>$r['nombre']], $data);
  $hasMore = ($offset + $limit) < (int)$total;

  echo json_encode([
    'results'    => $results,
    'pagination' => ['more' => $hasMore]
  ], JSON_UNESCAPED_UNICODE);
  exit;
}

echo json_encode([
  'success' => true,
  'total'   => (int)$total,
  'limit'   => $limit,
  'page'    => $page,
  'data'    => $data
], JSON_UNESCAPED_UNICODE);
