<?php
/**
 * PSR-4 Autoloader for TitanCart.
 *
 * Maps  TitanCart\  →  {TITANCART_SRC}
 *
 * @package TitanCart\Core
 */

namespace TitanCart\Core;

defined( 'ABSPATH' ) || exit;

class Autoloader {

    /**
     * Namespace prefix for this autoloader.
     */
    private const PREFIX = 'TitanCart\\';

    /**
     * Base directory for the namespace prefix.
     */
    private static string $base_dir = '';

    /**
     * Register the autoloader with PHP's SPL stack.
     */
    public static function register(): void {
        self::$base_dir = TITANCART_SRC;
        spl_autoload_register( [ self::class, 'load' ] );
    }

    /**
     * Load the class file for a given class name.
     *
     * @param string $class Fully-qualified class name.
     */
    public static function load( string $class ): void {
        // Check if class uses our namespace prefix.
        if ( strncmp( self::PREFIX, $class, strlen( self::PREFIX ) ) !== 0 ) {
            return;
        }

        // Strip prefix and convert namespace separators to directory separators.
        $relative = substr( $class, strlen( self::PREFIX ) );
        $file     = self::$base_dir . str_replace( '\\', DIRECTORY_SEPARATOR, $relative ) . '.php';

        if ( is_readable( $file ) ) {
            require_once $file;
        }
    }
}
