<?php
/**
 * PSR-4 Autoloader for Gmind Institute
 *
 * Manually implemented autoloader following PSR-4 standard.
 * This file replaces the need for Composer's autoload on the server.
 *
 * Namespaces:
 *   App\        → /app/
 *   Core\       → /app/Core/
 *   Admin\      → /admin/
 */

declare(strict_types=1);

// Project root is one level up from vendor/
$projectRoot = dirname(__DIR__);

spl_autoload_register(function (string $class) use ($projectRoot): void {
    // Define namespace prefixes and their base directories
    $prefixes = [
        'App\\Controllers\\' => $projectRoot . '/app/Controllers/',
        'App\\Models\\'      => $projectRoot . '/app/Models/',
        'App\\Core\\'        => $projectRoot . '/app/Core/',
        'Core\\'             => $projectRoot . '/app/Core/',
        'App\\'              => $projectRoot . '/app/',
        'Admin\\Controllers\\' => $projectRoot . '/admin/Controllers/',
        'Admin\\'            => $projectRoot . '/admin/',
    ];

    foreach ($prefixes as $prefix => $baseDir) {
        // Check if the class uses this namespace prefix
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) {
            continue;
        }

        // Get the relative class name
        $relativeClass = substr($class, $len);

        // Replace namespace separators with directory separators and append .php
        $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';

        // If the file exists, require it
        if (file_exists($file)) {
            require $file;
            return;
        }
    }
});
