<?php
/**
 * AI Auto Tool - Professional Autoloader
 * 
 * PSR-4 compliant autoloader giống Composer
 * Tối ưu hóa performance và lazy loading
 * 
 * @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_Autoloader {
    
    /**
     * Class map for fast loading
     * @var array
     */
    private static $classMap = array();
    
    /**
     * PSR-4 namespaces
     * @var array
     */
    private static $psr4Namespaces = array();
    
    /**
     * Fallback directories
     * @var array
     */
    private static $fallbackDirs = array();
    
    /**
     * Loaded classes cache
     * @var array
     */
    private static $loadedClasses = array();
    
    /**
     * Plugin root directory
     * @var string
     */
    private static $pluginDir;
    
    /**
     * Static flag to prevent multiple initializations
     * @var bool
     */
    private static $initialized = false;
    
    /**
     * Minimal mode flag (cached to avoid repeated get_option calls)
     * @var bool|null
     */
    private static $minimal_mode = null;
    
    /**
     * Initialize autoloader
     */
    public static function init() {
        // Prevent multiple initializations
        if (self::$initialized) {
            return;
        }
        
        self::$pluginDir = plugin_dir_path(__FILE__) . '../';
        
        // Check if minimal mode is enabled (cache result to avoid repeated get_option calls)
        // Only call get_option if WordPress is loaded, otherwise default to false
        if (self::$minimal_mode === null) {
            if (function_exists('get_option')) {
                // Use static cache and only check option once per request
                static $minimal_mode_checked = false;
                static $minimal_mode_value = false;
                
                if (!$minimal_mode_checked) {
                    $minimal_mode_value = get_option('aiautotool_autoloader_minimal_mode', 'false') === 'true';
                    $minimal_mode_checked = true;
                }
                
                self::$minimal_mode = $minimal_mode_value;
            } else {
                // WordPress not loaded yet, default to false
                self::$minimal_mode = false;
            }
        }
        
        // Register autoloader
        spl_autoload_register(array(__CLASS__, 'loadClass'));
        
        // Initialize PSR-4 namespaces
        self::initPSR4Namespaces();
        
        // Initialize class map (only core classes in minimal mode)
        if (self::$minimal_mode) {
            self::initMinimalClassMap();
        } else {
            self::initClassMap();
        }
        
        // Initialize fallback directories
        self::initFallbackDirs();
        
        self::$initialized = true;
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * Initialize PSR-4 namespaces
     */
    private static function initPSR4Namespaces() {
        self::$psr4Namespaces = array(
            // Core namespaces
            'AIAutoTool\\Core\\' => array(
                self::$pluginDir . 'inc/core/',
            ),
            
            // Feature namespaces
            'AIAutoTool\\Features\\' => array(
                self::$pluginDir . 'inc/features/',
            ),
            
            // AI Providers namespace
            'AIAutoTool\\AIProviders\\' => array(
                self::$pluginDir . 'inc/ai-providers/',
            ),
            
            // Extra Config namespace
            'AIAutoTool\\ExtraConfig\\' => array(
                self::$pluginDir . 'inc/extra-config/',
            ),
            
            // Library namespace
            'AIAutoTool\\Lib\\' => array(
                self::$pluginDir . 'lib/',
            ),
            
            // Legacy namespace (for backward compatibility)
            'AIAutoTool\\Legacy\\' => array(
                self::$pluginDir . 'inc/',
            ),
        );
    }
    
    /**
     * Initialize minimal class map for emergency mode
     */
    private static function initMinimalClassMap() {
        self::$classMap = array(
            // Only essential classes
            'rendersetting' => self::$pluginDir . 'lib/setting.php',
            'AIAutoTool\\Core\\MenuManager' => self::$pluginDir . 'inc/menu-manager.php',
            'AIAutoTool\\Core\\FeatureOptions' => self::$pluginDir . 'inc/feature-options.php',
            'AIAutoTool\\Core\\Migration' => self::$pluginDir . 'inc/migration.php',
            'aiautotool_Warning_Notice' => self::$pluginDir . 'lib/aiautotool_notice_control.php',
        );
    }
    
    /**
     * Initialize class map for fast loading
     */
    private static function initClassMap() {
        self::$classMap = array(
            // Core classes - Load rendersetting first (required by many classes)
            'rendersetting' => self::$pluginDir . 'lib/setting.php',
            
            // Core classes
            'AIAutoTool\\Core\\Plugin' => self::$pluginDir . 'inc/core/class-plugin.php',
            'AIAutoTool\\Core\\Settings' => self::$pluginDir . 'inc/core/class-settings.php',
            'AIAutoTool\\Core\\API' => self::$pluginDir . 'inc/core/class-api.php',
            
            // New Features namespace mapping
            'AIAutoTool\\Features\\AutoComment\\AutoComment' => self::$pluginDir . 'inc/features/auto-comment/auto-comment.php',
            'AIAutoTool\\Features\\AutoCreateTags\\AutoCreateTags' => self::$pluginDir . 'inc/features/auto-create-tags/auto-create-tags.php',
            'AIAutoTool\\Features\\BotSecurity\\BotSecurity' => self::$pluginDir . 'inc/features/bot-security/bot-security.php',
            'AIAutoTool\\Features\\CanonicalManager\\CanonicalManager' => self::$pluginDir . 'inc/features/canonical-manager/canonical-manager.php',
            'AIAutoTool\\Features\\CloudflareAI\\CloudflareAI' => self::$pluginDir . 'inc/features/cloudflare-ai/cloudflare-ai.php',
            'AIAutoTool\\Features\\ExternalLinks\\ExternalLinks' => self::$pluginDir . 'inc/features/external-links/external-links.php',
            'AIAutoTool\\Features\\FooterBase\\FooterBase' => self::$pluginDir . 'inc/features/footer-base/footer-base.php',
            'AIAutoTool\\Features\\ImageScanner\\ImageScanner' => self::$pluginDir . 'inc/features/image-scanner/image-scanner.php',
            'AIAutoTool\\Features\\InstallPlugin\\InstallPlugin' => self::$pluginDir . 'inc/features/install-plugin/install-plugin.php',
            'AIAutoTool\\Features\\KeywordAutopost\\KeywordAutopost' => self::$pluginDir . 'inc/features/keyword-autopost/keyword-autopost.php',
            'AIAutoTool\\Features\\PostExporter\\PostExporter' => self::$pluginDir . 'inc/features/post-exporter/post-exporter.php',
            'AIAutoTool\\Features\\PromptCPT\\PromptCPT' => self::$pluginDir . 'inc/features/prompt-cpt/prompt-cpt.php',
            'AIAutoTool\\Features\\PromptCustomer\\PromptCustomer' => self::$pluginDir . 'inc/features/prompt-customer/prompt-customer.php',
            'AIAutoTool\\Features\\SingleAI\\SingleAI' => self::$pluginDir . 'inc/features/single-ai/single-ai.php',
            'AIAutoTool\\Features\\SuggestAuto\\SuggestAuto' => self::$pluginDir . 'inc/features/suggest-auto/suggest-auto.php',
            'AIAutoTool\\Features\\SubmitIndex\\SubmitIndex' => self::$pluginDir . 'inc/features/submit-index/submit-index.php',
            'AIAutoTool\\Features\\UsernameGenerator\\UsernameGenerator' => self::$pluginDir . 'inc/features/username-generator/username-generator.php',
            'AIAutoTool\\Features\\WebStories\\WebStories' => self::$pluginDir . 'inc/features/web-stories/web-stories.php',
            
            // Legacy class mappings (for backward compatibility)
            'AIautotool_autocomment' => self::$pluginDir . 'inc/features/auto-comment/aiautotool_autocomment.php',
            'AIautotool_autocreatetags' => self::$pluginDir . 'inc/features/auto-create-tags/aiautotool_autocreatetag.php',
            'AIAutoToolSecurityBot' => self::$pluginDir . 'inc/features/bot-security/aiautotool_bot_scrurity.php',
            'Aiautotool_Canonical' => self::$pluginDir . 'inc/features/canonical-manager/canonical.php',
            'AI_AutoTool_cloudflareAI' => self::$pluginDir . 'inc/features/cloudflare-ai/AI_AutoTool_cloudfalreAI.php',
            'Aiautotool_exLink_backlink' => self::$pluginDir . 'inc/features/external-links/auto-ex-link.php',
            'Aiautotool_footer_base' => self::$pluginDir . 'inc/features/footer-base/Aiautotool_footer_base.php',
            'AIAutotool_Image404Scanner' => self::$pluginDir . 'inc/features/image-scanner/images.php',
            'Aiautotool_Install_Plugin' => self::$pluginDir . 'inc/features/install-plugin/install-plugin.php',
            'Keyword_Autopost_Plugin' => self::$pluginDir . 'inc/features/keyword-autopost/keyword-autopost.php',
            'Post_Exporter_Plugin' => self::$pluginDir . 'inc/features/post-exporter/post-exporter.php',
            'AIautotool_Prompt_CPT' => self::$pluginDir . 'inc/features/prompt-cpt/aiautotool-prompt-cpt.php',
            'AI_AutoTool_Prompt_Customer' => self::$pluginDir . 'inc/features/prompt-customer/AI_AutoTool_Prompt_Customer.php',
            'AIAutoToolsinglepost' => self::$pluginDir . 'inc/features/single-ai/singleai.php',
            'AI_AutoTool_suggetauto' => self::$pluginDir . 'inc/features/suggest-auto/AI_AutoTool_suggetauto.php',
            'AIAutoTool_SubmitIndex' => self::$pluginDir . 'inc/features/submit-index/aiautotool_submitindex.php',
            'aiautotool_AutoGenerateUsername' => self::$pluginDir . 'inc/features/username-generator/aiautotool_create_random_profileuser.php',
            'AIautotool_Web_Stories' => self::$pluginDir . 'inc/features/web-stories/webstories.php',
            
            // Extra Config classes
            'AIAutoTool\\ExtraConfig\\Security' => self::$pluginDir . 'inc/extra-config/class-security.php',
            'AIAutoTool\\ExtraConfig\\SettingsRegistry' => self::$pluginDir . 'inc/extra-config/class-settings-registry.php',
            'AIAutoTool\\ExtraConfig\\AdminRenderer' => self::$pluginDir . 'inc/extra-config/class-admin-renderer.php',
            'AIAutoTool\\ExtraConfig\\HTMLCompression' => self::$pluginDir . 'inc/extra-config/class-html-compression.php',
            'AIAutoTool\\ExtraConfig\\AJAXHandler' => self::$pluginDir . 'inc/extra-config/class-ajax-handler.php',
            'AIAutoTool\\ExtraConfig\\Manager' => self::$pluginDir . 'inc/extra-config/class-manager.php',
            'AIAutoTool\\ExtraConfig\\FeaturesManager' => self::$pluginDir . 'inc/extra-config/class-features-manager.php',
            
            // Library classes
            'AIAutoTool\\Lib\\AutoToolBox' => self::$pluginDir . 'lib/boxf.php',
            'AIAutoTool\\Lib\\AIautoTool_log' => self::$pluginDir . 'lib/AIautotool_logall.php',
            'AIAutoTool\\Lib\\FeatureDescriptions' => self::$pluginDir . 'lib/feature-descriptions.php',
            'AIAutoTool\\Lib\\BardGenContent' => self::$pluginDir . 'lib/bard.php',
            'AIAutoTool\\Lib\\Spintaxkct' => self::$pluginDir . 'lib/Spintaxkct.php',
            'aiautotool_Warning_Notice' => self::$pluginDir . 'lib/aiautotool_notice_control.php',
            
            // Additional library classes (from dependency scan)
            'activeCallBack' => self::$pluginDir . 'lib/info.php',
            'AutoToolBox' => self::$pluginDir . 'lib/boxf.php',
            'KCT_AIAutoTool_ImageUploader' => self::$pluginDir . 'lib/aiautotool_imagescontrol.php',
            'SinglePost' => self::$pluginDir . 'lib/singlepost.php',
            'aiautotool_Telegram_Notifications' => self::$pluginDir . 'lib/aiautotool_telegrambot.php',
            'Parsedown' => self::$pluginDir . 'lib/Parsedown.php',
            'ImgCloudflare' => self::$pluginDir . 'lib/imgCloudfalreAI.php',
            'Imagescontent' => self::$pluginDir . 'lib/imageinsert.php',
            'Minifier' => self::$pluginDir . 'lib/minify-js.php',
            'AIAutotool_API_Helper' => self::$pluginDir . 'lib/aiautotool_api_helper.php',
            'AIAutoTool_SEO' => self::$pluginDir . 'lib/aiautotool_seocontrol.php',
            'ai_internal_link_building_blocks' => self::$pluginDir . 'lib/ai_internal_link_building.php',
            
            // New optimized classes
            'AIAutoTool\\Core\\OptimizedLoader' => self::$pluginDir . 'inc/optimized-loader.php',
            'AIAutoTool\\Core\\FeatureOptions' => self::$pluginDir . 'inc/feature-options.php',
            'AIAutoTool\\Core\\FeatureManager' => self::$pluginDir . 'inc/feature-manager.php',
            'AIAutoTool\\Core\\Migration' => self::$pluginDir . 'inc/migration.php',
            'AIAutoTool\\Core\\MenuManager' => self::$pluginDir . 'inc/menu-manager.php',
            
            // Scan-related features (separated into folders)
            'AI_AutoTool_Autoblogging' => self::$pluginDir . 'inc/features/autoblogging/autoblogging.php',
            'AI_AutoTool_MarkdownParser' => self::$pluginDir . 'lib/markdown-parser.php',
            'AIAutoTool_Cron_Status_Widget' => self::$pluginDir . 'inc/cron-status-widget/cron-status-widget.php',
            
            // AI Provider classes (CRITICAL: Must be available for all features)
            'AIAutotool_AI_Helper' => self::$pluginDir . 'inc/ai-providers/aiautotool_ai_helper.php',
            'AIAutotool_AI_Provider_Manager' => self::$pluginDir . 'inc/ai-providers/aiautotool_ai_provider_manager.php',
            'AIAutotool_AI_Provider_Settings' => self::$pluginDir . 'inc/ai-providers/aiautotool_ai_provider_settings.php',
            'AIAutotool_AI_Provider_Base' => self::$pluginDir . 'inc/ai-providers/aiautotool_ai_provider_base.php',
            'AIAutotool_AI_Provider_OpenAI' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai.php',
            'AIAutotool_AI_Provider_OpenAI_Compatible' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_OpenRouter' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Groq' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_DeepSeek' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Mistral' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Together' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Fireworks' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Perplexity' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_XAI' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Ollama' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_openai_compatible.php',
            'AIAutotool_AI_Provider_Anthropic' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_anthropic.php',
            'AIAutotool_AI_Provider_Azure_OpenAI' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_azure_openai.php',
            'AIAutotool_AI_Provider_Gemini' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_gemini.php',
            'AIAutotool_AI_Provider_Pollinations' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_pollinations.php',
            'AIAutotool_AI_Provider_LLM7' => self::$pluginDir . 'inc/ai-providers/providers/aiautotool_ai_provider_pollinations.php', // Backward compatibility alias
        );
    }
    
    /**
     * Initialize fallback directories
     */
    private static function initFallbackDirs() {
        self::$fallbackDirs = array(
            self::$pluginDir . 'inc/',
            self::$pluginDir . 'lib/',
            self::$pluginDir . 'inc/ai-providers/',
            self::$pluginDir . 'inc/extra-config/',
            self::$pluginDir . 'inc/features/autoblogging/',
            self::$pluginDir . 'inc/cron-status-widget/',
            self::$pluginDir . 'inc/features/',
            self::$pluginDir . 'inc/features/auto-comment/',
            self::$pluginDir . 'inc/features/auto-create-tags/',
            self::$pluginDir . 'inc/features/bot-security/',
            self::$pluginDir . 'inc/features/canonical-manager/',
            self::$pluginDir . 'inc/features/cloudflare-ai/',
            self::$pluginDir . 'inc/features/external-links/',
            self::$pluginDir . 'inc/features/footer-base/',
            self::$pluginDir . 'inc/features/image-scanner/',
            self::$pluginDir . 'inc/features/install-plugin/',
            self::$pluginDir . 'inc/features/keyword-autopost/',
            self::$pluginDir . 'inc/features/post-exporter/',
            self::$pluginDir . 'inc/features/prompt-cpt/',
            self::$pluginDir . 'inc/features/prompt-customer/',
            self::$pluginDir . 'inc/features/single-ai/',
            self::$pluginDir . 'inc/features/suggest-auto/',
            self::$pluginDir . 'inc/features/submit-index/',
            self::$pluginDir . 'inc/features/username-generator/',
            self::$pluginDir . 'inc/features/web-stories/',
        );
    }
    
    /**
     * Load class using PSR-4 autoloading
     * OPTIMIZED: Uses cached file_exists() when available
     */
    public static function loadClass($className) {
        // Check if already loaded
        if (isset(self::$loadedClasses[$className])) {
            return true;
        }
        
        // Use cached file_exists if available
        $use_cache = class_exists('AIAutoTool_OptionCache');
        
        // Try class map first (fastest)
        if (isset(self::$classMap[$className])) {
            $file = self::$classMap[$className];
            $file_exists = $use_cache ? AIAutoTool_OptionCache::file_exists($file) : file_exists($file);
            if ($file_exists) {
                require_once $file;
                self::$loadedClasses[$className] = $file;
                
                
                return true;
            }
        }
        
        // Try PSR-4 namespaces
        foreach (self::$psr4Namespaces as $prefix => $dirs) {
            if (strpos($className, $prefix) === 0) {
                $relativeClass = substr($className, strlen($prefix));
                $fileName = str_replace('\\', '/', $relativeClass) . '.php';
                
                foreach ($dirs as $dir) {
                    $file = $dir . $fileName;
                    $file_exists = $use_cache ? AIAutoTool_OptionCache::file_exists($file) : file_exists($file);
                    if ($file_exists) {
                        require_once $file;
                        self::$loadedClasses[$className] = $file;
                        
                        
                        return true;
                    }
                }
            }
        }
        
        // Try fallback directories
        $fileName = str_replace('\\', '/', $className) . '.php';
        foreach (self::$fallbackDirs as $dir) {
            $file = $dir . $fileName;
            $file_exists = $use_cache ? AIAutoTool_OptionCache::file_exists($file) : file_exists($file);
            if ($file_exists) {
                require_once $file;
                self::$loadedClasses[$className] = $file;
                
               
                return true;
            }
        }
        
        // Try legacy naming convention
        $legacyFileName = strtolower(str_replace('_', '-', $className)) . '.php';
        foreach (self::$fallbackDirs as $dir) {
            $file = $dir . $legacyFileName;
            $file_exists = $use_cache ? AIAutoTool_OptionCache::file_exists($file) : file_exists($file);
            if ($file_exists) {
                require_once $file;
                self::$loadedClasses[$className] = $file;
                
                
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Add class to class map
     */
    public static function addClassMap($className, $filePath) {
        self::$classMap[$className] = $filePath;
    }
    
    /**
     * Add PSR-4 namespace
     */
    public static function addPSR4Namespace($prefix, $dirs) {
        self::$psr4Namespaces[$prefix] = $dirs;
    }
    
    /**
     * Add fallback directory
     */
    public static function addFallbackDir($dir) {
        if (!in_array($dir, self::$fallbackDirs)) {
            self::$fallbackDirs[] = $dir;
        }
    }
    
    /**
     * Get loaded classes
     */
    public static function getLoadedClasses() {
        return self::$loadedClasses;
    }
    
    /**
     * Check if class is loaded
     */
    public static function isClassLoaded($className) {
        return isset(self::$loadedClasses[$className]);
    }
    
    /**
     * Get class map
     */
    public static function getClassMap() {
        return self::$classMap;
    }
    
    /**
     * Generate optimized class map
     */
    public static function generateClassMap() {
        $classMap = array();
        
        // Scan directories for classes
        $directories = array(
            self::$pluginDir . 'inc/',
            self::$pluginDir . 'lib/',
            self::$pluginDir . 'inc/ai-providers/',
            self::$pluginDir . 'inc/extra-config/',
        );
        
        foreach ($directories as $dir) {
            if (is_dir($dir)) {
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($dir)
                );
                
                foreach ($files as $file) {
                    if ($file->isFile() && $file->getExtension() === 'php') {
                        $content = file_get_contents($file->getPathname());
                        
                        // Extract class names
                        if (preg_match('/^class\s+([a-zA-Z_][a-zA-Z0-9_]*)/m', $content, $matches)) {
                            $className = $matches[1];
                            $classMap[$className] = $file->getPathname();
                        }
                    }
                }
            }
        }
        
        return $classMap;
    }
    
    /**
     * Performance statistics
     */
    public static function getStats() {
        return array(
            'loaded_classes' => count(self::$loadedClasses),
            'class_map_size' => count(self::$classMap),
            'psr4_namespaces' => count(self::$psr4Namespaces),
            'fallback_dirs' => count(self::$fallbackDirs),
            'memory_usage' => memory_get_usage(true),
        );
    }
}

// DO NOT auto-initialize autoloader here
// It will be initialized explicitly by the main plugin class
// This prevents early initialization before WordPress is fully loaded
// AIAutoTool_Autoloader::init(); // REMOVED - causes memory issues
?>
