<?php
/**
 * AI Auto Tool - Menu Manager
 * 
 * Quản lý menu admin với autoloader system
 * Đảm bảo menu hiển thị đúng sau khi build autoloader
 * 
 * @package AI Auto Tool
 * @version 2.3.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutoTool_MenuManager {
    
    /**
     * Menu registry
     * @var array
     */
    private static $menuRegistry = array();
    
    /**
     * Loaded menu items
     * @var array
     */
    private static $loadedMenus = array();
    
    /**
     * Main plugin instance
     * @var AI_Auto_Tool
     */
    private static $mainInstance = null;
    
    /**
     * Initialize menu manager
     */
    public static function init($mainInstance = null) {
        if ($mainInstance) {
            self::$mainInstance = $mainInstance;
        }
        
        // Register menu hooks
        add_action('admin_menu', array(__CLASS__, 'registerMenus'), 5);
        add_action('admin_init', array(__CLASS__, 'loadMenuDependencies'), 1);
        
        // Initialize menu registry
        self::initMenuRegistry();
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * Initialize menu registry
     */
    private static function initMenuRegistry() {
        self::$menuRegistry = array(
            // Main menu (always loaded)
            'main' => array(
                'type' => 'menu',
                'title' => '<i class="fa-solid fa-gears"></i> Ai Auto Tool',
                'menu_title' => '<i class="fa-solid fa-gears"></i> Ai Auto Tool',
                'capability' => 'manage_options',
                'slug' => 'ai_auto_tool',
                'callback' => array(__CLASS__, 'renderMainPage'),
                'icon' => 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(plugin_dir_path(__FILE__) . '../images/logo.svg')),
                'position' => 3,
                'priority' => 1,
            ),
            
            // Submenus
            'integrations' => array(
                'type' => 'submenu',
                'parent' => 'ai_auto_tool',
                'title' => '<i class="fa-solid fa-wand-magic-sparkles"></i> Integrations',
                'menu_title' => '<i class="fa-solid fa-wand-magic-sparkles"></i> Integrations',
                'capability' => 'manage_options',
                'slug' => 'aiautotool_integrations',
                'callback' => array(__CLASS__, 'renderIntegrationsPage'),
                'priority' => 2,
            ),
            
        );
    }
    
    /**
     * Load menu dependencies
     */
    public static function loadMenuDependencies() {
        if (!is_admin()) {
            return;
        }
        
        // Load core dependencies first
        self::loadCoreDependencies();
        
        // Load feature-specific dependencies
        foreach (self::$menuRegistry as $menuKey => $menuConfig) {
            if (isset($menuConfig['condition'])) {
                if (self::shouldLoadMenu($menuKey)) {
                    self::loadMenuDependency($menuKey);
                }
            }
        }
    }
    
    /**
     * Load core dependencies
     */
    private static function loadCoreDependencies() {
        $coreFiles = array(
            'lib/setting.php', // rendersetting class
            'lib/aiautotool_notice_control.php', // aiautotool_Warning_Notice
            'lib/boxf.php', // AutoToolBox
            'lib/bard.php', // BardGenContent
            'lib/AIautotool_logall.php', // AIautoTool_log
        );
        
        $pluginDir = plugin_dir_path(__FILE__) . '../';
        
        foreach ($coreFiles as $file) {
            $filePath = $pluginDir . $file;
            if (file_exists($filePath)) {
                require_once $filePath;
            }
        }
    }
    
    /**
     * Load menu dependency
     */
    private static function loadMenuDependency($menuKey) {
        $menuConfig = self::$menuRegistry[$menuKey];
        
        // Map menu keys to their corresponding files
        $menuFileMap = array(
            // TEMPORARILY DISABLED: API Manager causing errors
            // 'api_manager' => 'inc/aiautotool_api_manager.php',
            'keyword_autopost' => 'inc/keyword-autopost.php',
            'singleai' => 'inc/singleai.php',
            'post_exporter' => 'inc/post-exporter.php',
            'canonical' => 'inc/canonical.php',
            'auto_ex_link' => 'inc/auto-ex-link.php',
            'submit_index' => 'inc/aiautotool_submitindex.php',
            'install_plugins' => 'inc/install-plugin.php',
        );
        
        if (isset($menuFileMap[$menuKey])) {
            $filePath = plugin_dir_path(__FILE__) . '../' . $menuFileMap[$menuKey];
            if (file_exists($filePath)) {
                require_once $filePath;
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
            }
        }
    }
    
    /**
     * Check if menu should be loaded
     */
    private static function shouldLoadMenu($menuKey) {
        $menuConfig = self::$menuRegistry[$menuKey];
        
        if (!isset($menuConfig['condition'])) {
            return true;
        }
        
        $condition = $menuConfig['condition'];
        
        // Check if feature is active
        return get_option($condition, 'false') === 'true';
    }
    
    /**
     * Register menus
     */
    public static function registerMenus() {
        // Sort menus by priority
        uasort(self::$menuRegistry, function($a, $b) {
            $priorityA = isset($a['priority']) ? $a['priority'] : 999;
            $priorityB = isset($b['priority']) ? $b['priority'] : 999;
            return $priorityA - $priorityB;
        });
        
        foreach (self::$menuRegistry as $menuKey => $menuConfig) {
            // Skip if condition not met
            if (isset($menuConfig['condition']) && !self::shouldLoadMenu($menuKey)) {
                continue;
            }
            
            if ($menuConfig['type'] === 'menu') {
                add_menu_page(
                    $menuConfig['title'],
                    $menuConfig['menu_title'],
                    $menuConfig['capability'],
                    $menuConfig['slug'],
                    $menuConfig['callback'],
                    $menuConfig['icon'],
                    $menuConfig['position']
                );
            } elseif ($menuConfig['type'] === 'submenu') {
                add_submenu_page(
                    $menuConfig['parent'],
                    $menuConfig['title'],
                    $menuConfig['menu_title'],
                    $menuConfig['capability'],
                    $menuConfig['slug'],
                    $menuConfig['callback']
                );
            }
            
            self::$loadedMenus[] = $menuKey;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * Render main page
     */
    public static function renderMainPage() {
        if (!self::$mainInstance) {
            echo '<div class="wrap"><h2>AI Auto Tool</h2><p>Main instance not available.</p></div>';
            return;
        }
        
        // Call the main instance's config_page method
        if (method_exists(self::$mainInstance, 'config_page')) {
            self::$mainInstance->config_page();
        } else {
            echo '<div class="wrap"><h2>AI Auto Tool</h2><p>Configuration page not available.</p></div>';
        }
    }
    
    /**
     * Render integrations page
     */
    public static function renderIntegrationsPage() {
        if (!self::$mainInstance) {
            echo '<div class="wrap"><h2>Integrations</h2><p>Main instance not available.</p></div>';
            return;
        }
        
        // Call the main instance's integrations method
        if (method_exists(self::$mainInstance, 'aiautotool_integrations')) {
            self::$mainInstance->aiautotool_integrations();
        } else {
            echo '<div class="wrap"><h2>Integrations</h2><p>Integrations page not available.</p></div>';
        }
    }
    
    /**
     * Render SSL settings page
     */
    /**
     * Render API Manager page
     */
    public static function renderAPIManagerPage() {
        // TEMPORARILY DISABLED: API Manager causing errors
        echo '<div class="wrap"><h2>API Manager</h2><p>API Manager is temporarily disabled due to errors.</p></div>';
        /*
        if (class_exists('AIAutotool_API_Manager')) {
            $apiManager = new AIAutotool_API_Manager();
            if (method_exists($apiManager, 'admin_page')) {
                $apiManager->admin_page();
            } else {
                echo '<div class="wrap"><h2>API Manager</h2><p>API Manager page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>API Manager</h2><p>API Manager class not found.</p></div>';
        }
        */
    }
    
    /**
     * Render Keyword Autopost page
     */
    public static function renderKeywordAutopostPage() {
        if (class_exists('Keyword_Autopost_Plugin')) {
            $keywordAutopost = new Keyword_Autopost_Plugin();
            if (method_exists($keywordAutopost, 'admin_page')) {
                $keywordAutopost->admin_page();
            } else {
                echo '<div class="wrap"><h2>Keyword Autopost</h2><p>Keyword Autopost page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Keyword Autopost</h2><p>Keyword Autopost class not found.</p></div>';
        }
    }
    
    /**
     * Render Single AI page
     */
    public static function renderSingleAIPage() {
        if (class_exists('AIAutoToolsinglepost')) {
            $singleAI = new AIAutoToolsinglepost();
            if (method_exists($singleAI, 'admin_page')) {
                $singleAI->admin_page();
            } else {
                echo '<div class="wrap"><h2>Single AI</h2><p>Single AI page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Single AI</h2><p>Single AI class not found.</p></div>';
        }
    }
    
    /**
     * Render Post Exporter page
     */
    public static function renderPostExporterPage() {
        if (class_exists('Post_Exporter_Plugin')) {
            $postExporter = new Post_Exporter_Plugin();
            if (method_exists($postExporter, 'admin_page')) {
                $postExporter->admin_page();
            } else {
                echo '<div class="wrap"><h2>Post Exporter</h2><p>Post Exporter page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Post Exporter</h2><p>Post Exporter class not found.</p></div>';
        }
    }
    
    /**
     * Render Canonical page
     */
    public static function renderCanonicalPage() {
        if (class_exists('Aiautotool_Canonical')) {
            $canonical = new Aiautotool_Canonical();
            if (method_exists($canonical, 'admin_page')) {
                $canonical->admin_page();
            } else {
                echo '<div class="wrap"><h2>Canonical</h2><p>Canonical page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Canonical</h2><p>Canonical class not found.</p></div>';
        }
    }
    
    /**
     * Render Auto External Link page
     */
    public static function renderAutoExLinkPage() {
        if (class_exists('Aiautotool_exLink_backlink')) {
            $autoExLink = new Aiautotool_exLink_backlink();
            if (method_exists($autoExLink, 'admin_page')) {
                $autoExLink->admin_page();
            } else {
                echo '<div class="wrap"><h2>Auto External Link</h2><p>Auto External Link page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Auto External Link</h2><p>Auto External Link class not found.</p></div>';
        }
    }
    
    /**
     * Render Submit Index page
     */
    public static function renderSubmitIndexPage() {
        if (class_exists('AIAutoTool_SubmitIndex')) {
            $submitIndex = new AIAutoTool_SubmitIndex();
            if (method_exists($submitIndex, 'admin_page')) {
                $submitIndex->admin_page();
            } else {
                echo '<div class="wrap"><h2>Submit Index</h2><p>Submit Index page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Submit Index</h2><p>Submit Index class not found.</p></div>';
        }
    }
    
    /**
     * Render Install Plugins page
     */
    public static function renderInstallPluginsPage() {
        if (class_exists('Auto_Install_Plugins')) {
            $installPlugins = new Auto_Install_Plugins();
            if (method_exists($installPlugins, 'admin_page_content')) {
                $installPlugins->admin_page_content();
            } else {
                echo '<div class="wrap"><h2>Auto Install Plugins</h2><p>Auto Install Plugins page not available.</p></div>';
            }
        } else {
            echo '<div class="wrap"><h2>Auto Install Plugins</h2><p>Auto Install Plugins class not found.</p></div>';
        }
    }
    
    /**
     * Get loaded menus
     */
    public static function getLoadedMenus() {
        return self::$loadedMenus;
    }
    
    /**
     * Get menu registry
     */
    public static function getMenuRegistry() {
        return self::$menuRegistry;
    }
    
    /**
     * Add custom menu
     */
    public static function addMenu($menuKey, $menuConfig) {
        self::$menuRegistry[$menuKey] = $menuConfig;
    }
    
    /**
     * Remove menu
     */
    public static function removeMenu($menuKey) {
        if (isset(self::$menuRegistry[$menuKey])) {
            unset(self::$menuRegistry[$menuKey]);
        }
    }
    
    /**
     * Performance statistics
     */
    public static function getStats() {
        return array(
            'loaded_menus' => count(self::$loadedMenus),
            'total_menus' => count(self::$menuRegistry),
            'loaded_menu_names' => self::$loadedMenus,
            'memory_usage' => memory_get_usage(true),
        );
    }
}
?>
