<?php
declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

$config = require BASE_PATH . '/config/config.php';
$GLOBALS['zalorox_config'] = $config;

require BASE_PATH . '/app/Core/Helpers.php';

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';

    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }

    $file = BASE_PATH . '/app/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';

    if (is_file($file)) {
        require $file;
    }
});

\App\Core\Session::start($config);
\App\Core\Lang::boot($config);

$router = new \App\Core\Router($config);
require BASE_PATH . '/routes.php';

try {
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $area = \App\Core\DomainRouter::area($host, $uri, $config);
    $response = $router->dispatch($method, $uri, $area);

    if ($response instanceof \App\Core\Response) {
        $response->send();
        return;
    }

    echo (string) $response;
} catch (Throwable $exception) {
    http_response_code(500);

    $logDir = $config['paths']['logs'] ?? BASE_PATH . '/storage/logs';
    if (is_dir($logDir)) {
        error_log('[' . date('c') . '] ' . $exception . PHP_EOL, 3, $logDir . '/app.log');
    }

    $message = ($config['APP_DEBUG'] ?? false)
        ? '<pre>' . App\Core\e($exception->getMessage()) . '</pre>'
        : '<p>Bir hata olustu. Lutfen daha sonra tekrar deneyin.</p>';

    echo \App\Core\View::page('main', 'pages/show', [
        'title' => 'Sunucu hatasi',
        'page' => [
            'title' => 'Sunucu hatasi',
            'content' => strip_tags($message),
        ],
    ]);
}
