<?php

/**
 * SiteCake PSR-4 Autoloader — replaces Composer's vendor/autoload.php
 *
 * Maps the Sitecake\ namespace to src/Sitecake/ and supports dynamic
 * PSR-4 prefix registration for plugins (via SitecakeClassLoader::setPsr4).
 */
final class SitecakeClassLoader
{
    /** @var array<string, string[]> */
    private static $prefixes = [];

    private function __construct() {}

    public static function register(): void
    {
        spl_autoload_register([self::class, 'loadClass']);
    }

    /**
     * Register an additional PSR-4 prefix (used by the plugin system).
     *
     * @param string   $prefix  Namespace prefix with trailing backslash, e.g. "Sitecake\Plugins\Foo\"
     * @param string[] $dirs    Array of base directories to search
     */
    public static function setPsr4(string $prefix, array $dirs): void
    {
        self::$prefixes[$prefix] = $dirs;
    }

    public static function loadClass(string $class): bool
    {
        // Check dynamically registered PSR-4 prefixes (plugins) first
        foreach (self::$prefixes as $prefix => $dirs) {
            $prefixLen = strlen($prefix);
            if (strncmp($class, $prefix, $prefixLen) !== 0) {
                continue;
            }
            $relative = substr($class, $prefixLen);
            $file     = str_replace('\\', DIRECTORY_SEPARATOR, $relative) . '.php';
            foreach ($dirs as $dir) {
                $path = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file;
                if (file_exists($path)) {
                    require $path;
                    return true;
                }
            }
        }

        // Built-in Sitecake\ namespace → src/Sitecake/
        if (strncmp($class, 'Sitecake\\', 9) === 0) {
            $relative = substr($class, 9);
            $path = __DIR__
                . DIRECTORY_SEPARATOR . 'Sitecake'
                . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relative)
                . '.php';
            if (file_exists($path)) {
                require $path;
                return true;
            }
        }

        return false;
    }
}

SitecakeClassLoader::register();
