<?php
/**
 * Runtime-safe helpers when multiple RSM plugins bundle different rsm-shared versions.
 *
 * @package Rsmspark_Suite
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'rsmspark_suite_shared_asset_url' ) ) {
	/**
	 * Resolve a public URL for a file under rsm-shared without relying on RSMSPARK_SUITE_URL.
	 *
	 * @param string $relative_path Path relative to the rsm-shared root.
	 * @param string $shared_dir    Optional absolute rsm-shared directory override.
	 * @return string Asset URL, or empty when the file is not readable.
	 */
	function rsmspark_suite_shared_asset_url( $relative_path, $shared_dir = '' ) {
		$relative = ltrim( (string) $relative_path, '/' );
		$dirs     = array();

		if ( '' !== (string) $shared_dir ) {
			$dirs[] = trailingslashit( (string) $shared_dir );
		}

		if ( defined( 'RSMSPARK_SUITE_DIR' ) ) {
			$dirs[] = RSMSPARK_SUITE_DIR;
		}

		foreach ( $dirs as $dir ) {
			$absolute = $dir . $relative;
			if ( ! is_readable( $absolute ) ) {
				continue;
			}

			return plugins_url( $relative, $dir . 'bootstrap.php' );
		}

		return '';
	}
}

if ( ! function_exists( 'rsmspark_suite_find_shared_asset' ) ) {
	/**
	 * Locate a readable rsm-shared asset across the bootstrap copy and active plugins.
	 *
	 * @param string $relative_path Path relative to the rsm-shared root.
	 * @return array{path:string,url:string,dir:string}|null
	 */
	function rsmspark_suite_find_shared_asset( $relative_path ) {
		$relative = ltrim( (string) $relative_path, '/' );
		$dirs     = array();

		if ( defined( 'RSMSPARK_SUITE_DIR' ) ) {
			$dirs[] = RSMSPARK_SUITE_DIR;
		}

		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		foreach ( array_keys( get_plugins() ) as $plugin_file ) {
			if ( ! is_plugin_active( $plugin_file ) ) {
				continue;
			}

			$plugin_root = WP_PLUGIN_DIR . '/' . dirname( $plugin_file );
			$shared_dir  = trailingslashit( $plugin_root ) . 'rsm-shared/';

			if ( in_array( $shared_dir, $dirs, true ) ) {
				continue;
			}

			$dirs[] = $shared_dir;
		}

		foreach ( $dirs as $dir ) {
			$absolute = $dir . $relative;
			if ( ! is_readable( $absolute ) ) {
				continue;
			}

			return array(
				'path' => $absolute,
				'url'  => plugins_url( $relative, $dir . 'bootstrap.php' ),
				'dir'  => $dir,
			);
		}

		return null;
	}
}

if ( ! function_exists( 'rsmspark_suite_reconcile_admin_menu_assets' ) ) {
	/**
	 * Replace broken rsmspark-suite-admin-menu URLs from older bootstrapped rsm-shared copies.
	 *
	 * @return void
	 */
	function rsmspark_suite_reconcile_admin_menu_assets() {
		static $done = false;

		if ( $done ) {
			return;
		}

		$done = true;

		wp_dequeue_style( 'rsmspark-suite-admin-menu' );
		wp_deregister_style( 'rsmspark-suite-admin-menu' );

		// Spark ships equivalent rules in assets/css/admin-menu.css on every wp-admin screen.
		if ( defined( 'RSMSPARK_SPARK_VERSION' ) ) {
			return;
		}

		$css_file = 'assets/css/admin-suite-menu.css';
		$asset    = rsmspark_suite_find_shared_asset( $css_file );

		if ( null === $asset ) {
			return;
		}

		wp_enqueue_style(
			'rsmspark-suite-admin-menu',
			$asset['url'],
			array(),
			defined( 'RSMSPARK_SUITE_VERSION' ) ? RSMSPARK_SUITE_VERSION : '1.7.1'
		);
	}

	add_action( 'admin_enqueue_scripts', 'rsmspark_suite_reconcile_admin_menu_assets', 999 );
}

if ( ! function_exists( 'rsmspark_suite_flag_getting_started_intro' ) ) {
	/**
	 * Flag a getting-started notice when supported by the loaded shared class.
	 *
	 * @param string $slug              Notice slug.
	 * @param string $minimum_version   Plugin version that introduced the notice.
	 * @param string $current_version   Active plugin version.
	 * @return void
	 */
	function rsmspark_suite_flag_getting_started_intro( $slug, $minimum_version, $current_version ) {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! class_exists( 'Rsmspark_Getting_Started_Notice', false ) || ! method_exists( 'Rsmspark_Getting_Started_Notice', 'flag_if_pending_introduction' ) ) {
			return;
		}

		Rsmspark_Getting_Started_Notice::flag_if_pending_introduction( $slug, $minimum_version, $current_version );
	}
}

if ( ! function_exists( 'rsmspark_suite_enqueue_shared_style' ) ) {
	/**
	 * Enqueue a stylesheet from the caller's bundled rsm-shared when provided.
	 *
	 * When $prefer_caller is true, replaces any prior registration for the handle
	 * so the active plugin's copy wins over whichever plugin bootstrapped Rsmspark_Suite first.
	 *
	 * @param string               $handle         Style handle.
	 * @param string               $relative_css   Path relative to rsm-shared root.
	 * @param string               $caller_dir     Absolute path to caller's rsm-shared directory.
	 * @param string               $caller_url     URL to caller's rsm-shared directory.
	 * @param string               $caller_version Asset version string.
	 * @param array<int, string>   $deps           Style dependencies.
	 * @param bool                 $prefer_caller  Prefer caller bundle over bootstrap winner.
	 * @return void
	 */
	function rsmspark_suite_enqueue_shared_style( $handle, $relative_css, $caller_dir = '', $caller_url = '', $caller_version = '', array $deps = array(), $prefer_caller = false ) {
		$css_file = ltrim( (string) $relative_css, '/' );
		$css_ver  = '' !== (string) $caller_version ? (string) $caller_version : ( defined( 'RSMSPARK_SUITE_VERSION' ) ? RSMSPARK_SUITE_VERSION : '1.0.0' );
		$css_url  = '';

		if ( $prefer_caller && '' !== (string) $caller_dir && is_readable( trailingslashit( (string) $caller_dir ) . $css_file ) ) {
			$css_url = trailingslashit( (string) $caller_url ) . $css_file;
		} elseif ( defined( 'RSMSPARK_SUITE_DIR' ) && is_readable( RSMSPARK_SUITE_DIR . $css_file ) ) {
			$css_url = function_exists( 'rsmspark_suite_shared_asset_url' )
				? rsmspark_suite_shared_asset_url( $css_file )
				: ( ( defined( 'RSMSPARK_SUITE_URL' ) ? RSMSPARK_SUITE_URL : '' ) . $css_file );
			if ( '' === (string) $caller_version ) {
				$css_ver = defined( 'RSMSPARK_SUITE_VERSION' ) ? RSMSPARK_SUITE_VERSION : $css_ver;
			}
		} elseif ( '' !== (string) $caller_dir && is_readable( trailingslashit( (string) $caller_dir ) . $css_file ) ) {
			$css_url = trailingslashit( (string) $caller_url ) . $css_file;
		}

		if ( '' === $css_url ) {
			return;
		}

		if ( $prefer_caller ) {
			if ( wp_style_is( $handle, 'enqueued' ) ) {
				wp_dequeue_style( $handle );
			}
			if ( wp_style_is( $handle, 'registered' ) ) {
				wp_deregister_style( $handle );
			}
		} elseif ( wp_style_is( $handle, 'enqueued' ) ) {
			return;
		}

		wp_enqueue_style( $handle, $css_url, $deps, $css_ver );
	}
}

if ( ! function_exists( 'rsmspark_suite_enqueue_admin_styles' ) ) {
	/**
	 * Enqueue shared admin-suite + button styles for the current plugin screen.
	 *
	 * @param string $caller_dir     Absolute path to caller's rsm-shared directory.
	 * @param string $caller_url     URL to caller's rsm-shared directory.
	 * @param string $caller_version Plugin version for cache busting.
	 * @return void
	 */
	function rsmspark_suite_enqueue_admin_styles( $caller_dir = '', $caller_url = '', $caller_version = '' ) {
		$prefer = '' !== (string) $caller_dir;

		rsmspark_suite_enqueue_shared_style(
			'rsmspark-suite-admin',
			'assets/css/admin-suite.css',
			$caller_dir,
			$caller_url,
			$caller_version,
			array(),
			$prefer
		);

		rsmspark_suite_enqueue_shared_style(
			'rsmspark-suite-buttons',
			'assets/css/admin-suite-buttons.css',
			$caller_dir,
			$caller_url,
			$caller_version,
			array( 'rsmspark-suite-admin' ),
			$prefer
		);
	}
}

if ( ! function_exists( 'rsmspark_suite_enqueue_button_styles' ) ) {
	/**
	 * Enqueue shared suite button styles.
	 *
	 * Pass the caller's bundled rsm-shared path to load that plugin's copy.
	 *
	 * @param string $fallback_shared_dir Absolute path to fallback rsm-shared directory.
	 * @param string $fallback_shared_url URL to fallback rsm-shared directory.
	 * @param string $version            Optional asset version string.
	 * @return void
	 */
	function rsmspark_suite_enqueue_button_styles( $fallback_shared_dir = '', $fallback_shared_url = '', $version = '' ) {
		rsmspark_suite_enqueue_shared_style(
			'rsmspark-suite-buttons',
			'assets/css/admin-suite-buttons.css',
			$fallback_shared_dir,
			$fallback_shared_url,
			$version,
			array( 'rsmspark-suite-admin' ),
			'' !== (string) $fallback_shared_dir
		);
	}
}

if ( ! function_exists( 'rsmspark_suite_render_admin_notice' ) ) {
	/**
	 * Render a branded suite admin notice (peach panel + Spark logo).
	 *
	 * @param string               $message Notice body.
	 * @param array<string, mixed> $args    Optional args for Rsmspark_Suite_Admin_Notice::render().
	 * @return void
	 */
	function rsmspark_suite_render_admin_notice( $message, array $args = array() ) {
		$message = (string) $message;
		if ( '' === $message ) {
			return;
		}

		if ( class_exists( 'Rsmspark_Suite_Admin_Notice', false ) ) {
			$args['message'] = $message;
			Rsmspark_Suite_Admin_Notice::render( $args );
			return;
		}

		echo '<div class="notice notice-info"><p>' . esc_html( $message ) . '</p></div>';
	}
}

if ( ! function_exists( 'rsmspark_suite_ensure_spark_news_loader' ) ) {
	/**
	 * Load the Spark News safe loader from this plugin's bundled rsm-shared copy.
	 *
	 * @param string $plugin_shared_dir Absolute path to the plugin's rsm-shared directory.
	 * @return void
	 */
	function rsmspark_suite_ensure_spark_news_loader( $plugin_shared_dir ) {
		if ( function_exists( 'rsmspark_suite_load_spark_news_module' ) ) {
			return;
		}

		$loader = trailingslashit( (string) $plugin_shared_dir ) . 'includes/rsmspark-news-loader.php';
		if ( ! is_readable( $loader ) ) {
			// Legacy filename before suite prefix hard-cut.
			$loader = trailingslashit( (string) $plugin_shared_dir ) . 'includes/rsm-spark-news-loader.php';
		}
		if ( is_readable( $loader ) ) {
			require_once $loader;
		}
	}
}


