<?php

declare(strict_types=1);

namespace BotGuard\Core;

/**
 * Minimal PSR-4 autoloader.
 *
 * The project ships with Composer, but this fallback lets the platform run on
 * shared hosting where `composer install` may not have been executed. It maps
 * the `BotGuard\` namespace to the `app/` directory and also loads the global
 * helper functions.
 *
 * Usage (only when vendor/autoload.php is absent):
 *   require app/Core/Autoloader.php;
 *   Autoloader::register();
 */
final class Autoloader
{
    private const PREFIX = 'BotGuard\\';

    public static function register(): void
    {
        $baseDir = dirname(__DIR__) . DIRECTORY_SEPARATOR; // .../app/

        spl_autoload_register(static function (string $class) use ($baseDir): void {
            if (! str_starts_with($class, self::PREFIX)) {
                return;
            }

            $relative = substr($class, strlen(self::PREFIX));
            $file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relative) . '.php';

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

        // Global helpers (mirrors composer's autoload.files).
        $helpers = $baseDir . 'Helpers' . DIRECTORY_SEPARATOR . 'functions.php';
        if (is_file($helpers)) {
            require_once $helpers;
        }
    }
}
