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

$bodega_id = (int)($_GET['bodega_id'] ?? 0);
if ($bodega_id <= 0){
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>'Parámetro bodega_id requerido'], JSON_UNESCAPED_UNICODE);
  exit;
}

$stmt = $conn->prepare("
  SELECT idubicacion AS id, detalle_ubicacion AS nombre
  FROM tb_ubicacion
  WHERE id_bodega = ? AND condicion = 1 AND activo = 1
  ORDER BY detalle_ubicacion
");
$stmt->bind_param("i", $bodega_id);
$stmt->execute();
$res = $stmt->get_result();

$out = [];
while ($r = $res->fetch_assoc()) $out[] = $r;

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