<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

ini_set('display_errors','0'); error_reporting(E_ALL);
set_error_handler(function($s,$m,$f,$l){ http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'PHP error','detail'=>"$m in $f:$l"], JSON_UNESCAPED_UNICODE); exit; });
set_exception_handler(function($e){ http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Exception','detail'=>$e->getMessage()], JSON_UNESCAPED_UNICODE); exit; });

require '../conex.php';
if (function_exists('mysqli_report')) mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$sql = "
  SELECT 
    idbodega AS id,
    TRIM(
      CONCAT(
        COALESCE(NULLIF(sigla,''),''),
        CASE WHEN COALESCE(NULLIF(sigla,''),'')<>'' THEN ' - ' ELSE '' END,
        detalle,
        CASE WHEN COALESCE(NULLIF(lugar,''),'')<>'' THEN CONCAT(' (',lugar,')') ELSE '' END
      )
    ) AS nombre
  FROM tb_bodega
  WHERE condicion = 1
  ORDER BY detalle
";
$res = $conn->query($sql);
$out = [];
while ($r = $res->fetch_assoc()) $out[] = $r;

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