<?php
// api/bodega_list.php
declare(strict_types=1);
session_start();

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') { exit; }

require_once __DIR__ . '/../conex.php';

// Soporta $conn o $conex
$db = $conn ?? ($conex ?? null);
if (!$db) {
  echo json_encode(['success' => false, 'message' => 'Sin conexión a la base de datos', 'data' => []]);
  exit;
}

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

// Ajusta los nombres de tabla y campos según tu base
$sql = "SELECT idbodega AS id, detalle AS nombre
        FROM tb_bodega
        WHERE condicion = 1
        ORDER BY detalle ASC";

$res = mysqli_query($db, $sql);
if (!$res) {
  echo json_encode([
    'success' => false,
    'message' => 'Error en consulta: ' . mysqli_error($db),
    'data' => []
  ]);
  exit;
}

$data = [];
while ($row = mysqli_fetch_assoc($res)) {
  $data[] = [
    'id'     => (int)$row['id'],
    'nombre' => (string)$row['nombre'],
  ];
}

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