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

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

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');

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

require __DIR__ . '/../../conex.php';
$cn = $conn ?? ($conex ?? null);
if (!$cn instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión BD'], JSON_UNESCAPED_UNICODE); exit;
}
mysqli_set_charset($cn, 'utf8mb4');

$sql = "SELECT
          u.idusuario, u.usuario, u.activo, u.raspadita,
          u.id_sucursal, COALESCE(u.saldo,0) AS saldo,
          s.sucursal
        FROM tbr_usuario u
        INNER JOIN tbr_sucursal s ON s.idsucursal = u.id_sucursal
        WHERE u.id_rol = 2 AND u.condicion = 1
        ORDER BY u.idusuario DESC";

$res = $cn->query($sql);
if (!$res) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error SQL','detail'=>$cn->error], JSON_UNESCAPED_UNICODE); exit;
}

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

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