<?php
/**
 * Menu Manager — FREE
 *
 * Applies two customizations to the WordPress admin menu:
 *   1. Role-based visibility — hides menu items for non-admin roles
 *      based on the saved per-role allow-list.
 *   2. Renames — replaces menu item labels with custom names.
 *
 * @package Panelra
 */

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

/**
 * Class Pnlrdb_Menu_Manager
 */
class Pnlrdb_Menu_Manager {

	/**
	 * Register hooks.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'customize_menu' ), 9999 );
	}

	/**
	 * Entry point — apply visibility rules and renames.
	 *
	 * @return void
	 */
	public function customize_menu() {
		global $menu, $submenu;
		$this->apply_role_visibility( $menu, $submenu );
		$this->apply_renames( $menu );
	}

	/**
	 * Remove menu items that are not in the current role's allow-list.
	 * Admins always have full access.
	 *
	 * @param array $menu    Global $menu array (passed by reference).
	 * @param array $submenu Global $submenu array (passed by reference).
	 * @return void
	 */
	private function apply_role_visibility( &$menu, &$submenu ) {
		if ( ! is_user_logged_in() || current_user_can( 'manage_options' ) ) {
			return;
		}

		$user = wp_get_current_user();
		$role = reset( $user->roles );
		if ( ! $role ) {
			return;
		}

		$vis     = get_option( 'pnlrdb_role_menu_visibility', array() );
		$allowed = isset( $vis[ $role ] ) ? (array) $vis[ $role ] : array();

		if ( empty( $allowed ) ) {
			return; // No restrictions configured for this role.
		}

		// Always keep Dashboard and Profile accessible.
		$allowed = array_unique( array_merge( $allowed, array( 'index.php', 'profile.php' ) ) );

		foreach ( $menu as $key => $item ) {
			$slug = $item[2] ?? '';
			if ( ! $slug || false !== strpos( $slug, 'separator' ) ) {
				continue;
			}
			if ( ! in_array( $slug, $allowed, true ) ) {
				unset( $menu[ $key ] );
				if ( isset( $submenu[ $slug ] ) ) {
					unset( $submenu[ $slug ] );
				}
			}
		}

		/**
		 * Fires after main menu visibility is applied.
		 * Pro uses this to also filter submenus.
		 *
		 * @param string $role    Current user's role slug.
		 * @param array  $allowed Allowed main menu slugs.
		 */
		do_action( 'pnlrdb_apply_submenu_visibility', $role, $allowed );
	}

	/**
	 * Replace menu item labels with administrator-defined custom names.
	 *
	 * @param array $menu Global $menu array (passed by reference).
	 * @return void
	 */
	private function apply_renames( &$menu ) {
		$names = get_option( 'pnlrdb_menu_names', array() );
		if ( empty( $names ) || ! is_array( $menu ) ) {
			return;
		}

		foreach ( $menu as $key => $item ) {
			$slug = $item[2] ?? '';
			if ( $slug && ! empty( $names[ $slug ] ) ) {
				$menu[ $key ][0] = esc_html( $names[ $slug ] );
			}
		}

		/**
		 * Fires after main menu renames are applied.
		 * Pro uses this to also rename submenus.
		 *
		 * @since 1.0.0
		 */
		do_action( 'pnlrdb_apply_submenu_renames' );
	}
}
