<?php
// api/andenes_ocupados.php
session_start();
date_default_timezone_set('America/Guayaquil');
header('Content-Type: application/json; charset=utf-8');

// No HTML de errores (evita "Unexpected token <")
ini_set('display_errors', '0');
error_reporting(E_ALL);
set_error_handler(function($sev,$msg,$file,$line){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'PHP error','detail'=>"$msg in $file:$line"], 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'; // Debe definir $conn (mysqli)
if (!isset($conn) || !$conn) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión a BD']);
  exit;
}

// Filtros opcionales
$idAnden     = isset($_GET['id_anden']) ? (int)$_GET['id_anden'] : null;
$idUbicacion = isset($_GET['id_ubicacion']) ? (int)$_GET['id_ubicacion'] : null;

// Base: TU CONSULTA tal cual
$sql = "
SELECT 
  a.id                AS id_anden,
  a.id_ubicacion,
  a.columna,
  a.fila, 
  d.iddatadai         AS id_vehiculo,
  d.chasis,
  d.marca,
  d.modelo,
  d.color,
  da.fecha_i,
  DATEDIFF(CURDATE(), da.fecha_i) AS dias_transcurridos,
  CURDATE() AS hoy
FROM tb_anden a
JOIN tb_datadai_anden da 
  ON da.id_anden = a.id 
  AND da.condicion = 1
JOIN tb_datadai d 
  ON d.iddatadai = da.id_datadai
WHERE a.condicion = 1
  AND a.activo = 1
";

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

if (!is_null($idAnden)) {
  $sql   .= " AND a.id = ? ";
  $types .= 'i';
  $params[] = $idAnden;
}
if (!is_null($idUbicacion)) {
  $sql   .= " AND a.id_ubicacion = ? ";
  $types .= 'i';
  $params[] = $idUbicacion;
}

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

$stmt = $conn->prepare($sql);
if (!$stmt) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error al preparar consulta']);
  exit;
}
if ($types !== '') {
  $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
while ($r = $res->fetch_assoc()) {
  // Formatea fechas para mostrar
  $r['fecha_i_fmt'] = $r['fecha_i'] ? date('Y-m-d H:i', strtotime($r['fecha_i'])) : null;
  $rows[] = $r;
}

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