<?php
/**
 * Name: Admin Menu Organizer
 * Description: Reorder, rename, hide, and reorganize admin menu items using drag-and-drop interface to customize navigation and create logical menu structure for better workflow
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Simplify Client Dashboard",
 *     "description": "Reorganize admin menu to put most-used items (Pages, Media, Forms) at the top for non-technical clients who get overwhelmed by default WordPress menu."
 *   },
 *   {
 *     "title": "WooCommerce Store Focus",
 *     "description": "Group all e-commerce related items (Products, Orders, Coupons, Shipping) together under a custom separator for store managers."
 *   },
 *   {
 *     "title": "Multi-Plugin Sites",
 *     "description": "On sites with 20+ plugins, organize scattered menu items by function (Content, Marketing, Analytics, SEO) to reduce menu clutter."
 *   }
 * ]
 * Added: 2025-07-18
 * Tags: menu, admin-menu, organize, reorder, customize
 * WhereToFind: {
 *   "location": "Admin Sidebar Menu",
 *   "url": "",
 *   "instructions": "Configure in module settings. Use drag-and-drop to reorder menu items, rename labels, hide items, or group under parent menus. Changes apply to admin sidebar.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardAdminMenuOrganizer {

    private $menu_config = [];
    private $original_menu = [];

    /**
     * Clean menu label by removing HTML, CSS, and other injected content
     * Some plugins (like WP Activity Log) inject inline CSS into menu titles
     */
    private function clean_menu_label($label) {
        // Remove span tags with notification counts
        $label = preg_replace('/<span[^>]*>.*?<\/span>/is', '', $label);
        // Remove style tags and their CSS content
        $label = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $label);
        // Remove any remaining HTML tags
        $label = strip_tags($label);
        // Remove CSS rule blocks like { position: absolute; ... }
        $label = preg_replace('/\{[^}]*\}/s', '', $label);
        // Remove CSS selectors like #id .class
        $label = preg_replace('/[#.][a-zA-Z0-9_-]+(\s*[#.][a-zA-Z0-9_-]+)*/s', '', $label);
        return trim($label);
    }

    public function __construct() {
        // Capture menu at maximum priority to ensure all plugins (including Google Site Kit) have registered
        // Google Site Kit and some other plugins register menus at very high priorities (9999+)
        // Using PHP_INT_MAX - 10 for capture and PHP_INT_MAX for customizations ensures we run last
        add_action('admin_menu', [$this, 'capture_original_menu'], PHP_INT_MAX - 10);
        add_action('admin_menu', [$this, 'apply_menu_customizations'], PHP_INT_MAX);
        add_action('wp_ajax_save_menu_config', [$this, 'save_menu_config']);
        add_action('wp_ajax_get_current_menu', [$this, 'get_current_menu']);
        add_action('admin_head', [$this, 'add_menu_styles']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_sortable']);
    }
    
    public function enqueue_sortable($hook) {
        // Only load on Switchboard page
        if ($hook !== 'toplevel_page_switchboard') {
            return;
        }
        
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-droppable');
    }
    
    public function capture_original_menu() {
        global $menu, $submenu;

        if (!is_array($menu)) $menu = [];
        if (!is_array($submenu)) $submenu = [];

        // Filter menu to only include visible items the user can access
        $filtered_menu = [];
        foreach ($menu as $key => $item) {
            // Skip separators
            if (!isset($item[2]) || strpos($item[2], 'separator') !== false) {
                $filtered_menu[$key] = $item;
                continue;
            }

            // Skip items with empty labels (hidden items)
            if (empty($item[0])) {
                continue;
            }

            // Skip items user doesn't have capability for
            $capability = isset($item[1]) ? $item[1] : 'read';
            if (!current_user_can($capability)) {
                continue;
            }

            $filtered_menu[$key] = $item;
        }

        // Store a copy of the filtered menu before our customizations
        $this->original_menu = [
            'menu' => $filtered_menu,
            'submenu' => $submenu
        ];

        // Also store it in a transient for AJAX access
        set_transient('switchboard_original_menu_' . get_current_user_id(), $this->original_menu, HOUR_IN_SECONDS);
    }
    
    public function apply_menu_customizations() {
        global $menu, $submenu;
        
        $this->menu_config = get_option('switchboard_menu_config', []);
        
        if (empty($this->menu_config) || !is_array($this->menu_config)) {
            return;
        }
        
        // Ensure config structure
        $this->menu_config = array_merge([
            'order' => [],
            'labels' => [],
            'hidden' => [],
            'icons' => [],
            'parents' => [],
            'hidden_by_role' => []
        ], $this->menu_config);
        
        // Apply custom order
        if (!empty($this->menu_config['order']) && is_array($this->menu_config['order'])) {
            $new_menu = [];
            $position = 5; // Start at position 5 to avoid conflicts with WP core items
            
            // Build a lookup array for quick access
            $menu_lookup = [];
            foreach ($menu as $key => $item) {
                if (isset($item[2])) {
                    $menu_lookup[$item[2]] = [$key, $item];
                }
            }
            
            // Reorder based on config
            foreach ($this->menu_config['order'] as $slug) {
                if (isset($menu_lookup[$slug])) {
                    $new_menu[$position] = $menu_lookup[$slug][1];
                    unset($menu_lookup[$slug]);
                    $position += 5;
                }
            }
            
            // Add any items not in config (new plugins, etc.)
            foreach ($menu_lookup as $slug => $data) {
                $new_menu[$position] = $data[1];
                $position += 5;
            }
            
            // Replace the global menu
            if (!empty($new_menu)) {
                $menu = $new_menu;
            }
        }
        
        // Apply custom labels (preserving notification bubbles)
        if (!empty($this->menu_config['labels']) && is_array($this->menu_config['labels'])) {
            foreach ($menu as $key => $item) {
                if (isset($item[2]) && isset($this->menu_config['labels'][$item[2]])) {
                    $original_label = $item[0];
                    $new_label = $this->menu_config['labels'][$item[2]];

                    // Get clean version of original label for comparison
                    $original_clean = $this->clean_menu_label($original_label);

                    // Only apply if the label was actually changed
                    if ($new_label !== $original_clean) {
                        // Extract notification bubbles (span tags) from original label
                        $notification_bubbles = '';
                        if (preg_match_all('/<span[^>]*>.*?<\/span>/is', $original_label, $matches)) {
                            $notification_bubbles = ' ' . implode('', $matches[0]);
                        }

                        // Apply new label with preserved notification bubbles
                        $menu[$key][0] = $new_label . $notification_bubbles;
                    }
                }
            }
        }
        
        // Apply hidden items (global hide)
        if (!empty($this->menu_config['hidden']) && is_array($this->menu_config['hidden'])) {
            foreach ($menu as $key => $item) {
                if (isset($item[2]) && in_array($item[2], $this->menu_config['hidden'], true)) {
                    unset($menu[$key]);
                }
            }
        }

        // Apply role-based hidden items
        if (!empty($this->menu_config['hidden_by_role']) && is_array($this->menu_config['hidden_by_role'])) {
            $current_user = wp_get_current_user();
            $user_roles = $current_user->roles;

            foreach ($menu as $key => $item) {
                if (isset($item[2]) && isset($this->menu_config['hidden_by_role'][$item[2]])) {
                    $hidden_roles = $this->menu_config['hidden_by_role'][$item[2]];
                    if (is_array($hidden_roles) && array_intersect($user_roles, $hidden_roles)) {
                        unset($menu[$key]);
                    }
                }
            }
        }
        
        // Apply custom icons
        if (!empty($this->menu_config['icons']) && is_array($this->menu_config['icons'])) {
            foreach ($menu as $key => $item) {
                if (isset($item[2]) && isset($this->menu_config['icons'][$item[2]])) {
                    $menu[$key][6] = $this->menu_config['icons'][$item[2]];
                }
            }
        }
        
        // Apply parent changes (move to submenu)
        if (!empty($this->menu_config['parents']) && is_array($this->menu_config['parents'])) {
            foreach ($this->menu_config['parents'] as $child_slug => $parent_slug) {
                // Find the menu item
                foreach ($menu as $key => $item) {
                    if (isset($item[2]) && $item[2] === $child_slug) {
                        // Add as submenu
                        if (!isset($submenu[$parent_slug])) {
                            $submenu[$parent_slug] = [];
                        }
                        $submenu[$parent_slug][] = [
                            $item[0], // Menu title
                            $item[1], // Capability
                            $item[2], // Slug
                        ];
                        // Remove from main menu
                        unset($menu[$key]);
                        break;
                    }
                }
            }
        }
    }
    
    public function add_menu_styles() {
        $hidden = !empty($this->menu_config['hidden']) ? $this->menu_config['hidden'] : [];
        
        if (!empty($hidden)) {
            echo '<style>';
            foreach ($hidden as $slug) {
                $safe_slug = esc_attr(str_replace('.', '\\.', $slug));
                echo '#adminmenu a[href="' . $safe_slug . '"] { display: none !important; }';
            }
            echo '</style>';
        }
    }
    
    public function get_current_menu() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
        }

        // Get the stored original menu
        $original = get_transient('switchboard_original_menu_' . get_current_user_id());

        if (!$original || empty($original['menu'])) {
            wp_send_json_error(['message' => esc_html__('Menu data not available. Please refresh the page and try again.', 'wpswitchboard')]);
        }

        $menu = $original['menu'];
        $submenu = $original['submenu'];
        $config = get_option('switchboard_menu_config', []);

        // If config is empty (reset), show items in their original WordPress order
        // by sorting menu by its array keys (which represent position)
        if (empty($config) || empty($config['order'])) {
            ksort($menu);
        }
        
        // Ensure config has proper structure
        if (!is_array($config)) {
            $config = [];
        }
        
        $config = array_merge([
            'order' => [],
            'labels' => [],
            'hidden' => [],
            'icons' => [],
            'parents' => [],
            'hidden_by_role' => []
        ], $config);
        
        // Build menu items array
        $menu_items = [];

        foreach ($menu as $item) {
            // Skip separators and empty items
            if (!isset($item[2]) || strpos($item[2], 'separator') !== false) {
                continue;
            }

            // Skip items with empty labels (hidden items)
            if (empty($item[0])) {
                continue;
            }

            $slug = $item[2];
            $capability = isset($item[1]) ? $item[1] : 'read';

            // Skip items user doesn't have access to
            if (!current_user_can($capability)) {
                continue;
            }

            // Clean the label - remove HTML tags, notification bubbles, and inline styles
            $label = $this->clean_menu_label($item[0]);
            
            $menu_items[] = [
                'label' => $label,
                'slug' => $slug,
                'capability' => isset($item[1]) ? $item[1] : 'read',
                'icon' => isset($item[6]) ? $item[6] : 'dashicons-admin-generic',
                'position' => $slug,
                'has_submenu' => isset($submenu[$slug]) && !empty($submenu[$slug])
            ];
        }
        
        // Apply saved order if exists
        if (!empty($config['order']) && is_array($config['order'])) {
            $ordered_items = [];
            $menu_lookup = [];
            
            // Create lookup
            foreach ($menu_items as $item) {
                $menu_lookup[$item['slug']] = $item;
            }
            
            // Reorder based on config
            foreach ($config['order'] as $slug) {
                if (isset($menu_lookup[$slug])) {
                    $ordered_items[] = $menu_lookup[$slug];
                    unset($menu_lookup[$slug]);
                }
            }
            
            // Add any new items not in config
            foreach ($menu_lookup as $item) {
                $ordered_items[] = $item;
            }
            
            $menu_items = $ordered_items;
        }
        
        wp_send_json_success([
            'menu' => $menu_items,
            'config' => $config
        ]);
    }
    
    public function save_menu_config() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
        }
        
        $config = isset($_POST['config']) ? json_decode(stripslashes($_POST['config']), true) : [];
        
        // Validate config structure
        if (!is_array($config)) {
            $config = [];
        }
        
        // Ensure all required keys exist and are arrays
        $config = array_merge([
            'order' => [],
            'labels' => [],
            'hidden' => [],
            'icons' => [],
            'parents' => [],
            'hidden_by_role' => []
        ], $config);

        // Sanitize the config
        $config['order'] = is_array($config['order']) ? array_map('sanitize_text_field', $config['order']) : [];
        $config['labels'] = is_array($config['labels']) ? array_map('sanitize_text_field', $config['labels']) : [];
        $config['hidden'] = is_array($config['hidden']) ? array_map('sanitize_text_field', $config['hidden']) : [];
        $config['icons'] = is_array($config['icons']) ? array_map('sanitize_text_field', $config['icons']) : [];
        $config['parents'] = is_array($config['parents']) ? array_map('sanitize_text_field', $config['parents']) : [];

        // Sanitize hidden_by_role (nested array: slug => [roles])
        if (is_array($config['hidden_by_role'])) {
            $sanitized_hidden_by_role = [];
            foreach ($config['hidden_by_role'] as $slug => $roles) {
                $sanitized_slug = sanitize_text_field($slug);
                if (is_array($roles) && !empty($roles)) {
                    $sanitized_hidden_by_role[$sanitized_slug] = array_map('sanitize_text_field', $roles);
                }
            }
            $config['hidden_by_role'] = $sanitized_hidden_by_role;
        } else {
            $config['hidden_by_role'] = [];
        }
        
        $result = update_option('switchboard_menu_config', $config, false);
        
        // Clear the transient to force menu reload
        delete_transient('switchboard_original_menu_' . get_current_user_id());
        
        wp_send_json_success([
            'message' => esc_html__('Menu configuration saved successfully', 'wpswitchboard'),
            'saved' => $result,
            'config' => $config
        ]);
    }

    /**
     * Render settings panel for Admin Menu Organizer
     * 
     * Displays interactive drag-and-drop menu organization interface with:
     * - Live preview of current admin menu items
     * - Move up/down buttons for reordering
     * - Rename menu labels
     * - Hide menu items
     * - Change parent menu (move to submenu)
     * - Reset to default
     * 
     * @param array $settings Current module settings (not used, config stored separately)
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        // Prepare translations for JavaScript
        $i18n = [
            'info' => esc_html__('Info:', 'wpswitchboard'),
            'infoMessage' => esc_html__('Drag to reorder, rename labels, hide items, or move to submenus. Changes apply after saving.', 'wpswitchboard'),
            'reloadMenu' => esc_html__('Reload Menu', 'wpswitchboard'),
            'resetToDefault' => esc_html__('Reset to Default', 'wpswitchboard'),
            'loadingMenuItems' => esc_html__('Loading menu items...', 'wpswitchboard'),
            'errorLoadingMenu' => esc_html__('Error loading menu:', 'wpswitchboard'),
            'unknownError' => esc_html__('Unknown error', 'wpswitchboard'),
            'errorRefreshPage' => esc_html__('Error loading menu. Please refresh the page.', 'wpswitchboard'),
            'menuLabel' => esc_html__('Menu Label', 'wpswitchboard'),
            'topLevel' => esc_html__('Top Level', 'wpswitchboard'),
            'hide' => esc_html__('Hide', 'wpswitchboard'),
            'hideForRoles' => esc_html__('Hide for roles', 'wpswitchboard'),
            'allRoles' => esc_html__('All roles', 'wpswitchboard'),
            'selectRoles' => esc_html__('Select roles...', 'wpswitchboard'),
            'rolesSelected' => esc_html__('roles selected', 'wpswitchboard'),
            'confirmReset' => esc_html__('Are you sure you want to reset the menu to default? This will remove all customizations.', 'wpswitchboard')
        ];
        ?>
        <script>
        var menuOrganizerI18n = <?php echo wp_json_encode($i18n); ?>;
        var menuOrganizerRoles = <?php echo wp_json_encode(wp_roles()->get_names()); ?>;
        </script>
        <input type="hidden" name="module" value="admin-menu-organizer">
        <input type="hidden" name="menu_config_data" id="menu-config-data" value="">

        <div id="menu-organizer-container">
            <!-- Info Banner -->
            <div class="sb-sp-alert sb-sp-alert-info">
                <p class="sb-sp-alert-text">
                    <strong><?php echo esc_html__('Info:', 'wpswitchboard'); ?></strong> <?php echo esc_html__('Drag to reorder, rename labels, hide items, or move to submenus. Changes apply after saving.', 'wpswitchboard'); ?>
                </p>
            </div>

            <!-- Action Buttons -->
            <div class="sb-sp-group">
            <div class="sb-sp-button-group">
                    <button type="button" id="load-current-menu-btn" class="button button-small button-primary"><?php echo esc_html__('Reload Menu', 'wpswitchboard'); ?></button>
                    <button type="button" id="reset-menu-btn" class="button button-small button-primary-outline"><?php echo esc_html__('Reset to Default', 'wpswitchboard'); ?></button>
                </div>
            </div>

            <!-- Menu Items Container -->
            <div id="menu-items-container" class="sb-sp-card">
                <div class="sb-sp-text-center">
                    <p class="sb-sp-mb-0"><?php echo esc_html__('Loading menu items...', 'wpswitchboard'); ?></p>
                </div>
            </div>
        </div>

        
        <script>
        jQuery(document).ready(function($) {
            let menuItems = [];
            let menuConfig = {
                order: [],
                labels: {},
                hidden: [],
                icons: {},
                parents: {},
                hidden_by_role: {}
            };
            
            // Auto-load menu on page load
            loadCurrentMenu();
            
            // Load current menu function
            function loadCurrentMenu() {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'get_current_menu',
                        nonce: '<?php echo wp_create_nonce('switchboard_settings'); ?>'
                    },
                    success: function(response) {
                        console.log('Menu loaded:', response);
                        if (response.success) {
                            menuItems = response.data.menu;
                            // Properly merge config with defaults
                            menuConfig = {
                                order: response.data.config.order || [],
                                labels: response.data.config.labels || {},
                                hidden: response.data.config.hidden || [],
                                icons: response.data.config.icons || {},
                                parents: response.data.config.parents || {},
                                hidden_by_role: response.data.config.hidden_by_role || {}
                            };
                            renderMenu();
                        } else {
                            $('#menu-items-container').html('<div class="sb-sp-status-error"><p class="sb-sp-m-0">' + menuOrganizerI18n.errorLoadingMenu + ' ' + (response.data.message || menuOrganizerI18n.unknownError) + '</p></div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX error:', error);
                        $('#menu-items-container').html('<div class="sb-sp-status-error"><p class="sb-sp-m-0">' + menuOrganizerI18n.errorRefreshPage + '</p></div>');
                    }
                });
            }
            
            // Load current menu button
            $('#load-current-menu-btn').on('click', function() {
                loadCurrentMenu();
            });
            
            // Helper function to get role dropdown label
            function getRoleDropdownLabel(selectedRoles) {
                if (!selectedRoles || selectedRoles.length === 0) {
                    return menuOrganizerI18n.allRoles;
                }
                if (selectedRoles.length === 1) {
                    return menuOrganizerRoles[selectedRoles[0]] || selectedRoles[0];
                }
                return selectedRoles.length + ' ' + menuOrganizerI18n.rolesSelected;
            }

            function renderMenu() {
                let html = '<div id="menu-list" class="sb-sp-sortable-container">';

                menuItems.forEach(function(item, index) {
                    const isHidden = menuConfig.hidden && menuConfig.hidden.includes(item.slug);
                    const customLabel = menuConfig.labels && menuConfig.labels[item.slug] ? menuConfig.labels[item.slug] : item.label;
                    const parentSlug = menuConfig.parents && menuConfig.parents[item.slug] ? menuConfig.parents[item.slug] : '';
                    const hiddenRoles = menuConfig.hidden_by_role && menuConfig.hidden_by_role[item.slug] ? menuConfig.hidden_by_role[item.slug] : [];

                    const itemClasses = isHidden ? 'menu-item sb-sp-sortable-item sb-sp-bg-red-50' : 'menu-item sb-sp-sortable-item';
                    html += '<div class="' + itemClasses + '" data-slug="' + item.slug + '" data-index="' + index + '" style="position: relative;">';

                    // Drag handle
                    html += '<span class="sb-sp-drag-handle">⋮⋮</span>';

                    html += '<span class="dashicons ' + item.icon + '" style="color: #64748b;"></span>';
                    html += '<input type="text" class="menu-label sb-sp-input sb-sp-col" value="' + customLabel + '" placeholder="' + menuOrganizerI18n.menuLabel + '">';

                    // Parent selector
                    html += '<select class="menu-parent sb-sp-select">';
                    html += '<option value="">' + menuOrganizerI18n.topLevel + '</option>';
                    menuItems.forEach(function(parentItem) {
                        if (parentItem.slug !== item.slug) {
                            html += '<option value="' + parentItem.slug + '" ' + (parentSlug === parentItem.slug ? 'selected' : '') + '>' + parentItem.label.substring(0, 18) + '</option>';
                        }
                    });
                    html += '</select>';

                    html += '<label class="sb-sp-checkbox-field">';
                    html += '<input type="checkbox" class="menu-hidden sb-sp-checkbox" ' + (isHidden ? 'checked' : '') + '>';
                    html += '<span class="sb-sp-text-sm">' + menuOrganizerI18n.hide + '</span>';
                    html += '</label>';

                    // Role-based hide dropdown
                    const hasRolesSelected = hiddenRoles.length > 0;
                    html += '<div class="role-dropdown-container" style="position: relative;">';
                    html += '<button type="button" class="role-dropdown-toggle" style="';
                    html += 'min-width: 140px; padding: 6px 12px; text-align: left; cursor: pointer; ';
                    html += 'background: ' + (hasRolesSelected ? 'var(--primary-50, #eff6ff)' : 'white') + '; ';
                    html += 'border: 1px solid ' + (hasRolesSelected ? 'var(--primary-300, #93c5fd)' : 'var(--gray-300, #cbd5e1)') + '; ';
                    html += 'border-radius: 6px; font-size: 13px; color: var(--gray-700, #374151); ';
                    html += 'display: flex; justify-content: space-between; align-items: center; gap: 8px;';
                    html += '">';
                    html += '<span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + getRoleDropdownLabel(hiddenRoles) + '</span>';
                    html += '<span style="color: var(--gray-400, #9ca3af); font-size: 10px;">▼</span>';
                    html += '</button>';
                    html += '<div class="role-dropdown-menu" style="';
                    html += 'display: none; position: absolute; top: calc(100% + 4px); right: 0; ';
                    html += 'z-index: 999999; background: white; ';
                    html += 'border: 1px solid var(--gray-200, #e5e7eb); border-radius: 6px; ';
                    html += 'min-width: 160px; max-height: 220px; overflow-y: auto; ';
                    html += 'box-shadow: 0 4px 12px rgba(0,0,0,0.1);';
                    html += '">';
                    const roleKeys = Object.keys(menuOrganizerRoles);
                    roleKeys.forEach(function(roleSlug, idx) {
                        const isChecked = hiddenRoles.includes(roleSlug) ? 'checked' : '';
                        const isLast = idx === roleKeys.length - 1;
                        html += '<label style="';
                        html += 'display: flex; align-items: center; padding: 7px 12px; margin: 0; cursor: pointer; ';
                        html += 'font-size: 13px; color: var(--gray-700, #374151); ';
                        html += 'border-bottom: ' + (isLast ? 'none' : '1px solid var(--gray-100, #f1f5f9)') + '; ';
                        html += 'transition: background 0.15s ease; box-sizing: border-box;';
                        html += '" onmouseover="this.style.background=\'var(--gray-50, #f9fafb)\'" onmouseout="this.style.background=\'transparent\'">';
                        html += '<input type="checkbox" class="role-checkbox" value="' + roleSlug + '" ' + isChecked + ' style="';
                        html += 'margin: 0 10px 0 0; width: 15px; height: 15px; cursor: pointer; accent-color: var(--primary-500, #3b82f6);';
                        html += '">';
                        html += '<span style="margin: 0; padding: 0;">' + menuOrganizerRoles[roleSlug] + '</span>';
                        html += '</label>';
                    });
                    html += '</div>';
                    html += '</div>';

                    html += '</div>';
                });

                html += '</div>';

                $('#menu-items-container').html(html);

                // Initialize sortable
                $('#menu-list').sortable({
                    items: '.menu-item',
                    handle: '.sb-sp-drag-handle',
                    placeholder: 'sortable-placeholder',
                    tolerance: 'pointer',
                    cursor: 'grabbing',
                    opacity: 0.8,
                    start: function(e, ui) {
                        ui.placeholder.height(ui.item.height());
                        ui.placeholder.css({
                            'background': 'var(--primary-100)',
                            'border': '2px dashed var(--primary-500)',
                            'border-radius': '4px',
                            'margin-bottom': '8px'
                        });
                        ui.item.css('box-shadow', '0 4px 12px rgba(0,0,0,0.15)');
                    },
                    stop: function(e, ui) {
                        ui.item.css('box-shadow', '');
                        // Rebuild menuItems array based on new DOM order
                        const newOrder = [];
                        $('#menu-list .menu-item').each(function() {
                            const slug = $(this).data('slug');
                            const item = menuItems.find(m => m.slug === slug);
                            if (item) {
                                newOrder.push(item);
                            }
                        });
                        menuItems = newOrder;
                        // Update data-index attributes
                        $('#menu-list .menu-item').each(function(i) {
                            $(this).attr('data-index', i);
                        });
                        updateMenuConfig();
                    }
                });
            }
            
            // Update label
            $(document).on('input', '.menu-label', function() {
                updateMenuConfig();
            });
            
            // Change parent
            $(document).on('change', '.menu-parent', function() {
                updateMenuConfig();
            });
            
            // Toggle hidden
            $(document).on('change', '.menu-hidden', function() {
                const $item = $(this).closest('.menu-item');
                if ($(this).is(':checked')) {
                    $item.css('background', '#fee2e2');
                } else {
                    $item.css('background', 'white');
                }
                updateMenuConfig();
            });

            // Toggle role dropdown
            $(document).on('click', '.role-dropdown-toggle', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const $menuItem = $(this).closest('.menu-item');
                const $menu = $(this).siblings('.role-dropdown-menu');
                // Close other open dropdowns and reset their z-index
                $('.menu-item').not($menuItem).css('z-index', '');
                $('.role-dropdown-menu').not($menu).hide();
                // Bring this menu item to front when opening
                if (!$menu.is(':visible')) {
                    $menuItem.css('z-index', '999999');
                } else {
                    $menuItem.css('z-index', '');
                }
                $menu.toggle();
            });

            // Close dropdown when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.role-dropdown-container').length) {
                    $('.role-dropdown-menu').hide();
                    $('.menu-item').css('z-index', '');
                }
            });

            // Role checkbox change
            $(document).on('change', '.role-checkbox', function() {
                const $container = $(this).closest('.role-dropdown-container');
                const $toggle = $container.find('.role-dropdown-toggle');
                const selectedRoles = [];
                $container.find('.role-checkbox:checked').each(function() {
                    selectedRoles.push($(this).val());
                });
                // Update button text
                $toggle.find('span:first').text(getRoleDropdownLabel(selectedRoles));
                // Update button styling based on selection
                if (selectedRoles.length > 0) {
                    $toggle.css({
                        'background': 'var(--primary-50, #eff6ff)',
                        'border-color': 'var(--primary-300, #93c5fd)'
                    });
                } else {
                    $toggle.css({
                        'background': 'white',
                        'border-color': 'var(--gray-300, #cbd5e1)'
                    });
                }
                updateMenuConfig();
            });

            function updateMenuConfig() {
                menuConfig = {
                    order: [],
                    labels: {},
                    hidden: [],
                    icons: {},
                    parents: {},
                    hidden_by_role: {}
                };

                // Build config from current menuItems order
                menuItems.forEach(function(item) {
                    menuConfig.order.push(item.slug);
                });

                // Get values from DOM
                $('#menu-list .menu-item').each(function() {
                    const slug = $(this).data('slug');
                    const label = $(this).find('.menu-label').val();
                    const isHidden = $(this).find('.menu-hidden').is(':checked');
                    const parent = $(this).find('.menu-parent').val();

                    if (label) {
                        menuConfig.labels[slug] = label;
                    }

                    if (isHidden) {
                        menuConfig.hidden.push(slug);
                    }

                    if (parent) {
                        menuConfig.parents[slug] = parent;
                    }

                    // Collect role-based hidden settings
                    const selectedRoles = [];
                    $(this).find('.role-checkbox:checked').each(function() {
                        selectedRoles.push($(this).val());
                    });
                    if (selectedRoles.length > 0) {
                        menuConfig.hidden_by_role[slug] = selectedRoles;
                    }
                });

                // Update hidden input for form submission
                $('#menu-config-data').val(JSON.stringify(menuConfig));
            }
            
            // Hook into the panel's save button
            $(document).on('click', '.settings-panel-save', function() {
                // Check if we're on the admin menu organizer settings
                if ($('#menu-organizer-container').length > 0 && menuItems.length > 0) {
                    updateMenuConfig();
                    
                    console.log('Saving menu config via panel save:', menuConfig);
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'save_menu_config',
                            config: JSON.stringify(menuConfig),
                            nonce: '<?php echo wp_create_nonce('switchboard_settings'); ?>'
                        },
                        success: function(response) {
                            console.log('Menu config save response:', response);
                        },
                        error: function(xhr, status, error) {
                            console.error('Menu config save error:', error);
                        }
                    });
                }
            });
            
            // Reset menu
            $('#reset-menu-btn').on('click', function() {
                if (!confirm(menuOrganizerI18n.confirmReset)) {
                    return;
                }

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'save_menu_config',
                        config: JSON.stringify({}),
                        nonce: '<?php echo wp_create_nonce('switchboard_settings'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload page to refresh the menu transient with default order
                            window.location.reload();
                        }
                    }
                });
            });
        });
        </script>
        <?php
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_menu_config',
            ],
            'option_patterns' => [
                '_transient_switchboard_original_menu_%',
                '_transient_timeout_switchboard_original_menu_%',
            ],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardAdminMenuOrganizer();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
