<?php

declare( strict_types=1 );

namespace StrykeWP\Modules\Branding;

/**
 * Manages WordPress admin menu visibility.
 *
 * Hides sensitive menu items from non-superadmin users and strips
 * the WordPress admin bar completely.
 * Migrated from stryke-branding (StrykeWP\Branding\MenuManager).
 *
 * @package StrykeWP\Modules\Branding
 */
class MenuManager {

	// -----------------------------------------------------------------------
	// Hook Registration
	// -----------------------------------------------------------------------

	public function register_hooks(): void {
		add_action( 'admin_menu', array( $this, 'reorganize_menu' ), 999 );
		if ( ! $this->is_super_admin() ) {
			add_action( 'admin_bar_menu', array( $this, 'strip_admin_bar' ), 9999 );
			add_filter( 'show_admin_bar', '__return_false' );
		}
	}

	// -----------------------------------------------------------------------
	// Callbacks
	// -----------------------------------------------------------------------

	/**
	 * Remove menu pages that non-superadmin users should not see.
	 */
	public function reorganize_menu(): void {
		if ( $this->is_super_admin() ) {
			return;
		}

		$hidden = array(
			'plugins.php',
			'themes.php',
			'tools.php',
			'users.php',
			'update-core.php',
			'edit.php?post_type=wp_navigation',
			'site-editor.php',
		);

		foreach ( $hidden as $slug ) {
			remove_menu_page( $slug );
		}

		// Remove Settings sub-pages except General and Permalinks.
		$hidden_settings = array(
			'options-writing.php',
			'options-reading.php',
			'options-discussion.php',
			'options-media.php',
			'options-privacy.php',
		);

		foreach ( $hidden_settings as $slug ) {
			remove_submenu_page( 'options-general.php', $slug );
		}
	}

	/**
	 * Remove all admin bar nodes (belt-and-suspenders since we hide it via CSS + filter).
	 */
	public function strip_admin_bar( \WP_Admin_Bar $wp_admin_bar ): void {
		$nodes = $wp_admin_bar->get_nodes();
		if ( $nodes ) {
			foreach ( array_keys( $nodes ) as $id ) {
				$wp_admin_bar->remove_node( $id );
			}
		}
	}

	// -----------------------------------------------------------------------
	// Helpers
	// -----------------------------------------------------------------------

	private function is_super_admin(): bool {
		if ( defined( 'STRYKE_SUPERADMIN' ) && STRYKE_SUPERADMIN === true ) {
			return true;
		}

		if ( is_multisite() && is_super_admin() ) {
			return true;
		}

		return current_user_can( 'manage_options' );
	}
}
