<?php
// api/datadai_buscar.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') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'GET') { 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'");

$chasis = strtoupper(preg_replace('/[^A-Z0-9]/','', (string)($_GET['chasis'] ?? '')));
$idEstado = $_GET['id_estado'] ?? null;
if ($chasis === '' || strlen($chasis) < 8 || strlen($chasis) > 25){
  echo json_encode(['success'=>false,'message'=>'Chasis inválido']); exit;
}

$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 = ?
    AND d.condicion = 1
";
$types = 's'; $params = [$chasis];

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);
$data = mysqli_fetch_assoc($res);

if ($data){
  echo json_encode(['success'=>true,'data'=>$data], JSON_UNESCAPED_UNICODE);
} else {
  echo json_encode(['success'=>false,'message'=>'No encontrado'], JSON_UNESCAPED_UNICODE);
}
