<?php
/**
 * JSON safety net for AJAX endpoints.
 *
 * Guarantees the client always receives valid JSON — even on a PHP fatal
 * (undefined function, parse error, out-of-memory, etc.) — instead of an empty
 * body that surfaces as "Unexpected end of JSON input" in the browser.
 *
 * Include this FIRST in an AJAX endpoint:  require_once __DIR__ . '/_json_guard.php';
 */
declare(strict_types=1);

if (!defined('EDUTRACK_JSON_GUARD')) {
    define('EDUTRACK_JSON_GUARD', true);

    register_shutdown_function(static function (): void {
        $err = error_get_last();
        if ($err === null) {
            return;
        }
        $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
        if (!in_array($err['type'], $fatalTypes, true)) {
            return;
        }
        // Log the full detail, but return a clean message to the client.
        error_log('[EduTrack AJAX fatal] ' . $err['message'] . ' in ' . $err['file'] . ':' . $err['line']);
        if (!headers_sent()) {
            header('Content-Type: application/json');
            http_response_code(500);
        }
        echo json_encode([
            'success' => false,
            'message' => 'Server error: ' . $err['message'],
        ]);
    });
}
