<?php
// Central API bootstrap to ensure clean JSON responses
// Usage: include_once __DIR__ . '/api-bootstrap.php';

if (!defined('SUPPRESS_ERRORS')) {
    define('SUPPRESS_ERRORS', true); // Ensure config suppresses display
}

// Start buffering early
if (!defined('API_OB_STARTED')) {
    ob_start();
    define('API_OB_STARTED', true);
}

// Standard headers (can be overridden later)
header('Content-Type: application/json; charset=utf-8');
header('X-API-Version: 1');

// Include config (respects SUPPRESS_ERRORS)
include_once __DIR__ . '/../includes/config.php';

// Unified JSON sender
function api_json($data, int $statusCode = 200): void {
    if (headers_sent() === false) {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
    }
    // Clean stray output
    if (defined('API_OB_STARTED')) {
        @ob_clean();
    }
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    }
    exit();
}

// Register shutdown handler to catch fatal errors that would output HTML
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=utf-8');
        }
        if (defined('API_OB_STARTED')) {
            @ob_clean();
        }
        echo json_encode([
            'success' => false,
            'message' => 'Fatal server error',
            'error' => $error['message'],
            'file' => basename($error['file']),
            'line' => $error['line']
        ]);
    }
});

// Helper for auth check
function api_require_login(): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    if (!isset($_SESSION['uid'])) {
        api_json(['success' => false, 'message' => 'Unauthorized'], 401);
    }
}

?>