<?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: string (opcional si usas 'placas')
  - placas: array|string (coma / espacio / salto de línea)
  - exact: bool (default false)
  - contains: bool (default false; si true y exact=false => %term%)
  - limit: int (1..100; default 50)
  - page:  int (>=1; default 1)
*/
$exact    = filter_var($input['exact'] ?? false, FILTER_VALIDATE_BOOLEAN);
$contains = filter_var($input['contains'] ?? false, FILTER_VALIDATE_BOOLEAN);
$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 placas */
$placas = [];

// placas[] como arreglo
if (isset($input['placas']) && is_array($input['placas'])) {
  $placas = $input['placas'];
}

// placas como string con separadores
if (isset($input['placas']) && is_string($input['placas'])) {
  $placas = array_merge($placas, preg_split('/[,\s\r\n]+/u', (string)$input['placas'], -1, PREG_SPLIT_NO_EMPTY));
}

// placa única
if (!empty($input['placa'])) {
  $placas[] = (string)$input['placa'];
}

$placas = array_values(array_filter(array_map(function($p){
  // Quita guiones/espacios, mayúsculas
  $p = strtoupper(trim((string)$p));
  $p = str_replace([' ', '-'], '', $p);
  return $p;
}, $placas), fn($p) => $p !== ''));

if (count($placas) === 0) {
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>'Falta el parámetro placa o placas'], 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 ";

/* ===== Filtro por placa(s) =====
   - exact=true  -> IN (?, ?, ...)
   - exact=false -> OR de LIKE; por defecto prefijo (ABC%) para uso de índice.
                    Si contains=true -> %ABC% (menos óptimo)
*/
$params = [];
$types  = "";

if ($exact) {
  $placeholders = implode(',', array_fill(0, count($placas), '?'));
  $sql .= " AND p.placa IN ($placeholders) ";
  foreach ($placas as $p) { $params[] = $p; $types .= 's'; }
} else {
  $sql .= " AND (";
  $conds = [];
  foreach ($placas as $p) {
    $conds[] = "p.placa LIKE ?";
    if ($contains) {
      $params[] = "%{$p}%";
    } else {
      // prefijo para permitir índice: ABC%
      $params[] = "{$p}%";
    }
    $types .= 's';
  }
  $sql .= implode(' OR ', $conds) . ") ";
}

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

/* ===== Preparar/Ejecutar ===== */
$stmt = $conn->prepare($sql);
if (!$stmt) {
  throw new Exception('No se pudo preparar la consulta: ' . $conn->error);
}

$stmt->bind_param($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);

/* ===== Limpieza ===== */
$stmt->close();
$conn->close();
