<?php

namespace Booktics\Admin;

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

use Booktics\Contracts\Hookable_Service_Contract;

class Menu_Permission_Hook implements Hookable_Service_Contract {

    /**
     * Register the menu permission hook.
     *
     * Adds the menu_permissions method to the 'booktics_menu' action hook.
     *
     * @return void
     */
    public function register() {
        add_action( 'booktics_menu', array(
            $this,
            'menu_permissions'
        ), 11, 1 );
    }

    /**
     * Filter menu items based on the current user's role.
     *
     * Removes certain menu items for users with the 'booktics_team_member' role,
     * while allowing administrators to see all menu items.
     *
     * @param array $menu_items The array of menu items to filter.
     *
     * @return array The filtered array of menu items.
     */
    public function menu_permissions( $menu_items ) {
        $current_user = wp_get_current_user();
        $roles        = $current_user->roles;
        if ( in_array( 'administrator', $roles ) ) {
            return $menu_items;
        }

        if ( in_array( 'booktics_team_member', $roles ) ) {
            $menu_items   = array_filter( $menu_items, function ( $item ) {
                return ! in_array( $item['id'], $this->team_member_menu_items() );
            } );
            $menu_items[] = array(
                'id'         => 'my-profile',
                'title'      => esc_html__( 'My Profile', 'booktics' ),
                'link'       => '/my-profile',
                'capability' => apply_filters( 'booktics_menu_permission_my_profile', 'manage_options' ),
                'position'   => apply_filters( 'booktics_menu_position_my_profile', 11 ),
            );

            return array_values( $menu_items );
        }

        return $menu_items;
    }

    /**
     * Get the menu item IDs that should be hidden from team members.
     *
     * @return array List of menu item IDs restricted for team members.
     */
    public function team_member_menu_items() {
        return array(
            'team',
            'license',
            'location',
            'settings',
            'modules',
            'customers',
            'short-code',
            'booktics-automation',
        );
    }
}