<?php
// views/pages/api/patio_map.php
declare(strict_types=1);
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

ini_set('display_errors','0');
error_reporting(E_ALL);
set_exception_handler(function($e){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Exception','detail'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
  exit;
});

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

/**
 * Parámetros opcionales:
 * - bodega   (string)  => nombre/alias (si tu esquema lo usa)
 * - ubicacion(int)     => id_ubicacion
 * - solo     (string)  => 'libres'|'ocupados'
 */
$bodega     = isset($_GET['bodega'])    ? trim((string)$_GET['bodega']) : '';
$idUbLocal  = isset($_GET['ubicacion']) ? (int)$_GET['ubicacion'] : 0;
$solo       = isset($_GET['solo'])      ? strtolower(trim((string)$_GET['solo'])) : '';

// ⚠️ Ajusta según tu esquema: campo en tb_ubicacion que identifique letra/área.
// Si tienes u.letra, úsalo. Si no, primera letra de detalle_ubicacion.
$AREA_FIELD = "COALESCE(u.letra, LEFT(u.detalle_ubicacion,1))";

$sql = "
SELECT
  $AREA_FIELD                 AS area,
  a.id                        AS id_anden,
  a.fila,
  a.columna,
  a.etiqueta,
  a.activo                    AS flag_activo_anden,
  a.id_ubicacion,
  u.detalle_ubicacion,

  da.id_datadai,
  da.fecha_i,

  d.iddatadai                 AS id_vehiculo,
  d.chasis,
  d.marca,
  d.modelo,
  d.color
FROM tb_anden a
JOIN tb_ubicacion u
  ON u.idubicacion = a.id_ubicacion
LEFT JOIN (
  SELECT x.*
  FROM tb_datadai_anden x
  INNER JOIN (
    SELECT id_anden, MAX(fecha_i) AS max_fecha
    FROM tb_datadai_anden
    WHERE condicion = 1
    GROUP BY id_anden
  ) m ON m.id_anden = x.id_anden AND m.max_fecha = x.fecha_i
  WHERE x.condicion = 1
) da
  ON da.id_anden = a.id
LEFT JOIN tb_datadai d
  ON d.iddatadai = da.id_datadai
WHERE a.condicion = 1 AND u.id_bodega = 1
";

$types=''; $params=[];

if ($idUbLocal > 0) { $sql .= " AND a.id_ubicacion = ? "; $types.='i'; $params[]=$idUbLocal; }
// Si tu esquema enlaza bodega, agrega filtro aquí. Ejemplo:
// if ($bodega !== '') { $sql .= " AND u.bodega = ? "; $types.='s'; $params[]=$bodega; }

if ($solo === 'libres')   $sql .= " AND da.id_datadai IS NULL ";
if ($solo === 'ocupados') $sql .= " AND da.id_datadai IS NOT NULL ";

$sql .= " ORDER BY area, a.fila, a.columna ";

$stmt = $conn->prepare($sql);
if (!$stmt) throw new RuntimeException('Prepare failed: '.$conn->error);
if ($types !== '') $stmt->bind_param($types, ...$params);
$stmt->execute();
$res = $stmt->get_result();

$areas = []; $now = new DateTimeImmutable('now');

while ($row = $res->fetch_assoc()) {
  $area = strtoupper(substr((string)$row['area'],0,1));
  if (!isset($areas[$area])) $areas[$area]=[];

  $ocupado = !empty($row['id_datadai']);
  $dias = null;
  if ($ocupado && !empty($row['fecha_i'])) {
    try { $fi=new DateTimeImmutable($row['fecha_i']); $dias=(int)$fi->diff($now)->format('%a'); }
    catch(Throwable $e){ $dias=null; }
  }

  $areas[$area][] = [
    'fila'        => (int)$row['fila'],
    'columna'     => (int)$row['columna'],
    'id_anden'    => (int)$row['id_anden'],
    'etiqueta'    => (string)$row['etiqueta'],
    'ocupado'     => $ocupado ? 1 : 0,
    'estado'      => $ocupado ? 'OCUPADO' : 'LIBRE',
    'fecha_i'     => $ocupado ? (string)$row['fecha_i'] : null,
    'dias_ocupado'=> $dias,
    'chasis'      => $ocupado ? (string)($row['chasis'] ?? '') : null,
    'marca'       => $ocupado ? (string)($row['marca'] ?? '')  : null,
    'modelo'      => $ocupado ? (string)($row['modelo'] ?? '') : null,
    'color'       => $ocupado ? (string)($row['color'] ?? '')  : null
  ];
}

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