<?php
/**
 * Visually trim the WordPress admin sidebar to the primary TradeSchool pages.
 * Other plugin pages stay fully registered and reachable by direct URL or the
 * in-plugin navigation, but no longer clutter the WordPress menu.
 *
 * Triggered after all plugin menus are registered (priority 9999).
 *
 * Admins who want the full submenu can append ?tsm_full_menu=1 in the URL,
 * which sets a per-user preference toggle.
 *
 * @package TradeSchoolManager
 * @since   1.11.0
 */

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

class TSMP_Admin_Menu_Trim {

	const META_KEY = 'tsm_full_admin_menu';

	/** Submenu slugs to KEEP under tsm-dashboard. */
	protected static function keep_slugs() {
		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- "tsm_" is this plugin's registered prefix.
		return apply_filters( 'tradeschool_manager_admin_menu_keep_slugs', array(
			'tsm-dashboard',
			'tsm-students',
			'tsm-classes',
			'tsm-gradebook',
			'tsm-email-students',
			'tsm-settings',
			'tsm-about',
		) );
	}

	public static function init() {
		add_action( 'admin_init', array( __CLASS__, 'handle_toggle' ) );
		add_action( 'admin_footer', array( __CLASS__, 'hide_extra_items' ), 9999 );
	}

	public static function handle_toggle() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Per-user UI preference toggle (menu visibility); no data mutation outside the current user's own meta.
		if ( ! isset( $_GET['tsm_full_menu'] ) || ! is_user_logged_in() ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Same per-user toggle as above.
		$val = sanitize_text_field( wp_unslash( $_GET['tsm_full_menu'] ) );
		update_user_meta( get_current_user_id(), self::META_KEY, ( '1' === $val ) ? 1 : 0 );
	}

	public static function user_wants_full() {
		return (bool) get_user_meta( get_current_user_id(), self::META_KEY, true );
	}

	public static function hide_extra_items() {
		if ( self::user_wants_full() ) {
			return;
		}
		$keep = wp_json_encode( array_values( self::keep_slugs() ) );
		TSM_Inline_Assets::script(
			'tsm-admin-menu-trim',
			"(function(){
				var keep = {$keep};
				var top = document.getElementById('toplevel_page_tsm-dashboard');
				if (!top) return;
				top.querySelectorAll('.wp-submenu a[href*=\"page=\"]').forEach(function(link){
					var href = link.getAttribute('href') || '';
					var match = href.match(/[?&]page=([^&#]+)/);
					var page = match ? decodeURIComponent(match[1]) : '';
					if (page && keep.indexOf(page) === -1 && link.parentNode) {
						link.parentNode.style.display = 'none';
					}
				});
			})();"
		);
	}
}

TSMP_Admin_Menu_Trim::init();
