<?php
/**
 * Mersal Suite — version-aware loader.
 *
 * Every Mersal plugin ships an identical copy of the Suite SDK so it can run
 * standalone. This loader lets all active copies agree on a single winner: the
 * highest SDK version registered wins, and the class is loaded exactly once on
 * `plugins_loaded`. Include this file early (during the plugin's main file) and
 * call mersal_suite_register_sdk( VERSION, PATH_TO_CLASS ).
 *
 * @package Mersal_Suite
 */

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

if ( ! function_exists( 'mersal_suite_register_sdk' ) ) {

	/**
	 * Register a copy of the Suite SDK. Highest version wins.
	 *
	 * @param string $version SDK version.
	 * @param string $path    Absolute path to class-mersal-suite.php.
	 */
	function mersal_suite_register_sdk( $version, $path ) {
		if ( ! isset( $GLOBALS['mersal_suite_sdk'] ) || version_compare( $version, $GLOBALS['mersal_suite_sdk']['version'], '>' ) ) {
			$GLOBALS['mersal_suite_sdk'] = array(
				'version' => $version,
				'path'    => $path,
			);
		}
		if ( ! has_action( 'plugins_loaded', 'mersal_suite_load' ) ) {
			add_action( 'plugins_loaded', 'mersal_suite_load', 2 );
		}
	}

	/**
	 * Load the winning SDK copy (once).
	 */
	function mersal_suite_load() {
		if ( class_exists( 'Mersal_Suite' ) ) {
			return;
		}
		if ( ! empty( $GLOBALS['mersal_suite_sdk']['path'] ) && file_exists( $GLOBALS['mersal_suite_sdk']['path'] ) ) {
			require_once $GLOBALS['mersal_suite_sdk']['path'];
		}
	}
}
