<?php
// api/datadai_buscar_lote.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: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'message'=>'Método no permitido']); exit; }

require_once __DIR__ . '/../conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db){ echo json_encode(['success'=>false,'message'=>'Sin conexión a la base de datos']); exit; }
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

$input = json_decode(file_get_contents('php://input'), true);
$lista = $input['chasis'] ?? null;
$idEstado = $input['id_estado'] ?? null;
if (!is_array($lista) || empty($lista)){
  echo json_encode(['success'=>false,'message'=>'Parámetro chasis[] requerido']); exit;
}

// Normalizar y limitar
$MAX = 200; $norm = [];
foreach ($lista as $s){
  $c = strtoupper(preg_replace('/[^A-Z0-9]/','',(string)$s));
  if ($c !== '' && strlen($c) >= 8 && strlen($c) <= 25 && !in_array($c,$norm,true)){
    $norm[] = $c;
  }
  if (count($norm) >= $MAX) break;
}
if (!$norm){ echo json_encode(['success'=>false,'message'=>'Sin chasis válidos']); exit; }

$placeholders = implode(',', array_fill(0, count($norm), '?'));
$sql = "
  SELECT
    d.iddatadai, d.item, d.descripcion, d.modelo, d.marca,
    d.fobunitario, d.fobitem, d.transporte, d.seguro,
    d.chasis, d.motor, d.color, d.valoraduana
  FROM tb_datadai AS d
  WHERE d.chasis IN ($placeholders)
    AND d.condicion = 1
";
$params = $norm;
$types  = str_repeat('s', count($norm));

if ($idEstado !== null && $idEstado !== '') {
  $sql .= " AND d.id_estado = ? ";
  $types .= 's';
  $params[] = (string)$idEstado;
}

$stmt = mysqli_prepare($db, $sql);
if (!$stmt){ echo json_encode(['success'=>false,'message'=>'Error al preparar la consulta']); exit; }

mysqli_stmt_bind_param($stmt, $types, ...$params);
if (!mysqli_stmt_execute($stmt)){ echo json_encode(['success'=>false,'message'=>'Error al ejecutar la consulta']); exit; }

$res = mysqli_stmt_get_result($stmt);
$map = [];
while ($row = mysqli_fetch_assoc($res)){
  $ch = $row['chasis'] ?? '';
  if ($ch) $map[$ch] = $row;
}

$found = []; $not_found = [];
foreach ($norm as $c){
  if (isset($map[$c])) $found[] = $map[$c];
  else $not_found[] = $c;
}

echo json_encode([
  'success'     => true,
  'count_in'    => count($norm),
  'count_found' => count($found),
  'found'       => $found,
  'not_found'   => $not_found
], JSON_UNESCAPED_UNICODE);
