<?php
/**
 * Plugin Autoloader
 */

namespace Merkulove\Readabler;

use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

final class Autoload {
	private static string $baseNamespace = 'Merkulove\\';
	private static string $baseDir;

	public static function load( string $class ): void {
		// Handle only our namespace
		if ( strpos( $class, self::$baseNamespace ) !== 0 ) {
			return;
		}

		// Normalize base directory
		if ( ! isset( self::$baseDir ) ) {
			self::$baseDir = realpath( dirname( __FILE__ ) ) ?: dirname( __FILE__ );
		}

		// Normalize namespace and clean up weird slashes
		$normalizedClass = str_replace( [ '\\\\', '/' ], [ '\\', '\\' ], $class );
		$normalizedClass = trim( $normalizedClass, '\\' );

		// Convert namespace to path
		$relativePath = str_replace( '\\', DIRECTORY_SEPARATOR, $normalizedClass ) . '.php';

		// Full path
		$file = self::$baseDir . DIRECTORY_SEPARATOR . $relativePath;

		// Attempt to include directly
		if ( file_exists( $file ) ) {
			include_once $file;

			return;
		}

		// Fallback: try lowercase first (for case-insensitive Windows)
		$lowercaseFile = strtolower( $file );
		if ( file_exists( $lowercaseFile ) ) {
			include_once $lowercaseFile;

			return;
		}

		// Optional recursive fallback — slower, but ensures legacy structure compatibility
		$filename = basename( $file );
		$found    = self::recursiveSearch( self::$baseDir, $filename );
		if ( $found ) {
			include_once $found;
		}
	}

	/**
	 * Recursively search for a file by name in subdirectories.
	 */
	private static function recursiveSearch( string $dir, string $filename ): ?string {
		$iterator = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS )
		);

		foreach ( $iterator as $file ) {
			if ( strcasecmp( $file->getFilename(), $filename ) === 0 ) {
				return $file->getPathname();
			}
		}

		return null;
	}
}

// Register autoloader
spl_autoload_register( __NAMESPACE__ . '\Autoload::load' );
