<?php
/**
 * Name: Move Switchboard to Tools Menu
 * Description: Moves the entire Switchboard menu (including all submenu items) as a submenu under the WordPress Tools menu for better organization
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Simplified Admin Menu",
 *     "description": "Reduce clutter in the admin sidebar by moving Switchboard under the existing Tools menu instead of having it as a separate top-level menu item."
 *   },
 *   {
 *     "title": "Better Menu Organization",
 *     "description": "Organize your admin menu by grouping Switchboard with other utility tools, making it easier for clients and team members to navigate."
 *   },
 *   {
 *     "title": "White Label Presentation",
 *     "description": "Create a cleaner white-label admin experience by consolidating management tools under the standard WordPress menus."
 *   }
 * ]
 * Added: 2025-11-13
 * Tags: admin, menu, tools, organization, customize
 * WhereToFind: {
 *   "location": "WordPress Admin → Tools → Switchboard",
 *   "url": "tools.php?page=switchboard",
 *   "instructions": "Once enabled, the Switchboard menu will appear under Tools in the admin sidebar. All Switchboard submenus will move with it.",
 *   "newTab": false
 * }
 */

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

class SwitchboardMoveToTools {

    private $submenu_callbacks = [];
    private $original_callback = null;

    public function __construct() {
        // Hook into admin_menu with very late priority to ensure Switchboard menu is already registered
        add_action('admin_menu', [$this, 'move_menu'], 999);

        // Add quick access menu to Switchboard header using the new hook
        add_action('switchboard_header_actions', [$this, 'add_quick_access_menu']);

        // Register with data registry
        $this->register_with_data_registry();
    }

    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }

    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    /**
     * Move the Switchboard menu under Tools
     */
    public function move_menu() {
        global $menu, $submenu;

        // Find and remove the Switchboard menu
        $switchboard_menu = null;
        $switchboard_position = null;

        foreach ($menu as $position => $item) {
            if (isset($item[2]) && $item[2] === 'switchboard') {
                $switchboard_menu = $item;
                $switchboard_position = $position;
                break;
            }
        }

        // If we found the Switchboard menu, remove it and add it under Tools
        if ($switchboard_menu !== null && $switchboard_position !== null) {
            // Store the original callback for use in redirect
            $this->original_callback = isset($switchboard_menu[6]) ? $switchboard_menu[6] : null;

            // Get all Switchboard submenus (if any exist) BEFORE we remove the menu
            $switchboard_submenus = isset($submenu['switchboard']) ? $submenu['switchboard'] : [];

            // Remove the main Switchboard menu from top-level
            unset($menu[$switchboard_position]);

            // Add Switchboard as a submenu item under Tools
            add_submenu_page(
                'tools.php',                    // Parent slug (Tools menu)
                'Switchboard Pro',              // Page title
                'Switchboard Pro',              // Menu title
                'manage_options',               // Capability
                'switchboard',                  // Menu slug
                [$this, 'redirect_to_main']     // Callback
            );

            // Keep the original submenu structure intact
            // This allows direct access to pages like admin.php?page=lean-analytics
            // Note: Due to WordPress limitations, these won't appear in the sidebar menu,
            // but they remain accessible via direct links and the Switchboard dashboard
        }
    }

    /**
     * Redirect to the main Switchboard callback
     */
    public function redirect_to_main() {
        // Get the main Switchboard instance and call its admin_page method
        if (class_exists('Switchboard')) {
            $switchboard = Switchboard::get_instance();
            if (method_exists($switchboard, 'admin_page')) {
                $switchboard->admin_page();
                return;
            }
        }

        // Fallback: if we stored the original callback, try to call it
        if (isset($this->original_callback) && is_callable($this->original_callback)) {
            call_user_func($this->original_callback);
        }
    }

    /**
     * Add quick access menu for Switchboard submenus
     */
    public function add_quick_access_menu() {
        global $submenu;

        // Get Switchboard submenus
        $switchboard_submenus = isset($submenu['switchboard']) ? $submenu['switchboard'] : [];

        if (empty($switchboard_submenus) || count($switchboard_submenus) <= 1) {
            return;
        }

        // Filter out the main menu item and build the quick access links
        $quick_links = [];
        foreach ($switchboard_submenus as $item) {
            // Skip if it's the main Switchboard item
            if (isset($item[2]) && $item[2] === 'switchboard') {
                continue;
            }

            // Build the admin URL
            $url = admin_url('admin.php?page=' . $item[2]);
            $title = $item[0]; // Menu title

            $quick_links[] = [
                'title' => $title,
                'url' => $url
            ];
        }

        if (empty($quick_links)) {
            return;
        }

        // Output the quick access menu
        ?>
        <div class="switchboard-quick-access">
            <button type="button" class="button switchboard-quick-access-trigger" style="border-radius: 6px;">
                Quick Access ▼
            </button>
            <div class="switchboard-quick-access-dropdown">
                <?php foreach ($quick_links as $link): ?>
                    <a href="<?php echo esc_url($link['url']); ?>">
                        <?php echo esc_html($link['title']); ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <script>
            (function() {
                const quickAccess = document.querySelector('.switchboard-quick-access');
                const trigger = document.querySelector('.switchboard-quick-access-trigger');

                if (trigger && quickAccess) {
                    trigger.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        quickAccess.classList.toggle('active');
                    });

                    // Close dropdown when clicking outside
                    document.addEventListener('click', function(e) {
                        if (!quickAccess.contains(e.target)) {
                            quickAccess.classList.remove('active');
                        }
                    });
                }
            })();
        </script>
        <?php
    }
}

// Instantiate and register the module
$switchboard_instance = new SwitchboardMoveToTools();
if (class_exists('Switchboard_Data_Registry')) {
    Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
}
