<?php
// views/pages/raspadita/api/coordinador_catalogos.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;
}
function jexit(array $p, int $c=200): void { http_response_code($c); echo json_encode($p, JSON_UNESCAPED_UNICODE); exit; }

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES' || (int)($_SESSION['id_rol'] ?? 0) !== 7) {
  jexit(['success'=>false,'message'=>'No autorizado'], 401);
}

require_once __DIR__ . '/../../conex.php';
$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'");

/* ===== PUNTOS DE VENTA =====
   ⚠️ Ajusta si tu PV usa otro rol:
*/
$ROL_PV = 2;

$puntos = [];
$stmt = mysqli_prepare($db, "
  SELECT idusuario, usuario
  FROM tbr_usuario
  WHERE activo=1 AND condicion=1
    AND id_rol=?
    AND COALESCE(raspadita,0)=1
  ORDER BY usuario ASC
");
if ($stmt) {
  mysqli_stmt_bind_param($stmt, "i", $ROL_PV);
  mysqli_stmt_execute($stmt);
  mysqli_stmt_store_result($stmt);
  mysqli_stmt_bind_result($stmt, $idusuario, $usuario);
  while (mysqli_stmt_fetch($stmt)) {
    $puntos[] = ['id'=>(int)$idusuario, 'text'=>(string)$usuario];
  }
  mysqli_stmt_close($stmt);
}

/* ===== CANILLITAS ===== */
$canillitas = [];
$stmt2 = mysqli_prepare($db, "
  SELECT id, canillita
  FROM tbr_canillita
  WHERE activo=1
  ORDER BY canillita ASC
");
if ($stmt2) {
  mysqli_stmt_execute($stmt2);
  mysqli_stmt_store_result($stmt2);
  mysqli_stmt_bind_result($stmt2, $idc, $nom);
  while (mysqli_stmt_fetch($stmt2)) {
    $canillitas[] = ['id'=>(int)$idc, 'text'=>(string)$nom];
  }
  mysqli_stmt_close($stmt2);
}

jexit(['success'=>true, 'puntos_venta'=>$puntos, 'canillitas'=>$canillitas]);