<?php
/**
 * Autoloader for the plugin.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes
 * @author     miniOrange
 */

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

/**
 * Autoloader function for the plugin.
 *
 * @param string $class_name The fully-qualified class name.
 * @return void
 */
function momcs_sync_autoloader( $class_name ) {
	// Check for both possible namespace prefixes.
	$prefixes = array(
		'MOMCS_Sync\\',
	);

	$prefix_matched = false;
	$base_namespace = '';

	// Check if the class uses one of our namespaces.
	foreach ( $prefixes as $prefix ) {
		if ( 0 === strpos( $class_name, $prefix ) ) {
			$prefix_matched = true;
			$base_namespace = $prefix;
			break;
		}
	}

	// If the class does not use any of our namespaces, skip it.
	if ( ! $prefix_matched ) {
		return;
	}

	// Convert namespace to file path.
	$file_path = str_replace( $base_namespace, '', $class_name );
	$file_path = str_replace( '\\', DIRECTORY_SEPARATOR, $file_path );
	$file_path = strtolower( $file_path );

	// Replace underscores with hyphens to match directory naming convention.
	$file_path = str_replace( '_', '-', $file_path );

	// Convert class name to file name.
	$parts      = explode( DIRECTORY_SEPARATOR, $file_path );
	$class_file = array_pop( $parts );

	// Check if it's an interface before adding the prefix.
	if ( strpos( $class_name, 'Interface' ) !== false ) {
		$class_file = 'interface-' . str_replace( '_', '-', $class_file ) . '.php';
	} else {
		$class_file = 'class-' . str_replace( '_', '-', $class_file ) . '.php';
	}

	// Build the file path.
	$file_path = implode( DIRECTORY_SEPARATOR, $parts ) . DIRECTORY_SEPARATOR . $class_file;
	$file_path = MOMCS_PLUGIN_DIR . $file_path;

	// If the file exists, require it.
	if ( file_exists( $file_path ) ) {
		require_once $file_path;
	}
}

// Register the autoloader.
spl_autoload_register( 'momcs_sync_autoloader' );

// Load Composer dependencies if available.
$composer_autoload = MOMCS_PLUGIN_DIR . 'vendor/autoload.php';
if ( file_exists( $composer_autoload ) ) {
	require_once $composer_autoload;
}
