<?php
// _api_bootstrap.php — JSON estricto con captura de salida y errores
declare(strict_types=1);

// === Salida: capturar TODO lo que se imprima por error ===
if (!defined('__API_OB_STARTED__')) {
  define('__API_OB_STARTED__', true);
  ob_start();
}

// === Encabezados JSON/CORS temprano ===
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); ob_end_clean(); exit; }

// === Errores: sin HTML y como excepciones ===
ini_set('display_errors', '0');
ini_set('html_errors', '0');
mysqli_report(MYSQLI_REPORT_OFF);

set_error_handler(function($severity, $message, $file, $line){
  if (!(error_reporting() & $severity)) return false; // respetar @
  throw new ErrorException($message, 0, $severity, $file, $line);
});

// === Helper central para responder JSON limpiamente ===
function api_json(array $payload, int $status = 200): void {
  if (!headers_sent()) http_response_code($status);
  $stray = ob_get_contents();
  if ($stray !== false && $stray !== '') {
    $payload['_stray_output'] = substr($stray, 0, 4000);
  }
  while (ob_get_level() > 0) ob_end_clean();
  header('Content-Type: application/json; charset=utf-8', true);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE);
  exit;
}

// === Captura fatales como JSON ===
register_shutdown_function(function(){
  $e = error_get_last();
  if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
    api_json([
      'success' => false,
      'message' => 'Fatal error',
      'detail'  => ['type'=>$e['type'], 'msg'=>$e['message'], 'file'=>$e['file'], 'line'=>$e['line']]
    ], 500);
  }
});

// === Conexión BD (sin producir salida) ===
$pathConex = realpath(__DIR__ . '/../conex.php')
         ?: realpath(__DIR__ . '/../../conex.php')
         ?: realpath(__DIR__ . '/conex.php');
if (!$pathConex) api_json(['success'=>false,'message'=>'No se encontró conex.php'], 500);

require_once $pathConex;
$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) api_json(['success'=>false,'message'=>'Sin conexión BD'], 500);
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone = '-05:00'");

// === Sesión obligatoria ===
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  api_json(['success'=>false,'message'=>'No autorizado'], 401);
}