<?php
// views/pages/api/datadai_por_chasis.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'message'=>'No autorizado']); exit;
}

require_once __DIR__ . '/../conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) { echo json_encode(['success'=>false,'message'=>'Sin conexión']); exit; }

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

$inRaw = file_get_contents('php://input');
$in    = json_decode($inRaw, true) ?: [];

$chasisMulti = array_values(array_unique(array_map(
  fn($s)=>strtoupper(trim((string)$s)),
  (array)($in['chasis_multi'] ?? [])
)));
$soloSimple = (int)($in['solo_simple'] ?? 0);
$estadoMax  = (int)($in['estado_max']  ?? 0);

if (!$chasisMulti) { echo json_encode(['success'=>false,'message'=>'Sin chasis']); exit; }

// Placeholders para IN (...)
$place = implode(',', array_fill(0, count($chasisMulti), '?'));

// IMPORTANTE: ajusta nombres si tu esquema difiere
// - tb_bodega: tabla de bodegas
// - b.id: clave primaria de bodega
// - b.nombre: nombre textual de la bodega (o 'descripcion' si así se llama)
$sql = "
  SELECT 
    d.iddatadai,
    UPPER(d.chasis) AS chasis,
    d.marca,
    d.modelo,
    d.color,
    d.id_bodega,
    COALESCE(b.detalle, '') AS bodega
  FROM tb_datadai AS d
  LEFT JOIN tb_bodega AS b ON b.idbodega = d.id_bodega
  WHERE d.condicion = 1
    AND UPPER(d.chasis) IN ($place)
";

$types  = str_repeat('s', count($chasisMulti));
$params = $chasisMulti;


if ($estadoMax > 0) {
  $sql   .= " AND IFNULL(d.id_estado,0) <= ?";
  $types .= 'i';
  $params[] = $estadoMax;
}

$stmt = $db->prepare($sql);
if (!$stmt) { echo json_encode(['success'=>false,'message'=>'Error SQL (prepare)']); exit; }

$stmt->bind_param($types, ...$params);
$stmt->execute();
$rs = $stmt->get_result();

$found = []; 
$seen  = [];

while ($r = $rs->fetch_assoc()) {
  $ch = strtoupper((string)$r['chasis']);
  $row = [
    'iddatadai' => (int)$r['iddatadai'],
    'chasis'    => $ch,
    'marca'     => (string)($r['marca']  ?? ''),
    'modelo'    => (string)($r['modelo'] ?? ''),
    'color'     => (string)($r['color']  ?? ''),
    'id_bodega' => isset($r['id_bodega']) ? (int)$r['id_bodega'] : null,
    'bodega'    => (string)($r['bodega'] ?? ''), // <- NOMBRE DE BODEGA PARA MOSTRAR EN #vehiculo
  ];
  $found[] = $row;
  $seen[$ch] = true;
}

$notFound = array_values(array_filter($chasisMulti, fn($c)=>empty($seen[$c])));

echo json_encode(['success'=>true,'found'=>$found,'not_found'=>$notFound], JSON_UNESCAPED_UNICODE);
