<?php
/**
 * PSR-4 Autoloader
 *
 * Lightweight PSR-4 compliant autoloader for WP PowerSuite.
 * No external dependencies required.
 *
 * @package WP_PowerSuite\Bootstrap
 * @since 1.0.0
 */

namespace WP_PowerSuite\Bootstrap;

/**
 * Register PSR-4 Autoloader
 *
 * Registers the PSR-4 autoloader for the WP PowerSuite namespace.
 * Maps 'WP_PowerSuite' namespace to 'src' directory.
 *
 * @since 1.0.0
 * @param string $namespace Namespace prefix (e.g., 'WP_PowerSuite').
 * @param string $base_dir Base directory for the namespace prefix.
 * @return bool True if autoloader was registered, false otherwise.
 */
function register_autoloader( string $namespace, string $base_dir ): bool {
	$prefix   = trim( $namespace, '\\' ) . '\\';
	$base_dir = rtrim( $base_dir, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;

	$autoloader_id = 'wp_powersuite_autoloader_' . md5( $prefix );
	$callback_id   = $autoloader_id . '_callback';
	if ( isset( $GLOBALS[ $autoloader_id ] ) && $GLOBALS[ $autoloader_id ] === true ) {
		return true;
	}

	/**
	 * PSR-4 Autoloader Callback
	 *
	 * @param string $class Fully qualified class name.
	 * @return void
	 */
	$autoloader = static function ( string $class ) use ( $prefix, $base_dir ): void {
		$len = strlen( $prefix );
		if ( strncmp( $prefix, $class, $len ) !== 0 ) {
			return;
		}

		$relative_class = str_replace( '\\', DIRECTORY_SEPARATOR, substr( $class, $len ) );
		$file           = $base_dir . $relative_class . '.php';

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

	$registered = spl_autoload_register( $autoloader, true, true );

	// Retain the callback so unregister_autoloader() can remove the same closure.
	if ( $registered ) {
		$GLOBALS[ $autoloader_id ] = true;
		$GLOBALS[ $callback_id ]   = $autoloader;
	}

	return $registered;
}

/**
 * Unregister PSR-4 Autoloader
 *
 * Unregisters the autoloader for the specified namespace.
 * Useful for testing or cleanup.
 *
 * @since 1.0.0
 * @param string $namespace Namespace prefix.
 * @return bool True if unregistered, false otherwise.
 */
function unregister_autoloader( string $namespace ): bool {
	$prefix = trim( $namespace, '\\' ) . '\\';

	$autoloader_id = 'wp_powersuite_autoloader_' . md5( $prefix );
	$callback_id   = $autoloader_id . '_callback';

	if ( empty( $GLOBALS[ $autoloader_id ] ) || ! isset( $GLOBALS[ $callback_id ] ) ) {
		return false;
	}

	$autoloader = $GLOBALS[ $callback_id ];
	if ( ! is_callable( $autoloader ) ) {
		unset( $GLOBALS[ $autoloader_id ], $GLOBALS[ $callback_id ] );
		return false;
	}

	$unregistered = spl_autoload_unregister( $autoloader );
	unset( $GLOBALS[ $autoloader_id ], $GLOBALS[ $callback_id ] );

	return $unregistered;
}



