<?php
// views/pages/api_app/vehiculos_estado6.php
// — API: Lista vehículos con id_estado = 6 (JSON)
// Opcionales (GET): q (búsqueda), limit, offset
// Ejemplo: vehiculos_estado6.php?q=ABC123&limit=50&offset=0

declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
// CORS (ajusta el origen si deseas restringirlo)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

date_default_timezone_set('America/Guayaquil');

$respond = function (int $code, array $payload): void {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
};

// Manejadores de error y excepción a JSON
set_exception_handler(function (Throwable $e) use ($respond) {
  $respond(500, [
    'success'   => false,
    'error'     => 'EXCEPTION',
    'message'   => $e->getMessage(),
    'timestamp' => date('c'),
  ]);
});
set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($respond) {
  // Convierte cualquier warning/notice en excepción JSON
  throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

require_once __DIR__ . '/../conex.php'; // ajusta la ruta si es necesario
if (!isset($conn) || !($conn instanceof mysqli)) {
  $respond(500, [
    'success' => false,
    'error'   => 'DB_CONNECTION',
    'message' => 'No se encontró una conexión mysqli válida ($conn).',
  ]);
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset('utf8mb4');

// Parámetros
$q      = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
$limit  = isset($_GET['limit'])  ? max(1, (int)$_GET['limit'])  : 100;  // por defecto 100
$offset = isset($_GET['offset']) ? max(0, (int)$_GET['offset']) : 0;    // por defecto 0

// Construcción dinámica de filtros
$where  = 'WHERE d.id_estado = 6';
$params = [];
$types  = '';

if ($q !== '') {
  $where .= ' AND (d.chasis LIKE ? OR d.marca LIKE ? OR d.modelo LIKE ? OR d.color LIKE ?)';
  $like = '%' . $q . '%';
  $params[] = $like; $types .= 's';
  $params[] = $like; $types .= 's';
  $params[] = $like; $types .= 's';
  $params[] = $like; $types .= 's';
}

// COUNT total
$sqlCount = "
  SELECT COUNT(*) AS total
  FROM tb_datadai AS d
  /* Si no existe la tabla tb_estado, elimina el JOIN del SELECT principal también */
  /* LEFT JOIN tb_estado AS e ON e.idestado = d.id_estado */
  $where
";

// DATA principal
$sqlData = "
  SELECT
    d.iddatadai              AS id,
    d.marca,
    d.modelo,
    d.chasis,
    d.color,
    d.id_estado,
    /* Si existe tb_estado, descomenta y obtén su nombre */
    /* e.descripcion            AS estado, */
    DATE_FORMAT(d.created_at, '%Y-%m-%d %H:%i:%s') AS created_at
  FROM tb_datadai AS d
  /* LEFT JOIN tb_estado AS e ON e.idestado = d.id_estado */
  $where
  ORDER BY COALESCE(d.created_at, '1970-01-01 00:00:00') DESC, d.iddatadai DESC
  LIMIT ? OFFSET ?
";

// Ejecutar COUNT
$stmtC = $conn->prepare($sqlCount);
if ($types !== '') {
  $stmtC->bind_param($types, ...$params);
}
$stmtC->execute();
$resC = $stmtC->get_result();
$rowC = $resC->fetch_assoc();
$total = (int)($rowC['total'] ?? 0);
$stmtC->close();

// Ejecutar DATA
$stmtD = $conn->prepare($sqlData);
$typesData = $types . 'ii';
$paramsData = $params;
$paramsData[] = $limit;
$paramsData[] = $offset;

// bind_param requiere referencias
$tmp = [];
$tmp[] = $typesData;
foreach ($paramsData as $k => $v) {
  $tmp[] = &$paramsData[$k];
}
call_user_func_array([$stmtD, 'bind_param'], $tmp);

$stmtD->execute();
$resD = $stmtD->get_result();

$data = [];
while ($r = $resD->fetch_assoc()) {
  $data[] = [
    'id'         => (int)$r['id'],
    'marca'      => $r['marca'],
    'modelo'     => $r['modelo'],
    'chasis'     => $r['chasis'],
    'color'      => $r['color'],
    'id_estado'  => isset($r['id_estado']) ? (int)$r['id_estado'] : null,
    // 'estado'     => $r['estado'] ?? null, // descomenta si usas el JOIN con tb_estado
    'created_at' => $r['created_at'],
  ];
}
$stmtD->close();

$respond(200, [
  'success'   => true,
  'timestamp' => date('c'),
  'query'     => [
    'q'      => $q,
    'limit'  => $limit,
    'offset' => $offset,
  ],
  'total'     => $total,
  'count'     => count($data),
  'data'      => $data,
]);
