<?php

declare( strict_types=1 );

namespace StrykeWP\Core;

/**
 * PSR-4 Autoloader for the StrykeWP namespace.
 *
 * Maps:  StrykeWP\Core\Logger    → {plugin_dir}/src/Core/Logger.php
 *        StrykeWP\Admin\Dashboard → {plugin_dir}/src/Admin/Dashboard.php
 *        StrykeWP\Modules\Backup\BackupModule → {plugin_dir}/src/Modules/Backup/BackupModule.php
 *
 * @package StrykeWP\Core
 */
final class Autoloader {

	private const NAMESPACE_PREFIX = 'StrykeWP\\';
	private const BASE_DIR         = STRYKE_WP_DIR . 'src/';

	/**
	 * Registers this autoloader with spl_autoload_register().
	 */
	public static function register(): void {
		spl_autoload_register( [ self::class, 'load' ] );
	}

	/**
	 * Resolves a fully-qualified class name to a file path and includes it.
	 *
	 * @param string $class Fully-qualified class name.
	 */
	public static function load( string $class ): void {
		// Only handle classes in our namespace.
		if ( ! str_starts_with( $class, self::NAMESPACE_PREFIX ) ) {
			return;
		}

		// Strip prefix, replace namespace separators with directory separators.
		$relative = substr( $class, strlen( self::NAMESPACE_PREFIX ) );
		$file     = self::BASE_DIR . str_replace( '\\', '/', $relative ) . '.php';
		$real     = realpath( $file );
		$base_dir = realpath( self::BASE_DIR );

		if ( false !== $real && false !== $base_dir && str_starts_with( $real, $base_dir . DIRECTORY_SEPARATOR ) ) {
			require_once $real;
		}
	}
}
