<?php
declare(strict_types=1);

namespace App\Core;

final class ExceptionHandler
{
    public static function register(): void
    {
        set_exception_handler([self::class, 'handleException']);
        set_error_handler([self::class, 'handleError']);
    }

    public static function handleException(\Throwable $e): void
    {
        Logger::error($e->getMessage(), [
            'file'  => $e->getFile(),
            'line'  => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);

        $data = ['exception' => $e];
        EventBus::dispatch('system.exception', $data);

        $debug = false;
        try {
            $debug = App::getInstance()->isDebug();
        } catch (\Throwable $t) {
            $debug = env('APP_DEBUG', false);
        }

        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');

        if ($debug) {
            echo '<html dir="rtl" lang="ar"><head><meta charset="utf-8"><title>خطأ</title>'
                . '<style>body{font-family:monospace,Cairo;padding:20px;background:#fef2f2;direction:ltr;text-align:left;}'
                . 'h1{color:#DC2626;}pre{background:#1a1a2e;color:#e5e7eb;padding:15px;border-radius:8px;overflow-x:auto;white-space:pre-wrap;}'
                . '.info{background:#fff;padding:10px;border:1px solid #e5e7eb;border-radius:4px;margin-bottom:10px;}</style></head><body>'
                . '<h1>💀 Exception: ' . htmlspecialchars(get_class($e)) . '</h1>'
                . '<div class="info"><strong>Message:</strong> ' . htmlspecialchars($e->getMessage()) . '</div>'
                . '<div class="info"><strong>File:</strong> ' . htmlspecialchars($e->getFile()) . ':' . $e->getLine() . '</div>'
                . '<pre>' . htmlspecialchars($e->getTraceAsString()) . '</pre>'
                . '</body></html>';
        } else {
            echo '<html dir="rtl" lang="ar"><head><meta charset="utf-8"><title>خطأ في الخادم</title>'
                . '<style>body{font-family:Cairo,sans-serif;text-align:center;padding:60px;background:#f9fafb;}'
                . 'h1{color:#DC2626;font-size:48px;}p{color:#6B7280;font-size:16px;}</style></head>'
                . '<body><h1>500</h1><p>عفواً، حدث خطأ في الخادم. يرجى المحاولة لاحقاً.</p></body></html>';
        }

        exit(1);
    }

    public static function handleError(int $errno, string $errstr, string $errfile, int $errline): bool
    {
        if (!(error_reporting() & $errno)) {
            return false;
        }

        throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
}