<?php
if (!defined('MUSIC_APP_ERROR_HANDLER')) {
    define('MUSIC_APP_ERROR_HANDLER', true);

    set_error_handler(function ($severity, $message, $file, $line) {
        if (!(error_reporting() & $severity)) return false;
        $level = in_array($severity, [E_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR], true) ? 'error' : 'warning';
        if (function_exists('writeAppLog')) {
            writeAppLog($level, 'php_error', $message, ['severity' => $severity, 'line' => $line], $file);
        }
        return true;
    });

    register_shutdown_function(function () {
        $error = error_get_last();
        if (!$error) return;
        if (!in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) return;
        if (function_exists('writeAppLog')) {
            writeAppLog('critical', 'php_error', $error['message'], ['type' => $error['type'], 'line' => $error['line']], $error['file']);
        }
    });
}
