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

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

/* ===== Errores como JSON ===== */
ini_set('display_errors', '0');
error_reporting(E_ALL);
set_error_handler(function($s,$m,$f,$l){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'PHP error','detail'=>"$m in $f:$l"], JSON_UNESCAPED_UNICODE);
  exit;
});
set_exception_handler(function($e){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Exception','detail'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
  exit;
});

require '../conex.php'; // Debe exponer $conn (mysqli)
mysqli_set_charset($conn, 'utf8mb4');
mysqli_query($conn, "SET time_zone = '-05:00'");

/* ===== Entrada ===== */
$input = $_SERVER['REQUEST_METHOD'] === 'POST'
  ? (json_decode(file_get_contents('php://input'), true) ?? $_POST)
  : $_GET;

/*
  Parámetros:
  - placa / placas: string | array
  - chasis / chasis_list: string | array
  - exact: bool (default false)
  - contains: bool (default false)
  - modo: "placa", "chasis" o "ambos" (default ambos)
  - limit / page
*/
$exact    = filter_var($input['exact'] ?? false, FILTER_VALIDATE_BOOLEAN);
$contains = filter_var($input['contains'] ?? false, FILTER_VALIDATE_BOOLEAN);
$modo     = strtolower($input['modo'] ?? 'ambos'); // placa | chasis | ambos
$limit    = isset($input['limit']) ? max(1, min(100, (int)$input['limit'])) : 50;
$page     = isset($input['page']) ? max(1, (int)$input['page']) : 1;
$offset   = ($page - 1) * $limit;

/* Normalizar valores */
function normalizarLista($entrada): array {
  if (empty($entrada)) return [];
  if (is_string($entrada)) {
    $entrada = preg_split('/[,\s\r\n]+/u', $entrada, -1, PREG_SPLIT_NO_EMPTY);
  }
  if (!is_array($entrada)) return [];
  $out = [];
  foreach ($entrada as $v) {
    $v = strtoupper(trim((string)$v));
    $v = str_replace([' ', '-'], '', $v);
    if ($v !== '') $out[] = $v;
  }
  return array_values(array_unique($out));
}

$placas = normalizarLista($input['placas'] ?? $input['placa'] ?? []);
$chasis = normalizarLista($input['chasis_list'] ?? $input['chasis'] ?? []);

if (count($placas) === 0 && count($chasis) === 0) {
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>'Falta parámetro placa o chasis'], JSON_UNESCAPED_UNICODE);
  exit;
}

/* ===== Query base ===== */
$sql = "SELECT
          d.iddatadai,
          t.nombre  AS transportista,
          d.marca, d.modelo, d.chasis, d.color,
          p.numero_doc, p.conductor,
          p.fecha_carga, p.fecha_descarga, p.guia
        FROM tb_datadai AS d
        INNER JOIN tb_estado          AS e  ON e.idestado  = d.id_estado
        INNER JOIN tb_asignar_datadai AS a  ON a.id_datadai = d.iddatadai
        INNER JOIN tb_asignar         AS p  ON p.id         = a.id_asignar
        INNER JOIN tb_destino         AS dt ON dt.id        = p.destino
        INNER JOIN tb_transporte      AS t  ON t.id         = p.transportista
        WHERE d.dai = 'Simple' AND d.condicion = 1 AND d.id_estado <= 2 ";

/* ===== Filtros ===== */
$params = [];
$types  = [];
$whereParts = [];

// Normalización SQL
$normPlaca  = "REPLACE(TRIM(UPPER(p.placa)),'-','')";
$normChasis = "REPLACE(TRIM(UPPER(d.chasis)),'-','')";

function buildConds(array $valores, string $campoSQL, bool $exact, bool $contains, array &$params, array &$types): string {
  $conds = [];
  if ($exact) {
    $placeholders = implode(',', array_fill(0, count($valores), '?'));
    foreach ($valores as $v) { $params[] = $v; $types[] = 's'; }
    return "$campoSQL IN ($placeholders)";
  } else {
    foreach ($valores as $v) {
      $conds[] = "$campoSQL LIKE ?";
      if ($contains) {
        $params[] = "%$v%";
      } else {
        $params[] = $v . "%"; // prefijo
      }
      $types[] = 's';
    }
    return '(' . implode(' AND ', $conds) . ')';
  }
}

// Placas
if (($modo === 'placa' || $modo === 'ambos') && $placas) {
  $whereParts[] = buildConds($placas, $normPlaca, $exact, $contains, $params, $types);
}

// Chasis
if (($modo === 'chasis' || $modo === 'ambos') && $chasis) {
  $whereParts[] = buildConds($chasis, $normChasis, $exact, $contains, $params, $types);
}

if ($whereParts) {
  $sql .= " AND (" . implode(' AND ', $whereParts) . ") ";
}

$sql .= " ORDER BY d.iddatadai DESC LIMIT ? OFFSET ? ";
$params[] = $limit;  $types[] = 'i';
$params[] = $offset; $types[] = 'i';

/* ===== Ejecutar ===== */
$stmt = $conn->prepare($sql);
if (!$stmt) throw new Exception('No se pudo preparar la consulta: ' . $conn->error);
$stmt->bind_param(implode('', $types), ...$params);
$stmt->execute();
$res  = $stmt->get_result();
$data = $res->fetch_all(MYSQLI_ASSOC);

/* ===== Respuesta ===== */
echo json_encode([
  'success' => true,
  'count'   => count($data),
  'page'    => $page,
  'limit'   => $limit,
  'data'    => $data
], JSON_UNESCAPED_UNICODE);

$stmt->close();
$conn->close();
