<?php
//views/pages/raspadita/api/canillitas_list.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(['success'=>false,'message'=>'Sin conexión BD'], 500);
}

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

// ✅ Params opcionales
$soloActivos = isset($_GET['soloActivos']) ? (int)$_GET['soloActivos'] : 1;

$where = "1=1";
if ($soloActivos === 1) $where .= " AND activo = 1";

$sql = "SELECT id, canillita, activo, COALESCE(saldo,0) saldo
        FROM tbr_canillita
        WHERE {$where}
        ORDER BY canillita ASC";

$r = mysqli_query($db, $sql);
if (!$r) jexit(['success'=>false,'message'=>'Error SQL','detail'=>mysqli_error($db)], 500);

$data = [];
while($row = mysqli_fetch_assoc($r)) {
  $id   = (int)$row['id'];
  $nom  = (string)$row['canillita'];
  $sal  = (float)$row['saldo'];

  // ✅ Texto para el select: "canillita — $saldo"
  $text = $nom . " — $" . number_format($sal, 2, '.', '');

  $data[] = [
    'id'       => $id,
    'canillita'=> $nom,
    'saldo'    => $sal,
    'activo'   => (int)$row['activo'],
    'text'     => $text
  ];
}

jexit(['success'=>true, 'data'=>$data]);
