<?php
declare(strict_types=1);

namespace EHxMe\Classes;

use EHxMe\Services\Request;

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

class AdminNavMenuHandler 
{
    /**
     * Constructor for the AdminNavMenuHandler class.
     *
     * Initializes the necessary actions and filters for customizing and controlling the visibility of menu items.
     */
    public function __construct() 
    {
        // Add custom fields to menu items in the admin panel
        add_action('wp_nav_menu_item_custom_fields', [$this, 'menuItemCustomFields'], 10, 4);

        // Save custom fields when menu items are updated
        add_action('wp_update_nav_menu_item', [$this, 'updateNavMenuItem'], 10, 2);

        // Filter menu items based on visibility settings
        add_filter('wp_nav_menu_objects', [$this, 'filterMenuObjects'], 10, 2);
    }

    /**
     * Add custom fields to menu items in the admin panel.
     *
     * @param int|string    $item_id  Menu item ID.
     * @param object $item     Menu item object.
     * @param int    $depth    Depth of the menu item.
     * @param array  $args     Additional arguments.
     */
    public function menuItemCustomFields($item_id, $item, $depth, $args) 
    {
        $visibility = get_post_meta($item_id, 'ehxme_menu_visibility', true);
        $roles = get_post_meta($item_id, 'ehxme_menu_roles', true);
        $roles = is_array($roles) ? $roles : [];
        ?>
            <div class="ehx-nav-edit">
                <div class="clear"></div>
                <h4 style="margin-bottom: 0.6em;"><?php esc_html_e('EHx Member Menu Settings', 'ehx-members'); ?></h4>

                <!-- Visibility Settings -->
                <p class="description description-wide ehx-nav-mode">
                    <label for="edit-ehxme_menu_visibility-<?php echo esc_attr($item_id); ?>">
                        <?php esc_html_e('Who can see this menu link?', 'ehx-members'); ?>
                        <br>
                        <select id="edit-ehxme_menu_visibility-<?php echo esc_attr($item_id); ?>" name="ehxme_menu_visibility[<?php echo esc_attr($item_id); ?>]" style="width: 100%;">
                            <option value="everyone" <?php selected($visibility, 'everyone'); ?>><?php esc_html_e('Everyone', 'ehx-members'); ?></option>
                            <option value="logged-in" <?php selected($visibility, 'logged-in'); ?>><?php esc_html_e('Logged-in Users', 'ehx-members'); ?></option>
                            <option value="logged-out" <?php selected($visibility, 'logged-out'); ?>><?php esc_html_e('Logged-out Users', 'ehx-members'); ?></option>
                        </select>
                    </label>
                </p>

                <!-- Role-Based Visibility -->
                <p class="description description-wide ehx-nav-roles">
                    <?php esc_html_e('Select the member roles that can see this link', 'ehx-members'); ?>
                    <br>
                    <span class="ehxme-form-fields-section" style="width:100% !important;">
                        <?php foreach (wp_roles()->roles as $role_slug => $role): ?>
                            <label for="edit-menu-item-ehx_nav_roles-<?php echo esc_attr($item_id); ?>_<?php echo esc_attr($role_slug); ?>">
                                <input type="checkbox" 
                                    id="edit-menu-item-ehx_nav_roles-<?php echo esc_attr($item_id); ?>_<?php echo esc_attr($role_slug); ?>" 
                                    name="ehxme_menu_roles[<?php echo esc_attr($item_id); ?>][<?php echo esc_attr($role_slug); ?>]" 
                                    value="<?php echo esc_attr($role_slug); ?>" 
                                    <?php checked(in_array($role_slug, $roles)); ?>>
                                <span><?php echo esc_html($role['name']); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </span>
                </p>
                <div class="clear"></div>
            </div>
        <?php
    }

    /**
     * Save custom fields for menu items.
     *
     * @param int $menu_id         Menu ID.
     * @param int $menu_item_db_id Menu item ID.
     */
    public function updateNavMenuItem($menu_id, $menu_item_db_id) 
    {
        $request = new Request();

        // Save visibility setting
        $visibility = $request->input('ehxme_menu_visibility');
        if (isset($visibility[$menu_item_db_id])) {
            update_post_meta($menu_item_db_id, 'ehxme_menu_visibility', sanitize_text_field($visibility[$menu_item_db_id]));
        } else {
            delete_post_meta($menu_item_db_id, 'ehxme_menu_visibility');
        }

        // Save role-based visibility
        // $roles = $request->input('ehxme_menu_roles');
        // if (isset($roles[$menu_item_db_id])) {
        //     $sanitized_roles = array_map('sanitize_text_field', array_keys($roles[$menu_item_db_id]));
        //     update_post_meta($menu_item_db_id, 'ehxme_menu_roles', $sanitized_roles);
        // } else {
        //     delete_post_meta($menu_item_db_id, 'ehxme_menu_roles');
        // }
    }

    /**
     * Filter menu items based on visibility settings.
     *
     * @param array $items Menu items.
     * @param array $args  Menu arguments.
     * @return array Filtered menu items.
     */
    public function filterMenuObjects($items, $args) 
    {
        foreach ($items as $key => $item) {
            $visibility = get_post_meta($item->ID, 'ehxme_menu_visibility', true);
            // $roles = get_post_meta($item->ID, 'ehxme_menu_roles', true);
            // $roles = is_array($roles) ? $roles : [];

            // Hide menu item based on visibility settings
            if ($visibility === 'logged-in' && !is_user_logged_in()) {
                unset($items[$key]); // Hide from guests
            } elseif ($visibility === 'logged-out' && is_user_logged_in()) {
                unset($items[$key]); // Hide from logged-in users
            }

            // Hide menu item based on role settings
            // if (!empty($roles) && is_user_logged_in()) {
            //     $user = wp_get_current_user();
            //     $user_roles = $user->roles;
            //     $has_access = array_intersect($user_roles, $roles);

            //     if (empty($has_access)) {
            //         unset($items[$key]); // Hide if user doesn't have the required role
            //     }
            // }
        }

        return $items;
    }
}