<?php
/**
 * AI Auto Tool - Keyword Autopost Plugin
 * Automatically create posts from keywords
 */

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

if (!class_exists('Keyword_Autopost_Plugin')) {
    class Keyword_Autopost_Plugin extends rendersetting {
        public $active = true;
    public $active_option_name = 'aiautotool_keyword_autopost_active';
    public $usage_option_name = 'Keyword_Autopost_usage';
    public $icon = '<i class="fa-solid fa-key"></i>';
    
    protected $table_name;
    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool;
    public $name_plan;
    public $config = array();
    public $notice;
    
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'aiautotool_keywords';
        
        $this->name_plan = esc_html__('Autopost from Keyword', 'ai-auto-tool');
        $this->plan_limit_aiautotool = 'plan_limit_aiautotool_' . $this->active_option_name;
        
        $this->notice = new aiautotool_Warning_Notice();
        
        // Auto-activate: ensure option is set properly if not exists
        $active_option = get_option($this->active_option_name);
        if ($active_option === false) {
            // Option doesn't exist, set it to 'false' to default inactive
            update_option($this->active_option_name, 'false');
            $this->active = 'false';
        } else {
            $this->active = $active_option;
        }
        // Always register menu (even if inactive, so user can activate from menu)
        add_action('admin_menu', array($this, 'add_menu'), 20);
        
        // Always register enqueue scripts (CSS needs to load even if feature is inactive)
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // Check active status (support multiple formats: 'true', true, 1, '1', etc.)
        $is_active = false;
        if (is_string($this->active)) {
            $is_active = (trim(strtolower($this->active)) === 'true');
        } elseif (is_bool($this->active)) {
            $is_active = ($this->active === true);
        } elseif (is_numeric($this->active)) {
            $is_active = (intval($this->active) === 1);
        }
        
        // Debug log (only if WP_DEBUG is enabled)
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        $this->create_keywords_table();
        
        $configs = get_option($this->plan_limit_aiautotool, array());
        if (!$this->aiautotool_has_plugin_data()) {
            $this->aiautotool_initialize_plugin_data();
            $configs = (array) $this->aiautotool_has_plugin_data();
        }
        
        if (!isset($configs['expiration'])) {
            $current_date = date('Y-m-d');
            $expiration = strtotime('+1 month', strtotime($current_date));
            $configs['expiration'] = date('Y-m-d', $expiration);
        }
        
        $this->config = array(
            'number_post' => $this->limit,
            'usage' => get_option($this->usage_option_name, 0, 'no'),
            'time_exprice' => $configs['expiration']
        );
        
        if (function_exists('aiautotool_can_use_pro_features') && aiautotool_can_use_pro_features()) {
            $fs = $this->is_premium();
            $license = ($fs && is_object($fs) && method_exists($fs, '_get_license')) ? $fs->_get_license() : null;
            $expiration = (is_object($license) && isset($license->expiration)) ? $license->expiration : $configs['expiration'];
            $this->config = array(
                'number_post' => -1,
                'usage' => get_option($this->usage_option_name, 0, 'no'),
                'time_exprice' => $expiration
            );
        }
        
        // Only register active features if feature is active
        if ($is_active) {
            // Menu and enqueue_scripts are already registered in constructor, no need to register again
            add_action('admin_init', array($this, 'aiautotool_check_post_limit'));
            
            if ($this->aiautotool_checklimit($this->config)) {
                add_filter('cron_schedules', array($this, 'keyword_autopost_schedule_cron_intervals'));
                
                if (!wp_next_scheduled('keyword_autopost_cron_event')) {
                    wp_schedule_event(time(), 'keyword_autopost_schedule_cron_intervals', 'keyword_autopost_cron_event');
                }
                
                add_action('keyword_autopost_cron_event', array($this, 'process_keyword_autopost'));
            } else {
                $this->notice->add_notice(
                    AIAUTOTOOL_TITLE_UPGRADE,
                    'notice-error',
                    null,
                    true,
                    'aiautotool'
                );
            }
        } else {
            // If feature is inactive, unschedule any existing cron jobs
            $timestamp = wp_next_scheduled('keyword_autopost_cron_event');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'keyword_autopost_cron_event');
            }
        }
        
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
        
        // Register AJAX handlers (always, so they work even if feature is inactive)
        add_action('wp_ajax_add_keywords', array($this, 'add_keywords_callback'));
        add_action('wp_ajax_delete_keyword', array($this, 'delete_keyword_callback'));
        add_action('wp_ajax_clear_keywords_log', array($this, 'clear_keywords_log_callback'));
        add_action('wp_ajax_get_keyword_queue', array($this, 'get_keyword_queue_callback'));
        add_action('wp_ajax_run_keyword_cron_now', array($this, 'run_keyword_cron_now_callback'));
        add_action('wp_ajax_get_cron_status', array($this, 'get_cron_status_callback'));
        add_action('wp_ajax_schedule_keyword_cron', array($this, 'schedule_keyword_cron_callback'));
        add_action('wp_ajax_bulk_delete_keywords', array($this, 'bulk_delete_keywords_callback'));
        add_action('wp_ajax_bulk_process_keywords', array($this, 'bulk_process_keywords_callback'));
    }
    
    public function create_keywords_table() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            keyword varchar(255) NOT NULL,
            category_id int(11) DEFAULT 0,
            tags text,
            language varchar(10) DEFAULT 'vi',
            status varchar(20) DEFAULT 'pending',
            priority int(11) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            processed_at datetime NULL,
            post_id int(11) DEFAULT 0,
            error_message text,
            PRIMARY KEY (id),
            KEY status (status),
            KEY priority (priority)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    public function init() {
        
        
        // AJAX handlers are already registered in constructor, no need to register again
    }
    
    public function keyword_autopost_schedule_cron_intervals($schedules) {
        $current_interval = get_option('keyword_autopost_time', 5);
        $schedules['keyword_autopost_schedule_cron_intervals'] = array(
            'interval' => intval($current_interval) * 60,
            'display' => __('Keyword autopost interval', 'ai-auto-tool')
        );
        return $schedules;
    }
    
    /**
     * Ensure cron job is scheduled
     * This function can be called from anywhere to ensure cron is active
     */
    public function ensure_cron_scheduled() {
        // Check if feature is active first
        $active_option = get_option($this->active_option_name, 'false');
        $is_active = false;
        if (is_string($active_option)) {
            $is_active = (trim(strtolower($active_option)) === 'true');
        } elseif (is_bool($active_option)) {
            $is_active = ($active_option === true);
        } elseif (is_numeric($active_option)) {
            $is_active = (intval($active_option) === 1);
        }
        
        if (!$is_active) {
            return false;
        }
        
        if ($this->aiautotool_checklimit($this->config)) {
            add_filter('cron_schedules', array($this, 'keyword_autopost_schedule_cron_intervals'));
            
            if (!wp_next_scheduled('keyword_autopost_cron_event')) {
                wp_schedule_event(time(), 'keyword_autopost_schedule_cron_intervals', 'keyword_autopost_cron_event');
                return true;
            }
        }
        return false;
    }
    
    public function process_keyword_autopost() {
        global $wpdb;
        
        // Check if feature is active before processing
        $active_option = get_option($this->active_option_name, 'false');
        $is_active = false;
        if (is_string($active_option)) {
            $is_active = (trim(strtolower($active_option)) === 'true');
        } elseif (is_bool($active_option)) {
            $is_active = ($active_option === true);
        } elseif (is_numeric($active_option)) {
            $is_active = (intval($active_option) === 1);
        }
        
        if (!$is_active) {
            // Feature is not active, unschedule cron and exit
            $timestamp = wp_next_scheduled('keyword_autopost_cron_event');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'keyword_autopost_cron_event');
            }
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return;
        }
        
        // Ensure textdomain is loaded (important for cron jobs)
        // Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
        if (!is_textdomain_loaded('ai-auto-tool')) {
            // Check if 'init' action has fired before loading textdomain
            if (did_action('init')) {
                // Safe to load textdomain after 'init' action
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
            // If 'init' hasn't fired yet, skip loading textdomain to avoid WordPress 6.7.0+ warning
            // Translations may not be available, but the code will still function
        }
        
        // Ensure AIautoTool_log class is loaded (important for cron jobs)
        if (!class_exists('AIautoTool_log')) {
            $log_file = plugin_dir_path(__FILE__) . '../../lib/AIautotool_logall.php';
            if (file_exists($log_file)) {
                require_once $log_file;
            } else {
                // Fallback: try plugin root
                $log_file = plugin_dir_path(__FILE__) . '../../../lib/AIautotool_logall.php';
                if (file_exists($log_file)) {
                    require_once $log_file;
                }
            }
        }
        
        // Check if class exists before instantiating
        if (!class_exists('AIautoTool_log')) {
            return;
        }
        
        $log = new AIautoTool_log();
        $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance();
        
        // Update last run time
        update_option('keyword_autopost_last_run', current_time('Y-m-d H:i:s'));
        
        // Update cron status - starting
        $cron_widget->update_cron_status(array(
            'is_running' => true,
            'current_task' => __('Searching for pending keywords...', 'aiautotool-cron-widget'),
            'current_post_title' => '',
            'progress' => 10,
            'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
        ));
        
        // Get pending keywords
        $pending_keywords = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$this->table_name} 
                WHERE status = 'pending' 
                ORDER BY priority DESC, created_at ASC 
                LIMIT 1"
            )
        );
        
        if (empty($pending_keywords)) {
            $cron_widget->update_cron_status(array(
                'is_running' => false,
                'current_task' => __('No pending keywords found', 'aiautotool-cron-widget'),
                'current_post_title' => '',
                'progress' => 100,
                'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
            ));
            return;
        }
        
        $keyword_data = $pending_keywords[0];
        
        // Mark as processing FIRST before doing anything else
        // This ensures the status is updated immediately in the database
        $wpdb->update(
            $this->table_name,
            array('status' => 'processing'),
            array('id' => $keyword_data->id)
        );
        
        // Update status - found keyword
        $cron_widget->update_cron_status(array(
            'is_running' => true,
            'current_task' => __('Processing keyword...', 'aiautotool-cron-widget'),
            'current_post_title' => $keyword_data->keyword,
            'progress' => 20,
            'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
        ));
        
        try {
            
            if ($this->aiautotool_checklimit($this->config)) {
                $log->set_log('keyword_autopost', array(
                    'keyword_id' => $keyword_data->id,
                    'keyword' => $keyword_data->keyword,
                    'msg' => 'Starting keyword processing'
                ));
                
                // Generate title from keyword
                $cron_widget->update_cron_status(array(
                    'is_running' => true,
                    'current_task' => __('Generating title from keyword...', 'aiautotool-cron-widget'),
                    'current_post_title' => $keyword_data->keyword,
                    'progress' => 30,
                    'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
                ));
                
                $title = $this->generate_title_from_keyword($keyword_data->keyword, $keyword_data->language);
                
                if (!$title) {
                    throw new Exception('Failed to generate title from keyword');
                }
                
                // Generate content
                $cron_widget->update_cron_status(array(
                    'is_running' => true,
                    'current_task' => __('Generating content...', 'aiautotool-cron-widget'),
                    'current_post_title' => $title,
                    'progress' => 50,
                    'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
                ));
                
                $content = $this->generate_content_from_keyword($keyword_data);
                
                if (!$content) {
                    throw new Exception('Failed to generate content from keyword');
                }
                
                // Process images
                $cron_widget->update_cron_status(array(
                    'is_running' => true,
                    'current_task' => __('Processing images...', 'aiautotool-cron-widget'),
                    'current_post_title' => $title,
                    'progress' => 70,
                    'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
                ));
                
                $content = $this->process_images_for_content($content, $title);
                
                // Validate and fix content before publishing (only if validation is enabled)
                if (get_option('keyword_autopost_content_validation', 1)) {
                    $content = $this->validate_and_fix_content($content);
                }
                
                // Create and publish post
                $cron_widget->update_cron_status(array(
                    'is_running' => true,
                    'current_task' => __('Creating and publishing post...', 'aiautotool-cron-widget'),
                    'current_post_title' => $title,
                    'progress' => 90,
                    'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
                ));
                
                $post_id = $this->create_and_publish_post($title, $content, $keyword_data);
                
                if ($post_id) {
                    // Update keyword status
                    $wpdb->update(
                        $this->table_name,
                        array(
                            'status' => 'completed',
                            'processed_at' => current_time('mysql'),
                            'post_id' => $post_id
                        ),
                        array('id' => $keyword_data->id)
                    );
                    
                    $this->aiautotool_update_usage();
                    
                    $log->set_log('keyword_autopost', array(
                        'keyword_id' => $keyword_data->id,
                        'keyword' => $keyword_data->keyword,
                        'post_id' => $post_id,
                        'msg' => 'Successfully created and published post'
                    ));
                    
                    $cron_widget->update_cron_status(array(
                        'is_running' => false,
                        'current_task' => __('Post published successfully', 'aiautotool-cron-widget'),
                        'current_post_title' => $title,
                        'progress' => 100,
                        'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
                    ));
                } else {
                    throw new Exception('Failed to create and publish post');
                }
            } else {
                throw new Exception('Usage limit exceeded');
            }
        } catch (Exception $e) {
            // Update keyword status to error
            $wpdb->update(
                $this->table_name,
                array(
                    'status' => 'error',
                    'error_message' => $e->getMessage(),
                    'processed_at' => current_time('mysql')
                ),
                array('id' => $keyword_data->id)
            );
            
            $log->set_log('keyword_autopost', array(
                'keyword_id' => $keyword_data->id,
                'keyword' => $keyword_data->keyword,
                'msg' => 'Error: ' . $e->getMessage()
            ));
            
            $cron_widget->update_cron_status(array(
                'is_running' => false,
                'current_task' => __('Error: ' . $e->getMessage(), 'aiautotool-cron-widget'),
                'current_post_title' => $keyword_data->keyword,
                'progress' => 100,
                'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
            ));
        }
    }
    
    private function generate_title_from_keyword($keyword, $language) {
        $bardGenContent = new BardGenContent();
        
        // Get selected model from settings, default to gemini-2.5-flash
        $selected_model = get_option('keyword_autopost_model', 'gemini-2.5-flash');
        
        // Load prompt options
        $allprompt = get_option('aiautotool_prompt_options', array());
        $auto = true;
        
        if (!empty($allprompt)) {
            // Check if there's a title prompt option (use article prompt as fallback)
            if (isset($allprompt['aiautotool_prompt_title'])) {
                $title_prompt = $allprompt['aiautotool_prompt_title'];
            } elseif (isset($allprompt['aiautotool_prompt_artcile'])) {
                $title_prompt = $allprompt['aiautotool_prompt_artcile'];
            } else {
                $title_prompt = '';
            }
            
            if (!empty($title_prompt)) {
                // Replace placeholders
                $title_prompt = str_replace('%%title%%', $keyword, $title_prompt);
                $title_prompt = str_replace('%%keyword%%', $keyword, $title_prompt);
                $title_prompt = str_replace('%%lang%%', $language, $title_prompt);
                $prompt = $this->aiautotool_fix_question($title_prompt, $keyword, $language, '', '', '');
                $auto = false;
            }
        }
        
        if ($auto) {
            // Default prompt if no custom prompt is set
            $prompt = "Generate a compelling, SEO-friendly title for the keyword: '{$keyword}'. The title should be engaging and include the keyword naturally. Write in {$language}.";
            return $bardGenContent->gentitle($prompt, $language, $selected_model);
        } else {
            // Use custom prompt with bardcontentmore
            return $bardGenContent->gentitle($prompt, $language, $selected_model);
        }
    }
    
    private function generate_content_from_keyword($keyword_data) {
        $bardGenContent = new BardGenContent();
        $keyword = $keyword_data->keyword;
        $language = $keyword_data->language;
        
        // Get selected model from settings, default to gemini-2.5-flash
        $selected_model = get_option('keyword_autopost_model', 'gemini-2.5-flash');
        
        // Get prompt data from extra_data (stored in error_message field)
        $prompt_mode = 'single';
        $aiautotool_prompt = '';
        $multiple_prompt_contents = array();
        
        if (!empty($keyword_data->error_message)) {
            $extra_data = json_decode($keyword_data->error_message, true);
            if (is_array($extra_data)) {
                if (isset($extra_data['prompt_mode'])) {
                    $prompt_mode = $extra_data['prompt_mode'];
                }
                if (isset($extra_data['aiautotool_prompt'])) {
                    $aiautotool_prompt = $extra_data['aiautotool_prompt'];
                }
                if (isset($extra_data['multiple_prompt_contents']) && is_array($extra_data['multiple_prompt_contents'])) {
                    $multiple_prompt_contents = $extra_data['multiple_prompt_contents'];
                }
            }
        }
        
        $auto = true;
        $prompt = '';
        
        // Use prompt from form if available
        if ($prompt_mode === 'multiple' && !empty($multiple_prompt_contents)) {
            // Randomly select one prompt content from the multiple prompts
            $random_prompt = $multiple_prompt_contents[array_rand($multiple_prompt_contents)];
            $artcle_prompt = $random_prompt['content'];
            
            // Replace placeholders
            $artcle_prompt = str_replace('%%title%%', $keyword, $artcle_prompt);
            $artcle_prompt = str_replace('%%keyword%%', $keyword, $artcle_prompt);
            $artcle_prompt = str_replace('%%lang%%', $language, $artcle_prompt);
            
            $content = '';
            $cate = '';
            $blogtitle = '';
            $prompt = $this->aiautotool_fix_question($artcle_prompt, $keyword, $language, $blogtitle, $cate, $content);
            $auto = false;
        } elseif ($prompt_mode === 'single' && !empty($aiautotool_prompt)) {
            // Use single prompt from form
            $artcle_prompt = $aiautotool_prompt;
            
            // Replace placeholders
            $artcle_prompt = str_replace('%%title%%', $keyword, $artcle_prompt);
            $artcle_prompt = str_replace('%%keyword%%', $keyword, $artcle_prompt);
            $artcle_prompt = str_replace('%%lang%%', $language, $artcle_prompt);
            
            $content = '';
            $cate = '';
            $blogtitle = '';
            $prompt = $this->aiautotool_fix_question($artcle_prompt, $keyword, $language, $blogtitle, $cate, $content);
            $auto = false;
        } else {
            // Fallback to global prompt options
            $allprompt = get_option('aiautotool_prompt_options', array());
            if (!empty($allprompt)) {
                // Check if there's an article prompt option
                if (isset($allprompt['aiautotool_prompt_artcile'])) {
                    $artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
                    
                    // Replace placeholders
                    $artcle_prompt = str_replace('%%title%%', $keyword, $artcle_prompt);
                    $artcle_prompt = str_replace('%%keyword%%', $keyword, $artcle_prompt);
                    $artcle_prompt = str_replace('%%lang%%', $language, $artcle_prompt);
                    
                    $content = '';
                    $cate = '';
                    $blogtitle = '';
                    $prompt = $this->aiautotool_fix_question($artcle_prompt, $keyword, $language, $blogtitle, $cate, $content);
                    $auto = false;
                }
            }
        }
        
        if ($auto) {
            // Enhanced default prompt to avoid markdown issues
            $prompt = "Write a comprehensive, informative article about '{$keyword}'. 
        
        Requirements:
        - Write in {$language}
        - Minimum 1000 words
        - Use proper HTML formatting (h2, h3, p, ul, li, strong, em)
        - Do NOT use markdown code blocks or ``` symbols
        - Do NOT use <pre><code> tags
        - Do NOT include DOCTYPE, HTML, HEAD, BODY tags
        - Do NOT return a complete HTML document
        - Use proper paragraph breaks with <p> tags
        - Include relevant headings with <h2> and <h3> tags
        - Use bullet points with <ul> and <li> tags when appropriate
        - Make it SEO-friendly with natural keyword usage
        - Include practical information and examples
        - Write in a conversational, engaging tone
        
        Structure the article with:
        1. Introduction paragraph
        2. Main content with 3-4 sections
        3. Conclusion paragraph
        
        Return ONLY the article content with HTML formatting, NOT a complete HTML document.";
            
            $content = $bardGenContent->bardcontentfull($prompt, $language, $selected_model);
        } else {
            // Use custom prompt with bardcontentmore
            $content = $bardGenContent->bardcontentmore($prompt, $language, $selected_model);
        }
        
        // Check if API returned an error array instead of content string
        if (is_array($content)) {
            // If it's an error array, extract the result or message
            if (isset($content['result']) && is_string($content['result']) && !empty($content['result'])) {
                $content = $content['result'];
            } elseif (isset($content['msg']) && is_string($content['msg'])) {
                // If no result but has message, use it or return false
                $content = false;
            } else {
                $content = false;
            }
        }
        
        // If content is still not a string or is empty, return false
        if (!is_string($content) || empty(trim($content))) {
            return false;
        }
        
        // Post-process the content to fix any remaining issues (only if validation is enabled)
        if (get_option('keyword_autopost_content_validation', 1)) {
            $content = $this->clean_and_format_content($content);
        }
        
        return $content;
    }
    
    /**
     * Fix question/prompt by replacing placeholders
     * Override parent method to add %%keyword%% placeholder support
     */
    public function aiautotool_fix_question($prompt, $title = '', $lang = '', $blog = '', $cate = '', $content = '') {
        $replacements = array(
            '%%title%%' => $title,
            '%%keyword%%' => $title, // Alias for keyword autopost
            '%%lang%%' => $lang,
            '%%blog%%' => $blog,
            '%%cate%%' => $cate,
            '%%content%%' => $content
        );

        $outprompt = str_replace(array_keys($replacements), array_values($replacements), $prompt);
        return $outprompt;
    }
    
    private function clean_and_format_content($content) {
        // Ensure content is a string
        if (is_array($content)) {
            // If it's an error array, extract the message or result
            if (isset($content['result']) && is_string($content['result'])) {
                $content = $content['result'];
            } elseif (isset($content['msg']) && is_string($content['msg'])) {
                $content = $content['msg'];
            } else {
                // If we can't extract a string, return empty or convert to string
                $content = is_string($content) ? $content : '';
            }
        }
        
        // Ensure it's a string after conversion
        if (!is_string($content)) {
            $content = (string) $content;
        }
        
        // Remove DOCTYPE, HTML, HEAD, BODY tags and other unwanted elements
        $content = preg_replace('/<!DOCTYPE[^>]*>/i', '', $content);
        $content = preg_replace('/<html[^>]*>/i', '', $content);
        $content = preg_replace('/<\/html>/i', '', $content);
        $content = preg_replace('/<head[^>]*>.*?<\/head>/is', '', $content);
        $content = preg_replace('/<body[^>]*>/i', '', $content);
        $content = preg_replace('/<\/body>/i', '', $content);
        $content = preg_replace('/<title[^>]*>.*?<\/title>/is', '', $content);
        $content = preg_replace('/<meta[^>]*>/i', '', $content);
        $content = preg_replace('/<link[^>]*>/i', '', $content);
        $content = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $content);
        $content = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $content);
        
        // Remove any markdown code blocks
        $content = preg_replace('/```[a-zA-Z]*\n(.*?)\n```/s', '<p>$1</p>', $content);
        $content = preg_replace('/`([^`]+)`/', '<code>$1</code>', $content);
        
        // Fix broken pre/code tags
        $content = preg_replace('/<pre><code[^>]*>/', '<p>', $content);
        $content = preg_replace('/<\/code><\/pre>/', '</p>', $content);
        $content = preg_replace('/<pre><code>/', '<p>', $content);
        $content = preg_replace('/<\/code><\/pre>/', '</p>', $content);
        
        // Remove any remaining pre tags
        $content = preg_replace('/<pre[^>]*>(.*?)<\/pre>/s', '<p>$1</p>', $content);
        
        // Fix common markdown issues
        $content = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $content);
        $content = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $content);
        
        // Fix heading formatting
        $content = preg_replace('/^### (.*?)$/m', '<h3>$1</h3>', $content);
        $content = preg_replace('/^## (.*?)$/m', '<h2>$1</h2>', $content);
        $content = preg_replace('/^# (.*?)$/m', '<h2>$1</h2>', $content);
        
        // Fix list formatting
        $content = preg_replace('/^- (.*?)$/m', '<li>$1</li>', $content);
        $content = preg_replace('/^\* (.*?)$/m', '<li>$1</li>', $content);
        
        // Wrap consecutive li elements in ul tags
        $content = preg_replace('/(<li>.*?<\/li>)+/s', '<ul>$0</ul>', $content);
        
        // Ensure paragraphs are properly wrapped
        $content = preg_replace('/^(?!<[h|u|o]|<li>)(.*?)$/m', '<p>$1</p>', $content);
        
        // Remove empty paragraphs
        $content = preg_replace('/<p>\s*<\/p>/', '', $content);
        
        // Fix double line breaks
        $content = preg_replace('/\n\s*\n/', '</p><p>', $content);
        
        // Clean up any remaining markdown artifacts
        $content = str_replace(['```', '`'], '', $content);
        
        // Remove any language attributes from code tags
        $content = preg_replace('/<code class="[^"]*">/', '<code>', $content);
        
        // Remove any remaining HTML comments
        $content = preg_replace('/<!--.*?-->/s', '', $content);
        
        // Remove any remaining unwanted HTML tags
        $content = preg_replace('/<div[^>]*>/i', '', $content);
        $content = preg_replace('/<\/div>/i', '', $content);
        $content = preg_replace('/<span[^>]*>/i', '', $content);
        $content = preg_replace('/<\/span>/i', '', $content);
        
        // Remove any empty or malformed paragraph tags
        $content = preg_replace('/<p>\s*<\/p>/', '', $content);
        $content = preg_replace('/<p><p>/', '<p>', $content);
        $content = preg_replace('/<\/p><\/p>/', '</p>', $content);
        
        // Ensure proper HTML structure
        $content = $this->ensure_proper_html_structure($content);
        
        return $content;
    }
    
    private function ensure_proper_html_structure($content) {
        // Ensure content is a string
        if (is_array($content)) {
            // If it's an error array, extract the message or result
            if (isset($content['result']) && is_string($content['result'])) {
                $content = $content['result'];
            } elseif (isset($content['msg']) && is_string($content['msg'])) {
                $content = $content['msg'];
            } else {
                // If we can't extract a string, return empty or convert to string
                $content = '';
            }
        }
        
        // Ensure it's a string after conversion
        if (!is_string($content)) {
            $content = (string) $content;
        }
        
        // Split content into lines
        $lines = explode("\n", $content);
        $formatted_lines = array();
        $in_list = false;
        
        foreach ($lines as $line) {
            $line = trim($line);
            
            if (empty($line)) {
                if ($in_list) {
                    $formatted_lines[] = '</ul>';
                    $in_list = false;
                }
                continue;
            }
            
            // Handle headings
            if (preg_match('/^<h[2-6]>/', $line)) {
                if ($in_list) {
                    $formatted_lines[] = '</ul>';
                    $in_list = false;
                }
                $formatted_lines[] = $line;
                continue;
            }
            
            // Handle list items
            if (preg_match('/^<li>/', $line)) {
                if (!$in_list) {
                    $formatted_lines[] = '<ul>';
                    $in_list = true;
                }
                $formatted_lines[] = $line;
                continue;
            }
            
            // Handle paragraphs
            if (preg_match('/^<p>/', $line)) {
                if ($in_list) {
                    $formatted_lines[] = '</ul>';
                    $in_list = false;
                }
                $formatted_lines[] = $line;
                continue;
            }
            
            // Handle other content
            if ($in_list) {
                $formatted_lines[] = '</ul>';
                $in_list = false;
            }
            
            // Wrap plain text in paragraphs
            if (!preg_match('/^</', $line)) {
                $formatted_lines[] = '<p>' . $line . '</p>';
            } else {
                $formatted_lines[] = $line;
            }
        }
        
        // Close any open list
        if ($in_list) {
            $formatted_lines[] = '</ul>';
        }
        
        return implode("\n", $formatted_lines);
    }
    
    private function process_images_for_content($content, $title) {
        $bardGenContent = new BardGenContent();
        $Imagescontent = new Imagescontent();
        
        $listimg = $bardGenContent->searchimg($title);
        
        if ($listimg) {
            $listimg10 = array_slice($listimg, 0, 10);
            shuffle($listimg10);
            $content = $Imagescontent->insertImages($content, $listimg10);
        }
        
        return $content;
    }
    
    private function create_and_publish_post($title, $content, $keyword_data) {
        $user_ids = get_users(array('fields' => 'ID'));
        $random_user_id = $user_ids[array_rand($user_ids)];
        
        // Get multiple categories from error_message field (if stored)
        $category_ids = array($keyword_data->category_id);
        $auto_generate_tags = 0;
        
        if (!empty($keyword_data->error_message)) {
            $extra_data = json_decode($keyword_data->error_message, true);
            if (is_array($extra_data)) {
                if (isset($extra_data['category_ids']) && is_array($extra_data['category_ids'])) {
                    $category_ids = array_map('intval', $extra_data['category_ids']);
                    $category_ids = array_filter($category_ids);
                }
                if (isset($extra_data['auto_generate_tags'])) {
                    $auto_generate_tags = intval($extra_data['auto_generate_tags']);
                }
            }
        }
        
        // If no categories, use default
        if (empty($category_ids)) {
            $category_ids = array($keyword_data->category_id);
        }
        
        // Generate automatic tags from content (only if enabled via auto_generate_tags or global setting)
        $auto_tags = '';
        if ($auto_generate_tags == 1 || get_option('keyword_autopost_auto_tags', 1)) {
            // Use AI to generate tags if auto_generate_tags is enabled
            if ($auto_generate_tags == 1 && class_exists('AIAutotool_AI_Helper') && AIAutotool_AI_Helper::is_available()) {
                $auto_tags = $this->generate_tags_with_ai($title, $content, $keyword_data->language);
            } else {
                // Fallback to content-based tag generation
                $auto_tags = $this->generate_tags_from_content($content, $keyword_data->keyword, $keyword_data->language);
            }
        }
        
        // Combine user-provided tags with auto-generated tags
        $final_tags = $keyword_data->tags;
        if (!empty($auto_tags)) {
            if (!empty($final_tags)) {
                $final_tags .= ', ' . $auto_tags;
            } else {
                $final_tags = $auto_tags;
            }
        }
        
        // Clean up tags (remove duplicates, extra spaces)
        $tag_array = array_map('trim', explode(',', $final_tags));
        $tag_array = array_unique($tag_array);
        $tag_array = array_filter($tag_array, function($tag) {
            return !empty($tag) && strlen($tag) > 1;
        });
        $final_tags = implode(', ', $tag_array);
        
        $post_data = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => 'publish',
            'post_author' => $random_user_id,
            'post_category' => $category_ids, // Use multiple categories
            'tags_input' => $final_tags,
            'post_type' => 'post'
        );
        
        $post_id = wp_insert_post($post_data);
        
        if ($post_id) {
            // Set language if Polylang is active
            if (in_array('polylang/polylang.php', apply_filters('active_plugins', get_option('active_plugins')))) {
                pll_set_post_language($post_id, $keyword_data->language);
            }
            
            // Send Telegram notification with tags info
            $pingback = new aiautotool_Telegram_Notifications('6845486754:AAH5KyPTuluu_OCRnPklp6UEbzVfe0CtHkU', '730694172');
            $message = "Keyword Autopost: " . get_permalink($post_id) . "\n";
            $message .= "Keyword: " . $keyword_data->keyword . "\n";
            $message .= "Tags: " . $final_tags . "\n";
            $message .= "Time: " . current_time('Y-m-d H:i:s') . "\n";
            $pingback->send_bot_message($message);
        }
        
        return $post_id;
    }
    
    /**
     * Generate tags using AI Helper
     * 
     * @param string $title Post title
     * @param string $content Post content
     * @param string $lang Language
     * @return string Comma-separated tags
     */
    private function generate_tags_with_ai($title, $content, $lang = 'vi') {
        if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) {
            return '';
        }
        
        // Prepare content excerpt for prompt (limit to avoid token limits)
        $content_excerpt = wp_trim_words(strip_tags($content), 200);
        
        // Get language name
        $languageCodes = $this->languageCodes;
        $lang_name = isset($languageCodes[$lang]) ? $languageCodes[$lang] : 'Vietnamese';
        
        // Build prompt for tag generation
        $prompt = "Based on the following blog post, generate 5-8 relevant tags (keywords) that best describe the content. ";
        $prompt .= "Tags should be SEO-friendly, specific, and relevant to the post topic.\n\n";
        $prompt .= "Post Title: {$title}\n\n";
        $prompt .= "Post Content:\n{$content_excerpt}\n\n";
        $prompt .= "Generate tags as a comma-separated list. Only return the tags, no explanations. ";
        $prompt .= "Write tags in {$lang_name} language if applicable, or use English for technical terms.";
        
        // Generate tags using AI
        $result = AIAutotool_AI_Helper::generate($prompt, array(
            'temperature' => 0.7,
            'max_tokens' => 200
        ));
        
        if (!$result['success'] || empty($result['content'])) {
            return '';
        }
        
        // Extract tags from AI response
        $ai_tags = trim($result['content']);
        
        // Clean up the response - remove any extra text, keep only tags
        $ai_tags = preg_replace('/^(tags?|keywords?|labels?)[:\s]*/i', '', $ai_tags);
        $ai_tags = preg_replace('/\n.*$/s', '', $ai_tags);
        $ai_tags = trim($ai_tags, " \n\r\t.,;");
        
        return $ai_tags;
    }
    
    public function add_keywords_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403);
        }
        
        // Ensure table exists (in case feature was just activated)
        $this->create_keywords_table();
        
        $keywords = sanitize_textarea_field($_POST['keywords']);
        
        // Handle multiple categories
        $category_ids = array();
        if (isset($_POST['category_ids']) && is_array($_POST['category_ids'])) {
            $category_ids = array_map('intval', $_POST['category_ids']);
            $category_ids = array_filter($category_ids); // Remove empty values
        } elseif (isset($_POST['category_id'])) {
            // Fallback for single category (backward compatibility)
            $category_id = intval($_POST['category_id']);
            if ($category_id > 0) {
                $category_ids = array($category_id);
            }
        }
        
        // Use first category for database (backward compatibility)
        $category_id = !empty($category_ids) ? $category_ids[0] : 0;
        
        $tags = sanitize_text_field($_POST['tags']);
        $auto_generate_tags = isset($_POST['auto_generate_tags']) ? intval($_POST['auto_generate_tags']) : 0;
        $language = sanitize_text_field($_POST['language']);
        $priority = intval($_POST['priority']);
        
        // Get prompt selection mode
        $prompt_mode = isset($_POST['prompt_selection_mode']) ? sanitize_text_field($_POST['prompt_selection_mode']) : 'single';
        $aiautotool_prompt = '';
        $multiple_prompt_contents = array();
        
        if ($prompt_mode === 'single') {
            // Single prompt mode - use the prompt from textarea
            $aiautotool_prompt = isset($_POST['aiautotool_prompt']) ? sanitize_textarea_field($_POST['aiautotool_prompt']) : '';
        } else if ($prompt_mode === 'multiple') {
            // Multiple prompts mode - get array of prompt contents from textareas
            if (isset($_POST['multiple_prompt_contents']) && !empty($_POST['multiple_prompt_contents'])) {
                $contents_json = sanitize_text_field($_POST['multiple_prompt_contents']);
                $decoded_contents = json_decode(stripslashes($contents_json), true);
                if (is_array($decoded_contents)) {
                    foreach ($decoded_contents as $item) {
                        if (isset($item['id']) && isset($item['content'])) {
                            $multiple_prompt_contents[] = array(
                                'id' => intval($item['id']),
                                'content' => sanitize_textarea_field($item['content'])
                            );
                        }
                    }
                }
            }
        }
        
        $keyword_list = explode(PHP_EOL, $keywords);
        $results = array();
        
        global $wpdb;
        
        foreach ($keyword_list as $keyword) {
            $keyword = trim($keyword);
            if (empty($keyword)) continue;
            
            $inserted = $wpdb->insert(
                $this->table_name,
                array(
                    'keyword' => $keyword,
                    'category_id' => $category_id,
                    'tags' => $tags,
                    'language' => $language,
                    'priority' => $priority,
                    'status' => 'pending'
                ),
                array('%s', '%d', '%s', '%s', '%d', '%s')
            );
            
            if ($inserted) {
                $keyword_id = $wpdb->insert_id;
                
                // Store multiple categories, auto_generate_tags, and prompt data in error_message field as JSON
                $extra_data = array(
                    'category_ids' => $category_ids,
                    'auto_generate_tags' => $auto_generate_tags,
                    'prompt_mode' => $prompt_mode,
                    'aiautotool_prompt' => $aiautotool_prompt,
                    'multiple_prompt_contents' => $multiple_prompt_contents
                );
                
                // Only update if there's extra data to store
                if (!empty($category_ids) && count($category_ids) > 1 || $auto_generate_tags || !empty($aiautotool_prompt) || !empty($multiple_prompt_contents)) {
                    $wpdb->update(
                        $this->table_name,
                        array('error_message' => json_encode($extra_data)),
                        array('id' => $keyword_id),
                        array('%s'),
                        array('%d')
                    );
                }
                
                $results[] = array(
                    'keyword' => $keyword,
                    'status' => 'added'
                );
            } else {
                $results[] = array(
                    'keyword' => $keyword,
                    'status' => 'error'
                );
            }
        }
        
        wp_send_json_success($results);
    }
    
    public function delete_keyword_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403);
        }
        
        $keyword_id = intval($_POST['keyword_id']);
        
        global $wpdb;
        $deleted = $wpdb->delete(
            $this->table_name,
            array('id' => $keyword_id),
            array('%d')
        );
        
        if ($deleted) {
            wp_send_json_success('Keyword deleted successfully');
        } else {
            wp_send_json_error('Failed to delete keyword');
        }
    }
    
    public function clear_keywords_log_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403);
        }
        
        global $wpdb;
        $wpdb->query("DELETE FROM {$this->table_name} WHERE status IN ('completed', 'error')");
        
        wp_send_json_success('Keywords log cleared successfully');
    }
    
    public function get_keyword_queue_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403);
        }
        
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $filter = isset($_POST['filter']) ? sanitize_text_field($_POST['filter']) : 'all';
        $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
        $sort_order = isset($_POST['sort_order']) ? sanitize_text_field($_POST['sort_order']) : 'recent-completed';
        
        $html = $this->render_keyword_queue_table($page, 20, $filter, $search, $sort_order);
        
        wp_send_json_success($html);
    }
    
    private function get_status_icon($status) {
        switch ($status) {
            case 'pending':
                return '<i class="fa-solid fa-clock" style="color: #f39c12;"></i>';
            case 'processing':
                return '<i class="fa-solid fa-cogs" style="color: #3498db;"></i>';
            case 'completed':
                return '<i class="fa-solid fa-check-circle" style="color: #27ae60;"></i>';
            case 'error':
                return '<i class="fa-solid fa-exclamation-triangle" style="color: #e74c3c;"></i>';
            default:
                return '<i class="fa-solid fa-question-circle" style="color: #95a5a6;"></i>';
        }
    }
    
    private function get_priority_badge($priority) {
        switch ($priority) {
            case 10:
                return '<span class="priority-badge urgent">Urgent</span>';
            case 5:
                return '<span class="priority-badge high">High</span>';
            case 1:
                return '<span class="priority-badge low">Low</span>';
            default:
                return '<span class="priority-badge normal">Normal</span>';
        }
    }
    
    private function calculate_processing_time($keyword) {
        if ($keyword->status == 'pending') {
            return esc_html__('Not started', 'ai-auto-tool');
        }
        
        if ($keyword->status == 'processing') {
            $start_time = strtotime($keyword->created_at);
            $elapsed = time() - $start_time;
            return $this->format_time($elapsed);
        }
        
        if ($keyword->processed_at) {
            $start_time = strtotime($keyword->created_at);
            $end_time = strtotime($keyword->processed_at);
            $duration = $end_time - $start_time;
            return $this->format_time($duration);
        }
        
        return esc_html__('Unknown', 'ai-auto-tool');
    }
    
    private function format_time($seconds) {
        if ($seconds < 60) {
            return $seconds . 's';
        } elseif ($seconds < 3600) {
            return round($seconds / 60, 1) . 'm';
        } else {
            $hours = floor($seconds / 3600);
            $minutes = round(($seconds % 3600) / 60);
            return $hours . 'h ' . $minutes . 'm';
        }
    }
    
    public function run_keyword_cron_now_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        global $wpdb;
        
        // Check if there are pending keywords
        $pending_count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->table_name} WHERE status = 'pending'"
            )
        );
        
        if ($pending_count == 0) {
            wp_send_json_error(array(
                'message' => __('No pending keywords found. Please add keywords first.', 'ai-auto-tool'),
                'pending_count' => 0
            ));
            return;
        }
        
        // Update last run time
        update_option('keyword_autopost_last_run', current_time('Y-m-d H:i:s'));
        
        // Get the first pending keyword to show in response
        $next_keyword = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table_name} 
                WHERE status = 'pending' 
                ORDER BY priority DESC, created_at ASC 
                LIMIT 1"
            )
        );
        
        if (!$next_keyword) {
            wp_send_json_error(array(
                'message' => __('No pending keywords found', 'ai-auto-tool'),
                'pending_count' => 0
            ));
            return;
        }
        
        // Update cron widget status BEFORE processing starts
        $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance();
        $cron_widget->update_cron_status(array(
            'is_running' => true,
            'current_task' => __('Starting keyword processing...', 'aiautotool-cron-widget'),
            'current_post_title' => $next_keyword->keyword,
            'progress' => 5,
            'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget')
        ));
        
        // Trigger the cron event directly - this will mark keyword as processing inside process_keyword_autopost()
        // Call the method directly instead of do_action to ensure it runs synchronously
        $this->process_keyword_autopost();
        
        // Wait a bit to ensure database is updated (200ms)
        usleep(200000);
        
        // Force database refresh
        $wpdb->flush();
        
        // Get updated keyword status immediately after processing starts
        $updated_keyword = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table_name} WHERE id = %d",
                $next_keyword->id
            )
        );
        
        $processing_keyword = null;
        if ($updated_keyword) {
            $processing_keyword = array(
                'id' => $updated_keyword->id,
                'keyword' => $updated_keyword->keyword,
                'status' => $updated_keyword->status,
                'created_at' => $updated_keyword->created_at
            );
        }
        
        wp_send_json_success(array(
            'message' => __('Cron job started successfully', 'ai-auto-tool'),
            'pending_count' => $pending_count,
            'processing_keyword' => $processing_keyword,
            'keyword_id' => $next_keyword->id
        ));
    }
    
    public function schedule_keyword_cron_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        // Ensure cron is scheduled
        $scheduled = $this->ensure_cron_scheduled();
        
        if ($scheduled) {
            wp_send_json_success('Cron job scheduled successfully');
        } else {
            $next_run = wp_next_scheduled('keyword_autopost_cron_event');
            if ($next_run) {
                wp_send_json_success('Cron job is already scheduled');
            } else {
                wp_send_json_error('Failed to schedule cron job. Please check your limits.');
            }
        }
    }
    
    public function get_cron_status_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        global $wpdb;
        
        // Try to ensure cron is scheduled if it's not
        $next_run = wp_next_scheduled('keyword_autopost_cron_event');
        if (!$next_run && $this->aiautotool_checklimit($this->config)) {
            $this->ensure_cron_scheduled();
            $next_run = wp_next_scheduled('keyword_autopost_cron_event');
        }
        
        // Get cron status
        $status_html = '';
        
        if ($next_run) {
            $status_html = '<span class="status-active"><i class="fa-solid fa-play"></i> Active</span>';
        } else {
            $status_html = '<span class="status-inactive"><i class="fa-solid fa-pause"></i> Inactive</span>';
        }
        
        // Get next run time
        $next_run_html = '';
        if ($next_run) {
            $next_run_html = '<span class="next-run">' . esc_html(date('Y-m-d H:i:s', $next_run)) . '</span>';
        } else {
            $next_run_html = '<span class="no-schedule">' . esc_html__('Not scheduled', 'ai-auto-tool') . '</span>';
        }
        
        // Get last run time
        $last_run = get_option('keyword_autopost_last_run', '');
        $last_run_html = $last_run ? esc_html($last_run) : esc_html__('Never', 'ai-auto-tool');
        
        // Get current processing status - check both database and cron widget
        $processing_keyword = $wpdb->get_row(
            "SELECT * FROM {$wpdb->prefix}aiautotool_keywords 
            WHERE status = 'processing' 
            ORDER BY created_at DESC 
            LIMIT 1"
        );
        
        // Also check cron widget status for real-time info
        $cron_widget_status = get_transient('aiautotool_cron_status');
        $is_cron_running = false;
        $cron_task = '';
        $cron_post_title = '';
        $cron_progress = 0;
        
        if ($cron_widget_status && is_array($cron_widget_status)) {
            $is_cron_running = isset($cron_widget_status['is_running']) && $cron_widget_status['is_running'];
            $cron_task = isset($cron_widget_status['current_task']) ? $cron_widget_status['current_task'] : '';
            $cron_post_title = isset($cron_widget_status['current_post_title']) ? $cron_widget_status['current_post_title'] : '';
            $cron_progress = isset($cron_widget_status['progress']) ? intval($cron_widget_status['progress']) : 0;
            
            // Check if it's for keyword autopost
            $cron_type = isset($cron_widget_status['cron_type']) ? $cron_widget_status['cron_type'] : '';
            if ($cron_type !== __('Keyword Autopost', 'aiautotool-cron-widget')) {
                $is_cron_running = false; // Only show if it's keyword autopost
            }
        }
        
        $processing_html = '';
        
        // If cron widget shows running or we have a processing keyword, show active status
        if ($is_cron_running || $processing_keyword) {
            $keyword_text = '';
            if ($processing_keyword) {
                $keyword_text = esc_html($processing_keyword->keyword);
            } elseif ($cron_post_title) {
                $keyword_text = esc_html($cron_post_title);
            }
            
            $task_text = $cron_task ? esc_html($cron_task) : esc_html__('Processing keyword...', 'ai-auto-tool');
            $progress_width = $cron_progress > 0 ? $cron_progress : 50;
            
            $processing_html = '<div class="processing-item active">';
            if ($keyword_text) {
                $processing_html .= '<div class="processing-keyword">' . $keyword_text . '</div>';
            }
            $processing_html .= '<div class="processing-task">' . $task_text . '</div>';
            if ($processing_keyword && $processing_keyword->created_at) {
                $processing_html .= '<div class="processing-time">' . esc_html__('Started:', 'ai-auto-tool') . ' ' . esc_html($processing_keyword->created_at) . '</div>';
            }
            $processing_html .= '<div class="processing-progress">';
            $processing_html .= '<div class="progress-bar">';
            $processing_html .= '<div class="progress-fill" style="width: ' . esc_attr($progress_width) . '%;"></div>';
            $processing_html .= '</div>';
            $processing_html .= '<span class="progress-text">' . esc_html($task_text) . ' (' . esc_html($progress_width) . '%)</span>';
            $processing_html .= '</div>';
            $processing_html .= '</div>';
        } else {
            $processing_html = '<div class="processing-item idle">';
            $processing_html .= '<div class="processing-message">' . esc_html__('No keywords currently being processed', 'ai-auto-tool') . '</div>';
            $processing_html .= '</div>';
        }
        
        wp_send_json_success(array(
            'status' => $status_html,
            'next_run' => $next_run_html,
            'last_run' => $last_run_html,
            'processing_html' => $processing_html
        ));
    }
    
    public static function check_quota() {
        return parent::check_quota();
    }
    
    public function get_keywords_stats() {
        global $wpdb;
        
        $stats = $wpdb->get_results("
            SELECT 
                status,
                COUNT(*) as count
            FROM {$this->table_name}
            GROUP BY status
        ");
        
        $result = array(
            'pending' => 0,
            'processing' => 0,
            'completed' => 0,
            'error' => 0
        );
        
        foreach ($stats as $stat) {
            $result[$stat->status] = $stat->count;
        }
        
        return $result;
    }
    
    private function calculate_estimated_completion_time($stats) {
        global $wpdb;
        
        // Get average processing time from recent completed keywords
        $avg_time = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT AVG(TIMESTAMPDIFF(SECOND, created_at, processed_at)) 
                FROM {$this->table_name} 
                WHERE status = 'completed' 
                AND processed_at IS NOT NULL 
                AND processed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)"
            )
        );
        
        if (!$avg_time || $avg_time <= 0) {
            $avg_time = 60; // Default 60 seconds if no data
        }
        
        // Calculate remaining keywords
        $remaining = $stats['pending'] + $stats['processing'];
        
        // Get cron interval in seconds
        $cron_interval = get_option('keyword_autopost_time', 5) * 60;
        
        // Calculate estimated time
        $estimated_seconds = ($remaining * $avg_time) / ($cron_interval / 60); // keywords per minute
        
        if ($estimated_seconds < 60) {
            return round($estimated_seconds) . ' ' . esc_html__('seconds', 'ai-auto-tool');
        } elseif ($estimated_seconds < 3600) {
            return round($estimated_seconds / 60, 1) . ' ' . esc_html__('minutes', 'ai-auto-tool');
        } else {
            $hours = floor($estimated_seconds / 3600);
            $minutes = round(($estimated_seconds % 3600) / 60);
            return $hours . ' ' . esc_html__('hours', 'ai-auto-tool') . ' ' . $minutes . ' ' . esc_html__('minutes', 'ai-auto-tool');
        }
    }
    
    private function get_average_processing_time() {
        global $wpdb;
        
        $avg_time = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT AVG(TIMESTAMPDIFF(SECOND, created_at, processed_at)) 
                FROM {$this->table_name} 
                WHERE status = 'completed' 
                AND processed_at IS NOT NULL 
                AND processed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)"
            )
        );
        
        if (!$avg_time || $avg_time <= 0) {
            return esc_html__('No data available', 'ai-auto-tool');
        }
        
        if ($avg_time < 60) {
            return round($avg_time) . ' ' . esc_html__('seconds', 'ai-auto-tool');
        } else {
            return round($avg_time / 60, 1) . ' ' . esc_html__('minutes', 'ai-auto-tool');
        }
    }
    
    public function render_setting() {
        ?>
        <div id="tab-keyword-autopost-setting" class="tab-content" style="display:none;">
            <h2><?php echo wp_kses_post($this->icon); ?> <?php esc_html_e('Keyword Autopost Settings', 'ai-auto-tool'); ?></h2>
            
            <?php
            if (!current_user_can('manage_options')) {
                return;
            }
            
            if (isset($_POST['keyword_autopost_save_settings'])) {
                $interval = intval($_POST['keyword_autopost_time']);
                update_option('keyword_autopost_time', $interval, null, 'no');
                
                $content_validation = isset($_POST['keyword_autopost_content_validation']) ? 1 : 0;
                update_option('keyword_autopost_content_validation', $content_validation, null, 'no');
                
                $auto_tags = isset($_POST['keyword_autopost_auto_tags']) ? 1 : 0;
                update_option('keyword_autopost_auto_tags', $auto_tags, null, 'no');
                
                $keyword_autopost_model = sanitize_text_field($_POST['keyword_autopost_model']); 
                update_option('keyword_autopost_model', $keyword_autopost_model, null, 'no');
                
                echo '<div class="updated"><p>Settings saved.</p></div>';
            }
            
            $current_interval = get_option('keyword_autopost_time', 5);
            $keyword_autopost_model = get_option('keyword_autopost_model', 'gemini-2.5-flash');
            ?>
            
            <div class="wrap">
                <form method="post" action="">
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Time interval between keyword processing (minutes)', 'ai-auto-tool'); ?>
                    </p>
                    <select id="keyword_autopost_time" name="keyword_autopost_time">
                        <option value="1" <?php selected($current_interval, 1); ?>>1 minute</option>
                        <option value="5" <?php selected($current_interval, 5); ?>>5 minutes</option>
                        <option value="10" <?php selected($current_interval, 10); ?>>10 minutes</option>
                        <option value="15" <?php selected($current_interval, 15); ?>>15 minutes</option>
                        <option value="30" <?php selected($current_interval, 30); ?>>30 minutes</option>
                        <option value="60" <?php selected($current_interval, 60); ?>>1 hour</option>
                    </select>
                    
                    <p class="ft-note">
                        <i class="fa-solid fa-shield-alt"></i>
                        <?php esc_html_e('Content validation and formatting', 'ai-auto-tool'); ?>
                    </p>
                    <label>
                        <input type="checkbox" name="keyword_autopost_content_validation" value="1" <?php checked(get_option('keyword_autopost_content_validation', 1), 1); ?>>
                        <?php esc_html_e('Enable content validation and markdown cleanup', 'ai-auto-tool'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Automatically fix markdown formatting issues and ensure proper HTML structure in generated content.', 'ai-auto-tool'); ?>
                    </p>
                    
                    <p class="ft-note">
                        <i class="fa-solid fa-tags"></i>
                        <?php esc_html_e('Automatic tag generation', 'ai-auto-tool'); ?>
                    </p>
                    <label>
                        <input type="checkbox" name="keyword_autopost_auto_tags" value="1" <?php checked(get_option('keyword_autopost_auto_tags', 1), 1); ?>>
                        <?php esc_html_e('Enable automatic tag generation from content', 'ai-auto-tool'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Automatically generate relevant tags from the article content using AI analysis. Tags will be combined with user-provided tags.', 'ai-auto-tool'); ?>
                    </p>
                    
                    <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                       <?php esc_html_e('AI Model for Content Generation','ai-auto-tool'); ?>:
                    </p>
                    <select id="keyword_autopost_model" name="keyword_autopost_model">
                        <?php 
                        $available_models = $this->get_available_models();
                        foreach ($available_models as $model_id => $model_name) {
                            $is_selected = selected($keyword_autopost_model, $model_id, false);
                            $is_default = ($model_id === 'gemini-2.5-flash') ? ' (Default)' : '';
                            echo '<option value="' . esc_attr($model_id) . '" ' . $is_selected . '>' . esc_html($model_name . $is_default) . '</option>';
                        }
                        ?>
                    </select>
                    
                    <p class="submit">
                        <input type="submit" name="keyword_autopost_save_settings" class="ft-submit" value="<?php esc_html_e('Save Configuration', 'ai-auto-tool'); ?>" />
                    </p>
                </form>
            </div>
        </div>
        <?php
    }
    
    public function render_tab_setting() {
        if ($this->active === 'true' || $this->active === true) {
            echo '<button href="#tab-keyword-autopost-setting" class="nav-tab sotab">' . wp_kses_post($this->icon) . ' ' . esc_html__('Keyword Autopost', 'ai-auto-tool') . '</button>';
        }
    }
    
    public function render_feature() {
        $autoToolBox = new AutoToolBox(
            wp_kses_post($this->icon) . ' ' . esc_html__('Keyword Autopost', 'ai-auto-tool'),
            "Automatically generate and publish articles from keywords. The system processes keywords from a queue and creates complete articles with AI-generated content and images.",
            "https://doc.aiautotool.com/integrations/keyword-autopost-guide",
            $this->active_option_name,
            $this->active,
            esc_url(plugins_url('../images/logo.svg', __FILE__))
        );
        echo ($autoToolBox->generateHTML());
    }
    
    public function add_menu() {
        

        add_submenu_page(
            MENUSUBPARRENT,
            wp_kses_post($this->icon).' '.esc_html__('Keyword Autopost AI post','ai-auto-tool'),          
            wp_kses_post($this->icon).' '.esc_html__('Keyword Autopost AI post','ai-auto-tool'),    
            'manage_options',
            'keyword-autopost',
            array($this, 'render_keyword_autopost_page')
        );
    }
    
    public function render_keyword_autopost_page() {
        $default_language = get_option('aiautotool_default_language', 'vi');
        $languages = $this->languageCodes;
        $stats = $this->get_keywords_stats();
        
        echo '<div class=" aiautotool_container">';
        ?>
        <div class="ft-wrap-top"></div>
        <div class="wrap ft-wrap">
            <div class="ft-wrap-body">
                <div class="ft-box">
                    <div class="ft-menu">
                    <div class="ft-logo"><img src="<?php echo esc_url(plugins_url('../../../images/logo.svg', __FILE__)); ?>">
                    <br>Keyword Autopost</div>
                    <button href="#tab-keyword-input" class="nav-tab sotabt "> <?php echo wp_kses_post($this->icon).' '. esc_html__('Keyword Autopost AI post','ai-auto-tool'); ?></button>
                    <button href="#tab-keyword-queue" class="nav-tab sotabt "><i class="fa-solid fa-list"></i> <?php esc_html_e('Keyword Queue', 'ai-auto-tool'); ?></button>
                    <button href="#tab-keyword-log" class="nav-tab sotabt "><i class="fa-regular fa-folder-closed"></i> <?php esc_html_e('Processing Log', 'ai-auto-tool'); ?></button>
                
                    </div>
                    <div class="ft-main">
                        <!-- Keyword Input Tab -->
                        <div id="tab-keyword-input" class="tab-content sotab-box ftbox">
                            <div class="autoblogging-header">
                                <h2><i class="fa-solid fa-key"></i> <?php esc_html_e('Keyword Autopost AI post','ai-auto-tool'); ?></h2>
                                <p class="autoblogging-subtitle"><?php esc_html_e('Enter keywords to automatically generate and publish blog posts. The system will create titles, content, and images for each keyword using AI.','ai-auto-tool'); ?></p>
                            </div>
                            
                            <!-- Step Header -->
                            <div class="autoblogging-steps-container">
                                <div class="autoblogging-step" id="step-1" data-step="1">
                                    <div class="step-number">1</div>
                                    <div class="step-content">
                                        <div class="step-title">Keywords</div>
                                        <div class="step-description">Enter keywords that will be used to generate AI content. Each keyword will create a separate post.</div>
                                    </div>
                                    <div class="step-indicator"></div>
                                </div>
                                <div class="autoblogging-step" id="step-2" data-step="2">
                                    <div class="step-number">2</div>
                                    <div class="step-content">
                                        <div class="step-title">Content Settings</div>
                                        <div class="step-description">Configure how AI generates content by selecting prompt template, category, tags, language, and priority preferences.</div>
                                    </div>
                                    <div class="step-indicator"></div>
                                </div>
                                <div class="autoblogging-step" id="step-3" data-step="3">
                                    <div class="step-number">3</div>
                                    <div class="step-content">
                                        <div class="step-title">Ready to Submit</div>
                                        <div class="step-description">Review your settings and submit to add keywords to the processing queue.</div>
                                    </div>
                                    <div class="step-indicator"></div>
                                </div>
                            </div>
                            
                            <!-- start form -->
                            <form id="add-keywords-form" method="post">
                            
                            <!-- Section 1: Keywords Card -->
                            <div class="autoblogging-card" id="section-keywords">
                                <div class="card-header">
                                    <div class="card-header-left">
                                        <i class="fa-solid fa-key"></i>
                                        <h3><?php esc_html_e('Keywords','ai-auto-tool'); ?></h3>
                                    </div>
                                    <button type="button" id="open-suggestion-modal-btn" class="aiautotool_idea_generated">
                                        <i class="fa-solid fa-magnifying-glass"></i> <?php esc_html_e('Get Suggestions','ai-auto-tool'); ?>
                                    </button>
                                </div>
                                <div class="card-body">
                                    <p class="card-description">
                                        <i class="fa-solid fa-info-circle"></i>
                                        <?php esc_html_e('Enter keywords (one per line). Each keyword will be processed to create a complete blog post with AI-generated title, content, and images.','ai-auto-tool'); ?>
                                    </p>
                                    <textarea id="keywords" class="autoblogging-textarea" name="keywords" rows="8" placeholder="<?php esc_attr_e('Enter keywords (one per line)...','ai-auto-tool'); ?>"></textarea>
                                    <div class="input-counter">
                                        <span id="keyword-count">0</span> <?php esc_html_e('keywords entered','ai-auto-tool'); ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Section 2: Content Settings Card -->
                            <div class="autoblogging-card" id="section-content">
                                <div class="card-header">
                                    <div class="card-header-left">
                                        <i class="fa-solid fa-sliders"></i>
                                        <h3><?php esc_html_e('Content Settings','ai-auto-tool'); ?></h3>
                                    </div>
                                    <button type="button" class="card-toggle" aria-expanded="true">
                                        <i class="fa-solid fa-chevron-up"></i>
                                    </button>
                                </div>
                                <div class="card-body">
                                    <?php 
                                    if (class_exists('\\AIautotool_Prompt_CPT')) {
                                        $AIautotool_Prompt_CPT = new \AIautotool_Prompt_CPT ();
                                        $AIautotool_Prompt_CPT->render_select_prompt();
                                    }
                                    ?>
                                    
                                    <div class="form-group">
                                        <label class="form-label">
                                            <i class="fa-solid fa-folder"></i>
                                            <?php esc_html_e('Categories','ai-auto-tool'); ?>
                                        </label>
                                        <p class="form-description"><?php esc_html_e('Select categories for posts when they are published.','ai-auto-tool'); ?></p>
                                        <div class="category-checkbox-list">
                                            <?php 
                                            $categories = get_categories(array(
                                                'hide_empty' => 0,
                                                'hierarchical' => 1
                                            ));
                                            
                                            if (!empty($categories)) {
                                                foreach ($categories as $category) {
                                                    $indent = '';
                                                    if ($category->parent) {
                                                        $parent = get_category($category->parent);
                                                        $level = 0;
                                                        while ($parent) {
                                                            $level++;
                                                            $parent = $parent->parent ? get_category($parent->parent) : false;
                                                        }
                                                        $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
                                                    }
                                                    echo '<label style="display: block; margin-bottom: 8px; cursor: pointer; padding: 5px; border-radius: 3px; transition: background 0.2s;">';
                                                    echo '<input type="checkbox" name="category_id[]" value="' . esc_attr($category->term_id) . '" class="post-category-checkbox" style="margin-right: 8px;">';
                                                    echo $indent . esc_html($category->name) . ' <span style="color: #999; font-size: 12px;">(' . $category->count . ')</span>';
                                                    echo '</label>';
                                                }
                                            } else {
                                                echo '<p>' . esc_html__('No categories found.', 'ai-auto-tool') . '</p>';
                                            }
                                            ?>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="form-label">
                                            <i class="fa-solid fa-tags"></i>
                                            <?php esc_html_e('Tags','ai-auto-tool'); ?>
                                        </label>
                                        <p class="form-description"><?php esc_html_e('Enter tags (comma-separated). The system will randomly select 3 tags from your input for each post.','ai-auto-tool'); ?></p>
                                        <input type="text" class="autoblogging-input" name="tags" id="tags" placeholder="<?php esc_attr_e('Enter tags (comma-separated)','ai-auto-tool'); ?>">
                                        
                                        <div class="form-switch-group">
                                            <label class="nut-switch">
                                                <input type="checkbox" name="auto_generate_tags" id="auto_generate_tags" value="1">
                                                <span class="slider"></span>
                                            </label>
                                            <label class="form-switch-label" for="auto_generate_tags">
                                                <?php esc_html_e('Auto generate tags with AI','ai-auto-tool'); ?>
                                            </label>
                                        </div>
                                        <p class="form-hint">
                                            <i class="fa-solid fa-info-circle"></i>
                                            <?php esc_html_e('If enabled, AI will automatically generate relevant tags based on post content. Manual tags above will be used as fallback if AI generation fails.','ai-auto-tool'); ?>
                                        </p>
                                    </div>
                                    
                                    <div class="form-row">
                                        <div class="form-group form-group-half">
                                            <label class="form-label">
                                                <i class="fa-solid fa-language"></i>
                                                <?php esc_html_e('Language','ai-auto-tool'); ?>
                                            </label>
                                            <p class="form-description"><?php esc_html_e('Select the language for AI-generated content.','ai-auto-tool'); ?></p>
                                            <select name="language" id="language" class="autoblogging-select">
                                                <?php foreach ($languages as $code => $name) { ?>
                                                    <option value="<?php echo esc_attr($code); ?>" <?php selected($default_language, $code, false); ?>><?php echo esc_html($name); ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group form-group-half">
                                            <label class="form-label">
                                                <i class="fa-solid fa-flag"></i>
                                                <?php esc_html_e('Priority','ai-auto-tool'); ?>
                                            </label>
                                            <p class="form-description"><?php esc_html_e('Set processing priority (higher number = higher priority).','ai-auto-tool'); ?></p>
                                            <select name="priority" id="priority" class="autoblogging-select">
                                                <option value="0"><?php esc_html_e('Normal','ai-auto-tool'); ?></option>
                                                <option value="1"><?php esc_html_e('Low','ai-auto-tool'); ?></option>
                                                <option value="5"><?php esc_html_e('High','ai-auto-tool'); ?></option>
                                                <option value="10"><?php esc_html_e('Urgent','ai-auto-tool'); ?></option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Section 3: Submit Section -->
                            <div class="autoblogging-submit-section">
                                <div class="submit-info">
                                    <div class="submit-info-item">
                                        <i class="fa-solid fa-list-check"></i>
                                        <span id="submit-keywords-count">0</span> <?php esc_html_e('keywords will be added to queue','ai-auto-tool'); ?>
                                    </div>
                                    <div class="submit-info-item">
                                        <i class="fa-solid fa-clock"></i>
                                        <?php esc_html_e('Keywords will be processed automatically','ai-auto-tool'); ?>
                                    </div>
                                </div>
                                <button type="submit" id="btnSubmitKeywords" class="autoblogging-submit-btn">
                                    <i class="fa-solid fa-plus-circle"></i>
                                    <span><?php esc_html_e('Add Keywords to Queue','ai-auto-tool'); ?></span>
                                    <div id="loading-icon" class="loader"></div>
                                </button>
                            </div>
                            
                            </form>
                            
                            <div id="keywords-result" class="keywords-result-container"></div>
                        </div>
                        
                        <!-- Keyword Queue Tab -->
                        <div id="tab-keyword-queue" class="tab-content sotab-box ftbox" style="display:none;">
                            <div class="autoblogging-header">
                                <h2><i class="fa-solid fa-list"></i> <?php esc_html_e('Keyword Queue', 'ai-auto-tool'); ?></h2>
                                <p class="autoblogging-subtitle"><?php esc_html_e('Monitor and manage your keyword processing queue. View status, progress, and manage pending keywords.','ai-auto-tool'); ?></p>
                            </div>
                            
                            <!-- Cron Job Status Section -->
                            <div class="cron-status-section">
                                <div class="cron-info-card">
                                    <div class="cron-header">
                                        <i class="fa-solid fa-clock"></i>
                                        <h3><?php esc_html_e('Cron Job Status', 'ai-auto-tool'); ?></h3>
                                    </div>
                                    <div class="cron-details">
                                        <div class="cron-item">
                                            <span class="cron-label"><?php esc_html_e('Status:', 'ai-auto-tool'); ?></span>
                                            <span class="cron-value" id="cron-status">
                                                <?php 
                                                if (wp_next_scheduled('keyword_autopost_cron_event')) {
                                                    echo '<span class="status-active"><i class="fa-solid fa-play"></i> Active</span>';
                                                } else {
                                                    echo '<span class="status-inactive"><i class="fa-solid fa-pause"></i> Inactive</span>';
                                                }
                                                ?>
                                            </span>
                                        </div>
                                        <div class="cron-item">
                                            <span class="cron-label"><?php esc_html_e('Interval:', 'ai-auto-tool'); ?></span>
                                            <span class="cron-value">
                                                <?php 
                                                $interval = get_option('keyword_autopost_time', 5);
                                                echo esc_html($interval) . ' ' . esc_html__('minutes', 'ai-auto-tool');
                                                ?>
                                            </span>
                                        </div>
                                        <div class="cron-item">
                                            <span class="cron-label"><?php esc_html_e('Next Run:', 'ai-auto-tool'); ?></span>
                                            <span class="cron-value" id="next-run-time">
                                                <?php 
                                                $next_run = wp_next_scheduled('keyword_autopost_cron_event');
                                                if ($next_run) {
                                                    echo '<span class="next-run">' . esc_html(date('Y-m-d H:i:s', $next_run)) . '</span>';
                                                } else {
                                                    echo '<span class="no-schedule">' . esc_html__('Not scheduled', 'ai-auto-tool') . '</span>';
                                                }
                                                ?>
                                            </span>
                                        </div>
                                        <div class="cron-item">
                                            <span class="cron-label"><?php esc_html_e('Last Run:', 'ai-auto-tool'); ?></span>
                                            <span class="cron-value" id="last-run-time">
                                                <?php 
                                                $last_run = get_option('keyword_autopost_last_run', '');
                                                if ($last_run) {
                                                    echo esc_html($last_run);
                                                } else {
                                                    echo esc_html__('Never', 'ai-auto-tool');
                                                }
                                                ?>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="cron-actions">
                                        <button type="button" id="run-cron-now" class="ft-submit"><?php esc_html_e('Run Now', 'ai-auto-tool'); ?></button>
                                        <button type="button" id="schedule-cron" class="ft-submit"><?php esc_html_e('Schedule Cron', 'ai-auto-tool'); ?></button>
                                        <button type="button" id="refresh-cron-status" class="ft-submit"><?php esc_html_e('Refresh', 'ai-auto-tool'); ?></button>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Current Processing Status -->
                            <div class="processing-status-section">
                                <div class="processing-info-card">
                                    <div class="processing-header">
                                        <i class="fa-solid fa-cogs"></i>
                                        <h3><?php esc_html_e('Current Processing', 'ai-auto-tool'); ?></h3>
                                    </div>
                                    <div class="processing-details" id="current-processing">
                                        <?php
                                        global $wpdb;
                                        $processing_keyword = $wpdb->get_row(
                                            "SELECT * FROM {$wpdb->prefix}aiautotool_keywords 
                                            WHERE status = 'processing' 
                                            ORDER BY created_at DESC 
                                            LIMIT 1"
                                        );
                                        
                                        if ($processing_keyword) {
                                            echo '<div class="processing-item active">';
                                            echo '<div class="processing-keyword">' . esc_html($processing_keyword->keyword) . '</div>';
                                            echo '<div class="processing-time">' . esc_html__('Started:', 'ai-auto-tool') . ' ' . esc_html($processing_keyword->created_at) . '</div>';
                                            echo '<div class="processing-progress">';
                                            echo '<div class="progress-bar">';
                                            echo '<div class="progress-fill" style="width: 50%;"></div>';
                                            echo '</div>';
                                            echo '<span class="progress-text">Processing...</span>';
                                            echo '</div>';
                                            echo '</div>';
                                        } else {
                                            echo '<div class="processing-item idle">';
                                            echo '<div class="processing-message">' . esc_html__('No keywords currently being processed', 'ai-auto-tool') . '</div>';
                                            echo '</div>';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="keyword-stats">
                                <div class="stat-box">
                                    <span class="stat-number"><?php echo esc_html($stats['pending']); ?></span>
                                    <span class="stat-label"><?php esc_html_e('Pending', 'ai-auto-tool'); ?></span>
                                </div>
                                <div class="stat-box">
                                    <span class="stat-number"><?php echo esc_html($stats['processing']); ?></span>
                                    <span class="stat-label"><?php esc_html_e('Processing', 'ai-auto-tool'); ?></span>
                                </div>
                                <div class="stat-box">
                                    <span class="stat-number"><?php echo esc_html($stats['completed']); ?></span>
                                    <span class="stat-label"><?php esc_html_e('Completed', 'ai-auto-tool'); ?></span>
                                </div>
                                <div class="stat-box">
                                    <span class="stat-number"><?php echo esc_html($stats['error']); ?></span>
                                    <span class="stat-label"><?php esc_html_e('Error', 'ai-auto-tool'); ?></span>
                                </div>
                            </div>
                            
                            <!-- Campaign Progress Section -->
                            <div class="campaign-progress-section">
                                <div class="campaign-progress-card">
                                    <div class="campaign-progress-header">
                                        <i class="fa-solid fa-chart-line"></i>
                                        <h3><?php esc_html_e('Campaign Progress', 'ai-auto-tool'); ?></h3>
                                    </div>
                                    <div class="campaign-progress-content">
                                        <?php
                                        $total_keywords = $stats['pending'] + $stats['processing'] + $stats['completed'] + $stats['error'];
                                        $completed_percentage = $total_keywords > 0 ? round(($stats['completed'] / $total_keywords) * 100, 1) : 0;
                                        $estimated_time = $this->calculate_estimated_completion_time($stats);
                                        ?>
                                        <div class="progress-overview">
                                            <div class="progress-text">
                                                <span class="progress-percentage"><?php echo esc_html($completed_percentage); ?>%</span>
                                                <span class="progress-fraction">(<?php echo esc_html($stats['completed']); ?>/<?php echo esc_html($total_keywords); ?> <?php esc_html_e('keywords', 'ai-auto-tool'); ?>)</span>
                                            </div>
                                            <div class="progress-bar-large">
                                                <div class="progress-fill-large" style="width: <?php echo esc_attr($completed_percentage); ?>%"></div>
                                            </div>
                                        </div>
                                        <div class="progress-details">
                                            <div class="progress-item">
                                                <span class="progress-label"><?php esc_html_e('Estimated completion:', 'ai-auto-tool'); ?></span>
                                                <span class="progress-value" id="estimated-completion"><?php echo esc_html($estimated_time); ?></span>
                                            </div>
                                            <div class="progress-item">
                                                <span class="progress-label"><?php esc_html_e('Average processing time:', 'ai-auto-tool'); ?></span>
                                                <span class="progress-value" id="avg-processing-time"><?php echo esc_html($this->get_average_processing_time()); ?></span>
                                            </div>
                                            <div class="progress-item">
                                                <span class="progress-label"><?php esc_html_e('Success rate:', 'ai-auto-tool'); ?></span>
                                                <span class="progress-value" id="success-rate">
                                                    <?php 
                                                    $total_processed = $stats['completed'] + $stats['error'];
                                                    $success_rate = $total_processed > 0 ? round(($stats['completed'] / $total_processed) * 100, 1) : 0;
                                                    echo esc_html($success_rate) . '%';
                                                    ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div id="keyword-queue-table">
                                <?php echo $this->render_keyword_queue_table(); ?>
                            </div>
                        </div>
                        
                        <!-- Processing Log Tab -->
                        <div id="tab-keyword-log" class="tab-content sotab-box ftbox" style="display:none;">
                            <div class="autoblogging-header">
                                <h2><i class="fa-regular fa-folder-closed"></i> <?php esc_html_e('Processing Log', 'ai-auto-tool'); ?></h2>
                                <p class="autoblogging-subtitle"><?php esc_html_e('View detailed logs of keyword processing activities, including successful posts and any errors encountered.','ai-auto-tool'); ?></p>
                            </div>
                            
                            <div class="autoblogging-card">
                                <div class="card-header">
                                    <div class="card-header-left">
                                        <i class="fa-solid fa-list"></i>
                                        <h3><?php esc_html_e('Log Entries','ai-auto-tool'); ?></h3>
                                    </div>
                                    <button type="button" id="clear-keywords-log-button" class="aiautotool_idea_generated" style="background: linear-gradient(135deg, #e74c3c, #c0392b);">
                                        <i class="fa-solid fa-trash"></i> <?php esc_html_e('Clear Log','ai-auto-tool'); ?>
                                    </button>
                                </div>
                                <div class="card-body">
                                    <?php
                                    $log = new AIautoTool_log();
                                    $log->show_log('keyword_autopost');
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <style>
            /* Prevent horizontal overflow */
            body, html {
                overflow-x: hidden !important;
            }
            
            .aiautotool_container {
                width: 100% !important;
                max-width: 100% !important;
                overflow-x: hidden !important;
                box-sizing: border-box !important;
            }
            
            .aiautotool_container * {
                box-sizing: border-box !important;
            }
            
            /* Full Width Layout */
            .aiautotool_container .ft-wrap {
                max-width: 100% !important;
                width: 100% !important;
                margin: 0 !important;
                padding: 20px !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            .aiautotool_container .ft-wrap-body {
                display: block !important;
                width: 100% !important;
                max-width: 100% !important;
                grid-template-columns: none !important;
                grid-gap: 0 !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            .aiautotool_container .ft-box {
                width: 100% !important;
                max-width: 100% !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            .aiautotool_container .ft-main {
                width: 100% !important;
                max-width: 100% !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            .aiautotool_container .ft-menu {
                width: 100% !important;
                max-width: 100% !important;
                box-sizing: border-box !important;
            }
            
            /* Ensure all cards and containers respect viewport */
            .autoblogging-card,
            .autoblogging-steps-container,
            .tab-content,
            .sotab-box {
                max-width: 100% !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            /* Fix tables and wide content */
            .aiautotool_container table {
                max-width: 100% !important;
                table-layout: auto !important;
                word-wrap: break-word !important;
            }
            
            .aiautotool_container .category-checkbox-list {
                max-width: 100% !important;
                overflow-x: hidden !important;
            }
            
            /* Fix form elements */
            .autoblogging-input,
            .autoblogging-select,
            .autoblogging-textarea {
                max-width: 100% !important;
                box-sizing: border-box !important;
            }
            
            /* Fix form rows */
            .form-row {
                max-width: 100% !important;
                box-sizing: border-box !important;
            }
            
            /* Fix all containers and wrappers */
            .aiautotool_container .wrap,
            .aiautotool_container .ft-wrap-top,
            .aiautotool_container .tab-content,
            .aiautotool_container .sotab-box {
                max-width: 100% !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            /* Fix submit section */
            .form-submit-section,
            .autoblogging-submit-section {
                max-width: 100% !important;
                box-sizing: border-box !important;
                overflow-x: hidden !important;
            }
            
            /* Fix stats and progress containers */
            .keyword-stats,
            .stat-box,
            .progress-container {
                max-width: 100% !important;
                box-sizing: border-box !important;
            }
            
            /* Fix buttons */
            .aiautotool_idea_generated,
            .ft-submit,
            .autoblogging-submit-btn {
                max-width: 100% !important;
                box-sizing: border-box !important;
                word-wrap: break-word !important;
            }
            
            /* Autoblogging Header */
            .autoblogging-header {
                margin-bottom: 30px;
                padding-bottom: 20px;
                border-bottom: 2px solid #e8e8e8;
            }
            
            .autoblogging-header h2 {
                margin: 0 0 10px 0;
                font-size: 28px;
                color: #2c3e50;
                display: flex;
                align-items: center;
                gap: 12px;
            }
            
            .autoblogging-subtitle {
                margin: 0;
                color: #666;
                font-size: 15px;
                line-height: 1.6;
            }
            
            /* Autoblogging Steps Styles */
            .autoblogging-steps-container {
                display: flex;
                flex-wrap: wrap;
                gap: 15px;
                margin: 25px 0 30px 0;
                padding: 20px;
                background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
                border-radius: 12px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            }
            
            .autoblogging-step {
                flex: 1;
                min-width: 200px;
                position: relative;
                padding: 20px;
                background: #ffffff;
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                transition: all 0.3s ease;
                opacity: 0.5;
                cursor: default;
            }
            
            .autoblogging-step.active {
                opacity: 1;
                border-color: #4a90e2;
                box-shadow: 0 4px 12px rgba(74, 144, 226, 0.2);
                transform: translateY(-2px);
            }
            
            .autoblogging-step.completed {
                opacity: 1;
                border-color: #27ae60;
                background: linear-gradient(135deg, #ffffff 0%, #f0f9f4 100%);
            }
            
            .autoblogging-step.completed .step-number {
                background: #27ae60;
                color: #ffffff;
            }
            
            .autoblogging-step.active .step-number {
                background: #4a90e2;
                color: #ffffff;
                animation: pulse 2s infinite;
            }
            
            .step-number {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background: #e0e0e0;
                color: #999;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                font-size: 18px;
                margin-bottom: 12px;
                transition: all 0.3s ease;
            }
            
            .step-content {
                flex: 1;
            }
            
            .step-title {
                font-size: 16px;
                font-weight: 600;
                color: #333;
                margin-bottom: 8px;
                transition: color 0.3s ease;
            }
            
            .autoblogging-step.active .step-title {
                color: #4a90e2;
            }
            
            .autoblogging-step.completed .step-title {
                color: #27ae60;
            }
            
            .step-description {
                font-size: 13px;
                color: #666;
                line-height: 1.5;
            }
            
            .step-indicator {
                position: absolute;
                top: 10px;
                right: 10px;
                width: 12px;
                height: 12px;
                border-radius: 50%;
                background: #e0e0e0;
                transition: all 0.3s ease;
            }
            
            .autoblogging-step.active .step-indicator {
                background: #4a90e2;
                box-shadow: 0 0 8px rgba(74, 144, 226, 0.6);
            }
            
            .autoblogging-step.completed .step-indicator {
                background: #27ae60;
                box-shadow: 0 0 8px rgba(39, 174, 96, 0.6);
            }
            
            .autoblogging-step.completed .step-indicator::after {
                content: '✓';
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                color: white;
                font-size: 8px;
                font-weight: bold;
            }
            
            @keyframes pulse {
                0%, 100% {
                    box-shadow: 0 0 0 0 rgba(74, 144, 226, 0.7);
                }
                50% {
                    box-shadow: 0 0 0 8px rgba(74, 144, 226, 0);
                }
            }
            
            @media (max-width: 768px) {
                .autoblogging-steps-container {
                    flex-direction: column;
                }
                .autoblogging-step {
                    min-width: 100%;
                }
            }
            
            /* Card-based Layout */
            .autoblogging-card {
                background: #ffffff;
                border-radius: 12px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
                margin-bottom: 20px;
                overflow: hidden;
                transition: all 0.3s ease;
                border: 1px solid #e8e8e8;
            }
            
            .autoblogging-card:hover {
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
                transform: translateY(-2px);
            }
            
            .card-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 20px 24px;
                background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
                border-bottom: 1px solid #e8e8e8;
            }
            
            .card-header-left {
                display: flex;
                align-items: center;
                gap: 12px;
            }
            
            .card-header-left i {
                font-size: 20px;
                color: #4a90e2;
            }
            
            .card-header h3 {
                margin: 0;
                font-size: 18px;
                font-weight: 600;
                color: #2c3e50;
            }
            
            .card-toggle {
                background: none;
                border: none;
                cursor: pointer;
                padding: 8px;
                color: #666;
                transition: all 0.3s ease;
                border-radius: 6px;
            }
            
            .card-toggle:hover {
                background: #f0f0f0;
                color: #4a90e2;
            }
            
            .card-body {
                padding: 24px;
            }
            
            .card-description {
                margin: 0 0 16px 0;
                padding: 12px 16px;
                background: #f0f7ff;
                border-left: 3px solid #4a90e2;
                border-radius: 6px;
                color: #555;
                font-size: 14px;
                line-height: 1.6;
            }
            
            .card-description i {
                color: #4a90e2;
                margin-right: 8px;
            }
            
            /* Form Elements */
            .form-group {
                margin-bottom: 24px;
            }
            
            .form-group:last-child {
                margin-bottom: 0;
            }
            
            .form-row {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 20px;
            }
            
            @media (max-width: 768px) {
                .form-row {
                    grid-template-columns: 1fr;
                }
            }
            
            .form-group-half {
                margin-bottom: 0;
            }
            
            .form-label {
                display: flex;
                align-items: center;
                gap: 8px;
                font-weight: 600;
                color: #2c3e50;
                margin-bottom: 8px;
                font-size: 15px;
            }
            
            .form-label i {
                color: #4a90e2;
                font-size: 16px;
            }
            
            .form-description {
                margin: 0 0 12px 0;
                color: #666;
                font-size: 13px;
                line-height: 1.5;
            }
            
            .autoblogging-input,
            .autoblogging-select,
            .autoblogging-textarea,
            select.autoblogging-select,
            #category_id {
                width: 100%;
                padding: 12px 16px;
                border: 2px solid #e0e0e0;
                border-radius: 8px;
                font-size: 14px;
                transition: all 0.3s ease;
                background: #fff;
                font-family: inherit;
            }
            
            .autoblogging-input:focus,
            .autoblogging-select:focus,
            .autoblogging-textarea:focus,
            select.autoblogging-select:focus,
            #category_id:focus {
                outline: none;
                border-color: #4a90e2;
                box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
            }
            
            .autoblogging-textarea {
                min-height: 150px;
                resize: vertical;
                font-family: inherit;
                line-height: 1.6;
            }
            
            .input-counter {
                margin-top: 8px;
                font-size: 12px;
                color: #666;
                text-align: right;
            }
            
            .input-counter span {
                font-weight: 600;
                color: #4a90e2;
            }
            
            /* Category Checkbox List */
            .category-checkbox-list {
                max-height: 250px;
                overflow-y: auto;
                border: 2px solid #e0e0e0;
                padding: 16px;
                border-radius: 8px;
                background: #fafafa;
            }
            
            .category-checkbox-list label {
                display: block;
                margin-bottom: 10px;
                cursor: pointer;
                padding: 10px 12px;
                border-radius: 6px;
                transition: all 0.2s ease;
                user-select: none;
            }
            
            .category-checkbox-list label:hover {
                background: #e8f4f8;
            }
            
            .category-checkbox-list input[type="checkbox"]:checked + * {
                font-weight: 600;
                color: #4a90e2;
            }
            
            .category-checkbox-list label:has(input:checked) {
                background: #e8f4f8;
                border-left: 3px solid #4a90e2;
            }
            
            /* Form Switch */
            .form-switch-group {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-top: 12px;
            }
            
            .form-switch-label {
                cursor: pointer;
                font-size: 14px;
                color: #2c3e50;
                font-weight: 500;
            }
            
            .form-hint {
                margin: 8px 0 0 0;
                padding: 8px 12px;
                background: #fff9e6;
                border-left: 3px solid #f1c40f;
                border-radius: 4px;
                color: #856404;
                font-size: 12px;
                line-height: 1.5;
            }
            
            .form-hint i {
                margin-right: 6px;
            }
            
            /* Switch styles */
            .nut-switch {
                position: relative;
                display: inline-block;
                width: 52px;
                height: 26px;
                margin-right: 12px;
            }
            
            .nut-switch input {
                opacity: 0;
                width: 0;
                height: 0;
            }
            
            .slider {
                position: absolute;
                cursor: pointer;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #e0e0e0;
                transition: .4s cubic-bezier(0.4, 0, 0.2, 1);
                border-radius: 26px;
                box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
            }
            
            .slider:before {
                position: absolute;
                content: "";
                height: 20px;
                width: 20px;
                left: 3px;
                bottom: 3px;
                background-color: white;
                transition: .4s cubic-bezier(0.4, 0, 0.2, 1);
                border-radius: 50%;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            }
            
            input:checked + .slider {
                background: linear-gradient(135deg, #4a90e2, #357abd);
            }
            
            input:checked + .slider:before {
                transform: translateX(26px);
            }
            
            /* Scrollbar styling for category list */
            .category-checkbox-list::-webkit-scrollbar {
                width: 8px;
            }
            
            .category-checkbox-list::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 4px;
            }
            
            .category-checkbox-list::-webkit-scrollbar-thumb {
                background: #c1c1c1;
                border-radius: 4px;
            }
            
            .category-checkbox-list::-webkit-scrollbar-thumb:hover {
                background: #a8a8a8;
            }
            
            /* Submit Section */
            .autoblogging-submit-section {
                background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
                border-radius: 12px;
                padding: 24px;
                margin-top: 30px;
                border: 2px solid #e8e8e8;
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 20px;
            }
            
            .submit-info {
                display: flex;
                gap: 24px;
                flex-wrap: wrap;
            }
            
            .submit-info-item {
                display: flex;
                align-items: center;
                gap: 8px;
                color: #666;
                font-size: 14px;
            }
            
            .submit-info-item i {
                color: #4a90e2;
            }
            
            .submit-info-item span {
                font-weight: 600;
                color: #2c3e50;
            }
            
            .autoblogging-submit-btn {
                background: linear-gradient(135deg, #4a90e2, #357abd);
                color: white;
                border: none;
                padding: 16px 32px;
                border-radius: 10px;
                cursor: pointer;
                font-size: 16px;
                font-weight: 600;
                display: inline-flex;
                align-items: center;
                gap: 12px;
                transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
                box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
                position: relative;
                overflow: hidden;
                min-width: 200px;
                justify-content: center;
            }
            
            .autoblogging-submit-btn:hover {
                background: linear-gradient(135deg, #357abd, #4a90e2);
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
            }
            
            .autoblogging-submit-btn:active {
                transform: translateY(0);
            }
            
            .autoblogging-submit-btn:disabled {
                opacity: 0.7;
                cursor: not-allowed;
                transform: none;
            }
            
            /* Button Styles */
            .aiautotool_idea_generated {
                background: linear-gradient(135deg, #27ae60, #229954);
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 8px;
                cursor: pointer;
                font-size: 13px;
                font-weight: 600;
                display: inline-flex;
                align-items: center;
                gap: 8px;
                transition: all 0.3s ease;
                box-shadow: 0 2px 6px rgba(39, 174, 96, 0.2);
            }
            
            .aiautotool_idea_generated:hover {
                background: linear-gradient(135deg, #229954, #27ae60);
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
            }
            
            .aiautotool_idea_generated.loading {
                pointer-events: none;
                opacity: 0.8;
            }
            
            /* Loading icon styles */
            .loader {
                display: none;
                width: 18px;
                height: 18px;
                border: 2px solid rgba(255,255,255,0.3);
                border-top: 2px solid #fff;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }
            
            .autoblogging-submit-btn .loader {
                display: none;
            }
            
            .autoblogging-submit-btn.loading .loader {
                display: block;
            }
            
            .autoblogging-submit-btn.loading span {
                display: none;
            }
            
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            
            /* Keywords Result Container */
            .keywords-result-container {
                margin-top: 20px;
            }
            
            .keywords-result-container .updated,
            .keywords-result-container .error {
                padding: 15px 20px;
                border-radius: 8px;
                margin-bottom: 15px;
            }
            
            .keywords-result-container .updated {
                background: #d4edda;
                border-left: 4px solid #27ae60;
                color: #155724;
            }
            
            .keywords-result-container .error {
                background: #f8d7da;
                border-left: 4px solid #e74c3c;
                color: #721c24;
            }
            
            /* Responsive Design */
            @media (max-width: 768px) {
                .autoblogging-submit-section {
                    flex-direction: column;
                    align-items: stretch;
                }
                
                .submit-info {
                    flex-direction: column;
                    gap: 12px;
                }
                
                .autoblogging-submit-btn {
                    width: 100%;
                }
                
                .card-header {
                    flex-wrap: wrap;
                    gap: 12px;
                }
                
                .aiautotool_idea_generated {
                    width: 100%;
                    justify-content: center;
                }
            }
            
            .loader {
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: spin 2s linear infinite;
    display: none; 
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
        .keyword-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .stat-box {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
            min-width: 100px;
        }
        
        .stat-number {
            display: block;
            font-size: 24px;
            font-weight: bold;
            color: #4a90e2;
        }
        
        .stat-label {
            display: block;
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .keyword-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .keyword-table th,
        .keyword-table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .keyword-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        
        .status-pending { color: #f39c12; }
        .status-processing { color: #3498db; }
        .status-completed { color: #27ae60; }
        .status-error { color: #e74c3c; }
        
        .delete-keyword {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .delete-keyword:hover {
            background: #c0392b;
        }
        
        .keyword-suggestion-section {
            margin: 20px 0;
            padding: 20px;
            background: #f9f9f9;
            border-radius: 8px;
            border: 1px solid #ddd;
        }
        
        .suggestion-input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .suggestion-input-group input {
            flex: 1;
        }
        
        .suggestion-input-group button {
            white-space: nowrap;
        }
        
        .status-secondKeywords {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            font-weight: bold;
        }
        
        .status-secondKeywords.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-secondKeywords.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status-secondKeywords.loading {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .keyword-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .keyword-actions button {
            flex: 1;
        }
        
        /* Cron Status Section Styles */
        .cron-status-section {
            margin-bottom: 30px;
        }
        
        .cron-info-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            overflow: hidden;
            border: 1px solid #e1e5e9;
        }
        
        .cron-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .cron-header h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }
        
        .cron-details {
            padding: 20px;
        }
        
        .cron-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .cron-item:last-child {
            border-bottom: none;
        }
        
        .cron-label {
            font-weight: 600;
            color: #555;
            min-width: 120px;
        }
        
        .cron-value {
            font-weight: 500;
            color: #333;
        }
        
        .status-active {
            color: #27ae60;
            font-weight: 600;
        }
        
        .status-active i {
            margin-right: 5px;
        }
        
        .status-inactive {
            color: #e74c3c;
            font-weight: 600;
        }
        
        .status-inactive i {
            margin-right: 5px;
        }
        
        .next-run {
            color: #3498db;
            font-weight: 600;
        }
        
        .no-schedule {
            color: #95a5a6;
            font-style: italic;
        }
        
        .cron-actions {
            padding: 20px;
            background: #f8f9fa;
            display: flex;
            gap: 10px;
        }
        
        /* Processing Status Section Styles */
        .processing-status-section {
            margin-bottom: 30px;
        }
        
        .processing-info-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            overflow: hidden;
            border: 1px solid #e1e5e9;
        }
        
        .processing-header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .processing-header h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }
        
        .processing-details {
            padding: 20px;
        }
        
        .processing-item {
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .processing-item.active {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            border: 1px solid #74b9ff;
        }
        
        .processing-item.idle {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            text-align: center;
        }
        
        .processing-keyword {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
        }
        
        .processing-time {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 15px;
        }
        
        .processing-progress {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .progress-bar {
            flex: 1;
            height: 8px;
            background: #ecf0f1;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #74b9ff, #0984e3);
            border-radius: 4px;
            animation: progress-animation 2s ease-in-out infinite;
        }
        
        @keyframes progress-animation {
            0% { width: 30%; }
            50% { width: 70%; }
            100% { width: 30%; }
        }
        
        .progress-text {
            font-size: 14px;
            font-weight: 600;
            color: #2c3e50;
            min-width: 100px;
        }
        
        .processing-message {
            font-size: 16px;
            color: #7f8c8d;
            font-style: italic;
        }
        
        /* Enhanced Stats Boxes */
        .keyword-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transition: transform 0.3s ease;
        }
        
        .stat-box:hover {
            transform: translateY(-2px);
        }
        
        .stat-number {
            display: block;
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stat-label {
            display: block;
            font-size: 14px;
            opacity: 0.9;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .cron-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
            
            .cron-actions {
                flex-direction: column;
            }
            
            .processing-progress {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .keyword-stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        /* Campaign Progress Section Styles */
        .campaign-progress-section {
            margin-bottom: 30px;
        }
        
        .campaign-progress-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            overflow: hidden;
            border: 1px solid #e1e5e9;
        }
        
        .campaign-progress-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .campaign-progress-header h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }
        
        .campaign-progress-content {
            padding: 25px;
        }
        
        .progress-overview {
            margin-bottom: 25px;
        }
        
        .progress-text {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .progress-percentage {
            font-size: 28px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .progress-fraction {
            font-size: 16px;
            color: #7f8c8d;
        }
        
        .progress-bar-large {
            width: 100%;
            height: 12px;
            background: #ecf0f1;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .progress-fill-large {
            height: 100%;
            background: linear-gradient(90deg, #74b9ff, #0984e3, #6c5ce7);
            border-radius: 6px;
            transition: width 0.5s ease;
            position: relative;
        }
        
        .progress-fill-large::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            animation: shimmer 2s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
        
        .progress-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }
        
        .progress-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #74b9ff;
        }
        
        .progress-label {
            font-weight: 600;
            color: #555;
        }
        
        .progress-value {
            font-weight: 600;
            color: #2c3e50;
        }
        
        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            display: none;
        }
        
        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-content h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #4a90e2;
            padding-bottom: 10px;
        }
        
        .suggestion-loading-indicator {
            text-align: center;
            padding: 20px;
        }
        
        .suggestion-loading-indicator .loader {
            margin: 10px auto;
        }
        
        .suggestion-results-container {
            display: none;
        }
        
        .modal-footer {
            margin-top: 20px;
            text-align: right;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }
        
        .modal-footer button {
            margin-left: 10px;
        }
        
        /* Enhanced Keyword Queue Table Styles */
        .keyword-queue-controls {
            margin-bottom: 20px;
        }
        
        .queue-filters {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .queue-filters input,
        .queue-filters select {
            min-width: 200px;
        }
        
        .bulk-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .ft-submit.danger {
            background: #e74c3c;
            border-color: #e74c3c;
        }
        
        .ft-submit.danger:hover {
            background: #c0392b;
            border-color: #c0392b;
        }
        
        .keyword-table-container {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow-x: auto;
            overflow-y: visible;
            max-width: 100%;
            width: 100%;
            box-sizing: border-box;
        }
        
        .keyword-table {
            width: 100%;
            max-width: 100%;
            border-collapse: collapse;
            margin: 0;
            table-layout: auto;
            box-sizing: border-box;
        }
        
        .keyword-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 10px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
        }
        
        .keyword-table th:first-child {
            width: 40px;
            text-align: center;
        }
        
        .keyword-table th:last-child {
            width: 120px;
            text-align: center;
        }
        
        .keyword-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
        }
        
        .keyword-table tr:hover {
            background: #f8f9fa;
        }
        
        .keyword-text {
            font-weight: 500;
            color: #2c3e50;
            max-width: 300px;
            word-wrap: break-word;
        }
        
        .keyword-actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }
        
        .keyword-actions button,
        .keyword-actions a {
            background: none;
            border: none;
            padding: 6px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
            text-decoration: none;
            color: #666;
        }
        
        .keyword-actions button:hover,
        .keyword-actions a:hover {
            background: #e9ecef;
        }
        
        .delete-keyword:hover {
            color: #e74c3c !important;
        }
        
        .view-error:hover {
            color: #f39c12 !important;
        }
        
        /* Status Styles */
        .status-pending {
            color: #f39c12;
            font-weight: 600;
        }
        
        .status-processing {
            color: #3498db;
            font-weight: 600;
        }
        
        .status-completed {
            color: #27ae60;
            font-weight: 600;
        }
        
        .status-error {
            color: #e74c3c;
            font-weight: 600;
        }
        
        /* Priority Badge Styles */
        .priority-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .priority-badge.urgent {
            background: #e74c3c;
            color: white;
        }
        
        .priority-badge.high {
            background: #f39c12;
            color: white;
        }
        
        .priority-badge.normal {
            background: #3498db;
            color: white;
        }
        
        .priority-badge.low {
            background: #95a5a6;
            color: white;
        }
        
        /* Error Details Styles */
        .error-details {
            background: #fff5f5;
        }
        
        .error-message {
            padding: 15px;
            background: #fed7d7;
            border-left: 4px solid #e74c3c;
            border-radius: 4px;
            color: #c53030;
        }
        
        .no-keywords {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
            padding: 40px !important;
        }
        
        .not-completed {
            color: #95a5a6;
            font-style: italic;
        }
        
        .completed-time {
            color: #27ae60;
            font-weight: 500;
        }
        
        /* Tags Styles */
        .keyword-tags {
            max-width: 200px;
            word-wrap: break-word;
        }
        
        .tag-item {
            display: inline-block;
            background: #e3f2fd;
            color: #1976d2;
            padding: 2px 6px;
            border-radius: 12px;
            font-size: 11px;
            margin: 1px 2px 1px 0;
            border: 1px solid #bbdefb;
        }
        
        .tag-item:hover {
            background: #bbdefb;
            color: #1565c0;
        }
        
        .no-tags {
            color: #95a5a6;
            font-style: italic;
            font-size: 12px;
        }
        
        /* Checkbox Styles */
        .keyword-checkbox {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
        
        #select-all-keywords {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
        
        /* Responsive Table */
        @media (max-width: 768px) {
            .queue-filters {
                flex-direction: column;
                align-items: stretch;
            }
            
            .queue-filters input,
            .queue-filters select {
                min-width: auto;
                max-width: 100%;
                box-sizing: border-box;
            }
            
            .keyword-table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }
            
            .keyword-table {
                font-size: 12px;
                min-width: 600px; /* Minimum width for table, will scroll if needed */
            }
            
            .keyword-table th,
            .keyword-table td {
                padding: 8px 5px;
                max-width: 150px;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }
            
            .keyword-text {
                max-width: 150px;
            }
        }
        
        /* Pagination Styles */
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .pagination-info {
            font-weight: 600;
            color: #495057;
        }
        
        .pagination-controls {
            display: flex;
            gap: 5px;
            align-items: center;
        }
        
        .pagination-btn {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            background: #fff;
            color: #495057;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
            min-width: 40px;
            text-align: center;
        }
        
        .pagination-btn:hover {
            background: #e9ecef;
            border-color: #adb5bd;
        }
        
        .pagination-btn.active {
            background: #007bff;
            border-color: #007bff;
            color: white;
        }
        
        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            // Keyword counter
            function updateKeywordCount() {
                var keywords = $('#keywords').val().trim();
                var count = keywords ? keywords.split('\n').filter(function(line) {
                    return line.trim().length > 0;
                }).length : 0;
                $('#keyword-count').text(count);
                $('#submit-keywords-count').text(count);
            }
            
            $('#keywords').on('input', updateKeywordCount);
            updateKeywordCount();
            
            // Step tracking functionality
            function updateStepStates() {
                // Step 1: Check if keywords are filled
                var keywords = $('#keywords').val().trim();
                var step1 = $('#step-1');
                if (keywords) {
                    step1.addClass('completed').removeClass('active');
                } else {
                    step1.removeClass('completed active');
                }
                
                // Step 2: Check content settings (prompt, category, tags, language, priority)
                var hasPrompt = false;
                var promptMode = $('input[name="prompt_selection_mode"]:checked').val();
                if (promptMode === 'multiple') {
                    $('.prompt-content-textarea').each(function() {
                        if ($(this).val().trim()) {
                            hasPrompt = true;
                            return false;
                        }
                    });
                } else {
                    var selectedPrompt = $('#aiautotool_prompt').val();
                    hasPrompt = selectedPrompt && selectedPrompt !== '' && selectedPrompt !== '0';
                }
                
                var hasCategory = $('.post-category-checkbox:checked').length > 0;
                var hasTags = $('#tags').val().trim() !== '';
                var hasLanguage = $('#language').val() && $('#language').val() !== '';
                var hasPriority = $('#priority').val() !== '';
                
                var step2 = $('#step-2');
                if (hasPrompt || hasCategory || hasTags || hasLanguage || hasPriority) {
                    step2.addClass('completed').removeClass('active');
                } else {
                    step2.removeClass('completed active');
                }
                
                // Step 3: Ready to submit (at least step 1 should be completed)
                var step3 = $('#step-3');
                if (keywords) {
                    step3.addClass('completed').removeClass('active');
                } else {
                    step3.removeClass('completed active');
                }
                
                // Set active step (first incomplete step or current step being filled)
                if (!keywords) {
                    step1.addClass('active');
                } else if (!hasPrompt && !hasCategory && !hasTags && !hasLanguage && !hasPriority) {
                    step2.addClass('active');
                } else {
                    step3.addClass('active');
                }
            }
            
            // Track form field changes
            $('#keywords').on('input change keyup', function() {
                updateKeywordCount();
                updateStepStates();
            });
            
            $('#tags, #language, #priority, #aiautotool_prompt').on('change', function() {
                updateStepStates();
            });
            
            // Track category checkbox changes
            $(document).on('change', '.post-category-checkbox', function() {
                updateStepStates();
            });
            
            // Track prompt selection mode changes
            $('input[name="prompt_selection_mode"]').on('change', function() {
                updateStepStates();
            });
            
            // Track prompt content textarea changes
            $('.prompt-content-textarea').on('input change keyup', function() {
                updateStepStates();
            });
            
            // Initial step state update
            setTimeout(updateStepStates, 500);
            setTimeout(updateStepStates, 1500);
            
            // Card toggle functionality
            $('.card-toggle').on('click', function() {
                var $card = $(this).closest('.autoblogging-card');
                var $body = $card.find('.card-body');
                var $icon = $(this).find('i');
                var isExpanded = $(this).attr('aria-expanded') === 'true';
                
                if (isExpanded) {
                    $body.slideUp(300);
                    $icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    $(this).attr('aria-expanded', 'false');
                } else {
                    $body.slideDown(300);
                    $icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
                    $(this).attr('aria-expanded', 'true');
                }
            });
            
            // Tab switching
            $('.sotabt').on('click', function(e) {
                e.preventDefault();
                var target = $(this).attr('href');
                
                $('.sotab-box').hide();
                $(target).show();
                
                $('.sotabt').removeClass('active');
                $(this).addClass('active');
                
                // Auto-refresh when switching to keyword queue tab
                if (target === '#tab-keyword-queue') {
                    refreshCronStatus();
                }
            });
            
            // Pagination click handler
            $(document).on('click', '.pagination-btn', function() {
                var page = $(this).data('page');
                var filter = $(this).data('filter');
                var search = $(this).data('search');
                var sortOrder = $('#sort-order').val();
                
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'get_keyword_queue',
                        page: page,
                        filter: filter,
                        search: search,
                        sort_order: sortOrder,
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#keyword-queue-table').html(response.data);
                        }
                    }
                });
            });
            
            // Enhanced Keyword Queue Features
            $(document).on('click', '#apply-filters', function() {
                var search = $('#keyword-search').val();
                var filter = $('#status-filter').val();
                var sortOrder = $('#sort-order').val();
                
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'get_keyword_queue',
                        page: 1, // Reset to first page when filtering
                        search: search,
                        filter: filter,
                        sort_order: sortOrder,
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#keyword-queue-table').html(response.data);
                        }
                    }
                });
            });
            
            // Hàm renderTableSuggesstion: thêm từ khóa phụ vào textarea (class secondKeywords)
            function renderTableSuggesstion(keywords) {
                let txtSecondKeywords = "";
                let totalKey = 0;
                for (let i = 0; i < keywords.length; i++) {
                    if (keywords[i].length > 10) {
                        txtSecondKeywords = txtSecondKeywords + keywords[i] + "\n";
                        totalKey += 1;
                    }
                }
                
                // Hide loading indicator and show results
                $('.suggestion-loading-indicator').hide();
                $('.suggestion-results-container').show();
                
                // Set suggested keywords
                $(".secondKeywords").val(txtSecondKeywords);
                
                // Update modal content to show success
                $('.modal-content p').html(`Found ${totalKey} keyword suggestions for your search.`);
            }

            // Hàm lấy gợi ý từ Google Suggest (JSONP)
            function getKeywordsSuggestion(keywordTxt, network = "web", language = "vi") {
                let outKeywords = [];
                if (network == "web") network = "";
                let hl = language === "vn" ? "vi" : language;
                
                // Set timeout for API call
                var timeout = setTimeout(function() {
                    $('.suggestion-loading-indicator').html('<p style="color: #e74c3c;">Request timeout. Please try again.</p>');
                }, 10000);
                
                $.getJSON("https://suggestqueries-clients6.youtube.com/complete/search?client=youtube&callback=?", {
                    "hl": hl,
                    "ds": network,
                    "jsonp": "suggestCallBack",
                    "q": keywordTxt,
                    "client": "chrome"
                }).fail(function() {
                    clearTimeout(timeout);
                    $('.suggestion-loading-indicator').html('<p style="color: #e74c3c;">Failed to fetch suggestions. Please check your internet connection and try again.</p>');
                });
                
                window.suggestCallBack = function (data) {
                    clearTimeout(timeout);
                    var suggestions = [];
                    if (data && data[1] && data[1].length > 0) {
                        $.each(data[1], function (key, val) {
                            outKeywords.push(val);
                        });
                        renderTableSuggesstion(outKeywords);
                    } else {
                        $('.suggestion-loading-indicator').html('<p style="color: #f39c12;">No suggestions found for this keyword.</p>');
                    }
                };
            }
            
            // Get suggestions button click
            $('#open-suggestion-modal-btn').on('click', function() {
                var keywords = $('#keywords').val().trim();
                var language = $('#language').val();
                
                if (!keywords) {
                    alert('Please enter at least one keyword to get suggestions.');
                    return;
                }
                
                // Get the first keyword for suggestions
                var firstKeyword = keywords.split('\n')[0].trim();
                
                var modalHtml = `
                    <div class="modal-overlay">
                        <div class="modal-content">
                            <h2><i class="fa-solid fa-magnifying-glass"></i> Get Keyword Suggestions</h2>
                            <p>Getting suggestions for: <strong>"${firstKeyword}"</strong></p>
                            <div class="suggestion-loading-indicator">
                                <p>Fetching suggestions from Google...</p>
                                <div class="loader"></div>
                            </div>
                            <div class="suggestion-results-container">
                                <p><strong>Suggested keywords:</strong></p>
                                <textarea id="secondKeywords" class="ft-code-textarea secondKeywords" style="height:200px" placeholder="Suggested keywords will appear here..."></textarea>
                                <div class="keyword-actions">
                                    <button type="button" id="add-suggestions-btn" class="ft-submit">Add to Main Keywords</button>
                                    <button type="button" id="clear-suggestions-btn" class="ft-submit">Clear</button>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="ft-submit" id="close-suggestion-modal-btn">Close</button>
                            </div>
                        </div>
                    </div>
                `;
                
                // Append modal to body
                $('body').append(modalHtml);
                
                // Show modal
                $('.modal-overlay').fadeIn(300);
                
                // Get suggestions
                getKeywordsSuggestion(firstKeyword, "web", language);
            });
            
            // Close modal button (using event delegation)
            $(document).on('click', '#close-suggestion-modal-btn', function() {
                $('.modal-overlay').fadeOut(300, function() {
                    $(this).remove();
                });
            });
            
            // Close modal when clicking overlay
            $(document).on('click', '.modal-overlay', function(e) {
                if (e.target === this) {
                    $(this).fadeOut(300, function() {
                        $(this).remove();
                    });
                }
            });
            
            // Add suggestions button (using event delegation)
            $(document).on('click', '#add-suggestions-btn', function() {
                var suggestedKeywords = $('#secondKeywords').val().trim();
                if (!suggestedKeywords) {
                    if (typeof aiautotool_alert_error !== 'undefined') {
                        aiautotool_alert_error('<?php echo esc_js(__('No suggestions to add.', 'ai-auto-tool')); ?>', '');
                    } else {
                        alert('<?php echo esc_js(__('No suggestions to add.', 'ai-auto-tool')); ?>');
                    }
                    return;
                }
                
                var mainKeywords = $('#keywords').val().trim();
                var mergedKeywords = mainKeywords;
                
                if (mainKeywords.length > 0) {
                    mergedKeywords += "\n";
                }
                mergedKeywords += suggestedKeywords;
                
                $('#keywords').val(mergedKeywords);
                updateKeywordCount();
                
                // Show success message
                $('#keywords-result').html('<div class="updated"><p><strong><?php echo esc_js(__('Suggested keywords added successfully!', 'ai-auto-tool')); ?></strong></p></div>');
                
                // Close modal
                $('.modal-overlay').fadeOut(300, function() {
                    $(this).remove();
                });
            });
            
            // Clear suggestions button (using event delegation)
            $(document).on('click', '#clear-suggestions-btn', function() {
                $('#secondKeywords').val('');
            });
            
            // Cron Job Management
            var statusPollInterval = null;
            
            $('#run-cron-now').on('click', function() {
                var button = $(this);
                var originalText = button.text();
                
                button.prop('disabled', true).text('Running...');
                
                // Clear any existing polling
                if (statusPollInterval) {
                    clearInterval(statusPollInterval);
                    statusPollInterval = null;
                }
                
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'run_keyword_cron_now',
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            var message = response.data && response.data.message ? response.data.message : 'Cron job executed successfully!';
                            var pendingCount = response.data && response.data.pending_count ? response.data.pending_count : 0;
                            var processingKeyword = response.data && response.data.processing_keyword ? response.data.processing_keyword : null;
                            
                            if (processingKeyword) {
                                $('#keywords-result').html('<div class="updated"><p>' + message + ' Processing keyword: <strong>' + processingKeyword.keyword + '</strong></p></div>');
                            } else {
                                $('#keywords-result').html('<div class="updated"><p>' + message + ' Checking status...</p></div>');
                            }
                            
                            // Refresh immediately
                            refreshCronStatus();
                            loadKeywordQueue();
                            
                            // Start polling status every 2 seconds for up to 60 seconds
                            var pollCount = 0;
                            var maxPolls = 30; // 30 polls * 2 seconds = 60 seconds max
                            
                            statusPollInterval = setInterval(function() {
                                pollCount++;
                                refreshCronStatus();
                                loadKeywordQueue();
                                
                                // Check if processing is active
                                var processingItem = $('#current-processing .processing-item.active');
                                if (processingItem.length === 0 && pollCount >= 3) {
                                    // No active processing after a few polls, stop polling
                                    clearInterval(statusPollInterval);
                                    statusPollInterval = null;
                                } else if (pollCount >= maxPolls) {
                                    // Stop polling after max time
                                    clearInterval(statusPollInterval);
                                    statusPollInterval = null;
                                }
                            }, 2000); // Poll every 2 seconds
                            
                        } else {
                            var errorMsg = 'Error running cron job';
                            if (response.data && response.data.message) {
                                errorMsg = response.data.message;
                            }
                            $('#keywords-result').html('<div class="error"><p>' + errorMsg + '</p></div>');
                            
                            // Still refresh to show current status
                            refreshCronStatus();
                            loadKeywordQueue();
                        }
                    },
                    error: function() {
                        $('#keywords-result').html('<div class="error"><p>Error running cron job</p></div>');
                    },
                    complete: function() {
                        button.prop('disabled', false).text(originalText);
                    }
                });
            });
            
            $('#schedule-cron').on('click', function() {
                var button = $(this);
                var originalText = button.text();
                
                button.prop('disabled', true).text('Scheduling...');
                
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'schedule_keyword_cron',
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#keywords-result').html('<div class="updated"><p>Cron job scheduled successfully!</p></div>');
                            refreshCronStatus();
                            loadKeywordQueue();
                        } else {
                            $('#keywords-result').html('<div class="error"><p>Error scheduling cron job: ' + (response.data || 'Unknown error') + '</p></div>');
                        }
                    },
                    error: function() {
                        $('#keywords-result').html('<div class="error"><p>Error scheduling cron job</p></div>');
                    },
                    complete: function() {
                        button.prop('disabled', false).text(originalText);
                    }
                });
            });
            
            $('#refresh-cron-status').on('click', function() {
                refreshCronStatus();
                loadKeywordQueue();
            });
            
            function refreshCronStatus() {
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'get_cron_status',
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#cron-status').html(response.data.status);
                            $('#next-run-time').html(response.data.next_run);
                            $('#last-run-time').html(response.data.last_run);
                            $('#current-processing').html(response.data.processing_html);
                        }
                    }
                });
            }
            
            // Auto-refresh every 30 seconds
            setInterval(function() {
                if ($('#tab-keyword-queue').is(':visible')) {
                    refreshCronStatus();
                    
                    // Also refresh the keyword queue table
                    var currentPage = $('.pagination-btn.active').data('page') || 1;
                    var currentFilter = $('#status-filter').val() || 'all';
                    var currentSearch = $('#keyword-search').val() || '';
                    var currentSortOrder = $('#sort-order').val() || 'recent-completed';
                    
                    $.ajax({
                        url: aiautotool_js_setting.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'get_keyword_queue',
                            page: currentPage,
                            filter: currentFilter,
                            search: currentSearch,
                            sort_order: currentSortOrder,
                            security: aiautotool_js_setting.security
                        },
                        success: function(response) {
                            if (response.success) {
                                $('#keyword-queue-table').html(response.data);
                            }
                        }
                    });
                }
            }, 30000);
            
            // Select all keywords
            $(document).on('change', '#select-all-keywords', function() {
                var isChecked = $(this).is(':checked');
                $('.keyword-checkbox').prop('checked', isChecked);
                updateSelectedCount();
            });
            
            // Individual keyword selection
            $(document).on('change', '.keyword-checkbox', function() {
                updateSelectedCount();
                
                // Update select all checkbox
                var totalCheckboxes = $('.keyword-checkbox').length;
                var checkedCheckboxes = $('.keyword-checkbox:checked').length;
                
                if (checkedCheckboxes === 0) {
                    $('#select-all-keywords').prop('indeterminate', false).prop('checked', false);
                } else if (checkedCheckboxes === totalCheckboxes) {
                    $('#select-all-keywords').prop('indeterminate', false).prop('checked', true);
                } else {
                    $('#select-all-keywords').prop('indeterminate', true);
                }
            });
            
            function updateSelectedCount() {
                var selectedCount = $('.keyword-checkbox:checked').length;
                // You can add a counter display here if needed
            }
            
            // View error details
            $(document).on('click', '.view-error', function() {
                var keywordId = $(this).data('id');
                var errorRow = $('.error-details[data-error-for="' + keywordId + '"]');
                
                if (errorRow.is(':visible')) {
                    errorRow.hide();
                } else {
                    $('.error-details').hide();
                    errorRow.show();
                }
            });
            
            // Bulk delete selected keywords
            $(document).on('click', '#bulk-delete-keywords', function() {
                var selectedKeywords = $('.keyword-checkbox:checked').map(function() {
                    return $(this).val();
                }).get();
                
                if (selectedKeywords.length === 0) {
                    alert('Please select keywords to delete.');
                    return;
                }
                
                if (confirm('Are you sure you want to delete ' + selectedKeywords.length + ' selected keywords?')) {
                    $.ajax({
                        url: aiautotool_js_setting.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'bulk_delete_keywords',
                            keyword_ids: selectedKeywords,
                            security: aiautotool_js_setting.security
                        },
                        success: function(response) {
                            if (response.success) {
                                // Refresh the table
                                $.ajax({
                                    url: aiautotool_js_setting.ajax_url,
                                    type: 'POST',
                                    data: {
                                        action: 'get_keyword_queue',
                                        page: 1,
                                        security: aiautotool_js_setting.security
                                    },
                                    success: function(tableResponse) {
                                        if (tableResponse.success) {
                                            $('#keyword-queue-table').html(tableResponse.data);
                                        }
                                    }
                                });
                                $('#keywords-result').html('<div class="updated"><p>Keywords deleted successfully!</p></div>');
                            } else {
                                $('#keywords-result').html('<div class="error"><p>Error deleting keywords</p></div>');
                            }
                        }
                    });
                }
            });
            
            // Bulk process selected keywords
            $(document).on('click', '#bulk-process-keywords', function() {
                var selectedKeywords = $('.keyword-checkbox:checked').map(function() {
                    return $(this).val();
                }).get();
                
                if (selectedKeywords.length === 0) {
                    alert('Please select keywords to process.');
                    return;
                }
                
                if (confirm('Are you sure you want to process ' + selectedKeywords.length + ' selected keywords?')) {
                    $.ajax({
                        url: aiautotool_js_setting.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'bulk_process_keywords',
                            keyword_ids: selectedKeywords,
                            security: aiautotool_js_setting.security
                        },
                        success: function(response) {
                            if (response.success) {
                                // Refresh the table
                                $.ajax({
                                    url: aiautotool_js_setting.ajax_url,
                                    type: 'POST',
                                    data: {
                                        action: 'get_keyword_queue',
                                        page: 1,
                                        security: aiautotool_js_setting.security
                                    },
                                    success: function(tableResponse) {
                                        if (tableResponse.success) {
                                            $('#keyword-queue-table').html(tableResponse.data);
                                        }
                                    }
                                });
                                $('#keywords-result').html('<div class="updated"><p>Keywords queued for processing!</p></div>');
                            } else {
                                $('#keywords-result').html('<div class="error"><p>Error processing keywords</p></div>');
                            }
                        }
                    });
                }
            });
            
            // Add keywords form
            $('#add-keywords-form').on('submit', function(e) {
                e.preventDefault();
                
                var keywords = $('#keywords').val().trim();
                if (!keywords) {
                    if (typeof aiautotool_alert_error !== 'undefined') {
                        aiautotool_alert_error('<?php echo esc_js(__('Please enter at least one keyword.', 'ai-auto-tool')); ?>', '');
                    } else {
                        alert('<?php echo esc_js(__('Please enter at least one keyword.', 'ai-auto-tool')); ?>');
                    }
                    return;
                }
                
                var $submitBtn = $('#btnSubmitKeywords');
                $submitBtn.prop('disabled', true).addClass('loading');
                
                // Get selected categories as array
                var selectedCategories = [];
                $('.post-category-checkbox:checked').each(function() {
                    selectedCategories.push($(this).val());
                });
                
                // Use first category for backward compatibility (if no categories selected, use 0)
                var categoryId = selectedCategories.length > 0 ? selectedCategories[0] : 0;
                
                // Get prompt selection mode and data
                var promptMode = $('input[name="prompt_selection_mode"]:checked').val();
                var aiautotool_prompt = $('#aiautotool_prompt').val();
                var multiplePromptContents = [];
                
                if (promptMode === 'multiple') {
                    // Get contents from all textareas
                    $('.prompt-content-textarea').each(function() {
                        var promptId = $(this).data('prompt-id');
                        var promptContent = $(this).val();
                        if (promptId && promptContent) {
                            multiplePromptContents.push({
                                id: promptId,
                                content: promptContent
                            });
                        }
                    });
                }
                
                var data = {
                    action: 'add_keywords',
                    keywords: keywords,
                    category_id: categoryId,
                    category_ids: selectedCategories, // Send all selected categories
                    tags: $('input[name="tags"]').val(),
                    auto_generate_tags: $('#auto_generate_tags').prop('checked') ? 1 : 0,
                    language: $('#language').val(),
                    priority: $('#priority').val(),
                    prompt_selection_mode: promptMode,
                    security: aiautotool_js_setting.security
                };
                
                // Add prompt data based on mode
                if (promptMode === 'single' && aiautotool_prompt) {
                    data.aiautotool_prompt = aiautotool_prompt;
                } else if (promptMode === 'multiple' && multiplePromptContents.length > 0) {
                    data.multiple_prompt_contents = JSON.stringify(multiplePromptContents);
                }
                
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        $submitBtn.prop('disabled', false).removeClass('loading');
                        
                        if (response.success) {
                            var resultHtml = '<div class="updated"><p><strong><?php echo esc_js(__('Keywords added successfully!', 'ai-auto-tool')); ?></strong></p><ul style="margin: 10px 0; padding-left: 20px;">';
                            var successCount = 0;
                            var errorCount = 0;
                            
                            response.data.forEach(function(item) {
                                if (item.status === 'added') {
                                    successCount++;
                                    resultHtml += '<li style="color: #27ae60;">✓ ' + item.keyword + '</li>';
                                } else {
                                    errorCount++;
                                    resultHtml += '<li style="color: #e74c3c;">✗ ' + item.keyword + ' - ' + item.status + '</li>';
                                }
                            });
                            
                            resultHtml += '</ul>';
                            resultHtml += '<p><strong>' + successCount + ' <?php echo esc_js(__('keywords added to queue', 'ai-auto-tool')); ?></strong></p>';
                            if (errorCount > 0) {
                                resultHtml += '<p style="color: #e74c3c;">' + errorCount + ' <?php echo esc_js(__('keywords failed', 'ai-auto-tool')); ?></p>';
                            }
                            resultHtml += '</div>';
                            
                            $('#keywords-result').html(resultHtml);
                            $('#keywords').val('');
                            updateKeywordCount();
                            
                            // Scroll to result
                            $('html, body').animate({
                                scrollTop: $('#keywords-result').offset().top - 100
                            }, 500);
                        } else {
                            var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error adding keywords', 'ai-auto-tool')); ?>';
                            $('#keywords-result').html('<div class="error"><p>' + errorMsg + '</p></div>');
                        }
                    },
                    error: function() {
                        $submitBtn.prop('disabled', false).removeClass('loading');
                        $('#keywords-result').html('<div class="error"><p><?php echo esc_js(__('Network error. Please try again.', 'ai-auto-tool')); ?></p></div>');
                    }
                });
            });
            
            // Load keyword queue
            function loadKeywordQueue() {
                $.ajax({
                    url: aiautotool_js_setting.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'get_keyword_queue',
                        security: aiautotool_js_setting.security
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#keyword-queue-table').html(response.data);
                        }
                    }
                });
            }
            
            // Delete keyword
            $(document).on('click', '.delete-keyword', function() {
                if (confirm('Are you sure you want to delete this keyword?')) {
                    var keywordId = $(this).data('id');
                    var row = $(this).closest('tr');
                    
                    $.ajax({
                        url: aiautotool_js_setting.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'delete_keyword',
                            keyword_id: keywordId,
                            security: aiautotool_js_setting.security
                        },
                        success: function(response) {
                            if (response.success) {
                                // Refresh the table to update counts and remove the row
                                $.ajax({
                                    url: aiautotool_js_setting.ajax_url,
                                    type: 'POST',
                                    data: {
                                        action: 'get_keyword_queue',
                                        page: 1,
                                        security: aiautotool_js_setting.security
                                    },
                                    success: function(tableResponse) {
                                        if (tableResponse.success) {
                                            $('#keyword-queue-table').html(tableResponse.data);
                                        }
                                    }
                                });
                            } else {
                                alert('Error deleting keyword');
                            }
                        }
                    });
                }
            });
            
            // Clear keywords log
            $('#clear-keywords-log-button').on('click', function() {
                if (confirm('Are you sure you want to clear the keywords log?')) {
                    $.ajax({
                        url: aiautotool_js_setting.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'clear_keywords_log',
                            security: aiautotool_js_setting.security
                        },
                        success: function(response) {
                            if (response.success) {
                                location.reload();
                            }
                        }
                    });
                }
            });
        });
        </script>
        <?php
    }
    
    public function enqueue_scripts($hook) {
        if (!current_user_can('manage_options') || !is_admin()) {
            return;
        }
        
        $user = wp_get_current_user();
        $user_roles = $user->roles;
        
        if (!in_array('administrator', $user_roles) && !is_super_admin()) {
            return;
        }
        
        // Check if we're on the keyword-autopost page
        $screen = get_current_screen();
        $is_keyword_autopost_page = false;
        
        // Check via GET parameter (most reliable for submenu pages)
        if (isset($_GET['page']) && $_GET['page'] === 'keyword-autopost') {
            $is_keyword_autopost_page = true;
        }
        
        // Check via hook (format: {parent_slug}_page_{menu_slug})
        if (strpos($hook, 'keyword-autopost') !== false || strpos($hook, 'keyword_autopost') !== false) {
            $is_keyword_autopost_page = true;
        }
        
        // Check via screen ID
        if ($screen && (strpos($screen->id, 'keyword-autopost') !== false || strpos($screen->id, 'keyword_autopost') !== false)) {
            $is_keyword_autopost_page = true;
        }
        
        // Enqueue CSS for keyword-autopost page
        if ($is_keyword_autopost_page) {
            $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(dirname(__FILE__))));
            $version = defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0';
            
            // Enqueue Font Awesome
            wp_enqueue_style(
                'font-awesome',
                $plugin_url . 'js/fontawesome/css/all.min.css',
                array(),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0'
            );
            
            // Enqueue main aiautotool.css
            wp_enqueue_style(
                'aiautotool',
                $plugin_url . 'css/aiautotool.css',
                array(),
                $version
            );
            
            // Enqueue SweetAlert2 CSS
            wp_enqueue_style(
                'sweetalert2',
                $plugin_url . 'js/sweetalert2/dist/sweetalert2.min.css',
                array(),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '11.26.3'
            );
            
            // Enqueue SweetAlert2 JS
            wp_enqueue_script(
                'sweetalert2',
                $plugin_url . 'js/sweetalert2/dist/sweetalert2.all.min.js',
                array(),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '11.26.3',
                false
            );
            
            // Enqueue jQuery if not already enqueued
            wp_enqueue_script('jquery');
            
            // Enqueue main aiautotool.js
            wp_enqueue_script(
                'kct_cr_scriptx',
                $plugin_url . 'js/aiautotool.js',
                array('jquery', 'sweetalert2'),
                $version,
                true
            );
            
        $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,
            'reason' => 'freemius_unavailable',
        );

            // Localize script after jQuery is enqueued
        wp_localize_script('jquery', 'aiautotool_js_setting', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'security' => wp_create_nonce('aiautotool_nonce'),
            'freemius_access' => $freemius_access,
            'aiautotool_premium' => ! empty($freemius_access['can_use_pro_features']),
            'is_admin' => true
        ));
        }
    }
    
    // Inherit methods from parent class
    private function aiautotool_has_plugin_data() {
        return get_option($this->plan_limit_aiautotool) !== false;
    }
    
    private function aiautotool_initialize_plugin_data() {
        $current_date = date('Y-m-d');
        $expiration = strtotime('+1 month', strtotime($current_date));
        $expiration = date('Y-m-d', $expiration);
        update_option($this->plan_limit_aiautotool, array('start_date' => $current_date, 'expiration' => $expiration));
    }
    
    public function aiautotool_check_post_limit() {
        $stored_data = get_option($this->plan_limit_aiautotool, array());
        $current_date = date('Y-m-d');
        if ($this->is_new_month($current_date, $stored_data['start_date'])) {
            $expiration = strtotime('+1 month', strtotime($current_date));
            $expiration = date('Y-m-d', $expiration);
            update_option($this->plan_limit_aiautotool, array('start_date' => $current_date, 'expiration' => $expiration));
            update_option($this->usage_option_name, 0, null, 'no');
        }
    }
    
    private function is_new_month($current_date, $start_date) {
        $current_month = date('m', strtotime($current_date));
        $start_month = date('m', strtotime($start_date));
        return ($current_month != $start_month);
    }
    
    public function aiautotool_checklimit($config) {
        return self::check_quota();
    }
    
    public function aiautotool_update_usage() {
        $this->aiautotool_check_post_limit();
        $current_value = get_option($this->usage_option_name, 0);
        $new_value = $current_value + 1;
        if ($this->config['number_post'] != -1) {
            if ($this->config['number_post'] > $new_value) {
                update_option($this->usage_option_name, $new_value, 'no');
            }
        } else {
            update_option($this->usage_option_name, $new_value, 'no');
        }
        return $new_value;
    }
    
    public function render_plan() {
        if ($this->active === 'true' || $this->active === true) {
            $quota = $this->config['number_post'] == -1 ? 'Unlimited' : esc_html($this->config['number_post']);
            echo wp_kses(
                '<p>' . $this->icon . ' ' . esc_html($this->name_plan) . 
                ': <strong>Usage: ' . esc_html($this->config['usage']) . '</strong></p>',
                [
                    'p' => [],
                    'i' => ['class' => []],
                    'strong' => [],
                ]
            );
        }
    }
    
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403);
        }
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, null, 'no');
            wp_send_json_success(array('active' => $active));
        }
        wp_die();
    }
    
    public function bulk_delete_keywords_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $keyword_ids = isset($_POST['keyword_ids']) ? array_map('intval', $_POST['keyword_ids']) : array();
        
        if (empty($keyword_ids)) {
            wp_send_json_error('No keywords selected');
        }
        
        global $wpdb;
        $deleted_count = 0;
        
        foreach ($keyword_ids as $keyword_id) {
            $deleted = $wpdb->delete(
                $this->table_name,
                array('id' => $keyword_id),
                array('%d')
            );
            
            if ($deleted) {
                $deleted_count++;
            }
        }
        
        wp_send_json_success(array(
            'message' => sprintf(__('%d keywords deleted successfully', 'ai-auto-tool'), $deleted_count),
            'deleted_count' => $deleted_count
        ));
    }
    
    public function bulk_process_keywords_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $keyword_ids = isset($_POST['keyword_ids']) ? array_map('intval', $_POST['keyword_ids']) : array();
        
        if (empty($keyword_ids)) {
            wp_send_json_error('No keywords selected');
        }
        
        global $wpdb;
        $updated_count = 0;
        
        foreach ($keyword_ids as $keyword_id) {
            $updated = $wpdb->update(
                $this->table_name,
                array('status' => 'pending'),
                array('id' => $keyword_id, 'status' => 'error'),
                array('%s'),
                array('%d', '%s')
            );
            
            if ($updated) {
                $updated_count++;
            }
        }
        
        wp_send_json_success(array(
            'message' => sprintf(__('%d keywords queued for processing', 'ai-auto-tool'), $updated_count),
            'updated_count' => $updated_count
        ));
    }
    
    public function render_keyword_queue_table($page = 1, $per_page = 20, $filter = 'all', $search = '', $sort_order = 'recent-completed') {
        global $wpdb;
        
        $offset = ($page - 1) * $per_page;
        
        $where_conditions = array();
        $where_values = array();
        
        // Apply status filter
        if ($filter !== 'all') {
            $where_conditions[] = 'status = %s';
            $where_values[] = $filter;
        }
        
        // Apply search filter
        if (!empty($search)) {
            $where_conditions[] = 'keyword LIKE %s';
            $where_values[] = '%' . $wpdb->esc_like($search) . '%';
        }
        
        $where_clause = '';
        if (!empty($where_conditions)) {
            $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
        }
        
        // Get total count for pagination
        $count_query = "SELECT COUNT(*) FROM {$this->table_name} {$where_clause}";
        if (!empty($where_values)) {
            $total_keywords = $wpdb->get_var($wpdb->prepare($count_query, $where_values));
        } else {
            $total_keywords = $wpdb->get_var($count_query);
        }
        
        // Build ORDER BY clause based on sort order
        $order_by = $this->build_order_by_clause($sort_order);
        
        // Get keywords for current page
        $keywords_query = "SELECT * FROM {$this->table_name} 
                           {$where_clause}
                           {$order_by}
                           LIMIT %d OFFSET %d";
        
        $query_values = array_merge($where_values, array($per_page, $offset));
        $keywords = $wpdb->get_results($wpdb->prepare($keywords_query, $query_values));
        
        $total_pages = ceil($total_keywords / $per_page);
        
        $html = '<div class="keyword-queue-controls">';
        $html .= '<div class="queue-filters">';
        $html .= '<input type="text" id="keyword-search" placeholder="' . esc_attr__('Search keywords...', 'ai-auto-tool') . '" class="ft-input-big" value="' . esc_attr($search) . '">';
        $html .= '<select id="status-filter" class="ft-input-big">';
        $html .= '<option value="all"' . selected($filter, 'all', false) . '>' . esc_html__('All Status', 'ai-auto-tool') . '</option>';
        $html .= '<option value="pending"' . selected($filter, 'pending', false) . '>' . esc_html__('Pending', 'ai-auto-tool') . '</option>';
        $html .= '<option value="processing"' . selected($filter, 'processing', false) . '>' . esc_html__('Processing', 'ai-auto-tool') . '</option>';
        $html .= '<option value="completed"' . selected($filter, 'completed', false) . '>' . esc_html__('Completed', 'ai-auto-tool') . '</option>';
        $html .= '<option value="error"' . selected($filter, 'error', false) . '>' . esc_html__('Error', 'ai-auto-tool') . '</option>';
        $html .= '</select>';
        $html .= '<select id="sort-order" class="ft-input-big">';
        $html .= '<option value="recent-completed">' . esc_html__('Recent Completed First', 'ai-auto-tool') . '</option>';
        $html .= '<option value="oldest-first">' . esc_html__('Oldest First', 'ai-auto-tool') . '</option>';
        $html .= '<option value="newest-first">' . esc_html__('Newest First', 'ai-auto-tool') . '</option>';
        $html .= '<option value="priority">' . esc_html__('Priority', 'ai-auto-tool') . '</option>';
        $html .= '</select>';
        $html .= '<button type="button" id="apply-filters" class="ft-submit">' . esc_html__('Apply Filters', 'ai-auto-tool') . '</button>';
        $html .= '</div>';
        $html .= '<div class="bulk-actions">';
        $html .= '<button type="button" id="bulk-delete-keywords" class="ft-submit danger">' . esc_html__('Delete Selected', 'ai-auto-tool') . '</button>';
        $html .= '<button type="button" id="bulk-process-keywords" class="ft-submit">' . esc_html__('Retry Failed', 'ai-auto-tool') . '</button>';
        $html .= '</div>';
        $html .= '</div>';
        
        $html .= '<div class="keyword-table-container">';
        $html .= '<table class="keyword-table">';
        $html .= '<thead>';
        $html .= '<tr>';
        $html .= '<th><input type="checkbox" id="select-all-keywords"></th>';
        $html .= '<th>' . esc_html__('Keyword', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Status', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Priority', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Tags', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Created', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Completed', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Processing Time', 'ai-auto-tool') . '</th>';
        $html .= '<th>' . esc_html__('Actions', 'ai-auto-tool') . '</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';
        
        if ($keywords) {
            foreach ($keywords as $keyword) {
                $status_class = 'status-' . $keyword->status;
                $status_icon = $this->get_status_icon($keyword->status);
                $processing_time = $this->calculate_processing_time($keyword);
                $priority_badge = $this->get_priority_badge($keyword->priority);
                
                $html .= '<tr class="keyword-row" data-id="' . esc_attr($keyword->id) . '">';
                $html .= '<td><input type="checkbox" class="keyword-checkbox" value="' . esc_attr($keyword->id) . '"></td>';
                $html .= '<td class="keyword-text">' . esc_html($keyword->keyword) . '</td>';
                $html .= '<td><span class="' . esc_attr($status_class) . '">' . $status_icon . ' ' . esc_html(ucfirst($keyword->status)) . '</span></td>';
                $html .= '<td>' . $priority_badge . '</td>';
                $html .= '<td class="keyword-tags">' . $this->format_tags_display($keyword->tags) . '</td>';
                $html .= '<td>' . esc_html(date('Y-m-d H:i', strtotime($keyword->created_at))) . '</td>';
                $html .= '<td class="completed-time">' . 
                    ($keyword->processed_at ? 
                        esc_html(date('Y-m-d H:i', strtotime($keyword->processed_at))) : 
                        '<span class="not-completed">' . esc_html__('Not completed', 'ai-auto-tool') . '</span>'
                    ) . '</td>';
                $html .= '<td>' . esc_html($processing_time) . '</td>';
                $html .= '<td class="keyword-actions">';
                
                if ($keyword->status == 'pending') {
                    $html .= '<button class="delete-keyword" data-id="' . esc_attr($keyword->id) . '" title="' . esc_attr__('Delete', 'ai-auto-tool') . '"><i class="fa-solid fa-trash"></i></button>';
                }
                
                if ($keyword->status == 'error') {
                    $html .= '<button class="view-error" data-id="' . esc_attr($keyword->id) . '" title="' . esc_attr__('View Error', 'ai-auto-tool') . '"><i class="fa-solid fa-exclamation-triangle"></i></button>';
                }
                
                if ($keyword->post_id > 0) {
                    $html .= '<a href="' . esc_url(get_edit_post_link($keyword->post_id)) . '" target="_blank" title="' . esc_attr__('View Post', 'ai-auto-tool') . '"><i class="fa-solid fa-external-link-alt"></i></a>';
                }
                
                $html .= '</td>';
                $html .= '</tr>';
                
                // Error details row (hidden by default)
                if ($keyword->status == 'error' && !empty($keyword->error_message)) {
                    $html .= '<tr class="error-details" data-error-for="' . esc_attr($keyword->id) . '" style="display:none;">';
                    $html .= '<td colspan="9">';
                    $html .= '<div class="error-message">';
                    $html .= '<strong>' . esc_html__('Error:', 'ai-auto-tool') . '</strong> ' . esc_html($keyword->error_message);
                    $html .= '</div>';
                    $html .= '</td>';
                    $html .= '</tr>';
                }
            }
        } else {
            $html .= '<tr><td colspan="9" class="no-keywords">' . esc_html__('No keywords found', 'ai-auto-tool') . '</td></tr>';
        }
        
        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>';
        
        // Pagination
        if ($total_pages > 1) {
            $html .= $this->render_pagination($page, $total_pages, $filter, $search);
        }
        
        return $html;
    }
    
    private function render_pagination($current_page, $total_pages, $filter, $search) {
        $html = '<div class="pagination-container">';
        $html .= '<div class="pagination-info">';
        $html .= '<span>' . sprintf(esc_html__('Page %d of %d', 'ai-auto-tool'), $current_page, $total_pages) . '</span>';
        $html .= '</div>';
        $html .= '<div class="pagination-controls">';
        
        // Previous button
        if ($current_page > 1) {
            $html .= '<button type="button" class="pagination-btn" data-page="' . ($current_page - 1) . '" data-filter="' . esc_attr($filter) . '" data-search="' . esc_attr($search) . '">';
            $html .= '<i class="fa-solid fa-chevron-left"></i> ' . esc_html__('Previous', 'ai-auto-tool');
            $html .= '</button>';
        }
        
        // Page numbers
        $start_page = max(1, $current_page - 2);
        $end_page = min($total_pages, $current_page + 2);
        
        for ($i = $start_page; $i <= $end_page; $i++) {
            $active_class = ($i == $current_page) ? 'active' : '';
            $html .= '<button type="button" class="pagination-btn ' . $active_class . '" data-page="' . $i . '" data-filter="' . esc_attr($filter) . '" data-search="' . esc_attr($search) . '">';
            $html .= $i;
            $html .= '</button>';
        }
        
        // Next button
        if ($current_page < $total_pages) {
            $html .= '<button type="button" class="pagination-btn" data-page="' . ($current_page + 1) . '" data-filter="' . esc_attr($filter) . '" data-search="' . esc_attr($search) . '">';
            $html .= esc_html__('Next', 'ai-auto-tool') . ' <i class="fa-solid fa-chevron-right"></i>';
            $html .= '</button>';
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        return $html;
    }
    
    private function validate_and_fix_content($content) {
        // Final validation and cleanup
        $issues_found = array();
        
        // Check for common markdown issues
        if (strpos($content, '```') !== false) {
            $issues_found[] = 'Found markdown code blocks';
            $content = preg_replace('/```[a-zA-Z]*\n(.*?)\n```/s', '<p>$1</p>', $content);
        }
        
        if (strpos($content, '<pre><code') !== false) {
            $issues_found[] = 'Found broken pre/code tags';
            $content = preg_replace('/<pre><code[^>]*>/', '<p>', $content);
            $content = preg_replace('/<\/code><\/pre>/', '</p>', $content);
            $content = preg_replace('/<pre><code>/', '<p>', $content);
            $content = preg_replace('/<\/code><\/pre>/', '</p>', $content);
        }
        
        if (strpos($content, 'language-') !== false) {
            $issues_found[] = 'Found language attributes';
            $content = preg_replace('/class="[^"]*language-[^"]*"/', '', $content);
        }
        
        // Check for DOCTYPE and HTML document tags
        if (strpos($content, '<!DOCTYPE') !== false) {
            $issues_found[] = 'Found DOCTYPE declaration';
            $content = preg_replace('/<!DOCTYPE[^>]*>/i', '', $content);
        }
        
        if (strpos($content, '<html') !== false) {
            $issues_found[] = 'Found HTML tags';
            $content = preg_replace('/<html[^>]*>/i', '', $content);
            $content = preg_replace('/<\/html>/i', '', $content);
        }
        
        if (strpos($content, '<head') !== false) {
            $issues_found[] = 'Found HEAD tags';
            $content = preg_replace('/<head[^>]*>.*?<\/head>/is', '', $content);
        }
        
        if (strpos($content, '<body') !== false) {
            $issues_found[] = 'Found BODY tags';
            $content = preg_replace('/<body[^>]*>/i', '', $content);
            $content = preg_replace('/<\/body>/i', '', $content);
        }
        
        // Check for malformed paragraph tags
        if (strpos($content, '<p><p>') !== false) {
            $issues_found[] = 'Found malformed paragraph tags';
            $content = preg_replace('/<p><p>/', '<p>', $content);
            $content = preg_replace('/<\/p><\/p>/', '</p>', $content);
        }
        
        // Check for unclosed tags
        $open_tags = array();
        preg_match_all('/<(\/?)([a-zA-Z0-9]+)/', $content, $matches);
        
        foreach ($matches[2] as $index => $tag) {
            if ($matches[1][$index] === '/') {
                // Closing tag
                if (end($open_tags) === $tag) {
                    array_pop($open_tags);
                }
            } else {
                // Opening tag (skip self-closing tags)
                if (!in_array($tag, array('img', 'br', 'hr', 'input', 'meta', 'link'))) {
                    $open_tags[] = $tag;
                }
            }
        }
        
        if (!empty($open_tags)) {
            $issues_found[] = 'Found unclosed tags: ' . implode(', ', $open_tags);
            // Close any remaining open tags
            foreach (array_reverse($open_tags) as $tag) {
                $content .= "</{$tag}>";
            }
        }
        
        // Ensure minimum content length
        $text_content = strip_tags($content);
        if (strlen($text_content) < 500) {
            $issues_found[] = 'Content too short';
        }
        
        // Log any issues found
        if (!empty($issues_found)) {
        }
        
        // Final cleanup
        $content = $this->final_content_cleanup($content);
        
        return $content;
    }
    
    private function final_content_cleanup($content) {
        // Remove any remaining DOCTYPE and HTML document elements
        $content = preg_replace('/<!DOCTYPE[^>]*>/i', '', $content);
        $content = preg_replace('/<html[^>]*>/i', '', $content);
        $content = preg_replace('/<\/html>/i', '', $content);
        $content = preg_replace('/<head[^>]*>.*?<\/head>/is', '', $content);
        $content = preg_replace('/<body[^>]*>/i', '', $content);
        $content = preg_replace('/<\/body>/i', '', $content);
        
        // Remove any remaining markdown artifacts
        $content = str_replace(['```', '`'], '', $content);
        
        // Fix any double spaces
        $content = preg_replace('/\s{2,}/', ' ', $content);
        
        // Fix any double line breaks
        $content = preg_replace('/\n\s*\n/', "\n", $content);
        
        // Ensure proper spacing around HTML tags
        $content = preg_replace('/>\s+</', '><', $content);
        
        // Remove any empty paragraphs
        $content = preg_replace('/<p>\s*<\/p>/', '', $content);
        
        // Remove any malformed paragraph tags
        $content = preg_replace('/<p><p>/', '<p>', $content);
        $content = preg_replace('/<\/p><\/p>/', '</p>', $content);
        
        // Ensure content starts and ends properly
        $content = trim($content);
        
        // Add a final paragraph wrapper if content doesn't start with a tag
        if (!preg_match('/^</', $content)) {
            $content = '<p>' . $content . '</p>';
        }
        
        return $content;
    }
    
    private function build_order_by_clause($sort_order) {
        switch ($sort_order) {
            case 'recent-completed':
                return "ORDER BY 
                    CASE 
                        WHEN status = 'completed' THEN 1
                        WHEN status = 'processing' THEN 2
                        WHEN status = 'pending' THEN 3
                        WHEN status = 'error' THEN 4
                    END,
                    CASE 
                        WHEN status = 'completed' THEN processed_at
                        ELSE created_at
                    END DESC";
                
            case 'oldest-first':
                return "ORDER BY created_at ASC";
                
            case 'newest-first':
                return "ORDER BY created_at DESC";
                
            case 'priority':
                return "ORDER BY priority DESC, created_at ASC";
                
            default:
                return "ORDER BY 
                    CASE 
                        WHEN status = 'completed' THEN 1
                        WHEN status = 'processing' THEN 2
                        WHEN status = 'pending' THEN 3
                        WHEN status = 'error' THEN 4
                    END,
                    CASE 
                        WHEN status = 'completed' THEN processed_at
                        ELSE created_at
                    END DESC";
        }
    }
    
    private function generate_tags_from_content($content, $keyword, $language) {
        $bardGenContent = new BardGenContent();
        
        // Get selected model from settings, default to gemini-2.5-flash
        $selected_model = get_option('keyword_autopost_model', 'gemini-2.5-flash');
        
        // Extract text content for analysis
        $text_content = strip_tags($content);
        
        // Limit content length for API call
        $text_content = substr($text_content, 0, 2000);
        
        $prompt = "Analyze this article content and generate 5-8 relevant tags for SEO and content organization.

Article keyword: '{$keyword}'
Language: {$language}

Content preview: " . substr($text_content, 0, 500) . "...

Requirements:
- Generate 5-8 relevant tags
- Tags should be related to the main keyword and content topics
- Use single words or short phrases (2-3 words max)
- Separate tags with commas
- Write in {$language}
- Focus on SEO-friendly terms
- Include the main keyword and related terms
- Avoid generic terms like 'article', 'content', 'information'

Return only the tags separated by commas, no additional text.";

        $tags_response = $bardGenContent->bardcontentfull($prompt, $language, $selected_model);
        
        if (!$tags_response) {
            // Fallback: return keyword-based tags
            return $keyword;
        }
        
        // Clean up the response
        $tags = trim($tags_response);
        
        // Remove any HTML tags that might be returned
        $tags = strip_tags($tags);
        
        // Remove quotes, extra punctuation
        $tags = str_replace(['"', "'", ';', '.'], '', $tags);
        
        // Split by commas and clean each tag
        $tag_array = array_map('trim', explode(',', $tags));
        
        // Filter out empty tags and limit to 8 tags
        $tag_array = array_filter($tag_array, function($tag) {
            return !empty($tag) && strlen($tag) > 1;
        });
        
        // Limit to 8 tags maximum
        $tag_array = array_slice($tag_array, 0, 8);
        
        // If no tags generated, use the keyword
        if (empty($tag_array)) {
            return $keyword;
        }
        
        return implode(',', $tag_array);
    }
    
    private function format_tags_display($tags) {
        if (empty($tags)) {
            return '<span class="no-tags">' . esc_html__('No tags', 'ai-auto-tool') . '</span>';
        }
        
        $tag_array = array_map('trim', explode(',', $tags));
        $tag_array = array_filter($tag_array, function($tag) {
            return !empty($tag) && strlen($tag) > 1;
        });
        
        if (empty($tag_array)) {
            return '<span class="no-tags">' . esc_html__('No tags', 'ai-auto-tool') . '</span>';
        }
        
        $formatted_tags = array();
        foreach ($tag_array as $tag) {
            $formatted_tags[] = '<span class="tag-item">' . esc_html($tag) . '</span>';
        }
        
        return implode(' ', $formatted_tags);
    }
    
    /**
     * Get available models from BardGenContent API
     * @return array Array of models with model_id => model_name
     */
    private function get_available_models() {
        $models = array();
        
        // Try to get models from Bard API
        if (class_exists('BardGenContent')) {
            try {
                $bardGenContent = new BardGenContent();
                $modelsResponse = $bardGenContent->getModels();
                
                if ($modelsResponse && is_array($modelsResponse)) {
                    // Handle OpenAI-compatible format: {'object': 'list', 'data': [...]}
                    if (isset($modelsResponse['data']) && is_array($modelsResponse['data'])) {
                        foreach ($modelsResponse['data'] as $model) {
                            if (isset($model['id']) && !empty($model['id'])) {
                                $modelId = $model['id'];
                                $modelName = $model['id']; // Use ID as display name
                                $models[$modelId] = $modelName;
                            }
                        }
                    }
                    // Handle direct array format
                    elseif (isset($modelsResponse[0]) && is_array($modelsResponse[0]) && isset($modelsResponse[0]['id'])) {
                        foreach ($modelsResponse as $model) {
                            if (isset($model['id']) && !empty($model['id'])) {
                                $modelId = $model['id'];
                                $modelName = $model['id'];
                                $models[$modelId] = $modelName;
                            }
                        }
                    }
                }
            } catch (Exception $e) {
                // Log error if WP_DEBUG is enabled
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
            }
        }
        
        // Fallback to default models if API fails or returns no models
        if (empty($models)) {
            $models = array(
                'gemini-2.5-flash' => 'gemini-2.5-flash',
                'gemini-2.5-flash-lite' => 'gemini-2.5-flash-lite',
                'gemini-2.5-pro' => 'gemini-2.5-pro',
                'gpt-4.1-nano-2025-04-14' => 'gpt-4.1-nano-2025-04-14',
                'gpt-5-mini' => 'gpt-5-mini',
                'gpt-5-chat' => 'gpt-5-chat',
                'deepseek-v3.1' => 'deepseek-v3.1',
                'deepseek-v3.2' => 'deepseek-v3.2',
                'claude-3-7-sonnet' => 'claude-3-7-sonnet',
                'claude-sonnet-4.5' => 'claude-sonnet-4.5',
                'glm-4.5' => 'glm-4.5',
                'glm-4.5-air' => 'glm-4.5-air',
                'mistral-small-3.1-24b-instruct-2503' => 'mistral-small-3.1-24b-instruct-2503',
                'llama-3.3' => 'llama-3.3',
                'qwen3-omni' => 'qwen3-omni'
            );
        }
        
        return $models;
    }
}
}
