<?php
if (!function_exists('mf_forms_debug_enabled')) {
    function mf_forms_debug_enabled()
    {
        if (isset($_GET['__debug']) && $_GET['__debug'] === '1') {
            return true;
        }
        return is_file(__DIR__ . '/.debug_forms');
    }
}

if (!function_exists('mf_forms_log_error')) {
    function mf_forms_log_error($label, $message, $context = array())
    {
        $dir = __DIR__ . '/logs';
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        $file = $dir . '/formularios_debug.log';
        $line = '[' . date('Y-m-d H:i:s') . '] ' . $label . ': ' . $message;
        if (!empty($context)) {
            $line .= ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        $line .= PHP_EOL;
        @file_put_contents($file, $line, FILE_APPEND);
    }
}

if (mf_forms_debug_enabled()) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);

    set_error_handler(function ($severity, $message, $file, $line) {
        if (!(error_reporting() & $severity)) {
            return false;
        }
        throw new ErrorException($message, 0, $severity, $file, $line);
    });

    register_shutdown_function(function () {
        $error = error_get_last();
        if (!$error) {
            return;
        }
        $fatalTypes = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
        if (!in_array($error['type'], $fatalTypes, true)) {
            return;
        }
        mf_forms_log_error('FATAL', $error['message'], array('file' => $error['file'], 'line' => $error['line']));
        if (!headers_sent()) {
            http_response_code(500);
            header('Content-Type: text/plain; charset=UTF-8');
        }
        echo "ERRO FATAL EM formularios.php

";
        echo $error['message'] . "
";
        echo 'Arquivo: ' . $error['file'] . "
";
        echo 'Linha: ' . $error['line'] . "

";
        echo "Consulte também: /0/diagnostico_formularios.php e /0/logs/formularios_debug.log
";
    });
}
