<?php
if (!function_exists('wr_runtime_safe_error_message')) { function wr_runtime_safe_error_message(){ return 'WinRacing runtime encountered an error. Request ID: '.wr_runtime_request_id(); } }
if (!function_exists('wr_runtime_emit_failure')) {
    function wr_runtime_emit_failure($type,$httpCode=500){
        if(!empty($GLOBALS['WR_RUNTIME_FAILURE_EMITTED'])) return; $GLOBALS['WR_RUNTIME_FAILURE_EMITTED']=true;
        if(wr_runtime_is_api()) wr_json_response(array('message'=>wr_runtime_safe_error_message()),'RUNTIME',WR_RUNTIME_V503,'ERROR',$httpCode,'',false);
        if(!headers_sent()) http_response_code($httpCode);
        echo '<div style="margin:20px;padding:16px;border:1px solid #8b2635;border-radius:10px;background:#fff4f5;color:#661522;font-family:Arial,sans-serif"><strong>WinRacing Runtime Error</strong><br>'.htmlspecialchars(wr_runtime_safe_error_message(),ENT_QUOTES,'UTF-8').'</div>';
    }
}
if (!function_exists('wr_runtime_error_handler')) {
    function wr_runtime_error_handler($severity,$message,$file,$line){
        if(!(error_reporting() & $severity)) return false;
        $level=in_array($severity,array(E_WARNING,E_USER_WARNING,E_CORE_WARNING,E_COMPILE_WARNING),true)?'WARNING':'ERROR';
        wr_runtime_log($level,$message,array('severity'=>$severity),$file,$line);
        return true;
    }
}
if (!function_exists('wr_runtime_exception_handler')) {
    function wr_runtime_exception_handler($e){ wr_runtime_log('EXCEPTION',$e->getMessage(),array('class'=>get_class($e),'code'=>$e->getCode()),$e->getFile(),$e->getLine()); wr_runtime_emit_failure('EXCEPTION',500); }
}
if (!function_exists('wr_runtime_shutdown_handler')) {
    function wr_runtime_shutdown_handler(){ $e=error_get_last(); if(!$e) return; if(in_array($e['type'],array(E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR,E_USER_ERROR),true)){ wr_runtime_log('FATAL',$e['message'],array('type'=>$e['type']),$e['file'],$e['line']); wr_runtime_emit_failure('FATAL',500); } }
}
if (!function_exists('wr_error_handler_init')) {
    function wr_error_handler_init(){ set_error_handler('wr_runtime_error_handler'); set_exception_handler('wr_runtime_exception_handler'); register_shutdown_function('wr_runtime_shutdown_handler'); $GLOBALS['WR_ERROR_HANDLER_ACTIVE']=true; }
}
