<?php
// api/patio_grid.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);

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

/** CONFIG: cambia a 1 si activo=1 significa OCUPADO en tu BD */
$OCUPADO_CUANDO_ACTIVO_ES = 0;

$stmt = $conn->prepare("
  SELECT 
    id, id_ubicacion, columna, fila, etiqueta, activo
  FROM tb_anden
  WHERE id_ubicacion = ? AND condicion = 1
");
$stmt->bind_param("i", $ubicacion_id);
$stmt->execute();
$res = $stmt->get_result();

$cells = [];
$max_col = 0; $max_row = 0;
while ($r = $res->fetch_assoc()){
  $ocupado = ((int)$r['activo'] === (int)$OCUPADO_CUANDO_ACTIVO_ES);

  // filtro servidor
  if ($solo && $ocupado) continue;
  if ($q !== ''){
    $needle = mb_strtolower($q, 'UTF-8');
    $etq = mb_strtolower($r['etiqueta'] ?? '', 'UTF-8');
    if (mb_strpos($etq, $needle) === false) continue;
  }

  $row = (int)$r['columna'];
  $col = (int)$r['fila'];
  if ($col > $max_col) $max_col = $col;
  if ($row > $max_row) $max_row = $row;

  $cells[] = [
    'id'       => (int)$r['id'],
    'columna'  => $col,
    'fila'     => $row,
    'etiqueta' => $r['columna'].$r['fila'],
    'ocupado'  => $ocupado ? 0 : 1
  ];
}

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