<?php
/// file: app/Core/ErrorHandler.php

declare(strict_types=1);

namespace App\Core;

final class ErrorHandler
{
    public static function register(string $basePath, bool $debug): void
    {
        set_exception_handler(function (\Throwable $e) use ($basePath, $debug): void {
            $logDir = $basePath . '/storage/logs';
            if (is_dir($logDir)) {
                $line = date('c') . ' ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . "\n" . $e->getTraceAsString() . "\n";
                @file_put_contents($logDir . '/app.log', $line, FILE_APPEND);
            }
            if (! headers_sent()) {
                http_response_code(500);
                header('Content-Type: text/html; charset=UTF-8');
            }
            if ($debug) {
                echo '<pre>' . htmlspecialchars($e->getMessage() . "\n" . $e->getTraceAsString(), ENT_QUOTES, 'UTF-8') . '</pre>';
            } else {
                $file = dirname(__DIR__, 1) . '/View/errors/500.php';
                if (is_file($file)) {
                    include $file;
                } else {
                echo 'An error occurred.';
                }
            }
        });
    }
}
