<?php
/**
 * Autoloader file.
 *
 * @package automation-web-platform
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Load global helper functions.
require_once __DIR__ . '/wawp-functions.php';

// Load Composer-managed vendor libraries (Guzzle, Carbon, libphonenumber, etc.).
$wawp_vendor_autoload = WAWP_PLUGIN_DIR . 'vendor/autoload.php';
if ( file_exists( $wawp_vendor_autoload ) ) {
	require_once $wawp_vendor_autoload;

	// Critical Fix: Namespace aliasing for partially scoped interfaces
	// This prevents "Interface not found" errors when some libraries are scoped and others are not.
	$wawp_psr_aliases = array(
		'Psr\Clock\ClockInterface'                  => 'WAWP\Vendor\Psr\Clock\ClockInterface',
		'Psr\Log\LoggerInterface'                   => 'WAWP\Vendor\Psr\Log\LoggerInterface',
		'libphonenumber\PhoneNumberUtil'            => 'WAWP\Vendor\libphonenumber\PhoneNumberUtil',
		'libphonenumber\PhoneNumberToCarrierMapper' => 'WAWP\Vendor\libphonenumber\PhoneNumberToCarrierMapper',
	);

	foreach ( $wawp_psr_aliases as $wawp_original => $wawp_scoped ) {
		if ( ( interface_exists( $wawp_original ) && ! interface_exists( $wawp_scoped ) ) || ( class_exists( $wawp_original ) && ! class_exists( $wawp_scoped ) ) ) {
			class_alias( $wawp_original, $wawp_scoped );
		}
	}
}

unset( $wawp_vendor_autoload );

// Plugin-specific autoloader (WAWP_* classes only).
spl_autoload_register(
	function ( $class_name ) {
		if ( 0 !== strpos( $class_name, 'WAWP_' ) ) {
			return;
		}

		$clean_class = strtolower( str_replace( '_', '-', $class_name ) );
		$is_trait    = ( false !== strpos( $clean_class, '-trait' ) );

		// Specialized directories based on class name patterns.
		$search_map = array();

		if ( 0 === strpos( $class_name, 'WAWP_Rest_' ) ) {
			$search_map[] = 'includes/api/';
		} elseif ( 0 === strpos( $class_name, 'WAWP_Notif_' ) ) {
			$search_map[] = 'includes/notifications/';
			$search_map[] = 'includes/notifications/Triggers/';
		} elseif ( $is_trait ) {
			$search_map[] = 'includes/traits/';
		}

		// General fallback directories.
		$search_map = array_merge(
			$search_map,
			array(
				'includes/helpers/',
				'includes/general/',
				'includes/messaging-tools/',
				'includes/auth-services/',
				'includes/abandoned-cart/',
				'includes/logs/',
				'includes/senders/',
				'includes/notifications/',
				'includes/notifications/Triggers/',
				'includes/campaigns/',
				'includes/',
			)
		);

		$search_map = array_unique( $search_map );

		foreach ( $search_map as $dir ) {
			$files = array(
				'class-' . $clean_class . '.php',
				'trait-' . $clean_class . '.php',
			);

			if ( $is_trait ) {
				$files[] = 'trait-' . str_replace( '-trait', '', $clean_class ) . '.php';
			}

			foreach ( $files as $f ) {
				$path = WAWP_PLUGIN_DIR . $dir . $f;
				if ( file_exists( $path ) ) {
					require_once $path;
					return;
				}
			}
		}
	}
);
