<?php

namespace Core;

class Autoloader {
    /**
     * Register the autoloader.
     */
    public static function register() {
        spl_autoload_register([__CLASS__, 'autoload']);
    }

    /**
     * Autoload method for controllers.
     * 
     * @param string $className
     */
    private static function autoload($className) {
        // Handle App\Controllers namespace
        if (strpos($className, 'App\\Controllers\\') === 0) {
            // Extract the class name without namespace
            $classNameOnly = str_replace('App\\Controllers\\', '', $className);
            // Path to the controller files (lowercase 'controllers')
            $controllerPath = dirname(__DIR__) . '/app/controllers/' . $classNameOnly . '.php';

            // Check if the file exists and require it
            if (file_exists($controllerPath)) {
                require_once $controllerPath;
                return;
            } else {
                // Handle error if the controller does not exist
                die("Controller file not found: " . $controllerPath);
            }
        }
        
        // Check if the class belongs to the 'Controller' namespace (legacy support)
        if (strpos($className, 'Controller') !== false) {
            // Path to the controller files
            $controllerPath = dirname(__DIR__)  . '/app/controllers/' . $className . '.php';

            // Check if the file exists and require it
            if (file_exists($controllerPath)) {
                require_once $controllerPath;
            } else {
                // Handle error if the controller does not exist
                die("Controller file not found: " . $controllerPath);
            }
        }
    }
}
