<?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-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

/* ===== Conexión ===== */
require __DIR__ . '/../conex.php';
if (!$conn instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error de 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 ===== */
$id_seccion = isset($_GET['id_seccion']) ? (int)$_GET['id_seccion'] : 0;
$q          = isset($_GET['q']) ? trim((string)$_GET['q']) : ''; // opcional: búsqueda por texto

try {
  $sql = "SELECT idparte AS value, detalleparte AS label
          FROM tb_parte
          WHERE condicion = 1";
  $types = '';
  $vals  = [];

  if ($id_seccion > 0) {
    $sql .= " AND id_seccion = ?";
    $types .= 'i';
    $vals[] = $id_seccion;
  }
  if ($q !== '') {
    $sql .= " AND detalleparte LIKE ?";
    $types .= 's';
    $vals[] = "%{$q}%";
  }

  $sql .= " ORDER BY detalleparte ASC";

  $stmt = $conn->prepare($sql);
  if ($types !== '') {
    $stmt->bind_param($types, ...$vals);
  }
  $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);
}
