<?php
/**
 * AI Auto Tool Asset Manager
 * 
 * Quản lý tập trung việc enqueue JS/CSS cho plugin
 * Chỉ load assets khi thực sự cần thiết để tối ưu hiệu suất
 * 
 * @package AI Auto Tool
 * @version 1.0.0
 */

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

class AIAutoTool_Asset_Manager {
    
    /**
     * Instance
     */
    private static $instance = null;
    
    /**
     * Registered assets by feature
     */
    private $registered_assets = array();
    
    /**
     * Pages that need core assets
     */
    private $core_asset_pages = array(
        'ai_auto_tool',
        'aiautotool_integrations',
    );
    
    /**
     * Get instance
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_core_assets'), 10);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_feature_assets'), 20);
    }
    
    /**
     * Register assets for a feature
     * 
     * @param string $feature_key Feature identifier
     * @param array $assets Array of assets to register
     */
    public function register_feature_assets($feature_key, $assets) {
        if (!isset($this->registered_assets[$feature_key])) {
            $this->registered_assets[$feature_key] = array(
                'scripts' => array(),
                'styles' => array(),
                'pages' => array(), // Pages where these assets should load
                'conditions' => array(), // Callback functions for conditional loading
            );
        }
        
        if (isset($assets['scripts'])) {
            $this->registered_assets[$feature_key]['scripts'] = array_merge(
                $this->registered_assets[$feature_key]['scripts'],
                $assets['scripts']
            );
        }
        
        if (isset($assets['styles'])) {
            $this->registered_assets[$feature_key]['styles'] = array_merge(
                $this->registered_assets[$feature_key]['styles'],
                $assets['styles']
            );
        }
        
        if (isset($assets['pages'])) {
            $this->registered_assets[$feature_key]['pages'] = array_merge(
                $this->registered_assets[$feature_key]['pages'],
                $assets['pages']
            );
        }
        
        if (isset($assets['conditions'])) {
            $this->registered_assets[$feature_key]['conditions'] = array_merge(
                $this->registered_assets[$feature_key]['conditions'],
                $assets['conditions']
            );
        }
    }
    
    /**
     * Enqueue core assets (loaded on all plugin admin pages)
     */
    public function enqueue_core_assets($hook) {
        // Check if we're on a plugin page
        if (!$this->is_plugin_page($hook)) {
            return;
        }
        
        // Load rendersetting class if needed
        if (!class_exists('rendersetting')) {
            $rendersetting_file = plugin_dir_path(dirname(__FILE__)) . 'lib/setting.php';
            if (file_exists($rendersetting_file)) {
                require_once $rendersetting_file;
            }
        }
        
        $version = defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0';
        
        // Core CSS - Load in optimized order
        // Font Awesome - Only load if needed (checked via filter or option)
        $load_fontawesome = apply_filters('aiautotool_load_fontawesome', true);
        if ($load_fontawesome) {
            wp_enqueue_style(
                'font-awesome',
                AIAUTOTOOL_URI . 'js/fontawesome/css/all.min.css',
                array(),
                $version
            );
        }
        
        // Main plugin CSS - Always load first
        wp_enqueue_style(
            'aiautotool',
            plugin_dir_url(dirname(__FILE__)) . 'css/aiautotool.css',
            $load_fontawesome ? array('font-awesome') : array(),
            $version
        );
        
        // Feature description modal CSS
        wp_enqueue_style(
            'feature-description-modal',
            plugin_dir_url(dirname(__FILE__)) . 'css/feature-description-modal.css',
            array('aiautotool'),
            $version
        );
        
        // UI Optimizations CSS
        wp_enqueue_style(
            'aiautotool-ui-optimizations',
            plugin_dir_url(dirname(__FILE__)) . 'css/aiautotool-ui-optimizations.css',
            array('aiautotool'),
            $version
        );
        
        // SweetAlert2 CSS - Lazy load if possible
        wp_enqueue_style(
            'sweetalert2',
            AIAUTOTOOL_URI . 'js/sweetalert2/dist/sweetalert2.min.css',
            array(),
            $version
        );
        
        // Core JS
        wp_enqueue_script('jquery');
        wp_enqueue_media();
        
        // SweetAlert2 - Load in footer for better performance
        wp_enqueue_script(
            'sweetalert2',
            AIAUTOTOOL_URI . 'js/sweetalert2/dist/sweetalert2.all.min.js',
            array(),
            $version,
            true // Load in footer
        );
        
        // Main plugin script - Defer loading
        wp_register_script(
            'kct_cr_scriptx',
            plugin_dir_url(dirname(__FILE__)) . 'js/aiautotool.js',
            array('jquery'),
            $version,
            true // Load in footer
        );
        
        wp_enqueue_script(
            'feature-description-modal',
            plugin_dir_url(dirname(__FILE__)) . 'js/feature-description-modal.js',
            array('jquery'),
            $version,
            true // Load in footer
        );
        
        // Performance utilities - Load before main script
        wp_enqueue_script(
            'aiautotool-performance',
            plugin_dir_url(dirname(__FILE__)) . 'js/aiautotool-performance.js',
            array('jquery'),
            $version,
            true // Load in footer
        );
        
        // Localize script with settings
        $js_setting = $this->get_js_settings();
        wp_localize_script('kct_cr_scriptx', 'aiautotool_js_setting', $js_setting);
        wp_enqueue_script('kct_cr_scriptx');
        
        // Add defer/async attributes for better performance
        add_filter('script_loader_tag', array($this, 'add_defer_async_attributes'), 10, 3);
    }
    
    /**
     * Enqueue feature-specific assets
     */
    public function enqueue_feature_assets($hook) {
        foreach ($this->registered_assets as $feature_key => $assets) {
            // Check if assets should be loaded on this page
            if (!$this->should_load_feature_assets($feature_key, $hook, $assets)) {
                continue;
            }
            
            // Enqueue scripts
            foreach ($assets['scripts'] as $handle => $script_config) {
                if (is_string($script_config)) {
                    // Simple string URL
                    wp_enqueue_script(
                        $handle,
                        $script_config,
                        array('jquery'),
                        defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0',
                        true
                    );
                } elseif (is_array($script_config)) {
                    // Full configuration
                    $deps = isset($script_config['deps']) ? $script_config['deps'] : array('jquery');
                    $version = isset($script_config['version']) ? $script_config['version'] : (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0');
                    $in_footer = isset($script_config['in_footer']) ? $script_config['in_footer'] : true;
                    $localize = isset($script_config['localize']) ? $script_config['localize'] : null;
                    
                    wp_register_script(
                        $handle,
                        $script_config['src'],
                        $deps,
                        $version,
                        $in_footer
                    );
                    
                    // Localize if needed
                    if ($localize && is_array($localize)) {
                        $data = $localize['data'];
                        // Support closure/callable for lazy loading
                        if (is_callable($data) && !is_string($data)) {
                            $data = call_user_func($data);
                        }
                        wp_localize_script($handle, $localize['object_name'], $data);
                    }
                    
                    wp_enqueue_script($handle);
                }
            }
            
            // Enqueue styles
            foreach ($assets['styles'] as $handle => $style_config) {
                if (is_string($style_config)) {
                    // Simple string URL
                    wp_enqueue_style(
                        $handle,
                        $style_config,
                        array(),
                        defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0'
                    );
                } elseif (is_array($style_config)) {
                    // Full configuration
                    $deps = isset($style_config['deps']) ? $style_config['deps'] : array();
                    $version = isset($style_config['version']) ? $style_config['version'] : (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0');
                    $media = isset($style_config['media']) ? $style_config['media'] : 'all';
                    
                    wp_enqueue_style(
                        $handle,
                        $style_config['src'],
                        $deps,
                        $version,
                        $media
                    );
                }
            }
        }
    }
    
    /**
     * Check if we should load feature assets
     */
    private function should_load_feature_assets($feature_key, $hook, $assets) {
        // If pages are specified, check if current page matches
        if (!empty($assets['pages'])) {
            $match = false;
            foreach ($assets['pages'] as $page) {
                if (strpos($hook, $page) !== false) {
                    $match = true;
                    break;
                }
            }
            if (!$match) {
                return false;
            }
        }
        
        // Check custom conditions
        if (!empty($assets['conditions'])) {
            foreach ($assets['conditions'] as $condition) {
                if (is_callable($condition)) {
                    if (!call_user_func($condition, $hook)) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    /**
     * Check if current page is a plugin page
     */
    private function is_plugin_page($hook) {
        // Check if hook contains any of our page identifiers
        foreach ($this->core_asset_pages as $page) {
            if (strpos($hook, $page) !== false) {
                return true;
            }
        }
        
        // Check for main menu page
        if (defined('MENUSUBPARRENT') && strpos($hook, MENUSUBPARRENT) !== false) {
            return true;
        }
        
        // Check current screen
        $screen = get_current_screen();
        if ($screen) {
            // Check if it's our plugin page by checking screen ID
            if (strpos($screen->id, 'ai_auto_tool') !== false || 
                strpos($screen->id, 'aiautotool') !== false) {
                return true;
            }
            
            // Check by screen base
            if (strpos($screen->base, 'ai_auto_tool') !== false || 
                strpos($screen->base, 'aiautotool') !== false) {
                return true;
            }
        }
        
        // Check GET parameter for page
        if (isset($_GET['page'])) {
            $page = sanitize_text_field($_GET['page']);
            foreach ($this->core_asset_pages as $plugin_page) {
                if (strpos($page, $plugin_page) !== false) {
                    return true;
                }
            }
            if (defined('MENUSUBPARRENT') && $page === MENUSUBPARRENT) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Get JS settings for localization
     */
    private function get_js_settings() {
        // Load rendersetting if needed
        if (!class_exists('rendersetting')) {
            $rendersetting_file = plugin_dir_path(dirname(__FILE__)) . 'lib/setting.php';
            if (file_exists($rendersetting_file)) {
                require_once $rendersetting_file;
            }
        }
        
        $setting = class_exists('rendersetting') ? new rendersetting() : null;
        
        $langcodedefault = get_option('aiautotool_default_language', 'vi');
        
        global $post;
        $settingseditornumberline = '';
        $freemius_access = function_exists('aiautotool_get_freemius_access_status') ? aiautotool_get_freemius_access_status() : array(
            'can_use_pro_features' => false,
            'is_free' => true,
            'is_trial' => false,
            'trial_days_remaining' => null,
            'trial_ends' => null,
            'reason' => 'freemius_unavailable',
        );
        
        $js_setting = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'security' => wp_create_nonce('aiautotool_nonce'),
            'languageCodes' => $setting ? $setting->languageCodes : array(),
            'langcodedefault' => $langcodedefault,
            'fsdata' => $setting ? rendersetting::aiautotool_getdata() : array(),
            'freemius_access' => $freemius_access,
            'aiautotool_premium' => ! empty($freemius_access['can_use_pro_features']),
            'code_mirrror' => $settingseditornumberline,
            'gemini_api' => defined('AIAUTOTOOL_API_GEM') ? AIAUTOTOOL_API_GEM : '',
            'prompt' => get_option('aiautotool_prompt_options', array())
        );
        
        if (isset($post->ID)) {
            $js_setting['postID'] = $post->ID;
            $js_setting['postTitle'] = $post->post_title;
        }
        
        return $js_setting;
    }
    
    /**
     * Add defer/async attributes to scripts for better performance
     * 
     * @param string $tag Script tag
     * @param string $handle Script handle
     * @param string $src Script source
     * @return string Modified script tag
     */
    public function add_defer_async_attributes($tag, $handle, $src) {
        // Scripts that should be deferred (non-critical, can load after page parse)
        $defer_scripts = array(
            'kct_cr_scriptx',
            'feature-description-modal',
            'sweetalert2'
        );
        
        // Scripts that can be async (independent, don't block rendering)
        $async_scripts = array();
        
        if (in_array($handle, $defer_scripts)) {
            // Only add defer if not already present
            if (strpos($tag, ' defer') === false && strpos($tag, 'async') === false) {
                $tag = str_replace(' src', ' defer src', $tag);
            }
        } elseif (in_array($handle, $async_scripts)) {
            // Only add async if not already present
            if (strpos($tag, ' async') === false && strpos($tag, 'defer') === false) {
                $tag = str_replace(' src', ' async src', $tag);
            }
        }
        
        return $tag;
    }
    
    /**
     * Get registered assets (for debugging)
     */
    public function get_registered_assets() {
        return $this->registered_assets;
    }
}

// Initialize Asset Manager
AIAutoTool_Asset_Manager::instance();

/**
 * Helper function to register feature assets
 * 
 * Usage example:
 * 
 * aiautotool_register_assets('single-ai', array(
 *     'scripts' => array(
 *         'kct_aipost' => array(
 *             'src' => plugin_dir_url(__FILE__) . 'assets/js/aipost.js',
 *             'deps' => array('jquery'),
 *             'version' => '1.0',
 *             'in_footer' => true,
 *             'localize' => array(
 *                 'object_name' => 'aipost',
 *                 'data' => array(
 *                     'ajax_url' => admin_url('admin-ajax.php'),
 *                     'security' => wp_create_nonce('aiautotool_aipost_nonce')
 *                 )
 *             )
 *         )
 *     ),
 *     'styles' => array(
 *         'aiautotool-singleai-modern' => array(
 *             'src' => plugin_dir_url(__FILE__) . 'assets/css/singleai-modern.css',
 *             'version' => '1.0'
 *         )
 *     ),
 *     'pages' => array('ai_single_post'), // Load only on these pages
 *     'conditions' => array( // Optional: Custom conditions
 *         function($hook) {
 *             $screen = get_current_screen();
 *             return $screen && strpos($screen->id, 'ai_single_post') !== false;
 *         }
 *     )
 * ));
 * 
 * @param string $feature_key Feature identifier
 * @param array $assets Assets configuration
 */
function aiautotool_register_assets($feature_key, $assets) {
    $manager = AIAutoTool_Asset_Manager::instance();
    $manager->register_feature_assets($feature_key, $assets);
}

/**
 * Quick helper to register a single script
 * 
 * @param string $feature_key Feature identifier
 * @param string $handle Script handle
 * @param string $src Script URL
 * @param array $deps Dependencies
 * @param string $version Version
 * @param bool $in_footer Load in footer
 * @param array $pages Pages to load on (empty = all plugin pages)
 */
function aiautotool_register_script($feature_key, $handle, $src, $deps = array('jquery'), $version = '1.0', $in_footer = true, $pages = array()) {
    $assets = array(
        'scripts' => array(
            $handle => array(
                'src' => $src,
                'deps' => $deps,
                'version' => $version,
                'in_footer' => $in_footer
            )
        ),
        'pages' => $pages
    );
    aiautotool_register_assets($feature_key, $assets);
}

/**
 * Quick helper to register a single style
 * 
 * @param string $feature_key Feature identifier
 * @param string $handle Style handle
 * @param string $src Style URL
 * @param array $deps Dependencies
 * @param string $version Version
 * @param string $media Media type
 * @param array $pages Pages to load on (empty = all plugin pages)
 */
function aiautotool_register_style($feature_key, $handle, $src, $deps = array(), $version = '1.0', $media = 'all', $pages = array()) {
    $assets = array(
        'styles' => array(
            $handle => array(
                'src' => $src,
                'deps' => $deps,
                'version' => $version,
                'media' => $media
            )
        ),
        'pages' => $pages
    );
    aiautotool_register_assets($feature_key, $assets);
}
