<?php
// /api/api_buscar_chasis.php
// POST JSON: { "chasis": ["AAA","BBB", ...] }
// RESP: { success:true, items:[ {id, chasis, color, marca, modelo}, ... ] }

declare(strict_types=1);
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Methods: POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !$conn instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error de conexión a BD']); exit;
}
mysqli_set_charset($conn, 'utf8mb4');
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }

function read_json(): array {
  $raw = file_get_contents('php://input');
  if (!$raw) return [];
  $j = json_decode($raw, true);
  return is_array($j) ? $j : [];
}

$payload = read_json();
$lista = $payload['chasis'] ?? [];
if (!is_array($lista) || count($lista) === 0) {
  echo json_encode(['success'=>false,'message'=>'Lista de chasis vacía']); exit;
}

// Normalizar y únicos
$norm = [];
foreach ($lista as $c) {
  $x = strtoupper(trim((string)$c));
  if ($x !== '' && strlen($x) >= 4) $norm[$x] = true;
}
$keys = array_keys($norm);
if (count($keys) === 0) {
  echo json_encode(['success'=>false,'message'=>'Sin chasis válidos']); exit;
}

$ph = implode(',', array_fill(0, count($keys), '?'));

// Ajusta nombres de tabla/campos si difieren (asumo tb_datadai)
$sql = "
  SELECT 
    d.iddatadai AS id,
    d.chasis    AS chasis,
    d.color     AS color,
    d.marca     AS marca,
    d.modelo    AS modelo
  FROM tb_datadai d
  WHERE UPPER(d.chasis) IN ($ph)
";

try {
  $stmt = $conn->prepare($sql);
  $types = str_repeat('s', count($keys));
  $stmt->bind_param($types, ...$keys);
  $stmt->execute();
  $res = $stmt->get_result();

  $items = [];
  while ($row = $res->fetch_assoc()) {
    $items[] = [
      'id'     => (string)$row['id'],
      'chasis' => (string)$row['chasis'],
      'color'  => $row['color']  !== null ? (string)$row['color']  : '',
      'marca'  => $row['marca']  !== null ? (string)$row['marca']  : '',
      'modelo' => $row['modelo'] !== null ? (string)$row['modelo'] : '',
    ];
  }

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

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error en consulta','error'=>$e->getMessage()]);
}
