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

session_start();
date_default_timezone_set('America/Guayaquil');

ini_set('display_errors','0');
ini_set('log_errors','1');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

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

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') jexit(['success'=>false,'message'=>'Use POST'], 405);

ob_start();
require __DIR__ . '/../../conex.php';
ob_end_clean();

$cn = $conn ?? ($conex ?? null);
if (!$cn instanceof mysqli) jexit(['success'=>false,'message'=>'Sin conexión BD'], 500);
mysqli_set_charset($cn, 'utf8mb4');

$sql = "SELECT idsucursal, sucursal
        FROM tbr_sucursal
        WHERE condicion=1 AND activo=1
        ORDER BY sucursal ASC";

$res = $cn->query($sql);
if (!$res) jexit(['success'=>false,'message'=>'Error SQL','detail'=>$cn->error], 500);

$data = [];
while ($row = $res->fetch_assoc()) $data[] = $row;

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