<?php
/**
 * AI Auto Tool - Optimized Loading Strategy
 * 
 * Kế hoạch tối ưu hóa loading các file inc và lib
 * 
 * @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_OptimizedLoader {
    
    private static $instance = null;
    private $loaded_files = array();
    private $core_files_loaded = false;
    
    /**
     * Singleton instance
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor - Initialize optimized loading
     */
    public function __construct() {
        add_action('init', array($this, 'load_core_files'), 5);
        add_action('wp_loaded', array($this, 'load_conditional_files'), 15);
        add_action('admin_init', array($this, 'load_admin_files'), 10);
    }
    
    /**
     * PHASE 1: Load core files immediately
     */
    public function load_core_files() {
        if ($this->core_files_loaded) {
            return;
        }
        
        $inc_directory = plugin_dir_path(__FILE__) . 'inc';
        $lib_directory = plugin_dir_path(__FILE__) . 'lib';
        
        // Core INC files (essential for basic functionality)
        $core_inc_files = array(
            'aiautotool_api_manager.php',     // API management
            'canonical.php',                  // SEO canonical
            'auto-ex-link.php',               // Auto external links
            'ssl.php',                        // SSL management
        );
        
        // Core LIB files (essential helpers)
        $core_lib_files = array(
            'aiautotool_api_helper.php',      // API helper
            'setting.php',                    // Settings
            'info.php',                       // Info
        );
        
        // Load core INC files
        foreach ($core_inc_files as $file) {
            $file_path = $inc_directory . '/' . $file;
            if (file_exists($file_path)) {
                include $file_path;
                $this->loaded_files[] = $file;
            }
        }
        
        // Load core LIB files
        foreach ($core_lib_files as $file) {
            $file_path = $lib_directory . '/' . $file;
            if (file_exists($file_path)) {
                include $file_path;
                $this->loaded_files[] = $file;
            }
        }
        
        $this->core_files_loaded = true;
        
        // Log loading for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * PHASE 2: Load conditional files based on settings
     */
    public function load_conditional_files() {
        $inc_directory = plugin_dir_path(__FILE__) . 'inc';
        
        // Conditional files mapping
        $conditional_files = array(
            'keyword-autopost.php' => 'keyword_autopost_active',
            'images.php' => 'images_active', 
            'singleai.php' => 'singleai_active',
            'scan.php' => 'scan_active',
            'post-exporter.php' => 'post_exporter_active',
            'aiautotool_autocomment.php' => 'autocomment_active',
            'webstories.php' => 'webstories_active',
            'aiautotool_autocreatetag.php' => 'autocreatetag_active',
            'AI_AutoTool_cloudfalreAI.php' => 'cloudflare_ai_active',
            'AI_AutoTool_suggetauto.php' => 'suggest_auto_active',
        );
        
        foreach ($conditional_files as $file => $option_name) {
            if (get_option($option_name, false) === 'true') {
                $file_path = $inc_directory . '/' . $file;
                if (file_exists($file_path)) {
                    include $file_path;
                    $this->loaded_files[] = $file;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
        }
    }
    
    /**
     * PHASE 3: Load admin-specific files
     */
    public function load_admin_files() {
        if (!is_admin()) {
            return;
        }
        
        $inc_directory = plugin_dir_path(__FILE__) . 'inc';
        $lib_directory = plugin_dir_path(__FILE__) . 'lib';
        
        // Admin-specific files
        $admin_files = array(
            'inc' => array(
                'install-plugin.php',
                'cron-status-widget.php',
                'aiautotool-prompt-cpt.php',
            ),
            'lib' => array(
                'feature-descriptions.php',
                'aiautotool_seocontrol.php',
                'aiautotool_notice_control.php',
                'aiautotool_imagescontrol.php',
            )
        );
        
        foreach ($admin_files['inc'] as $file) {
            $file_path = $inc_directory . '/' . $file;
            if (file_exists($file_path)) {
                include $file_path;
                $this->loaded_files[] = $file;
            }
        }
        
        foreach ($admin_files['lib'] as $file) {
            $file_path = $lib_directory . '/' . $file;
            if (file_exists($file_path)) {
                include $file_path;
                $this->loaded_files[] = $file;
            }
        }
    }
    
    /**
     * PHASE 4: Lazy loading for specific features
     */
    public function load_on_demand($feature) {
        $inc_directory = plugin_dir_path(__FILE__) . 'inc';
        $lib_directory = plugin_dir_path(__FILE__) . 'lib';
        
        $lazy_files = array(
            'parsing' => array(
                'lib' => 'Parsedown.php',
            ),
            'minification' => array(
                'lib' => 'minify-js.php',
            ),
            'bard_api' => array(
                'lib' => 'bard.php',
            ),
            'ai_providers' => array(
                'inc' => 'ai-providers/index.php',
            ),
            'extra_config' => array(
                'inc' => 'extra-config/bootstrap.php',
            ),
        );
        
        if (isset($lazy_files[$feature])) {
            foreach ($lazy_files[$feature] as $dir => $file) {
                $file_path = (($dir === 'inc') ? $inc_directory : $lib_directory) . '/' . $file;
                if (file_exists($file_path)) {
                    require_once $file_path;
                    $this->loaded_files[] = $file;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
        }
    }
    
    /**
     * Get loaded files for debugging
     */
    public function get_loaded_files() {
        return $this->loaded_files;
    }
    
    /**
     * Check if file is loaded
     */
    public function is_file_loaded($filename) {
        return in_array($filename, $this->loaded_files);
    }
}

// Initialize optimized loader
add_action('plugins_loaded', function() {
    AIAutoTool_OptimizedLoader::instance();
}, 5);
?>
