<?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;
}

/* Charset correcto para evitar mojibake (e.g. “conexi贸n”) */
mysqli_set_charset($conn, 'utf8mb4');

/* (Opcional) MySQLi estricto para atrapar errores como excepciones */
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }

try {
  // tb_seccion(id, seccion, condicion)
  $sql = "SELECT id AS value, seccion AS label
          FROM tb_seccion
          WHERE condicion = 1
          ORDER BY seccion ASC";

  $res = $conn->query($sql);

  $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);
}
