<?php

declare(strict_types=1);

namespace App\Core;

final class App
{
    /** @var array<string, mixed> */
    private static array $config = [];

    private static string $basePath = '';

    public static function boot(): void
    {
        self::$config = require dirname(__DIR__, 2) . '/config.php';
        self::$basePath = self::detectBasePath();
        date_default_timezone_set(self::config('app')['timezone']);

        if (self::config('app')['debug']) {
            ini_set('display_errors', '1');
            error_reporting(E_ALL);
        } else {
            ini_set('display_errors', '0');
        }

        require __DIR__ . '/polyfills.php';

        // PSR-4 style autoloader for the App\ namespace.
        spl_autoload_register(function (string $class): void {
            if (!str_starts_with($class, 'App\\')) {
                return;
            }
            $path = dirname(__DIR__) . '/' . str_replace('\\', '/', substr($class, 4)) . '.php';
            if (file_exists($path)) {
                require $path;
            }
        });
    }

    /** @return array<string, mixed> */
    public static function config(string $key): array
    {
        return self::$config[$key] ?? [];
    }

    /**
     * URL prefix the app is served under ('' at the domain root,
     * '/backend' when installed in a subfolder). Used for routing,
     * redirects and every URL printed in the admin views.
     */
    public static function basePath(): string
    {
        return self::$basePath;
    }

    private static function detectBasePath(): string
    {
        $configured = self::config('app')['base_path'] ?? null;
        if (is_string($configured)) {
            return rtrim($configured, '/');
        }

        // Auto-detect: the longest ancestor of SCRIPT_NAME that prefixes the
        // request path. Handles both direct subfolder installs
        // (/backend/public/admin) and rewrites from a parent folder
        // (/backend/admin -> backend/public/index.php).
        $uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
        $dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/'));
        while ($dir !== '' && $dir !== '/' && $dir !== '.') {
            if ($uri === $dir || str_starts_with($uri, $dir . '/')) {
                return $dir;
            }
            $dir = dirname($dir);
        }
        return '';
    }
}
