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

/* JSON + CORS */
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; }

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

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

try {
  if ($q !== '') {
    $like = '%'.$q.'%';
    $sql = 'SELECT id AS value, nombre AS label
            FROM tb_inspeccion
            WHERE condicion = 1 AND nombre LIKE ?
            ORDER BY id ASC';
    if ($limit > 0) { $sql .= ' LIMIT ?'; }
    $stmt = $conn->prepare($sql);
    if ($limit > 0) { $stmt->bind_param('si', $like, $limit); }
    else            { $stmt->bind_param('s',  $like); }
  } else {
    $sql = 'SELECT id AS value, nombre AS label
            FROM tb_inspeccion
            WHERE condicion = 1
            ORDER BY id ASC';
    if ($limit > 0) { $sql .= ' LIMIT ?'; }
    $stmt = $conn->prepare($sql);
    if ($limit > 0) { $stmt->bind_param('i', $limit); }
  }

  $stmt->execute();
  $res = $stmt->get_result();
  $data = [];
  while ($row = $res->fetch_assoc()) { $data[] = $row; }

  echo json_encode(['success'=>true,'data'=>$data], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error en la consulta','detail'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
} finally {
  if (isset($stmt)&&$stmt instanceof mysqli_stmt) $stmt->close();
  if (isset($conn)&&$conn instanceof mysqli) $conn->close();
}
