<?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
    {
        if ($e instanceof Exceptions\ValidationException) {
            $referer = $_SERVER['HTTP_REFERER'] ?? '/';
            header('Location: ' . $referer);
            exit;
        }

        if ($e instanceof Exceptions\BusinessLogicException) {
            try {
                $session = App::getInstance()->session();
                $session->flash('_alerts', [['type' => 'error', 'message' => $e->getMessage()]]);
            } catch (\Throwable $t) {
            }
            $referer = $_SERVER['HTTP_REFERER'] ?? '/';
            header('Location: ' . $referer);
            exit;
        }

        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);
        }

        $httpCode = in_array($e->getCode(), [401, 403, 404], true) ? $e->getCode() : 500;

        $isAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
                || (isset($_SERVER['HTTP_ACCEPT']) && str_contains($_SERVER['HTTP_ACCEPT'], 'application/json'))
                || (isset($_SERVER['CONTENT_TYPE']) && str_contains($_SERVER['CONTENT_TYPE'], 'json'));

        if ($isAjax) {
            http_response_code($httpCode);
            header('Content-Type: application/json; charset=utf-8');
            $payload = ['success' => false, 'error' => 'حدث خطأ في الخادم'];
            if ($debug) {
                $payload['error'] = $e->getMessage();
                $payload['file'] = $e->getFile() . ':' . $e->getLine();
            }
            echo json_encode($payload, JSON_UNESCAPED_UNICODE);
            exit(1);
        }

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

        if ($httpCode === 403) {
            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;}'
                . 'a{color:#0D7377;text-decoration:none;}</style></head>'
                . '<body><h1>403</h1><p>ليس لديك صلاحية للوصول إلى هذه الصفحة.</p>'
                . '<a href="/dashboard">العودة للوحة التحكم</a></body></html>';
        } elseif ($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);
    }
}