<?php
// views/pages/api/patio_inventario_data.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';
$db = $conn ?? ($conex ?? null);
if (!$db) { http_response_code(500); echo json_encode(['success'=>false,'message'=>'Sin conexión a BD']); exit; }
mysqli_set_charset($db,'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

/* Helpers */
function tableExists(mysqli $db, string $t): bool {
  $t = mysqli_real_escape_string($db,$t);
  $res = mysqli_query($db, "SHOW TABLES LIKE '$t'");
  return $res && mysqli_num_rows($res) > 0;
}
function colExists(mysqli $db, string $t, string $c): bool {
  $t = mysqli_real_escape_string($db,$t);
  $c = mysqli_real_escape_string($db,$c);
  $res = mysqli_query($db, "SHOW COLUMNS FROM `$t` LIKE '$c'");
  return $res && mysqli_num_rows($res) > 0;
}

/* Solo catálogo de bodegas */
if (isset($_GET['only_bodegas'])) {
  $bodegas = [];
  if (tableExists($db,'tb_bodega')) {
    $q = mysqli_query($db, "SELECT id, COALESCE(nombre,descripcion,nombre_bodega) AS nombre
                            FROM tb_bodega ORDER BY nombre");
    if ($q) while($r=mysqli_fetch_assoc($q)){
      $bodegas[] = ['id'=>(int)$r['id'], 'nombre'=> (string)$r['nombre']];
    }
  }
  echo json_encode(['success'=>true,'bodegas'=>$bodegas], JSON_UNESCAPED_UNICODE);
  exit;
}

/* Parámetros */
$q         = trim((string)($_GET['q'] ?? ''));
$estado    = trim((string)($_GET['estado'] ?? '2')); // en patio por defecto
$bodega_id = (int)($_GET['bodega_id'] ?? 0);
$multiRaw  = trim((string)($_GET['multi'] ?? ''));
$multiList = $multiRaw ? preg_split('/[\s,;]+/',$multiRaw,-1,PREG_SPLIT_NO_EMPTY) : [];
$multiList = array_values(array_unique(array_map('trim',$multiList)));

/* Detección de joins opcionales */
$join = [];
$sel  = [
  "d.iddatadai",
  "COALESCE(DATE_FORMAT(d.fecha_ingreso,'%Y-%m-%d'),'') AS fecha_ingreso",
  "GREATEST(DATEDIFF(CURDATE(), COALESCE(d.fecha_ingreso,CURDATE())),0) AS dias",
  "COALESCE(d.marca,'')  AS marca",
  "COALESCE(d.modelo,'') AS modelo",
  "COALESCE(d.color,'')  AS color",
  "COALESCE(d.chasis,'') AS chasis",
  "d.id_estado"
];
$has_bodega_id   = colExists($db,'tb_datadai','id_bodega');
$has_bodega_txt  = colExists($db,'tb_datadai','bodega');
if ($has_bodega_id && tableExists($db,'tb_bodega')){
  $join[] = "LEFT JOIN tb_bodega b ON b.id = d.id_bodega";
  $sel[]  = "COALESCE(b.nombre,b.descripcion,b.nombre_bodega,'') AS bodega";
} elseif ($has_bodega_txt){
  $sel[] = "COALESCE(d.bodega,'') AS bodega";
} else { $sel[] = "'' AS bodega"; }

$has_anden_id = colExists($db,'tb_datadai','id_anden');
if ($has_anden_id && tableExists($db,'tb_anden')){
  $join[] = "LEFT JOIN tb_anden a ON a.id = d.id_anden";
  $sel[]  = "COALESCE(a.nombre,a.descripcion,'') AS anden";
} else { $sel[] = "'' AS anden"; }

$has_zona_id = colExists($db,'tb_datadai','id_zona');
if ($has_zona_id && tableExists($db,'tb_zona')){
  $join[] = "LEFT JOIN tb_zona z ON z.id = d.id_zona";
  $sel[]  = "COALESCE(z.nombre,z.descripcion,'') AS zona";
} else { $sel[] = "'' AS zona"; }

$has_seccion_id = colExists($db,'tb_datadai','id_seccion');
if ($has_seccion_id && tableExists($db,'tb_seccion')){
  $join[] = "LEFT JOIN tb_seccion s ON s.id = d.id_seccion";
  $sel[]  = "COALESCE(s.nombre,s.descripcion,'') AS seccion";
} else { $sel[] = "'' AS seccion"; }

$has_pedido     = colExists($db,'tb_datadai','pedido');
$has_origen_loc = colExists($db,'tb_datadai','origen_localidad');
$sel[] = $has_pedido ? "COALESCE(d.pedido,'') AS pedido" : "'' AS pedido";

if (tableExists($db,'tb_estado')){
  $join[] = "LEFT JOIN tb_estado e ON e.idestado = d.id_estado";
  $sel[]  = "COALESCE(e.descripcion, CONCAT('Estado ', d.id_estado)) AS estado";
} else {
  $sel[]  = "CONCAT('Estado ', d.id_estado) AS estado";
}

$selectSQL = implode(",\n  ", $sel);
$joinSQL   = $join ? "\n" . implode("\n", $join) : "";

/* WHERE + params */
$where  = "1";
$params = [];
$types  = "";

if ($estado !== ''){
  $where .= " AND d.id_estado = ?";
  $params[] = (int)$estado; $types .= "i";
}
if ($bodega_id > 0 && $has_bodega_id){
  $where .= " AND d.id_bodega = ?";
  $params[] = $bodega_id; $types .= "i";
}
if ($q !== ''){
  $where .= " AND (d.marca LIKE ? OR d.modelo LIKE ? OR d.color LIKE ? OR d.chasis LIKE ?"
          . ($has_pedido ? " OR d.pedido LIKE ?" : "")
          . ($has_origen_loc ? " OR d.origen_localidad LIKE ?" : "")
          . ")";
  $like = "%$q%";
  $params = array_merge($params, [$like,$like,$like,$like]);
  $types .= "ssss";
  if ($has_pedido){ $params[] = $like; $types .= "s"; }
  if ($has_origen_loc){ $params[] = $like; $types .= "s"; }
}
if (!empty($multiList)){
  $subs = [];
  foreach ($multiList as $m){
    if (mb_strlen($m) >= 6){ $subs[] = "d.chasis = ?";  $params[] = $m;     $types .= "s"; }
    else {                   $subs[] = "d.chasis LIKE ?"; $params[] = "%$m%"; $types .= "s"; }
  }
  if ($subs){ $where .= " AND (" . implode(" OR ", $subs) . ")"; }
}

$sql = "SELECT
  $selectSQL
FROM tb_datadai d
$joinSQL
WHERE $where
ORDER BY d.fecha_ingreso ASC, d.iddatadai ASC
LIMIT 2000";

$stmt = mysqli_prepare($db, $sql);
if (!$stmt){
  echo json_encode(['success'=>false,'message'=>'Error preparando consulta']); exit;
}
if ($types !== ""){ mysqli_stmt_bind_param($stmt, $types, ...$params); }
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

$data = [];
if ($res){
  while($r=mysqli_fetch_assoc($res)){
    $data[] = [
      'fecha_ingreso' => (string)$r['fecha_ingreso'],
      'dias'          => (int)$r['dias'],
      'bodega'        => (string)$r['bodega'],
      'anden'         => (string)$r['anden'],
      'zona'          => (string)$r['zona'],
      'seccion'       => (string)$r['seccion'],
      'marca'         => (string)$r['marca'],
      'modelo'        => (string)$r['modelo'],
      'color'         => (string)$r['color'],
      'chasis'        => (string)$r['chasis'],
      'pedido'        => (string)$r['pedido'],
      'estado'        => (string)$r['estado']
    ];
  }
}
mysqli_stmt_close($stmt);

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