<?php
// tipolavada_list.php — lista de tipos de lavada activos (formato: options=[{id,text}])
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');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Método no permitido']); exit;
}

session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'message'=>'No autorizado']); exit;
}

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

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

$sql = "SELECT idtipo_lavada, lavada
        FROM tb_tipolavada
        WHERE condicion = 1
        ORDER BY lavada ASC";

$rs = $db->query($sql);
if ($rs === false) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error al consultar','sql_error'=>$db->error]); exit;
}

$options = [];
while ($r = $rs->fetch_assoc()) {
  $options[] = [
    'id'   => (int)$r['idtipo_lavada'],
    'text' => (string)$r['lavada'],
  ];
}
$rs->free();

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