<?php
// views/pages/raspadita/api/usuario_sucursal_concat.php
// Devuelve usuarios (rol=2, condicion=1) en formato para <select> / Select2:
// { success:true, results:[ {id:5, text:"Sucursal - Usuario"} ] }
//
// GET o POST(JSON)
// Params opcionales:
//   sep: separador (default " - ")
//   q / search: texto a buscar (Select2 usa "q")
//   limit: limite de resultados (default 200)

declare(strict_types=1);
date_default_timezone_set('America/Guayaquil');

/* ===== HEADERS / CORS ===== */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, 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; }

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

$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$input = [];

if ($method === 'POST') {
  $raw = file_get_contents('php://input');
  if ($raw !== false && trim($raw) !== '') {
    $decoded = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) $input = $decoded;
  }
}

/* ===== Params ===== */
$sep = (string)($input['sep'] ?? ($_GET['sep'] ?? ' - '));
if ($sep === '') $sep = ' - ';

// Select2 suele enviar "q"
$q = trim((string)($input['q'] ?? ($_GET['q'] ?? ($input['search'] ?? ($_GET['search'] ?? '')))));

$limit = (int)($input['limit'] ?? ($_GET['limit'] ?? 200));
if ($limit <= 0) $limit = 200;
if ($limit > 1000) $limit = 1000;

/* ===== DB ===== */
require_once __DIR__ . '/../../conex.php';
$db = $conn ?? ($conex ?? null);

if (!$db instanceof mysqli) {
  json_out(['success' => false, 'message' => 'Sin conexión a la base de datos'], 500);
}
mysqli_set_charset($db, 'utf8mb4');

/* ===== SQL ===== */
$sql = "
SELECT
  u.idusuario AS id,
  CONCAT(s.sucursal, ?, u.usuario) AS text
FROM tbr_usuario u
INNER JOIN tbr_sucursal s ON s.idsucursal = u.id_sucursal
WHERE u.condicion = 1
  AND u.id_rol = 2
";

$types  = "s";
$params = [$sep];

if ($q !== '') {
  $sql .= " AND (s.sucursal LIKE CONCAT('%', ?, '%') OR u.usuario LIKE CONCAT('%', ?, '%')) ";
  $types .= "ss";
  $params[] = $q;
  $params[] = $q;
}

$sql .= " ORDER BY s.sucursal ASC, u.usuario ASC LIMIT ? ";
$types .= "i";
$params[] = $limit;

$stmt = $db->prepare($sql);
if (!$stmt) {
  json_out(['success'=>false,'message'=>'Error prepare','detail'=>$db->error], 500);
}

$stmt->bind_param($types, ...$params);

if (!$stmt->execute()) {
  json_out(['success'=>false,'message'=>'Error execute','detail'=>$stmt->error], 500);
}

$res = $stmt->get_result();
$results = [];

while ($row = $res->fetch_assoc()) {
  $results[] = [
    'id'   => (int)$row['id'],
    'text' => (string)$row['text'],
  ];
}

$stmt->close();

json_out([
  'success' => true,
  'count'   => count($results),
  'results' => $results
]);
