<?php
/**
 * Backward-compatible submenu ordering when an older bundled rsm-shared loads first.
 *
 * @package Rsmspark_Suite
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'rsmspark_suite_register_submenu_order' ) ) {
	/**
	 * Queue submenu order for the suite coordinator or fall back to legacy reorder.
	 *
	 * @param string             $plugin_id   Plugin id from register_plugin().
	 * @param array<int, string> $owned_slugs Submenu slugs owned by this plugin.
	 * @return void
	 */
	function rsmspark_suite_register_submenu_order( $plugin_id, array $owned_slugs ) {
		$plugin_id = sanitize_key( (string) $plugin_id );
		if ( '' === $plugin_id || empty( $owned_slugs ) ) {
			return;
		}

		$owned_slugs = array_values( array_unique( array_map( 'strval', $owned_slugs ) ) );

		if ( class_exists( 'Rsmspark_Suite', false ) && method_exists( 'Rsmspark_Suite', 'register_submenu_order' ) ) {
			Rsmspark_Suite::register_submenu_order( $plugin_id, $owned_slugs );
			return;
		}

		static $legacy_queue = array();
		static $legacy_hooked = false;

		$legacy_queue[ $plugin_id ] = $owned_slugs;

		if ( $legacy_hooked ) {
			return;
		}

		$legacy_hooked = true;
		add_action(
			'admin_menu',
			static function () use ( &$legacy_queue ) {
				if ( ! class_exists( 'Rsmspark_Suite', false ) || ! method_exists( 'Rsmspark_Suite', 'reorder_plugin_submenu' ) ) {
					return;
				}
				foreach ( $legacy_queue as $id => $slugs ) {
					Rsmspark_Suite::reorder_plugin_submenu( $id, $slugs );
				}
			},
			1001
		);
	}
}

