<?php
require_once __DIR__ . '/WorkflowExceptions.php';

function generate_correlation_id() {
    return uniqid('corr_');
}

function handle_exception(Throwable $e, $correlation_id) {
    if ($e instanceof WorkflowException) {
        http_response_code($e->getHttpCode());
        $response = [
            'error' => [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'details' => $e->getDetails(),
            ],
            'correlation_id' => $correlation_id,
        ];
    } else {
        http_response_code(500);
        error_log("Correlation ID: $correlation_id, Uncaught Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString());
        $response = [
            'error' => [
                'code' => 500,
                'message' => 'Internal Server Error',
            ],
            'correlation_id' => $correlation_id,
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

function register_error_handler() {
    $GLOBALS['correlation_id'] = generate_correlation_id();
    set_exception_handler(function(Throwable $e) {
        handle_exception($e, $GLOBALS['correlation_id']);
    });
    // You can also set a general error handler for non-exception errors
    set_error_handler(function($severity, $message, $file, $line) {
        if (!(error_reporting() & $severity)) {
            return;
        }
        error_log("Correlation ID: {$GLOBALS['correlation_id']}, Error: [$severity] $message in $file on line $line");
        // Don't output anything to the user for non-fatal errors, just log them
    });
}
