<?php
//views/pages/raspadita/api/canillitas_select2.php
declare(strict_types=1);

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');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

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

date_default_timezone_set('America/Guayaquil');

function jexit(array $payload, int $code=200): void {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE);
  exit;
}

require_once __DIR__ . '/../../conex.php'; // ajusta si tu ruta cambia
$db = $conn ?? null;

if (!$db instanceof mysqli) {
  jexit(['results'=>[], 'pagination'=>['more'=>false], 'error'=>'Sin conexión BD'], 500);
}

mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

// ===== Params Select2 =====
$q    = trim((string)($_GET['q'] ?? $_GET['term'] ?? '')); // select2 usa q o term
$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;

$limit  = 20;
$offset = ($page - 1) * $limit;

// ===== WHERE =====
$where  = "WHERE activo = 1";
$params = [];
$types  = "";

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

// ===== Conteo total =====
$sqlCount = "SELECT COUNT(*) AS total FROM tbr_canillita {$where}";
$stmt = mysqli_prepare($db, $sqlCount);
if (!$stmt) jexit(['results'=>[], 'pagination'=>['more'=>false], 'error'=>'Error prepare COUNT', 'detail'=>mysqli_error($db)], 500);

if ($types !== '') mysqli_stmt_bind_param($stmt, $types, ...$params);

mysqli_stmt_execute($stmt);
$resCount = mysqli_stmt_get_result($stmt);
$total = (int)(mysqli_fetch_assoc($resCount)['total'] ?? 0);
mysqli_stmt_close($stmt);

// ===== Datos =====
$sql = "
  SELECT id, canillita, saldo
  FROM tbr_canillita
  {$where}
  ORDER BY canillita ASC
  LIMIT {$limit} OFFSET {$offset}
";
$stmt = mysqli_prepare($db, $sql);
if (!$stmt) jexit(['results'=>[], 'pagination'=>['more'=>false], 'error'=>'Error prepare SELECT', 'detail'=>mysqli_error($db)], 500);

if ($types !== '') mysqli_stmt_bind_param($stmt, $types, ...$params);

mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

$results = [];
while ($row = mysqli_fetch_assoc($res)) {
  $id  = (int)$row['id'];
  $nom = (string)$row['canillita'];
  $sal = (float)($row['saldo'] ?? 0);

  $results[] = [
    'id'   => $id,
    'text' => $nom . ' — $' . number_format($sal, 2, '.', ''),
  ];
}
mysqli_stmt_close($stmt);

$more = ($offset + $limit) < $total;

jexit([
  'results' => $results,
  'pagination' => ['more' => $more],
]);
