<?php
/**
 * Safe loader for bundled Spark News module copies across RSM plugins.
 *
 * Plugins still ship includes/rsm-spark-news.php with rsm_spark_news_* symbols.
 * Accept both legacy and rsmspark_* names so second plugins do not re-require
 * a different path and fatal on "Cannot redeclare function".
 *
 * @package Rsmspark_Suite
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'rsmspark_suite_load_spark_news_module' ) ) {
	/**
	 * Load Spark News once per request regardless of plugin load order.
	 *
	 * @param string $module_path Absolute path to includes/rsm-spark-news.php.
	 * @param string $asset_url   Plugin assets base URL.
	 * @param string $asset_path  Plugin assets base filesystem path.
	 * @return void
	 */
	function rsmspark_suite_load_spark_news_module( $module_path, $asset_url, $asset_path ) {
		if ( ! is_admin() ) {
			return;
		}

		if (
			defined( 'RSM_SPARK_NEWS_BOOTSTRAPPED' )
			|| defined( 'RSMSPARK_NEWS_BOOTSTRAPPED' )
			|| defined( 'RSM_SPARK_NEWS_MODULE_LOADED' )
			|| defined( 'RSMSPARK_NEWS_MODULE_LOADED' )
		) {
			rsmspark_suite_maybe_bootstrap_spark_news(
				array(
					'asset_url'  => (string) $asset_url,
					'asset_path' => (string) $asset_path,
				)
			);
			return;
		}

		if (
			function_exists( 'rsm_spark_news_bootstrap' )
			|| function_exists( 'rsmspark_news_bootstrap' )
		) {
			rsmspark_suite_maybe_bootstrap_spark_news(
				array(
					'asset_url'  => (string) $asset_url,
					'asset_path' => (string) $asset_path,
				)
			);
			return;
		}

		$module_path = (string) $module_path;
		if ( '' === $module_path || ! is_readable( $module_path ) ) {
			return;
		}

		require_once $module_path;

		rsmspark_suite_maybe_bootstrap_spark_news(
			array(
				'asset_url'  => (string) $asset_url,
				'asset_path' => (string) $asset_path,
			)
		);
	}
}

if ( ! function_exists( 'rsmspark_suite_maybe_bootstrap_spark_news' ) ) {
	/**
	 * Invoke whichever Spark News bootstrap symbol exists.
	 *
	 * @param array<string, string> $config Asset URLs/paths.
	 * @return void
	 */
	function rsmspark_suite_maybe_bootstrap_spark_news( array $config ) {
		if ( function_exists( 'rsm_spark_news_bootstrap' ) ) {
			rsm_spark_news_bootstrap( $config );
			return;
		}
		if ( function_exists( 'rsmspark_news_bootstrap' ) ) {
			rsmspark_news_bootstrap( $config );
		}
	}
}
