<?php
/**
 * AI Auto Tool - Autoblogging Feature
 * Automatically create blog posts from URLs using AI
 * 
 * Features:
 * - URL content extraction
 * - AI-powered content generation
 * - Scheduled posting
 * - Cron job management
 * - Usage tracking and limits
 */

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

// Include markdown parser
require_once dirname(__FILE__) . '/../../../lib/markdown-parser.php';
// Include rendersetting base class
require_once dirname(__FILE__) . '/../../../lib/setting.php';
// Include AI thumbnail generator
require_once dirname(__FILE__) . '/../../../lib/aiautotool_thumbnail_generator.php';

if (!class_exists('AI_AutoTool_Autoblogging')) {
    class AI_AutoTool_Autoblogging extends rendersetting{
    /**
     * Flag to prevent multiple initialization
     */
    private static $initialized = false;
    
    public  $active = true;
    public  $active_option_name = 'AI_AutoTool_Autoblogging_active';
    public  $usage_option_name = 'Schedule_AI_usage';
    public  $icon = '<i class="fa-solid fa-blog"></i>';
   
    protected $postfields = array();
    protected $shortcodes = array();
    protected $htmltags = array();
    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool ;
    public $name_plan ;
    public $config = array();
    public $notice ;
    public function __construct() {
        // Prevent multiple initialization of hooks and actions
        // Check if this instance's class has already been initialized
        $class_name = get_class($this);
        
        // If already initialized, skip hook registration
        if (self::$initialized) {
            // Still set basic properties for this instance
            $this->name_plan = esc_html__('Autoblogging AI','ai-auto-tool');
            $this->active_option_name = 'AI_AutoTool_Autoblogging_active';
            if (class_exists('AIAutoTool_FeatureOptions')) {
                $this->active = AIAutoTool_FeatureOptions::get_option($this->active_option_name, 'false');
            } else {
                $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name;
                $this->active = get_option($normalized_name, 'false');
            }
            return;
        }
        
        // Mark as initialized
        self::$initialized = true;
        
        // Store instance in global variable for standalone functions
        global $aiautotool_scan_instance;
        $aiautotool_scan_instance = $this;
        
        $this->name_plan =  esc_html__('Autoblogging AI','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 to 'false' if not exists (default inactive)
        // Use FeatureOptions to get the option (normalizes the option name)
        if (class_exists('AIAutoTool_FeatureOptions')) {
            $active_option = AIAutoTool_FeatureOptions::get_option($this->active_option_name, 'false');
            if ($active_option === 'false' || $active_option === false) {
                // Option doesn't exist or is false, ensure it's set to 'false' (default inactive)
                AIAutoTool_FeatureOptions::set_option($this->active_option_name, 'false');
                $this->active = 'false';
            } else {
                $this->active = $active_option;
            }
        } else {
            // Fallback: check both normalized and non-normalized option names for backward compatibility
            $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name;
            $active_option = get_option($normalized_name, false);
            if ($active_option === false) {
                // Also check the old non-normalized name
                $active_option = get_option($this->active_option_name, false);
            }
            if ($active_option === false) {
                // Option doesn't exist, set it to 'false' to default inactive (use normalized name)
                update_option($normalized_name, 'false');
                $this->active = 'false';
            } else {
                $this->active = $active_option;
                // Migrate to normalized name if using old name
                if (get_option($normalized_name) === false && get_option($this->active_option_name) !== false) {
                    update_option($normalized_name, $active_option);
                }
            }
        }
        
        // Only run init logic if active
        if ($this->active === 'true' || $this->active === true) {
            $this->init();
        }
        
        // Register AJAX handler only once
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
        add_action('wp_ajax_add_post', array($this, 'add_post_callback'));

    }
    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') {
            $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_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            // Use FeatureOptions if available to normalize option name
            if (class_exists('AIAutoTool_FeatureOptions')) {
                AIAutoTool_FeatureOptions::set_option($this->active_option_name, $active);
            } else {
                // Fallback: ensure option name starts with aiautotool_ if it doesn't
                $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name;
                update_option($normalized_name, $active, null, 'no');
            }
            print_r($active);
        }
        
        wp_die();
    }

    public function init(){
        // Add admin menu and scripts
        add_action('admin_menu', array($this, 'add_menu'));
        add_action('admin_init', array($this, 'aiautotool_check_post_limit'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // IMPORTANT: Register cron schedules early, before any cron events are scheduled
        // This must be done regardless of checklimit to prevent "Event schedule does not exist" errors
        add_filter('cron_schedules', array($this, 'aiautotool_schedule_cron_intervals'));
        add_filter('cron_schedules', array($this, 'schedule_create_content'));
        
        // Register cron action hooks early
        add_action('aiautotool_autoblogging_publish_draft_posts', array($this, 'autoblogging_cron_publish_draft_posts'));
        add_action('aiautotool_autoblogging_generate_content_for_draft', array($this, 'autoblogging_cron_generate_content_for_draft'));
        
        // Initialize configs
        $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
            );
        }
        if ($this->aiautotool_checklimit($this->config)) {
            // Schedule cron events only if limit check passes
            if (!wp_next_scheduled('aiautotool_autoblogging_publish_draft_posts')) {
                wp_schedule_event(time(), 'aiautotool_schedule_cron_intervals', 'aiautotool_autoblogging_publish_draft_posts');
            }
            if (!wp_next_scheduled('aiautotool_autoblogging_generate_content_for_draft')) {
                wp_schedule_event(time(), 'schedule_create_content', 'aiautotool_autoblogging_generate_content_for_draft');
            }
        }else{
             $this->notice->add_notice(
                                AIAUTOTOOL_TITLE_UPGRADE,
                                'notice-error',
                                null,
                                true,
                                'aiautotool'
                            );
        }
        add_action('wp_ajax_add_post', array($this, 'add_post_callback'));
        add_action('rest_api_init', array($this, 'register_aiautotool_scan_route'));
        
        // Flush rewrite rules if endpoint registration version changed
        $this->maybe_flush_rewrite_rules();
        
        add_action('wp_ajax_clear_log_action', array($this, 'clear_log_action_callback'));
        add_action('url_scanner_clear_log_cron', array($this, 'clear_log_action_callback'));
        if (!wp_next_scheduled('url_scanner_clear_log_cron')) {
            wp_schedule_event(time(), 'twicedaily', 'url_scanner_clear_log_cron');
        }
         add_action('wp_ajax_aiautotool_idea_title_post', array($this, 'aiautotool_idea_title_post'));
         add_action('wp_ajax_run_autoblogging_cron', array($this, 'run_autoblogging_cron_callback'));
    }
    
    public function render_setting() {
        ?>
        <div id="tab-scan-setting" class="tab-content" style="display:none;">
            <h2><?php echo wp_kses_post($this->icon); ?> <?php esc_html_e('Schedule Post','ai-auto-tool'); ?></h2>
            <?php
        if (!current_user_can('manage_options')) {
            return;
        }
        if (isset($_POST['aiautotool_draft_public_save_settings'])) {
            $translate_interval = intval($_POST['aiautotool_draft_public_time']); 
            update_option('aiautotool_draft_public_time', $translate_interval,null, 'no');
             $number_post = intval($_POST['aiautotool_draft_public_number_post']); 
            update_option('aiautotool_draft_public_number_post', $number_post,null, 'no');
            $aiautotool_draft_public_turnoff_auto_images = isset($_POST['turnoff_auto_images']) ? true : false; 
            update_option('aiautotool_draft_public_turnoff_auto_images', $aiautotool_draft_public_turnoff_auto_images,null, 'no');
            $default_language = sanitize_text_field($_POST['aiautotool_default_language']); 
            update_option('aiautotool_default_language', $default_language,null, 'no');
            $autoblogging_model = isset($_POST['aiautotool_autoblogging_model']) ? sanitize_text_field(wp_unslash($_POST['aiautotool_autoblogging_model'])) : '';
            update_option('aiautotool_autoblogging_model', $autoblogging_model,null, 'no');
            echo '<div class="updated"><p>Settings saved.</p></div>';
        }
        $current_interval = get_option('aiautotool_draft_public_time', 5);
        $number_post = get_option('aiautotool_draft_public_number_post', 1);
        $aiautotool_draft_public_turnoff_auto_images = get_option('aiautotool_draft_public_turnoff_auto_images', false);
        $default_language = get_option('aiautotool_default_language', 'vi');
        $autoblogging_model = get_option('aiautotool_autoblogging_model', '');
        $languages = $this->languageCodes;
        ?>
        <div class="wrap">
            <form method="post" action="">
                 <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                    <?php esc_html_e('Time public Draft','ai-auto-tool'); ?>
                    </p>
                     <select id="aiautotool_draft_public_time" name="aiautotool_draft_public_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>
                            <option value="180" <?php selected($current_interval, 180); ?>>3 hour</option>
                            <option value="300" <?php selected($current_interval, 300); ?>>5 hour</option>
                            <option value="600" <?php selected($current_interval, 600); ?>>10 hour</option>
                            <option value="900" <?php selected($current_interval, 900); ?>>15 hour</option>
                            <option value="1440" <?php selected($current_interval, 1440); ?>>24 hour</option>
                        </select>
                <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                   <?php esc_html_e('Number Post for one public Draft','ai-auto-tool'); ?>:
                    </p>
                <select id="aiautotool_draft_public_number_post" name="aiautotool_draft_public_number_post">
                            <option value="1" <?php selected($number_post, 1); ?>>1</option>
                            <option value="2" <?php selected($number_post, 2); ?>>2</option>
                            <option value="3" <?php selected($number_post, 3); ?>>3</option>
                        </select>
                <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                   <?php esc_html_e('Default Language for Auto Generated Posts','ai-auto-tool'); ?>:
                    </p>
                <select id="aiautotool_default_language" name="aiautotool_default_language">
                    <?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>
                <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                   <?php esc_html_e('AI Provider / Model for Content Generation','ai-auto-tool'); ?>:
                    </p>
                <select id="aiautotool_autoblogging_model" name="aiautotool_autoblogging_model">
                    <?php 
                    $available_models = $this->get_available_models();
                    if ($autoblogging_model !== '' && !isset($available_models[$autoblogging_model])) {
                        $autoblogging_model = '';
                        update_option('aiautotool_autoblogging_model', $autoblogging_model, false);
                    }
                    foreach ($available_models as $model_id => $model_name) {
                        echo '<option value="' . esc_attr($model_id) . '" ' . selected($autoblogging_model, $model_id, false) . '>' . esc_html($model_name) . '</option>';
                    }
                    ?>
                </select>
                <p class="ft-note"><i class="fa-solid fa-lightbulb"></i>
                   <?php esc_html_e('Turn off auto image when public post','ai-auto-tool'); ?>:
                    </p>

                     <label class="nut-switch">
                                    <input type="checkbox" name="turnoff_auto_images" id="turnoff_auto_images"  value="1" <?php if ( isset( $aiautotool_draft_public_turnoff_auto_images) && true ==  $aiautotool_draft_public_turnoff_auto_images ) echo 'checked="checked"'; ?>>
                                    <span class="slider"></span></label>
                                    <label class="ft-label-right"><?php esc_html_e('Disable auto Image in post.','ai-auto-tool'); ?></label>
                                    </p>

                <p class="submit">
                    <input type="submit" name="aiautotool_draft_public_save_settings" class=" ft-submit" value="<?php esc_html_e('Save Configuration','ai-auto-tool'); ?>" />
                </p>
            </form>
            <hr>
            
          
            
        </div>
        </div>
            <?php
    }
    public function render_tab_setting() {
        if ($this->active=='true') {
        echo '<button href="#tab-scan-setting" class="nav-tab sotab"> '. wp_kses_post($this->icon).' '.esc_html__('Autoblogging AI post','ai-auto-tool').'</button>';
        }
    }
    function add_post_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $languageCodes =  $this->languageCodes;
        $post_titles = sanitize_textarea_field($_POST['post_titles']);
        // Handle multiple categories
        $post_categories = array();
        if (isset($_POST['post_category']) && is_array($_POST['post_category'])) {
            $post_categories = array_map('intval', $_POST['post_category']);
            $post_categories = array_filter($post_categories); // Remove empty values
        } elseif (isset($_POST['post_category'])) {
            // Fallback for single category (backward compatibility)
            $post_categories = array(intval($_POST['post_category']));
        }
        // If no categories selected, use default (empty array)
        if (empty($post_categories)) {
            $post_categories = array();
        }
        $post_tags = sanitize_text_field($_POST['post_tags']);
        $post_language = sanitize_text_field($_POST['post_language']);
        $anchor_text = wp_kses_post($_POST['anchor_text']);
        $auto_change_title = 0;//isset($_POST['auto_change_title']) ? true : false;
        $auto_generate_tags = isset($_POST['auto_generate_tags']) ? 1 : 0; 
        
        // 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'])
                            );
                        }
                    }
                }
            }
        } else if ($prompt_mode === 'auto') {
            // Auto prompt mode - no prompt needed, will use generate_article_from_title
            $aiautotool_prompt = '';
        }
        
        // Get post author mode and selected user
        $post_author_mode = isset($_POST['post_author_mode']) ? sanitize_text_field($_POST['post_author_mode']) : 'random';
        $post_author_user = isset($_POST['post_author_user']) ? intval($_POST['post_author_user']) : 0;

        $titles = explode(PHP_EOL, $post_titles);
        $user_id = '';
        
        // Get users based on author mode
        $user_ids = array();
        if ($post_author_mode === 'random_no_admin') {
            // Get all users except admin
            $all_users = get_users(array('fields' => 'ID'));
            foreach ($all_users as $uid) {
                $user_obj = get_userdata($uid);
                if ($user_obj && !in_array('administrator', $user_obj->roles)) {
                    $user_ids[] = $uid;
                }
            }
            if (empty($user_ids)) {
                // Fallback to all users if no non-admin users found
                $user_ids = get_users(array('fields' => 'ID'));
            }
        } elseif ($post_author_mode === 'list_users' && $post_author_user > 0) {
            // Use selected specific user
            $user_ids = array($post_author_user);
        } else {
            // Random - get all users
            $user_ids = get_users(array('fields' => 'ID'));
        }
        
        $kq = array();
        foreach ($titles as $title) {
            $words = explode(",", $post_tags);
            if (count($words) > 3) {
                        $randomWords = array_rand($words, 3); 
                        $result = [];
                        foreach ($randomWords as $index) {
                            $result[] = $words[$index]; 
                        }
            } else {
                $result = $words; 
            }

            $post_tags = implode(",", $result);
            $title = ucwords(mb_strtolower(html_entity_decode($title)));
            
            // Determine user ID based on mode
            if ($post_author_mode === 'list_users' && $post_author_user > 0) {
                $user_id = $post_author_user;
            } elseif (!empty($user_ids)) {
                $user_id = $user_ids[array_rand($user_ids)];
            } else {
                // Fallback to current user if no users found
                $user_id = get_current_user_id();
            }
            
            // Determine which prompt to use for this post
            $prompt_for_this_post = $aiautotool_prompt;
            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)];
                $prompt_for_this_post = $random_prompt['content'];
            }
            
            $new_post = array(
                'post_title' => $title,
                'post_content' => '',
                'post_name' => sanitize_title($title),
                'post_status' => 'draft',
                'post_author'=>$user_id,
                'post_category' => $post_categories,
                'tags_input' => $post_tags,
                'post_type' => 'post',
                'lang' => $post_language
            );
            $post_id = wp_insert_post($new_post);
            $selectedLanguageName = '';
            if(array_key_exists($post_language, $languageCodes)) {
                $selectedLanguageName = $languageCodes[$post_language];
                if(in_array('polylang/polylang.php', apply_filters('active_plugins', get_option('active_plugins')))){ 
                   pll_set_post_language($post_id, $post_language);
                }

               
            }
            update_post_meta($post_id, 'lang', $selectedLanguageName);
            update_post_meta($post_id, 'aiautotool_prompt', $prompt_for_this_post);
            update_post_meta($post_id, 'auto_change_title', $auto_change_title);
            update_post_meta($post_id, 'aiautotool_linkin', $anchor_text);
            update_post_meta($post_id, 'auto_generate_tags', $auto_generate_tags);
            // Save prompt_mode for later use
            update_post_meta($post_id, 'prompt_selection_mode', $prompt_mode);
            $kq[] = array('title'=>$title,'url_edit'=>get_edit_post_link($post_id));
        }
        wp_send_json_success($kq);
    }
    private function fix_content_spin($content){
        $spintax = new Spintaxkct();
        $content = $spintax->process($content);
        return trim($content);
    }

    public function aiautotool_schedule_cron_intervals($schedules) 
    {
        $current_interval = get_option('aiautotool_draft_public_time', 5);
        $schedules['aiautotool_schedule_cron_intervals'] = array(
            'interval' => intval($current_interval) * 60,
            'display'  => __('aiautotool run generate content for draft', 'ai-auto-tool')
        );
        return $schedules;
    }
    public function schedule_create_content($schedules) {
        $schedules['schedule_create_content'] = array(
            'interval' =>  60, 
            'display' => 'Schedule create content'
        );
        return $schedules;
    }

    public function schedule_cron() {
        if (!wp_next_scheduled('url_scanner_cron')) {
            wp_schedule_event(time(), 'minute', 'url_scanner_cron');
        }
    }
    /**
     * Cron job: Generate content for draft posts that have empty content
     * This function finds draft posts with empty content and generates AI content for them
     * 
     * @return int|null Post ID if a post was created, null otherwise
     */
    public function autoblogging_cron_generate_content_for_draft(){
        // 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') || !is_textdomain_loaded('aiautotool-cron-widget')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        // Set execution time limit for long-running cron jobs (10 minutes)
        @set_time_limit(600);
        @ini_set('max_execution_time', 600);
        @ignore_user_abort(true);
        
        // Load required classes
        if (!class_exists('BardGenContent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        }
        if (!class_exists('Imagescontent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
        }
        if (!class_exists('AIautoTool_log')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/AIautotool_logall.php';
        }
        
        global $wpdb;
        $log = new AIautoTool_log();
        
        // Log immediately that cron was called
        $log->set_log('schedule_gen_content', array(
            'msg' => 'autoblogging_cron_generate_content_for_draft started',
            'timestamp' => current_time('mysql'),
            'memory_usage' => memory_get_usage(true)
        ));
        
        $cron_widget = $this->get_cron_widget();
        
        // Update cron status - starting (only if widget is available)
        $this->update_cron_progress($cron_widget, __('Searching for draft posts...', 'aiautotool-cron-widget'), '', 10);
        
        if (false === ($draft_posts = get_transient('aiautotool_draft_posts'))) {
                $query = $wpdb->prepare(
                    "SELECT ID FROM {$wpdb->prefix}posts 
                    WHERE post_content = '' 
                    AND post_status = 'draft' 
                    AND post_type = 'post'
                    LIMIT 50"
                );
                $draft_posts = $wpdb->get_col($query);
                set_transient('aiautotool_draft_posts', $draft_posts, 24 * HOUR_IN_SECONDS);
        }
        $post_id = array_shift($draft_posts);
        if (!$post_id) {
            // No draft posts found
            $log->set_log('schedule_gen_content', array(
                'msg' => 'No draft posts found to process',
                'draft_posts_count' => count($draft_posts)
            ));
            $this->update_cron_progress($cron_widget, __('No draft posts found to publish', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
            return null;
        }
        
        $log->set_log('schedule_gen_content', array(
            'msg' => 'Found draft post to process',
            'post_id' => $post_id
        ));
        
        $post = get_post($post_id);
        if (!$post) {
            $log->set_log('schedule_gen_content', array(
                'post_id' => $post_id,
                'msg' => 'Error: Post not found in database'
            ));
            $this->update_cron_progress($cron_widget, __('Error: Post not found', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
            return null;
        }
        $attachThumbnail = '';
        
        // Check limit and log
        $limit_check = $this->aiautotool_checklimit($this->config);
        $log->set_log('schedule_gen_content', array(
            'post_id' => $post_id,
            'post_title' => get_the_title($post_id),
            'msg' => 'Checking limit before creating content',
            'limit_check' => $limit_check ? 'passed' : 'failed',
            'config' => $this->config
        ));
        
        if($limit_check){
            $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>get_the_title($post_id),'msg'=>'star run create content'));
            
            // Update status - found post
            $this->update_cron_progress($cron_widget, __('Creating content for post...', 'aiautotool-cron-widget'), get_the_title($post_id), 20);
            
            if ($post) {
                $post_id = $post->ID;
                $auto_generate_title = 0;
                $aiautotool_prompt = get_post_meta($post_id, 'aiautotool_prompt', true);
                $lang = get_post_meta($post_id, 'lang', 'Vietnamese');
                if (empty($lang) || $lang === 'Vietnamese') {
                    $default_language = get_option('aiautotool_default_language', 'vi');
                    $lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
                }
                $aiautotool_linkin = get_post_meta($post_id, 'aiautotool_linkin', true);
                $bardGenContent = new BardGenContent();
                $Imagescontent = new Imagescontent();
                $title = self::fix_years(get_the_title($post_id));
                // Get prompt_mode for this post
                $prompt_mode = get_post_meta($post_id, 'prompt_selection_mode', true);
                if (empty($prompt_mode)) {
                    $prompt_mode = 'single'; // Default to single if not set
                }
                
                $allprompt = get_option('aiautotool_prompt_options',array());
                $auto = true;
                
                // If prompt_mode is 'auto', always use auto mode
                if ($prompt_mode === 'auto') {
                    $auto = true;
                } else if(empty($allprompt)){
                    $auto = true;
                }else{
                    if($aiautotool_prompt==''){
                        if(isset($allprompt['aiautotool_prompt_artcile']))
                        {
                            $artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
                        }
                    }else{
                        $artcle_prompt = $aiautotool_prompt;
                    }
                            
                    $artcle_prompt = str_replace('%%title%%',$title,$artcle_prompt);
                            $content='';
                            $cate = '';
                            $blogtitle = '';
                        $prompt = $this->aiautotool_fix_question($artcle_prompt,$title,$lang,$blogtitle,$cate,$content);
                        $auto = false;
                    
                }
                
                // Get selected provider/model from AI Provider settings.
                $selected_model = get_option('aiautotool_autoblogging_model', '');
                
                // Get provider_id from settings if available
                $provider_id = '';
                if (class_exists('AIAutotool_AI_Provider_Manager')) {
                    $manager = AIAutotool_AI_Provider_Manager::get_instance();
                    $active_provider = $manager->get_active_provider();
                    if ($active_provider) {
                        $provider_id = $active_provider->get_id();
                    }
                }
                
                // Update status - calling AI
                $this->update_cron_progress($cron_widget, __('Calling AI to generate content...', 'aiautotool-cron-widget'), $title, 40);
                
                if($auto){
                        // Use new article generation function with full analysis (same as manual writing)
                        // This is used for both auto mode and when no prompt is set
                        $newcontent = $this->generate_article_from_title($title, $lang, $selected_model, $provider_id);
                        
                        // If generation failed, fallback to old method
                        if ($newcontent === false || empty($newcontent)) {
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                            // Update progress during fallback
                            $this->update_cron_progress($cron_widget, __('Trying alternative method...', 'aiautotool-cron-widget'), $title, 45);
                            $newcontent = $bardGenContent->bardcontentfull($title, $lang, $selected_model);
                        }
                }else{
                        $newcontent = $bardGenContent->bardcontentmore($prompt,$lang, $selected_model);
                }
                
                // Update progress after AI call completes
                $this->update_cron_progress($cron_widget, __('Processing AI response...', 'aiautotool-cron-widget'), $title, 50);
                
                // Check if content is valid string (not array from API error)
                if (is_array($newcontent)) {
                    $error_msg = isset($newcontent['msg']) ? $newcontent['msg'] : 'API returned error';
                    $error_code = isset($newcontent['code']) ? $newcontent['code'] : 'unknown';
                    $log->set_log('schedule_gen_content',array(
                        'post_id'=>$post_id,
                        'post_title'=>$title,
                        'msg'=>'API Error - Code: '.$error_code.', Message: '.$error_msg,
                        'response'=>$newcontent
                    ));
                    $newcontent = ''; // Reset to empty string to prevent saving array
                } else {
                    $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'run bard api create contet post'.(is_string($newcontent) ? substr($newcontent, 0, 100) : '')));
                    // Update progress after content validation
                    $this->update_cron_progress($cron_widget, __('Content generated successfully', 'aiautotool-cron-widget'), $title, 55);
                }
                
                if (!empty($newcontent) && is_string($newcontent)) {
                    $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'create content success, next step find img'));

                    // Update status - content created, finding images
                    $this->update_cron_progress($cron_widget, __('Searching for images...', 'aiautotool-cron-widget'), $title, 60);
                    
                    if (!$this->is_auto_image_disabled()) {
                        $listimg = $bardGenContent->searchimg($title);
                        // Update progress after image search
                        $this->update_cron_progress($cron_widget, __('Images found, processing...', 'aiautotool-cron-widget'), $title, 65);
                    }else{
                        $listimg = false;
                        $this->update_cron_progress($cron_widget, __('Skipping image search...', 'aiautotool-cron-widget'), $title, 65);
                    }
                    
                    
                    $current_content = $post->post_content;
                    $current_content = apply_filters('the_content', $current_content);
                    $current_content = str_replace(']]>', ']]&gt;', $current_content);
                    $current_content = preg_replace('#<img.*?>#i', '', $current_content);

                    $updated_content = $newcontent . $current_content;
                    $updated_content =  self::fix_years($updated_content);
                    
                    $random_count = mt_rand(1, 3);
                    if (!empty($listimg) && is_array($listimg) && is_int($random_count) && $random_count > 0) {
                        $random_count = min($random_count, count($listimg));
                        $random_keys = array_rand($listimg, $random_count);
                    } 

                    
                    if (!empty($listimg) && is_array($listimg)) {
                        $this->update_cron_progress($cron_widget, __('Inserting images into content...', 'aiautotool-cron-widget'), $title, 70);
                        $listimg10 = array_slice($listimg, 0, 10);
                        shuffle($listimg10);
                        $updated_content = $Imagescontent->insertImages($updated_content,$listimg10);
                        $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'Found image success, next step update content to post.'));
                            
                    }else{
                        $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'No found image.'));
                    }
                    
                    // Update status - processing images
                    $this->update_cron_progress($cron_widget, __('Processing images...', 'aiautotool-cron-widget'), $title, 75);
                    
                    $postname = $this->kct_aiautotool_sanitize($title);
                    $html = stripslashes($updated_content);
                    preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
                    $listimg1 =  $matches[1]; 
                    $imgUploaded = array();
                    $attachThumbnail = 0;
                        if (!empty($listimg1)){
                        $total_images = count($listimg1);
                        $image_index = 0;
                        foreach ($listimg1 as $post_image_url){
                            $image_index++;
                            // Update progress during image upload loop
                            $upload_progress = 75 + (($image_index / $total_images) * 5); // 75% to 80%
                            $this->update_cron_progress($cron_widget, sprintf(__('Uploading image %d/%d...', 'aiautotool-cron-widget'), $image_index, $total_images), $title, round($upload_progress));
                            
                            try {
                                            $image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname);
                                            if (!empty($image_url_new)){
                                                $imgUploaded[] = $image_url_new;
                                                if ($attachThumbnail == 0) {
                                                    $attachThumbnail = $image_url_new['attach_id'];
                                                }
                                                    
                                            }
                                        }catch (Exception $e) {
                                        }
                        }
                        }
                        foreach ($imgUploaded as $img){
                        $updated_content = str_replace($img['url'],$img['baseurl'],$updated_content);
                    }
                            
                    if($auto_generate_title != 0){
                        $title = $bardGenContent->gentitle($title,$lang);
                    }
                    
                    // Set thumbnail: use existing or generate AI thumbnail
                    // Wrap in try-catch to prevent errors from blocking post creation
                    try {
                        if ($attachThumbnail != 0) {
                            set_post_thumbnail($post_id, $attachThumbnail);
                        } elseif (!$this->is_auto_image_disabled()) {
                            // Generate AI thumbnail using Pollinations if no thumbnail exists
                            // Let the generator fetch content from post_id automatically
                            $ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, '');
                            if ($ai_thumbnail_id) {
                                set_post_thumbnail($post_id, $ai_thumbnail_id);
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                            }
                        }
                    } catch (Exception $e) {
                        // Log error but don't block post creation
                        $log->set_log('schedule_gen_content',array(
                            'post_id'=>$post_id,
                            'post_title'=>$title,
                            'msg'=>'Thumbnail generation error: ' . $e->getMessage()
                        ));
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                    }
                    
                    if($aiautotool_linkin!=''){
                        
                        $textadd = self::fix_content_spin($aiautotool_linkin);
                        $updated_content = self::insert_text_after_third_paragraph($updated_content, $textadd);
                        
                    }
                    
                    // Update status - saving post
                    $this->update_cron_progress($cron_widget, __('Saving post...', 'aiautotool-cron-widget'), $title, 90);
                        
                    $post_data = array(
                        'ID' => $post_id,
                        'post_title'=>$title,
                        'post_content' => $updated_content,
                        'post_status'=>'draft'
                    );

                    $post_id = wp_update_post($post_data);
                    
                    // Auto generate tags with AI if enabled
                    $auto_generate_tags = get_post_meta($post_id, 'auto_generate_tags', true);
                    if ($auto_generate_tags == 1) {
                        try {
                            $this->generate_tags_for_post($post_id, $title, $updated_content, $lang);
                        } catch (Exception $e) {
                            $log->set_log('schedule_gen_content', array(
                                'post_id' => $post_id,
                                'post_title' => $title,
                                'msg' => 'Auto generate tags error: ' . $e->getMessage()
                            ));
                        }
                    }
                    
                    $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'create content success and Update content to post draft : '.$title));
                    $this->aiautotool_update_usage();
                    $this->notice->add_notice( 'create content success and Update content to post draft : '.$title , 'notice-info', null, true,$this->name_plan );
                    
                    // Update status - completed
                    $this->update_cron_progress($cron_widget, __('Content creation completed', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
                    
                    // Store post ID for AJAX callback
                    if (defined('DOING_AJAX') && DOING_AJAX) {
                        set_transient('aiautotool_last_created_post_id', $post_id, 60);
                    }
                    
                    wp_reset_postdata();
                    return $post_id; // Return post ID if created successfully
                    
                }else{
                        $log->set_log('schedule_gen_content',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'create content Error '.$title));
                        
                        // Update status - error
                        $this->update_cron_progress($cron_widget, __('Error: Unable to create content', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
                }
                wp_reset_postdata();
            }

            if (!empty($draft_posts)) {
                set_transient('aiautotool_draft_posts', $draft_posts, 24 * HOUR_IN_SECONDS);
            } else {
                delete_transient('aiautotool_draft_posts');
            }
            
            // Return null if no post was created
            return null;
        }else{
            $log->set_log('schedule_gen_content', array(
                'post_id' => $post_id,
                'post_title' => get_the_title($post_id),
                'msg' => 'Usage limit exceeded, cannot create content',
                'config' => $this->config
            ));
            
             $this->notice->add_notice(
                                AIAUTOTOOL_TITLE_UPGRADE,
                                'notice-error',
                                null,
                                true,
                                'aiautotool'
                            );
                            
            // Update status - quota exceeded
            $this->update_cron_progress($cron_widget, __('Usage limit exceeded', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
        }
        
        // Return null if no post was created
        return null;
}

public static function insert_text_after_third_paragraph($content, $text) {
    preg_match_all('/<p(.*?)<\/p>/', $content, $matches, PREG_OFFSET_CAPTURE);

    $total_paragraphs = count($matches[0]);

    $random_position = mt_rand(2, $total_paragraphs - 1);

    if (isset($matches[0][$random_position])) {
        $paragraph_pos = $matches[0][$random_position][1] + strlen($matches[0][$random_position][0]);
        $content = substr($content, 0, $paragraph_pos) . $text . substr($content, $paragraph_pos);
    }

    return $content;
}


    private function process_post_content($post_id, $title, $lang, $auto_generate_title, $log){

    }

    /**
     * Generate tags for a post using AI based on post content
     * 
     * @param int $post_id Post ID
     * @param string $title Post title
     * @param string $content Post content
     * @param string $lang Language
     * @return bool True if tags were generated successfully
     */
    private function generate_tags_for_post($post_id, $title, $content, $lang = 'Vietnamese') {
        // Check if AI Helper is available
        if (!class_exists('AIAutotool_AI_Helper')) {
            return false;
        }
        
        if (!AIAutotool_AI_Helper::is_available()) {
            return false;
        }
        
        // Prepare content excerpt for prompt (limit to avoid token limits)
        $content_excerpt = wp_trim_words(strip_tags($content), 200);
        
        // 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} 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 false;
        }
        
        // Extract tags from AI response
        $ai_tags = trim($result['content']);
        
        // Clean up the response - remove any extra text, keep only tags
        // Remove common prefixes like "Tags:", "Keywords:", etc.
        $ai_tags = preg_replace('/^(tags?|keywords?|labels?)[:\s]*/i', '', $ai_tags);
        $ai_tags = preg_replace('/\n.*$/s', '', $ai_tags); // Remove everything after first line
        $ai_tags = trim($ai_tags, " \n\r\t.,;");
        
        // Split by comma and clean each tag
        $tags_array = array_map('trim', explode(',', $ai_tags));
        $tags_array = array_filter($tags_array, function($tag) {
            return !empty($tag) && strlen($tag) > 1;
        });
        
        // Limit to 8 tags max
        $tags_array = array_slice($tags_array, 0, 8);
        
        if (empty($tags_array)) {
            return false;
        }
        
        // Set tags for the post
        wp_set_post_tags($post_id, $tags_array, false);
        
        return true;
    }

    /**
     * Cron job: Publish draft posts with content (Legacy method)
     * This is the legacy version that uses transient for draft posts list
     */
    public function autoblogging_cron_publish_draft_posts_legacy() {
        // 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') || !is_textdomain_loaded('aiautotool-cron-widget')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        // Load required classes
        if (!class_exists('BardGenContent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        }
        if (!class_exists('Imagescontent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
        }
        if (!class_exists('AIautoTool_log')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/AIautotool_logall.php';
        }
        
        $log = new AIautoTool_log();
        set_time_limit(300);
        $draft_posts = get_transient('aiautotool_draft_posts_public');
        if (false === $draft_posts) {
            $number_post = get_option('aiautotool_draft_public_number_post', 500);
            $args = array(
                'post_type' => 'post',
                'post_status' => 'draft',
                'posts_per_page' => $number_post,
            );
            $draft_posts_query = new WP_Query($args);

            if ($draft_posts_query->have_posts()) {
                $draft_posts = array();
                while ($draft_posts_query->have_posts()) {
                    $draft_posts_query->the_post();
                    $draft_posts[] = get_the_ID();
                }
                set_transient('aiautotool_draft_posts_public', $draft_posts, 24 * HOUR_IN_SECONDS);
            } else {
                
                return;
            }
        }

        $post_id = array_shift($draft_posts);

        if (!$post_id) {
            delete_transient('aiautotool_draft_posts_public');
            return;
        }

        $content_post = get_post($post_id);
        $current_content = $content_post->post_content;
        if (strlen($current_content) < 255) {
             if($this->aiautotool_checklimit($this->config)){
                $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api'));
                
                        $auto_generate_title = 0;//get_post_meta($post_id, 'auto_generate_title', false);
                        $aiautotool_prompt = get_post_meta($post_id, 'aiautotool_prompt', true);
                        $lang = get_post_meta($post_id, 'lang', 'Vietnamese');
                        // Use default language if post doesn't have language set
                        if (empty($lang) || $lang === 'Vietnamese') {
                            $default_language = get_option('aiautotool_default_language', 'vi');
                            $lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
                        }
                        $aiautotool_linkin = get_post_meta($post_id, 'aiautotool_linkin', true);
                        $bardGenContent = new BardGenContent();
                        $Imagescontent = new Imagescontent();
                        $title = self::fix_years(get_the_title($post_id));
                        
                        // Get prompt_mode for this post
                        $prompt_mode = get_post_meta($post_id, 'prompt_selection_mode', true);
                        if (empty($prompt_mode)) {
                            $prompt_mode = 'single'; // Default to single if not set
                        }
                        
                        $allprompt = get_option('aiautotool_prompt_options',array());
                        $auto = true;
                        
                        // If prompt_mode is 'auto', always use auto mode
                        if ($prompt_mode === 'auto') {
                            $auto = true;
                        } else if(empty($allprompt)){
                            $auto = true;
                        }else{
                            if($aiautotool_prompt==''){
                                if(isset($allprompt['aiautotool_prompt_artcile']))
                                {
                                    $artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
                                }
                            }else{
                                $artcle_prompt = $aiautotool_prompt;
                            }
                                 
                                 $content='';
                                 $cate = '';
                                 $blogtitle = '';
                                $prompt = $this->aiautotool_fix_question($artcle_prompt,$title,$lang,$blogtitle,$cate,$content);
                                $auto = false;
                            
                        }
                        // Get selected provider/model from AI Provider settings.
                        $selected_model = get_option('aiautotool_autoblogging_model', '');
                        
                        // Get provider_id from settings if available
                        $provider_id = '';
                        if (class_exists('AIAutotool_AI_Provider_Manager')) {
                            $manager = AIAutotool_AI_Provider_Manager::get_instance();
                            $active_provider = $manager->get_active_provider();
                            if ($active_provider) {
                                $provider_id = $active_provider->get_id();
                            }
                        }
                        
                        if($auto){
                            // Use new article generation function with full analysis (same as manual writing)
                            $newcontent = $this->generate_article_from_title($title, $lang, $selected_model, $provider_id);
                            
                            // If generation failed, fallback to old method
                            if ($newcontent === false || empty($newcontent)) {
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                $newcontent = $bardGenContent->bardcontentfull($title, $lang, $selected_model);
                            }
                        }else{
                             $newcontent = $bardGenContent->bardcontentmore($prompt,$lang, $selected_model);
                        }

                $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api'));
                 if (!empty($newcontent)) {
                    $listimg = false;
                    if (!$this->is_auto_image_disabled()) {
                        $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api success next step search img'));
                        $listimg = $bardGenContent->searchimg($title);
                    } else {
                        $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'auto image disabled, skip image search'));
                    }
                   
                    $current_content = apply_filters('the_content', $current_content);
                    $current_content = str_replace(']]>', ']]&gt;', $current_content);
                    $current_content = preg_replace('#<img.*?>#i', '', $current_content);

                    $updated_content = $newcontent . $current_content;
                    $updated_content =  self::fix_years($updated_content);
                    // $updated_content = self::preserveHtmlTagsShortcodes($updated_content);
                    $random_count = mt_rand(1, 3);
                    if (!empty($listimg) && is_array($listimg)) {
                        $random_count = min($random_count, count($listimg));
                        $random_keys = array_rand($listimg, $random_count);
                    }


                    if (!empty($listimg) && is_array($listimg)) {

                        $listimg10 = array_slice($listimg, 0, 10);

                        shuffle($listimg10);
                        $updated_content = $Imagescontent->insertImages($updated_content,$listimg10);
                        $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Had found images , add to content'));
                    }else{
                        $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'No found images.'));
                    }
                    $postname = $this->kct_aiautotool_sanitize($title);
                    $html = stripslashes($updated_content);
                    preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
                    $listimg1 =  $matches[1]; 
                    $imgUploaded = array();
                    $attachThumbnail = 0;
                     if (!empty($listimg1)){
                        foreach ($listimg1 as $post_image_url){
                            try {
                                            $image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname);
                                            if (!empty($image_url_new)){
                                                $imgUploaded[] = $image_url_new;
                                                if ($attachThumbnail == 0) {
                                                    $attachThumbnail = $image_url_new['attach_id'];
                                                }
                                                 
                                            }
                                        }catch (Exception $e) {
                                        }
                        }
                     }
                     foreach ($imgUploaded as $img){
                        $updated_content = str_replace($img['url'],$img['baseurl'],$updated_content);
                    }
                            
                    if($auto_generate_title!=0){
                        $title = $bardGenContent->gentitle($title,$lang);
                    }
                    
                    // Set thumbnail: use existing or generate AI thumbnail
                    // Wrap in try-catch to prevent errors from blocking post publish
                    try {
                        if ($attachThumbnail ) {
                            set_post_thumbnail($post_id, $attachThumbnail);
                        } elseif (!$this->is_auto_image_disabled()) {
                            // Generate AI thumbnail using Pollinations if no thumbnail exists
                            // Let the generator fetch content from post_id automatically
                            $ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, '');
                            if ($ai_thumbnail_id) {
                                set_post_thumbnail($post_id, $ai_thumbnail_id);
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                            }
                        }
                    } catch (Exception $e) {
                        // Log error but don't block post publishing
                        $log->set_log('schedule_publish',array(
                            'post_id'=>$post_id,
                            'post_title'=>get_the_title(),
                            'msg'=>'Thumbnail generation error: ' . $e->getMessage()
                        ));
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                    }
                    
                    $post_data = array(
                        'ID' => $post_id,
                        'post_title'=>$title,
                        'post_content' => $updated_content,
                        'post_status'=>'draft'
                    );

                    $post_id = wp_update_post($post_data);
                     $this->update_and_publish_post( $post_id );
                    $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
                    $this->aiautotool_update_usage();
                }else{
                     $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content Error 1 '.$title));
                }
            }else{
                $this->notice->add_notice(
                    AIAUTOTOOL_TITLE_UPGRADE,
                    'notice-error',
                    null,
                    true,
                    $this->name_plan
                );

            }
            set_transient('aiautotool_draft_posts_public', $draft_posts, 24 * HOUR_IN_SECONDS);
        } else {
            $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api and next step: publish post has content post.'));
            $result = $this->update_and_publish_post( $post_id );

            $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
        }

        wp_reset_postdata();
    }

    /**
     * Cron job: Publish draft posts that have content
     * This function finds draft posts with content and publishes them automatically
     */
    public function autoblogging_cron_publish_draft_posts() {
        // 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') || !is_textdomain_loaded('aiautotool-cron-widget')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        // Load required classes
        if (!class_exists('BardGenContent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        }
        if (!class_exists('Imagescontent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
        }
        if (!class_exists('AIautoTool_log')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/AIautotool_logall.php';
        }
        
        set_time_limit(300);
        $log = new AIautoTool_log();
        $cron_widget = $this->get_cron_widget();
        
        // Debug: Start cron task
        $log->set_log('cron_task_debug', array(
            'step' => 'START',
            'msg' => 'Cron task bắt đầu chạy',
            'timestamp' => current_time('mysql')
        ));
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        // Update cron status - starting publish task
        $this->update_cron_progress($cron_widget, __('Searching for posts to publish...', 'aiautotool-cron-widget'), '', 10);
        
        $number_post = get_option('aiautotool_draft_public_number_post', 1);
        $args = array(
            'post_type' => 'post',
            'post_status' => 'draft',
            'posts_per_page' => $number_post, 
        );

        $draft_posts = new WP_Query($args);
        
        // Debug: Found posts
        $log->set_log('cron_task_debug', array(
            'step' => 'FIND_POSTS',
            'msg' => 'Tìm thấy ' . $draft_posts->found_posts . ' bài viết draft',
            'posts_count' => $draft_posts->found_posts,
            'posts_per_page' => $number_post
        ));
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }

        if ($draft_posts->have_posts()) {
            $post_index = 0;
            while ($draft_posts->have_posts()) {
                $draft_posts->the_post();
                $post_id = get_the_ID();
                $post_index++;
                $post_title = get_the_title($post_id);
                $content_post = get_post($post_id);
                $current_content = $content_post->post_content;
                
                // Debug: Start processing post
                $log->set_log('cron_task_debug', array(
                    'step' => 'PROCESS_POST',
                    'post_id' => $post_id,
                    'post_title' => $post_title,
                    'post_index' => $post_index,
                    'total_posts' => $draft_posts->found_posts,
                    'current_content_length' => strlen($current_content),
                    'msg' => "Bắt đầu xử lý bài viết #{$post_index}: {$post_title} (ID: {$post_id})"
                ));
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                if(strlen($current_content) < 255){
                        if($this->aiautotool_checklimit($this->config)){
                            // Initialize variables before using them
                            $auto_generate_title = 0;
                            $aiautotool_prompt = get_post_meta($post_id, 'aiautotool_prompt', true);
                            $lang = get_post_meta($post_id, 'lang', 'Vietnamese');
                            if (empty($lang) || $lang === 'Vietnamese') {
                                $default_language = get_option('aiautotool_default_language', 'vi');
                                $lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
                            }
                            $aiautotool_linkin = get_post_meta($post_id, 'aiautotool_linkin', true);
                            $bardGenContent = new BardGenContent();
                            $Imagescontent = new Imagescontent();
                            $title = self::fix_years(get_the_title($post_id));
                            
                            // Get prompt_mode for this post
                            $prompt_mode = get_post_meta($post_id, 'prompt_selection_mode', true);
                            if (empty($prompt_mode)) {
                                $prompt_mode = 'single'; // Default to single if not set
                            }
                            
                            $allprompt = get_option('aiautotool_prompt_options',array());
                            $auto = true;
                            
                            // If prompt_mode is 'auto', always use auto mode
                            if ($prompt_mode === 'auto') {
                                $auto = true;
                            } else if(empty($allprompt)){
                                $auto = true;
                            }else{
                                if($aiautotool_prompt==''){
                                    if(isset($allprompt['aiautotool_prompt_artcile']))
                                    {
                                        $artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
                                    }
                                }else{
                                    $artcle_prompt = $aiautotool_prompt;
                                }
                                        
                                $artcle_prompt = str_replace('%%title%%',$title,$artcle_prompt);
                                $content='';
                                $cate = '';
                                $blogtitle = '';
                                $prompt = $this->aiautotool_fix_question($artcle_prompt,$title,$lang,$blogtitle,$cate,$content);
                                $auto = false;
                            }
                            
                            // Get selected provider/model from AI Provider settings.
                            $selected_model = get_option('aiautotool_autoblogging_model', '');
                            
                            // Debug: Content generation type
                            $content_gen_type = $auto ? 'AUTO' : 'MANUAL_PROMPT';
                            $log->set_log('cron_task_debug', array(
                                'step' => 'CONTENT_GEN_TYPE',
                                'post_id' => $post_id,
                                'post_title' => $title,
                                'content_gen_type' => $content_gen_type,
                                'prompt_mode' => $prompt_mode,
                                'selected_model' => $selected_model,
                                'language' => $lang,
                                'msg' => "Loại gen content: {$content_gen_type} | Model: {$selected_model} | Ngôn ngữ: {$lang}"
                            ));
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                if (!$auto) {
                                }
                            }
                            
                            $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api'));
                            
                            // Update status - found post to process
                            $this->update_cron_progress($cron_widget, __('Creating content for post to publish...', 'aiautotool-cron-widget'), get_the_title($post_id), 20);
                            
                            // Update status - calling AI
                            $this->update_cron_progress($cron_widget, __('Calling AI to generate content...', 'aiautotool-cron-widget'), $title, 40);
                            
                            // Get provider_id from settings if available
                            $provider_id = '';
                            if (class_exists('AIAutotool_AI_Provider_Manager')) {
                                $manager = AIAutotool_AI_Provider_Manager::get_instance();
                                $active_provider = $manager->get_active_provider();
                                if ($active_provider) {
                                    $provider_id = $active_provider->get_id();
                                }
                            }
                            
                            // Debug: Before calling AI
                            $log->set_log('cron_task_debug', array(
                                'step' => 'CALLING_AI',
                                'post_id' => $post_id,
                                'post_title' => $title,
                                'content_gen_type' => $content_gen_type,
                                'msg' => "Đang gọi AI để gen content..."
                            ));
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                            
                            if($auto){
                                // Use new article generation function with full analysis (same as manual writing)
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'AI_GENERATE_AUTO',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'method' => 'generate_article_from_title',
                                    'msg' => "Sử dụng phương thức AUTO: generate_article_from_title"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                                $newcontent = $this->generate_article_from_title($title, $lang, $selected_model, $provider_id);
                                
                                // If generation failed, fallback to old method
                                if ($newcontent === false || empty($newcontent)) {
                                    $log->set_log('cron_task_debug', array(
                                        'step' => 'AI_FALLBACK',
                                        'post_id' => $post_id,
                                        'post_title' => $title,
                                        'method' => 'bardcontentfull',
                                        'msg' => "AUTO generation failed, fallback sang bardcontentfull"
                                    ));
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                    $this->update_cron_progress($cron_widget, __('Trying alternative method...', 'aiautotool-cron-widget'), $title, 45);
                                    $newcontent = $bardGenContent->bardcontentfull($title, $lang, $selected_model);
                                }
                            }else{
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'AI_GENERATE_MANUAL',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'method' => 'bardcontentmore',
                                    'msg' => "Sử dụng phương thức MANUAL: bardcontentmore với prompt"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                 $newcontent = $bardGenContent->bardcontentmore($prompt,$lang, $selected_model);
                            }
                            
                            // Update progress after AI call completes
                            $this->update_cron_progress($cron_widget, __('Processing AI response...', 'aiautotool-cron-widget'), $title, 50);
                            
                            // Debug: After AI response
                            $content_length = is_string($newcontent) ? strlen($newcontent) : 0;
                            $log->set_log('cron_task_debug', array(
                                'step' => 'AI_RESPONSE',
                                'post_id' => $post_id,
                                'post_title' => $title,
                                'content_length' => $content_length,
                                'is_array' => is_array($newcontent),
                                'msg' => "AI đã trả về response. Độ dài: {$content_length} ký tự"
                            ));
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                if (is_array($newcontent)) {
                                }
                            }

                              // $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'Prompt with create contet post'.$prompt));

                            // Check if content is valid string (not array from API error)
                            if (is_array($newcontent)) {
                                $error_msg = isset($newcontent['msg']) ? $newcontent['msg'] : 'API returned error';
                                $error_code = isset($newcontent['code']) ? $newcontent['code'] : 'unknown';
                                $log->set_log('schedule_publish',array(
                                    'post_id'=>$post_id,
                                    'post_title'=>get_the_title(),
                                    'msg'=>'API Error - Code: '.$error_code.', Message: '.$error_msg,
                                    'response'=>$newcontent
                                ));
                                $newcontent = ''; // Reset to empty string to prevent saving array
                            } else {
                                $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api'));
                                // Update progress after content validation
                                $this->update_cron_progress($cron_widget, __('Content generated successfully', 'aiautotool-cron-widget'), $title, 55);
                            }
                            
                             if (!empty($newcontent) && is_string($newcontent)) {
                                $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api success next step search img'));
                                
                                // Debug: Content created successfully
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'CONTENT_CREATED',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'content_length' => strlen($newcontent),
                                    'msg' => "Content đã được tạo thành công. Bước tiếp theo: tìm ảnh"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                                $listimg = false;
                                if (!$this->is_auto_image_disabled()) {
                                    // Update status - content created, finding images
                                    $this->update_cron_progress($cron_widget, __('Searching for images...', 'aiautotool-cron-widget'), $title, 60);
                                    $listimg = $bardGenContent->searchimg($title);
                                    // Update progress after image search
                                    $this->update_cron_progress($cron_widget, __('Images found, processing...', 'aiautotool-cron-widget'), $title, 65);
                                } else {
                                    $this->update_cron_progress($cron_widget, __('Skipping image search...', 'aiautotool-cron-widget'), $title, 65);
                                }
                                
                                // Debug: Image search result
                                $img_count = is_array($listimg) ? count($listimg) : 0;
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'SEARCH_IMAGES',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'images_found' => $img_count,
                                    'msg' => "Tìm thấy {$img_count} ảnh"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                // $content_post = get_post($post_id);
                                // $current_content = $content_post->post_content;
                                $current_content = apply_filters('the_content', $current_content);
                                $current_content = str_replace(']]>', ']]&gt;', $current_content);
                                $current_content = preg_replace('#<img.*?>#i', '', $current_content);

                                $updated_content = $newcontent . $current_content;
                                $updated_content =  self::fix_years($updated_content);
                                // $updated_content = self::preserveHtmlTagsShortcodes($updated_content);
                                $random_count = mt_rand(1, 3);
                                if (!empty($listimg) && is_array($listimg)) {
                                    $random_count = min($random_count, count($listimg));
                                    $random_keys = array_rand($listimg, $random_count);
                                }


                                if (!empty($listimg) && is_array($listimg)) {
                                    $this->update_cron_progress($cron_widget, __('Inserting images into content...', 'aiautotool-cron-widget'), $title, 70);
                                    $listimg10 = array_slice($listimg, 0, 10);
                                    shuffle($listimg10);
                                    $updated_content = $Imagescontent->insertImages($updated_content,$listimg10);
                                    $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Had found images , add to content'));
                                }else{
                                    $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'No found images.'));
                                }
                                
                                // Update status - processing images
                                $this->update_cron_progress($cron_widget, __('Processing images...', 'aiautotool-cron-widget'), $title, 75);
                                
                                $postname = $this->kct_aiautotool_sanitize($title);
                                $html = stripslashes($updated_content);
                                preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
                                $listimg1 =  $matches[1]; 
                                
                                // Debug: Images extracted from content
                                $extracted_img_count = count($listimg1);
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'EXTRACT_IMAGES',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'images_extracted' => $extracted_img_count,
                                    'msg' => "Đã trích xuất {$extracted_img_count} ảnh từ content"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                                $imgUploaded = array();
                                $attachThumbnail = 0;
                                 if (!empty($listimg1)){
                                    $total_images = count($listimg1);
                                    $upload_success = 0;
                                    $upload_failed = 0;
                                    foreach ($listimg1 as $img_index => $post_image_url){
                                        $img_index_1 = $img_index + 1;
                                        // Update progress during image upload loop
                                        $upload_progress = 75 + (($img_index_1 / $total_images) * 5); // 75% to 80%
                                        $this->update_cron_progress($cron_widget, sprintf(__('Uploading image %d/%d...', 'aiautotool-cron-widget'), $img_index_1, $total_images), $title, round($upload_progress));
                                        
                                        try {
                                                        $image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname);
                                                        if (!empty($image_url_new)){
                                                            $imgUploaded[] = $image_url_new;
                                                            $upload_success++;
                                                            if ($attachThumbnail == 0) {
                                                                $attachThumbnail = $image_url_new['attach_id'];
                                                            }
                                                             
                                                        } else {
                                                            $upload_failed++;
                                                        }
                                                    }catch (Exception $e) {
                                                        $upload_failed++;
                                                        if (defined('WP_DEBUG') && WP_DEBUG) {
                                                        }
                                                    }
                                    }
                                    
                                    // Debug: Image upload results
                                    $log->set_log('cron_task_debug', array(
                                        'step' => 'UPLOAD_IMAGES',
                                        'post_id' => $post_id,
                                        'post_title' => $title,
                                        'upload_success' => $upload_success,
                                        'upload_failed' => $upload_failed,
                                        'thumbnail_id' => $attachThumbnail,
                                        'msg' => "Upload ảnh: {$upload_success} thành công, {$upload_failed} thất bại"
                                    ));
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                        if ($attachThumbnail > 0) {
                                        }
                                    }
                                 }
                                 foreach ($imgUploaded as $img){
                                    $updated_content = str_replace($img['url'],$img['baseurl'],$updated_content);
                                }
                                        
                                if($auto_generate_title!=0){
                                    $title = $bardGenContent->gentitle($title,$lang);
                                }
                                
                                // Set thumbnail: use existing or generate AI thumbnail
                                // Wrap in try-catch to prevent errors from blocking post publish
                                try {
                                    if ($attachThumbnail != 0) {
                                        set_post_thumbnail($post_id, $attachThumbnail);
                                    } elseif (!$this->is_auto_image_disabled()) {
                                        // Generate content excerpt for AI thumbnail
                                        $content_excerpt = wp_trim_words(strip_tags($updated_content), 50);
                                        
                                        // Generate AI thumbnail using Pollinations if no thumbnail exists
                                        $ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, $content_excerpt);
                                        if ($ai_thumbnail_id) {
                                            set_post_thumbnail($post_id, $ai_thumbnail_id);
                                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                            }
                                        }
                                    }
                                } catch (Exception $e) {
                                    // Log error but don't block post publishing
                                    $log->set_log('schedule_publish',array(
                                        'post_id'=>$post_id,
                                        'post_title'=>get_the_title(),
                                        'msg'=>'Thumbnail generation error: ' . $e->getMessage()
                                    ));
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                }
                                
                                // Debug: Before publishing
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'BEFORE_PUBLISH',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'final_content_length' => strlen($updated_content),
                                    'msg' => "Chuẩn bị publish bài viết. Độ dài content cuối: " . strlen($updated_content) . " ký tự"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                                // Update status - publishing post
                                $this->update_cron_progress($cron_widget, __('Publishing post...', 'aiautotool-cron-widget'), $title, 90);
                                
                                $post_data = array(
                                    'ID' => $post_id,
                                    'post_title'=>$title,
                                    'post_content' => $updated_content,
                                    'post_status'=>'draft'
                                );

                                $post_id = wp_update_post($post_data);
                                
                                // Auto generate tags with AI if enabled
                                $auto_generate_tags = get_post_meta($post_id, 'auto_generate_tags', true);
                                if ($auto_generate_tags == 1) {
                                    $log->set_log('cron_task_debug', array(
                                        'step' => 'GENERATE_TAGS',
                                        'post_id' => $post_id,
                                        'post_title' => $title,
                                        'msg' => "Đang tự động gen tags cho bài viết"
                                    ));
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                    try {
                                        $this->generate_tags_for_post($post_id, $title, $updated_content, $lang);
                                        $log->set_log('cron_task_debug', array(
                                            'step' => 'GENERATE_TAGS_SUCCESS',
                                            'post_id' => $post_id,
                                            'post_title' => $title,
                                            'msg' => "Gen tags thành công"
                                        ));
                                    } catch (Exception $e) {
                                        $log->set_log('schedule_publish', array(
                                            'post_id' => $post_id,
                                            'post_title' => get_the_title(),
                                            'msg' => 'Auto generate tags error: ' . $e->getMessage()
                                        ));
                                        $log->set_log('cron_task_debug', array(
                                            'step' => 'GENERATE_TAGS_ERROR',
                                            'post_id' => $post_id,
                                            'post_title' => $title,
                                            'error' => $e->getMessage(),
                                            'msg' => "Lỗi khi gen tags: " . $e->getMessage()
                                        ));
                                    }
                                }
                                
                                 $this->update_and_publish_post( $post_id );
                                $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
                                
                                // Debug: Post published
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'POST_PUBLISHED',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'msg' => "Bài viết đã được publish thành công!"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                                $this->aiautotool_update_usage();
                                
                                // Update status - completed
                                $this->update_cron_progress($cron_widget, __('Content creation completed', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
                                
                                // Debug: Post processing completed
                                $log->set_log('cron_task_debug', array(
                                    'step' => 'POST_COMPLETED',
                                    'post_id' => $post_id,
                                    'post_title' => $title,
                                    'post_index' => $post_index,
                                    'msg' => "Hoàn thành xử lý bài viết #{$post_index}: {$title}"
                                ));
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                
                            }else{
                                 // Debug: Content creation failed
                                 $log->set_log('cron_task_debug', array(
                                     'step' => 'CONTENT_CREATION_FAILED',
                                     'post_id' => $post_id,
                                     'post_title' => $title,
                                     'content_gen_type' => $content_gen_type,
                                     'msg' => "Lỗi: Không thể tạo content cho bài viết"
                                 ));
                                 if (defined('WP_DEBUG') && WP_DEBUG) {
                                 }
                                 
                                 $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content Error 1 '.$title));
                                 
                                 // Update status - error
                                 $this->update_cron_progress($cron_widget, __('Error: Unable to create content', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
                            }
                        }else{
                            // Debug: Quota exceeded
                            $log->set_log('cron_task_debug', array(
                                'step' => 'QUOTA_EXCEEDED',
                                'post_id' => $post_id,
                                'post_title' => $title,
                                'msg' => "Đã vượt quá giới hạn sử dụng, không thể xử lý bài viết"
                            ));
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                            
                            $this->notice->add_notice(
                                AIAUTOTOOL_TITLE_UPGRADE,
                                'notice-error',
                                null,
                                true,
                                $this->name_plan
                            );

                            // Update status - quota exceeded
                            $this->update_cron_progress($cron_widget, __('Usage limit exceeded', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);

                        }
                }else{
                    // Debug: Post already has content
                    $log->set_log('cron_task_debug', array(
                        'step' => 'POST_HAS_CONTENT',
                        'post_id' => $post_id,
                        'post_title' => get_the_title($post_id),
                        'content_length' => strlen($current_content),
                        'msg' => "Bài viết đã có content đủ dài, chỉ cần publish"
                    ));
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api and next step: publish post has content post.'));
                    
                    // Update status - publishing existing content
                    $this->update_cron_progress($cron_widget, __('Publishing post with existing content...', 'aiautotool-cron-widget'), get_the_title($post_id), 90);
                    
                    $result = $this->update_and_publish_post( $post_id );

                    $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
                    
                    // Debug: Post with existing content published
                    $log->set_log('cron_task_debug', array(
                        'step' => 'POST_PUBLISHED_EXISTING',
                        'post_id' => $post_id,
                        'post_title' => get_the_title($post_id),
                        'msg' => "Đã publish bài viết có sẵn content"
                    ));
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    // Update status - completed
                    $this->update_cron_progress($cron_widget, __('Post published successfully', 'aiautotool-cron-widget'), get_the_title($post_id), 100, __('Auto Content', 'aiautotool-cron-widget'), false);
                }
               
                
            }
            
            // Debug: All posts processed
            $log->set_log('cron_task_debug', array(
                'step' => 'ALL_POSTS_PROCESSED',
                'total_posts' => $draft_posts->found_posts,
                'msg' => "Đã xử lý xong tất cả {$draft_posts->found_posts} bài viết"
            ));
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
        } else {
            // Debug: No posts found
            $log->set_log('cron_task_debug', array(
                'step' => 'NO_POSTS_FOUND',
                'msg' => "Không tìm thấy bài viết draft nào để publish"
            ));
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // No draft posts found
            $this->update_cron_progress($cron_widget, __('No draft posts found to publish', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
        }
        
        // Debug: End cron task
        $log->set_log('cron_task_debug', array(
            'step' => 'END',
            'msg' => 'Cron task kết thúc',
            'timestamp' => current_time('mysql')
        ));
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }

        wp_reset_postdata();
    }
    public function update_and_publish_post($post_id) {
        $current_time = current_time('mysql');

        $post_data = array(
            'ID'            => $post_id,
            'post_date'     => $current_time,
            'post_date_gmt' => get_gmt_from_date($current_time),
            'post_status' =>'publish'
        );

        wp_update_post($post_data);

        $pingback = new aiautotool_Telegram_Notifications('6845486754:AAH5KyPTuluu_OCRnPklp6UEbzVfe0CtHkU','730694172');
        $message = "Publish article:".get_permalink($post_id)."\n";
        $message .= "timeactive: " . current_time('Y-m-d H:i:s') . "\n";
        $pingback->send_bot_message($message);

        // Update cron status with success notification (only if cron_widget is available)
        $cron_widget = $this->get_cron_widget();
        if ($cron_widget) {
            $cron_widget->update_cron_status(array(
                'is_running' => false,
                'current_task' => __('Post published successfully', 'aiautotool-cron-widget'),
                'current_post_title' => get_the_title($post_id),
                'progress' => 100,
                'cron_type' => __('Auto Content', 'aiautotool-cron-widget')
            ));
        }
        
    }
    /**
     * Generate content and publish a draft post immediately
     * This function generates AI content for a draft post and publishes it right away
     * 
     * @param int $post_id Post ID to generate content and publish
     * @return string|false Post permalink on success, false on failure
     */
    public function autoblogging_generate_and_publish_post($post_id){
        // Load required classes
        if (!class_exists('BardGenContent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        }
        if (!class_exists('Imagescontent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
        }

            $auto_generate_title = get_post_meta($post_id, 'auto_generate_title', true); // Lấy giá trị meta
            $lang = get_post_meta($post_id, 'lang', true);
            // Use default language if post doesn't have language set
            if (empty($lang)) {
                $default_language = get_option('aiautotool_default_language', 'vi');
                $lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
            }

            $bardGenContent = new BardGenContent();
            $Imagescontent = new Imagescontent();
            $title = self::fix_years(get_the_title($post_id)); // Lấy tiêu đề của bài viết dựa trên ID
            // Get selected provider/model from AI Provider settings.
            $selected_model = get_option('aiautotool_autoblogging_model', '');
            $ai_selection = $this->resolve_autoblogging_ai_selection($selected_model);
            $newcontent = $bardGenContent->bardcontent($title, $lang, $ai_selection['model']);

            if (!empty($newcontent)) {
                $listimg = !$this->is_auto_image_disabled() ? $bardGenContent->searchimg($title) : false;
                $content_post = get_post($post_id);
                $current_content = $content_post->post_content;
                $current_content = apply_filters('the_content', $current_content);
                $current_content = str_replace(']]>', ']]&gt;', $current_content);
                $current_content = preg_replace('#<img.*?>#i', '', $current_content);

                $updated_content = $newcontent . $current_content;
                $updated_content =  self::fix_years($updated_content);

                $random_count = mt_rand(1, 3);
                if (!empty($listimg) && is_array($listimg)) {
                    $random_count = min($random_count, count($listimg));
                    $random_keys = array_rand($listimg, $random_count);
                }

                if (!empty($listimg) && is_array($listimg)) {
                    $listimg10 = array_slice($listimg, 0, 10);
                    shuffle($listimg10);
                    $updated_content = $Imagescontent->insertImages($updated_content, $listimg10);
                }

                $postname = $this->kct_aiautotool_sanitize($title);
                $html = stripslashes($updated_content);
                preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
                $listimg1 =  $matches[1]; 
                $imgUploaded = array();
                $attachThumbnail = 0;

                if (!empty($listimg1)){
                    foreach ($listimg1 as $post_image_url){
                        try {
                            $image_url_new = $this->kct_aiautotool_save_image($post_image_url, $postname);
                            if (!empty($image_url_new)){
                                $imgUploaded[] = $image_url_new;
                                if ($attachThumbnail == 0) {
                                    $attachThumbnail = $image_url_new['attach_id'];
                                }
                            }
                        } catch (Exception $e) {
                        }
                    }
                }

                foreach ($imgUploaded as $img){
                    $updated_content = str_replace($img['url'], $img['baseurl'], $updated_content);
                }

                if ($auto_generate_title){
                    $title = $bardGenContent->gentitle($title, $lang);
                }

                // Set thumbnail: use existing or generate AI thumbnail
                // Wrap in try-catch to prevent errors from blocking post creation
                try {
                    if ($attachThumbnail != 0) {
                        set_post_thumbnail($post_id, $attachThumbnail);
                    } elseif (!$this->is_auto_image_disabled()) {
                        // Generate content excerpt for AI thumbnail
                        $content_excerpt = wp_trim_words(strip_tags($updated_content), 50);
                        
                        // Generate AI thumbnail using Pollinations if no thumbnail exists
                        $ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, $content_excerpt);
                        if ($ai_thumbnail_id) {
                            set_post_thumbnail($post_id, $ai_thumbnail_id);
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                        }
                    }
                } catch (Exception $e) {
                    // Log error but don't block post creation
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }

                $post_data = array(
                    'ID' => $post_id,
                    'post_title' => $title,
                    'post_content' => $updated_content,
                    'post_status' => 'publish'
                );

                $post_id = wp_update_post($post_data);
                
                // Auto generate tags with AI if enabled
                $auto_generate_tags = get_post_meta($post_id, 'auto_generate_tags', true);
                if ($auto_generate_tags == 1) {
                    try {
                        $this->generate_tags_for_post($post_id, $title, $updated_content, $lang);
                    } catch (Exception $e) {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                    }
                }
                
                return get_permalink($post_id);
            }else{
                return false;
            }
        } 


    public function kct_aiautotool_save_image($imgURL,$post_title){
            
            $imageUploader = new KCT_AIAutoTool_ImageUploader();
            $kq = $imageUploader->saveImage($imgURL, $post_title);
            return $kq;
        }
    public function kct_aiautotool_sanitize($title) {
                $replacement = '-';
                $map = array();
                $quotedReplacement = preg_quote($replacement, '/');
                $default = array(
                    '/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|å/' => 'a',
                    '/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|ë/' => 'e',
                    '/ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|î/' => 'i',
                    '/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|ø/' => 'o',
                    '/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|ů|û/' => 'u',
                    '/ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ/' => 'y',
                    '/đ|Đ/' => 'd',
                    '/ç/' => 'c',
                    '/ñ/' => 'n',
                    '/ä|æ/' => 'ae',
                    '/ö/' => 'oe',
                    '/ü/' => 'ue',
                    '/Ä/' => 'Ae',
                    '/Ü/' => 'Ue',
                    '/Ö/' => 'Oe',
                    '/ß/' => 'ss',
                    '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
                    '/\\s+/' => $replacement,
                    sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
                );
                //Some URL was encode, decode first
                $title = urldecode($title);
                $map = array_merge($map, $default);
                return strtolower(preg_replace(array_keys($map), array_values($map), $title));
            }
    public function preserveHtmlTagsShortcodes($string) {
        //preserve shortcodes
        if (preg_match_all("/\[.*\]/", $string , $shortcodes)) {
            $this->shortcodes = $shortcodes[0];
            foreach($this->shortcodes as $num => $tag) {
                $string = str_replace($tag, "[3x" . (10000+ $num) . "]", $string);
            }
        }
        
        // and html tags
        if(preg_match_all('@<[\/\!]*?[^<>]*?>@si', $string, $htmltags)) {
            $this->htmltags = $htmltags[0];
            foreach($this->htmltags as $num => $tag) {
                $string = str_replace($tag, "[3x" . (1000+ $num) . "]", $string);
            }
        }
        return $string;
    }
    
    public function replaceHTMLTagsShortcodes($string) {
         // replace the preserved html tags
        foreach($this->htmltags as $num => $tag) {
            $string = str_replace("[3x" . (1000+ $num) . "]", $tag, $string);
        }
        // and shortcodes
        foreach($this->shortcodes as $num => $tag) {
            $string = str_replace("[3x" . (10000+ $num) . "]", $tag, $string);
        }
        return $string;
    }

    
    public function fix_years($title) {
        

        return $title;
    }
    /**
     * Flush rewrite rules nếu cần (khi có thay đổi endpoint)
     */
    private function maybe_flush_rewrite_rules() {
        $option_key = 'aiautotool_rest_endpoints_version';
        $current_version = '1.0.1'; // Tăng version khi có thay đổi endpoint
        
        if (get_option($option_key) !== $current_version) {
            flush_rewrite_rules();
            update_option($option_key, $current_version, 'no');
        }
    }
    
    public function register_aiautotool_scan_route(){
        register_rest_route('aiautotool/v1', '/bardcontent', array(
            'methods' => 'POST',
            'callback' => array($this, 'autoblogging_generate_content_via_rest_api'),
            'permission_callback' => '__return_true'
        ));
        register_rest_route('aiautotool/v1', '/createcontentbard', array(
            'methods' => 'POST',
            'callback' => array($this, 'autoblogging_handle_content_generation_ajax'),
            'permission_callback' => '__return_true'
        ));
    }
    
    /**
     * AJAX/REST API handler: Generate content and publish post
     * Handles AJAX request to generate content and publish a draft post
     * 
     * @param WP_REST_Request|array $request Request object with post_id
     * @return WP_REST_Response JSON response with post permalink
     */
    public function autoblogging_handle_content_generation_ajax($request){
        $idpost = $request['post_id'];
        $kq = $this->autoblogging_generate_and_publish_post($idpost);
        return wp_send_json_success($kq );
    }
    
    /**
     * REST API handler: Generate content for a post via REST API
     * This function generates content for a post and updates it via REST API
     * 
     * @param WP_REST_Request|array $request Request object with title and id
     * @return WP_REST_Response JSON response with generated content
     */
    public function autoblogging_generate_content_via_rest_api($request){
        // Load required classes
        if (!class_exists('BardGenContent')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        }
        
        $title = $request['title'];
        $idpost = $request['id'];
        $bardGenContent = new BardGenContent();
        $newcontent = $bardGenContent->sendRequest($title);

         if (!empty($newcontent)) {

            $content_post = get_post($idpost);
            $current_content = $content_post->post_content;
            $current_content = apply_filters('the_content', $current_content);
            $current_content = str_replace(']]>', ']]&gt;', $current_content);
            $updated_content = $newcontent . $current_content;

            // Cập nhật nội dung của bài viết
            $post_data = array(
                'ID' => $idpost,
                'post_content' => $updated_content,
            );

            $post_id = wp_update_post($post_data);
        }

        return wp_send_json_success($newcontent);
    }

    public function aiautotool_get_all_draft() {
        $drafts = get_posts(array(
            'post_type' => 'post',
            'post_status' => 'draft',
            'numberposts' => -1,
        ));

        $draftsWithContent = 0;
        $draftsWithoutContent = 0;

        foreach ($drafts as $draft) {
            $content = get_post_field('post_content', $draft->ID);

            if (empty($content)) {
                // Nếu nội dung rỗng, tăng counter cho draft chưa có nội dung
                $draftsWithoutContent++;
            } else {
                // Ngược lại, tăng counter cho draft đã có nội dung
                $draftsWithContent++;
            }
        }
        if(count($drafts)==0){
            return array('total'=>0,'hascontent'=>0,'nocontent'=>0);
        }else{
            return array('total'=>count($drafts),'hascontent'=>$draftsWithContent,'nocontent'=>$draftsWithoutContent);
        }

        
    }
    public function add_menu() {
        // Always add the menu, regardless of active status
        add_submenu_page(
            MENUSUBPARRENT,       
            wp_kses_post($this->icon).' '.esc_html__('Autoblogging AI post','ai-auto-tool'),          
            wp_kses_post($this->icon).' '.esc_html__('Autoblogging AI post','ai-auto-tool'),    
            'manage_options',             
            'add-post-draft',  
            array($this, 'add_key_to_post')  
        );
    }


        public function clear_log_action_callback() {
            // Check if called via AJAX
            if (defined('DOING_AJAX') && DOING_AJAX) {
                check_ajax_referer('aiautotool_nonce', 'security');
                
                if (!current_user_can('manage_options')) {
                    wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
                }
            } else {
                // Called via cron - verify it's actually cron
                if (!defined('DOING_CRON') || !DOING_CRON) {
                    return;
                }
            }
           
            update_option('aiautotool_logall', array(),null, 'no');

            wp_send_json_success('Log cleared successfully.');
            wp_die();
        }
        
        /**
         * AJAX callback to manually run autoblogging cron
         */
        public function run_autoblogging_cron_callback() {
            check_ajax_referer('aiautotool_nonce', 'security');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
                wp_die();
            }
            
            // Run the cron function
            try {
                $post_id = $this->autoblogging_cron_generate_content_for_draft();
                
                // Check if a post was created
                if ($post_id && is_numeric($post_id)) {
                    $edit_url = admin_url('post.php?action=edit&post=' . $post_id);
                    $post_title = get_the_title($post_id);
                    
                    wp_send_json_success(array(
                        'message' => __('Post created successfully!', 'ai-auto-tool'),
                        'post_id' => $post_id,
                        'edit_url' => $edit_url,
                        'post_title' => $post_title
                    ));
                } else {
                    // Also check transient in case return didn't work
                    $transient_post_id = get_transient('aiautotool_last_created_post_id');
                    if ($transient_post_id) {
                        delete_transient('aiautotool_last_created_post_id');
                        $edit_url = admin_url('post.php?action=edit&post=' . $transient_post_id);
                        $post_title = get_the_title($transient_post_id);
                        
                        wp_send_json_success(array(
                            'message' => __('Post created successfully!', 'ai-auto-tool'),
                            'post_id' => $transient_post_id,
                            'edit_url' => $edit_url,
                            'post_title' => $post_title
                        ));
                    } else {
                        wp_send_json_success(array(
                            'message' => __('Cron completed. No new posts were created. Make sure you have draft posts with empty content.', 'ai-auto-tool'),
                            'post_id' => null
                        ));
                    }
                }
            } catch (Exception $e) {
                wp_send_json_error(array(
                    'message' => __('Error running cron: ', 'ai-auto-tool') . $e->getMessage()
                ));
            }
            
            wp_die();
        }


    public function add_key_to_post() {
        

        $default_language = get_option('aiautotool_default_language', 'vi');
        $languages = $this->languageCodes;

      

        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>Autoblogging</div>
                    <button href="#tab-schedule" class="nav-tab sotabt "> <?php echo wp_kses_post($this->icon).' '. esc_html__('Autoblogging AI post','ai-auto-tool'); ?></button>
                    <button href="#tab-log-schedule" class="nav-tab sotabt "><i class="fa-regular fa-folder-closed"></i> <?php esc_html_e('View log schedule','ai-auto-tool'); ?></button>
                    <button href="#tab-cron-widget" class="nav-tab sotabt "><i class="fa-regular fa-clock"></i> <?php esc_html_e('Cron Status','ai-auto-tool'); ?></button>
                
                </div>
                <div class="ft-main">

                    <div id="tab-schedule" class="tab-content sotab-box ftbox">
                         <div class="autoblogging-header">
                            <h2><i class="fa-solid fa-blog"></i> <?php esc_html_e('Autoblogging AI post','ai-auto-tool'); ?></h2>
                            <p class="autoblogging-subtitle"><?php esc_html_e('Create multiple blog posts automatically using AI. Enter titles, configure settings, and let AI generate content for you.','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">Post Titles</div>
                                        <div class="step-description">Enter multiple post titles that will be used to generate AI content. Each title 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, and language 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">Advanced Settings</div>
                                        <div class="step-description">Add anchor text and links to enhance your blog posts with internal or external references.</div>
                                    </div>
                                    <div class="step-indicator"></div>
                                </div>
                                <div class="autoblogging-step" id="step-4" data-step="4">
                                    <div class="step-number">4</div>
                                    <div class="step-content">
                                        <div class="step-title">Ready to Submit</div>
                                        <div class="step-description">Review your settings and submit to start generating AI-powered blog posts automatically.</div>
                                    </div>
                                    <div class="step-indicator"></div>
                                </div>
                            </div>
                               
                            <!-- start form -->
                            <form id="add-post-form" method="post">
                            
                            <!-- Section 1: Post Titles Card -->
                            <div class="autoblogging-card" id="section-titles">
                                <div class="card-header">
                                    <div class="card-header-left">
                                        <i class="fa-solid fa-heading"></i>
                                        <h3><?php esc_html_e('Post Titles','ai-auto-tool'); ?></h3>
                                    </div>
                                    <button type="button" class="aiautotool_idea_generated" title="AI Suggest Post title....">
                                        <i class="ai-idea-icon fa-solid fa-bolt"></i> <?php esc_html_e('AI Idea Title','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 multiple post titles (one per line). Each title will create a separate draft post. You can use the AI Idea button to generate title suggestions.','ai-auto-tool'); ?>
                                    </p>
                                    <textarea id="post-titles" class="autoblogging-textarea" name="post_titles" rows="8" placeholder="<?php esc_attr_e('Enter post titles, one per line...','ai-auto-tool'); ?>"></textarea>
                                    <div class="input-counter">
                                        <span id="title-count">0</span> <?php esc_html_e('titles 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="post_category[]" 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="post_tags" id="post_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="post_language" id="post_language" class="autoblogging-select">
                                                <?php 
                                                foreach ($languages as $code => $name) {
                                                    $is_selected = selected($default_language, $code, false);
                                                    echo '<option value="' . esc_attr($code) . '" ' . $is_selected . '>' . esc_html($name) . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group form-group-half">
                                            <label class="form-label">
                                                <i class="fa-solid fa-user"></i>
                                                <?php esc_html_e('Post Author','ai-auto-tool'); ?>
                                            </label>
                                            <p class="form-description"><?php esc_html_e('Select how to assign the author for generated posts.','ai-auto-tool'); ?></p>
                                            <select name="post_author_mode" id="post_author_mode" class="autoblogging-select">
                                                <option value="random"><?php esc_html_e('Random user','ai-auto-tool'); ?></option>
                                                <option value="random_no_admin"><?php esc_html_e('Random user (exclude admin)','ai-auto-tool'); ?></option>
                                                <option value="list_users"><?php esc_html_e('Select specific user','ai-auto-tool'); ?></option>
                                            </select>
                                            
                                            <div id="user_select_container" class="form-group-nested" style="display: none; margin-top: 15px;">
                                                <?php
                                                $users = get_users(array(
                                                    'orderby' => 'display_name',
                                                    'order' => 'ASC'
                                                ));
                                                echo '<select name="post_author_user" id="post_author_user" class="autoblogging-select user-search-select">';
                                                echo '<option value="">' . esc_html__('Search and select user...', 'ai-auto-tool') . '</option>';
                                                foreach ($users as $user) {
                                                    $display_name = $user->display_name . ' (' . $user->user_login . ')';
                                                    echo '<option value="' . esc_attr($user->ID) . '" data-search="' . esc_attr(strtolower($user->display_name . ' ' . $user->user_login . ' ' . $user->user_email)) . '">' . esc_html($display_name) . '</option>';
                                                }
                                                echo '</select>';
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Section 3: Advanced Settings Card (Collapsible) -->
                            <div class="autoblogging-card" id="section-advanced">
                                <div class="card-header">
                                    <div class="card-header-left">
                                        <i class="fa-solid fa-cog"></i>
                                        <h3><?php esc_html_e('Advanced Settings','ai-auto-tool'); ?></h3>
                                    </div>
                                    <button type="button" class="card-toggle" aria-expanded="false">
                                        <i class="fa-solid fa-chevron-down"></i>
                                    </button>
                                </div>
                                <div class="card-body" style="display: none;">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <i class="fa-regular fa-star"></i>
                                            <?php esc_html_e('Anchor Text & Links','ai-auto-tool'); ?>
                                        </label>
                                        <p class="form-description">
                                            <?php esc_html_e('Add anchor text with links that will be automatically inserted into your blog posts. You can include HTML links, internal or external URLs, and use spintax syntax for content variation. This helps improve SEO and internal linking structure.','ai-auto-tool'); ?>
                                        </p>
                                        <?php
                                        $anchor_text_value = '';
                                        $editor_settings = array(
                                            'textarea_name' => 'anchor_text',
                                            'textarea_rows' => 5, 
                                            'teeny' => false, 
                                            'quicktags' => true, 
                                            'tinymce' => true, 
                                        );
                                        wp_editor($anchor_text_value, 'anchor_text_editor', $editor_settings);
                                        ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Section 4: 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-titles-count">0</span> <?php esc_html_e('posts will be created','ai-auto-tool'); ?>
                                    </div>
                                    <div class="submit-info-item">
                                        <i class="fa-solid fa-clock"></i>
                                        <?php esc_html_e('Posts will be saved as drafts','ai-auto-tool'); ?>
                                    </div>
                                </div>
                                <button type="submit" id="btnSubmitaddpost" class="autoblogging-submit-btn">
                                    <i class="fa-solid fa-plus-circle"></i>
                                    <span><?php esc_html_e('Create Draft Posts','ai-auto-tool'); ?></span>
                                    <div id="loading-icon" class="loader"></div>
                                </button>
                            </div>
                            
                            </form>
                            
                            <div id="progress-bar-container" style="display: none;">
                                <div class="progress-bar-wrapper">
                                    <div class="progress-bar-label">
                                        <span id="progress-text"><?php esc_html_e('Creating posts...','ai-auto-tool'); ?></span>
                                        <span id="progress-percent">0%</span>
                                    </div>
                                    <div id="progress-bar">
                                        <div class="progress-fill"></div>
                                    </div>
                                </div>
                            </div>

                            <div id="post-list" class="post-list-results"></div>
                            
                            <script type="text/javascript">
                            jQuery(document).ready(function($) {
                                // AI Idea Title Button Handler
                                $('.aiautotool_idea_generated').on('click', function(e) {
                                    e.preventDefault();
                                    console.log('Idea click');
                                    
                                    function suggestIdea(retries) {
                                        showLoading();
                                        
                                        // Get selected categories
                                        var selectedCategories = [];
                                        var categoryNames = [];
                                        $('.post-category-checkbox:checked').each(function() {
                                            var catId = $(this).val();
                                            var catName = $(this).parent().text().trim();
                                            catName = catName.replace(/\s*\(\d+\)\s*$/, '').trim();
                                            if (catId && catName) {
                                                selectedCategories.push(catId);
                                                categoryNames.push(catName);
                                            }
                                        });
                                        
                                        var categoryData = {};
                                        if (selectedCategories.length > 0) {
                                            categoryData.category_id = selectedCategories[0];
                                            categoryData.category_name = categoryNames[0];
                                            if (selectedCategories.length > 1) {
                                                categoryData.category_name = categoryNames.join(', ');
                                            }
                                        }

                                        $.ajax({
                                            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', 
                                            type: 'POST',
                                            data: {
                                                action: 'aiautotool_idea_title_post',
                                                security: aiautotool_js_setting.security,
                                                category_id: categoryData.category_id || '',
                                                category_name: categoryData.category_name || ''
                                            },
                                            success: function(response) {
                                                if (response.success) {
                                                    hideLoading();
                                                    var output = response.data.output;
                                                    if (Array.isArray(output)) {
                                                        var itemDivtong = '';
                                                        output.forEach(function(item) {
                                                            itemDivtong += item.title+"\n";
                                                        });
                                                        $('#post-titles').val(itemDivtong);
                                                        updateTitleCount();
                                                    } else {
                                                        retryRequestidea(retries);
                                                    }
                                                } else {
                                                    retryRequestidea(retries);
                                                }
                                            },
                                            error: function() {
                                                retryRequestidea(retries);
                                            }
                                        });
                                    }
                                    
                                    function retryRequestidea(retries) {
                                        if (retries > 0) {
                                            console.log('Retrying request... Attempts left: ' + retries);
                                            suggestIdea(retries - 1);
                                        } else {
                                            hideLoading();
                                            aiautotool_alert_error('Failed to generate ideas!', '');
                                        }
                                    }

                                    suggestIdea(2);
                                });
                                
                                // 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');
                                    }
                                });
                                
                                // Title counter
                                function updateTitleCount() {
                                    var titles = $('#post-titles').val().trim();
                                    var count = titles ? titles.split('\n').filter(function(line) {
                                        return line.trim().length > 0;
                                    }).length : 0;
                                    $('#title-count').text(count);
                                    $('#submit-titles-count').text(count);
                                }
                                
                                $('#post-titles').on('input', updateTitleCount);
                                updateTitleCount();
                            });
                            </script>
                                  
                                  <div id="progress-bar-container">
                                        <div id="progress-bar" style="width: 0;"></div>
                                    </div>

                                  <style type="text/css">
                                      /* 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);
                                      }
                                      
                                      /* 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-group-nested {
                                          margin-top: 15px;
                                      }
                                      
                                      .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;
                                      }
                                      
                                      .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;
                                      }
                                      
                                      .autoblogging-input,
                                      .autoblogging-select,
                                      .autoblogging-textarea {
                                          width: 100%;
                                          padding: 12px 16px;
                                          border: 2px solid #e0e0e0;
                                          border-radius: 8px;
                                          font-size: 14px;
                                          transition: all 0.3s ease;
                                          background: #fff;
                                      }
                                      
                                      .autoblogging-input:focus,
                                      .autoblogging-select:focus,
                                      .autoblogging-textarea: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;
                                      }

                                      .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%;
                                          }
                                      }

                                      /* 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;
                                      }
                                      
                                      /* Progress Bar */
                                      #progress-bar-container {
                                          margin-top: 20px;
                                          display: none;
                                      }
                                      
                                      .progress-bar-wrapper {
                                          background: #ffffff;
                                          border-radius: 12px;
                                          padding: 20px;
                                          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
                                          border: 1px solid #e8e8e8;
                                      }
                                      
                                      .progress-bar-label {
                                          display: flex;
                                          justify-content: space-between;
                                          align-items: center;
                                          margin-bottom: 12px;
                                          font-size: 14px;
                                          font-weight: 600;
                                          color: #2c3e50;
                                      }
                                      
                                      #progress-percent {
                                          color: #4a90e2;
                                      }
                                      
                                      #progress-bar {
                                          width: 100%;
                                          height: 12px;
                                          background: #f0f0f0;
                                          border-radius: 6px;
                                          overflow: hidden;
                                          position: relative;
                                      }
                                      
                                      #progress-bar .progress-fill {
                                          position: absolute;
                                          top: 0;
                                          left: 0;
                                          height: 100%;
                                          width: 0;
                                          background: linear-gradient(90deg, #4a90e2, #357abd);
                                          transition: width 0.3s ease-in-out;
                                          border-radius: 6px;
                                      }
                                      
                                      /* Post List Results */
                                      .post-list-results {
                                          margin-top: 20px;
                                      }
                                      
                                      .post-list-results ul {
                                          list-style: none;
                                          padding: 0;
                                          margin: 0;
                                      }
                                      
                                      .post-list-results li {
                                          background: #ffffff;
                                          padding: 16px 20px;
                                          margin-bottom: 10px;
                                          border-radius: 8px;
                                          border-left: 4px solid #4a90e2;
                                          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                                          display: flex;
                                          align-items: center;
                                          gap: 12px;
                                      }
                                      
                                      .post-list-results li a {
                                          color: #4a90e2;
                                          text-decoration: none;
                                          font-weight: 500;
                                          transition: color 0.3s ease;
                                      }
                                      
                                      .post-list-results li a:hover {
                                          color: #357abd;
                                          text-decoration: underline;
                                      }
                                      
                                      .post-list-results .post-number {
                                          color: #999;
                                          font-weight: 600;
                                          margin-right: 8px;
                                      }
                                      
                                      /* 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;
                                      }
                                      
                                      /* 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 .ai-idea-icon {
                                          font-size: 16px;
                                      }
                                      
                                      .aiautotool_idea_generated.loading {
                                          pointer-events: none;
                                          opacity: 0.8;
                                      }
                                      
                                      .aiautotool_idea_generated.loading .ai-idea-icon {
                                          animation: spin 1s linear infinite;
                                      }
                                      
                                      /* 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); }
                                      }
                                      
                                      /* 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;
                                          }
                                      }

/* 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);
}

.ft-label-right {
    font-size: 14px;
    color: #2c3e50;
    font-weight: 500;
    vertical-align: middle;
}

/* Focus styles */
.aiautotool_idea_generated:focus,
.ft-submit:focus {
    outline: none;
    box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.3);
}

/* Disabled state */
.aiautotool_idea_generated:disabled,
.ft-submit:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}
                                   </style>
                                  <script type="text/javascript">
                                     jQuery('#tab-setting').show();

                                  </script>
                            <!-- end form -->
                    </div>
                    
                     <div id="tab-log-schedule" class="tab-content sotab-box ftbox" style="display:none;">
                        <div class="aiautotool-log-container">
                            <!-- Header Section -->
                            <div class="aiautotool-log-header">
                                <div class="aiautotool-log-header-content">
                                    <h2 class="aiautotool-log-title">
                                        <i class="fa-solid fa-list-alt"></i>
                                        <?php esc_html_e('Logs','ai-auto-tool'); ?>
                                    </h2>
                                    <button id="clear-log-button" class="aiautotool-log-clear-btn">
                                        <i class="fa-solid fa-trash-can"></i>
                                        <?php esc_html_e('Clear Log', 'ai-auto-tool'); ?>
                                    </button>
                                </div>
                            </div>

                            <!-- Stats Section -->
                            <div class="aiautotool-log-stats">
                                <?php $draft = self::aiautotool_get_all_draft(); ?>
                                <div class="aiautotool-stat-card">
                                    <div class="aiautotool-stat-icon">
                                        <i class="fa-solid fa-file-lines"></i>
                                    </div>
                                    <div class="aiautotool-stat-content">
                                        <div class="aiautotool-stat-label"><?php esc_html_e('Has content','ai-auto-tool'); ?></div>
                                        <div class="aiautotool-stat-value">
                                            <span class="aiautotool-stat-number"><?php echo esc_html($draft['hascontent']); ?></span>
                                            <span class="aiautotool-stat-separator">/</span>
                                            <span class="aiautotool-stat-total"><?php echo esc_html($draft['total']); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Logs Section -->
                            <div class="aiautotool-logs-wrapper">
                                <?php  
                                    $log = new AIautoTool_log();
                                    
                                    // Schedule Publish Logs
                                    echo '<div class="aiautotool-log-section">';
                                    echo '<h3 class="aiautotool-log-section-title">';
                                    echo '<i class="fa-solid fa-paper-plane"></i>';
                                    echo esc_html__('Schedule Publish Logs', 'ai-auto-tool');
                                    echo '</h3>';
                                    $log->show_log('schedule_publish');
                                    echo '</div>';
                                    
                                    // Schedule Generate Content Logs
                                    echo '<div class="aiautotool-log-section">';
                                    echo '<h3 class="aiautotool-log-section-title">';
                                    echo '<i class="fa-solid fa-wand-magic-sparkles"></i>';
                                    echo esc_html__('Schedule Generate Content Logs', 'ai-auto-tool');
                                    echo '</h3>';
                                    $log->show_log('schedule_gen_content');
                                    echo '</div>';
                                ?>
                            </div>
                        </div>
                    </div>
                    <script>
    jQuery(document).ready(function($) {
        $('#clear-log-button').on('click', function(event) {
            event.preventDefault();
            
            // Get security nonce - use from global setting if available, otherwise create new one
            var securityNonce = (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) 
                ? aiautotool_js_setting.security 
                : '<?php echo wp_create_nonce('aiautotool_nonce'); ?>';
            
            // Gửi yêu cầu xóa log thông qua AJAX
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: {
                    action: 'clear_log_action',
                    security: securityNonce
                },
                success: function(response) {
                    // Nếu thành công, làm mới nội dung log
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error clearing log', 'ai-auto-tool')); ?>');
                    }
                },
                error: function(xhr, status, error) {
                    alert('<?php echo esc_js(__('AJAX error occurred', 'ai-auto-tool')); ?>: ' + error);
                }
            });
        });
    });
</script>

                    <div id="tab-cron-widget" class="tab-content sotab-box ftbox" style="display:none;">
                        <h2><i class="fa-regular fa-clock"></i> <?php esc_html_e('Cron Status Widget', 'aiautotool-cron-widget'); ?></h2>
                          <!-- Run Cron Button Section -->
            <div style="margin-top: 30px; padding: 20px; background: #f9f9f9; border-radius: 8px; border: 1px solid #ddd;">
                <h3 style="margin-top: 0;">
                    <i class="fa-solid fa-play-circle"></i> 
                    <?php esc_html_e('Run Cron Manually', 'ai-auto-tool'); ?>
                </h3>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Click the button below to manually trigger the cron job that generates content for draft posts. If a post is created, you will be redirected to edit it.', 'ai-auto-tool'); ?>
                </p>
                <button type="button" id="run-cron-button" class="ft-submit" style="background: #4CAF50; border-color: #4CAF50;">
                    <i class="fa-solid fa-play"></i>
                    <span class="button-text"><?php esc_html_e('Run Cron Now', 'ai-auto-tool'); ?></span>
                    <span class="button-loading" style="display: none;">
                        <i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Running...', 'ai-auto-tool'); ?>
                    </span>
                </button>
                <div id="cron-status-message" style="margin-top: 15px; display: none; padding: 10px; border-radius: 4px;"></div>
            </div>
            
            <script>
            jQuery(document).ready(function($) {
                $('#run-cron-button').on('click', function(e) {
                    e.preventDefault();
                    
                    var $button = $(this);
                    var $message = $('#cron-status-message');
                    var $buttonText = $button.find('.button-text');
                    var $buttonLoading = $button.find('.button-loading');
                    
                    // Disable button and show loading
                    $button.prop('disabled', true);
                    $buttonText.hide();
                    $buttonLoading.show();
                    $message.hide().removeClass('notice notice-success notice-error');
                    
                    // Get security nonce
                    var securityNonce = (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) 
                        ? aiautotool_js_setting.security 
                        : '<?php echo wp_create_nonce('aiautotool_nonce'); ?>';
                    
                    // Make AJAX request
                    $.ajax({
                        url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                        type: 'POST',
                        data: {
                            action: 'run_autoblogging_cron',
                            security: securityNonce
                        },
                        timeout: 300000, // 5 minutes timeout
                        success: function(response) {
                            if (response.success) {
                                if (response.data.post_id) {
                                    // Post was created - redirect to edit page
                                    $message.html('<i class="fa-solid fa-check-circle"></i> ' + response.data.message + ' <strong>' + response.data.post_title + '</strong>')
                                        .addClass('notice notice-success')
                                        .show();
                                    
                                    // Redirect after 1 second
                                    setTimeout(function() {
                                        window.location.href = response.data.edit_url;
                                    }, 1000);
                                } else {
                                    // No post created
                                    $message.html('<i class="fa-solid fa-info-circle"></i> ' + response.data.message)
                                        .addClass('notice notice-info')
                                        .show();
                                    
                                    // Re-enable button
                                    $button.prop('disabled', false);
                                    $buttonText.show();
                                    $buttonLoading.hide();
                                }
                            } else {
                                // Error occurred
                                $message.html('<i class="fa-solid fa-exclamation-circle"></i> ' + (response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('An error occurred', 'ai-auto-tool')); ?>'))
                                    .addClass('notice notice-error')
                                    .show();
                                
                                // Re-enable button
                                $button.prop('disabled', false);
                                $buttonText.show();
                                $buttonLoading.hide();
                            }
                        },
                        error: function(xhr, status, error) {
                            var errorMsg = '<?php echo esc_js(__('AJAX error occurred', 'ai-auto-tool')); ?>';
                            if (status === 'timeout') {
                                errorMsg = '<?php echo esc_js(__('Request timed out. The cron may still be running in the background.', 'ai-auto-tool')); ?>';
                            }
                            
                            $message.html('<i class="fa-solid fa-exclamation-circle"></i> ' + errorMsg)
                                .addClass('notice notice-error')
                                .show();
                            
                            // Re-enable button
                            $button.prop('disabled', false);
                            $buttonText.show();
                            $buttonLoading.hide();
                        }
                    });
                });
            });
            </script>
                        
                        <style>
                        .cron-widget-preview {
                            margin: 20px 0;
                        }
                        
                        .widget-preview-box {
                            width: 320px;
                            background: #fff;
                            border-radius: 12px;
                            box-shadow: 0 8px 32px rgba(0,0,0,0.12);
                            border: 1px solid #e1e5e9;
                            overflow: hidden;
                            margin: 20px 0;
                        }
                        
                        .preview-header {
                            background: linear-gradient(135deg, #4a90e2, #357abd);
                            color: white;
                            padding: 12px 16px;
                            display: flex;
                            align-items: center;
                            font-weight: 600;
                        }
                        
                        .preview-header i {
                            margin-right: 8px;
                            font-size: 16px;
                        }
                        
                        .preview-content {
                            padding: 16px;
                        }
                        
                        .preview-status {
                            display: flex;
                            align-items: center;
                            gap: 8px;
                            margin-bottom: 16px;
                        }
                        
                        .preview-dot {
                            width: 8px;
                            height: 8px;
                            border-radius: 50%;
                            background: #4caf50;
                            animation: pulse 1s infinite;
                        }
                        
                        .preview-progress {
                            margin-bottom: 16px;
                        }
                        
                        .preview-progress-bar {
                            width: 100%;
                            height: 6px;
                            background: #f0f0f0;
                            border-radius: 3px;
                            overflow: hidden;
                            margin-bottom: 8px;
                        }
                        
                        .preview-progress-fill {
                            height: 100%;
                            background: linear-gradient(90deg, #4caf50, #8bc34a);
                            transition: width 0.3s ease;
                        }
                        
                        .preview-progress-text {
                            font-size: 12px;
                            color: #666;
                            text-align: center;
                        }
                        
                        .preview-details {
                            font-size: 12px;
                            color: #666;
                        }
                        
                        .preview-details > div {
                            margin-bottom: 4px;
                        }
                        </style>
                    </div>
                    </div>
                </div>
            </div>
        </div>
        </div>

        <style>
            .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); }
}

/* User search styles */
.user-search-wrapper {
    position: relative;
}

.user-search-input {
    width: 100%;
    padding: 8px 12px;
    border: 2px solid #ddd;
    border-radius: 5px;
    font-size: 14px;
}

.user-search-input:focus {
    border-color: var(--aiautotool-color, #4a90e2);
    outline: none;
}

#post_author_user {
    width: 100%;
}

#post_author_user option[hidden] {
    display: none;
}

/* Override ft-wrap-body for autoblogging page only */
.aiautotool_container .ft-wrap-body {
    display: block !important;
    width: 100% !important;
    max-width: 100% !important;
    grid-template-columns: none !important;
    grid-gap: 0 !important;
}

        </style>
        <script>
        jQuery(document).ready(function($) {
    const loadingIcon = document.getElementById("loading-icon");
    const btnSubmitKeyword = document.getElementById("btnSubmitaddpost");
    const progressBar = $('#progress-bar');

    // Step tracking functionality
    function updateStepStates() {
        // Step 1: Check if post titles are filled
        var postTitles = $('#post-titles').val().trim();
        var step1 = $('#step-1');
        if (postTitles) {
            step1.addClass('completed').removeClass('active');
        } else {
            step1.removeClass('completed active');
        }

        // Step 2: Check content settings (prompt, category, tags, language)
        var hasPrompt = false;
        var promptMode = $('input[name="prompt_selection_mode"]:checked').val();
        
        // If prompt_mode is 'auto', prompt is not required
        if (promptMode === 'auto') {
            hasPrompt = true;
        } else 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';
        }
        
        // Check if any category checkbox is checked
        var hasCategory = $('.post-category-checkbox:checked').length > 0;
        var hasTags = $('#post_tags').val().trim() !== '';
        var hasLanguage = $('#post_language').val() && $('#post_language').val() !== '';
        
        var step2 = $('#step-2');
        if (hasPrompt || hasCategory || hasTags || hasLanguage) {
            step2.addClass('completed').removeClass('active');
        } else {
            step2.removeClass('completed active');
        }

        // Step 3: Check advanced settings (anchor text)
        var hasAnchorText = false;
        if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
            var anchorContent = tinymce.activeEditor.getContent().trim();
            hasAnchorText = anchorContent !== '' && anchorContent !== '<p></p>' && anchorContent !== '<p><br></p>';
        }
        
        var step3 = $('#step-3');
        if (hasAnchorText) {
            step3.addClass('completed').removeClass('active');
        } else {
            step3.removeClass('completed active');
        }

        // Step 4: Ready to submit (at least step 1 should be completed)
        var step4 = $('#step-4');
        if (postTitles) {
            step4.addClass('completed').removeClass('active');
        } else {
            step4.removeClass('completed active');
        }

        // Set active step (first incomplete step or current step being filled)
        if (!postTitles) {
            step1.addClass('active');
        } else if (!hasPrompt && !hasCategory && !hasTags && !hasLanguage) {
            step2.addClass('active');
        } else if (!hasAnchorText) {
            step3.addClass('active');
        } else {
            step4.addClass('active');
        }
    }

    // Track form field changes
    $('#post-titles').on('input change keyup', function() {
        updateStepStates();
    });

    $('#aiautotool_prompt, #post_tags, #post_language').on('change', function() {
        updateStepStates();
    });

    // Handle post author mode change
    $('#post_author_mode').on('change', function() {
        var mode = $(this).val();
        if (mode === 'list_users') {
            $('#user_select_container').slideDown(200);
        } else {
            $('#user_select_container').slideUp(200);
            $('#post_author_user').val('');
        }
        updateStepStates();
    });

    // User search functionality - simple filter on input
    var userSearchInitialized = false;
    $('#post_author_user').on('focus', function() {
        if (!userSearchInitialized) {
            var $select = $(this);
            
            // Create search input wrapper if not exists
            if ($select.prev('.user-search-wrapper').length === 0) {
                var $wrapper = $('<div class="user-search-wrapper" style="position: relative; margin-bottom: 10px;"></div>');
                var $searchInput = $('<input type="text" class="ft-input-big user-search-input" placeholder="' + $select.find('option:first').text() + '" style="margin-bottom: 10px;" />');
                $wrapper.append($searchInput);
                $select.before($wrapper);
                
                // Filter options on search
                $searchInput.on('input', function() {
                    var searchTerm = $(this).val().toLowerCase();
                    $select.find('option').each(function() {
                        var $option = $(this);
                        if ($option.val() === '') {
                            return; // Keep placeholder option visible
                        }
                        var searchText = $option.attr('data-search') || $option.text().toLowerCase();
                        if (searchText.indexOf(searchTerm) !== -1) {
                            $option.show();
                        } else {
                            $option.hide();
                        }
                    });
                });
                
                // Update search input when select changes
                $select.on('change', function() {
                    if ($(this).val()) {
                        $searchInput.val($(this).find('option:selected').text());
                    } else {
                        $searchInput.val('');
                    }
                    // Show all options again
                    $select.find('option').show();
                    updateStepStates();
                });
            }
            userSearchInitialized = true;
        }
    });

    // Track category checkbox changes
    $(document).on('change', '.post-category-checkbox', function() {
        updateStepStates();
    });

    $('input[name="prompt_selection_mode"]').on('change', function() {
        updateStepStates();
    });


    $('.prompt-content-textarea').on('input change keyup', function() {
        updateStepStates();
    });

    // Track TinyMCE editor changes
    function setupTinyMCETracking() {
        if (typeof tinymce !== 'undefined') {
            // Check if editor is already initialized
            if (tinymce.get('anchor_text_editor')) {
                var editor = tinymce.get('anchor_text_editor');
                editor.on('keyup change SetContent', function() {
                    setTimeout(updateStepStates, 100);
                });
            }
            
            // Listen for editor initialization
            $(document).on('tinymce-editor-init', function(event, editor) {
                if (editor.id === 'anchor_text_editor') {
                    editor.on('keyup change SetContent', function() {
                        setTimeout(updateStepStates, 100);
                    });
                }
            });
            
            // Also listen for WordPress editor setup
            if (typeof wp !== 'undefined' && wp.domReady) {
                wp.domReady(function() {
                    setTimeout(function() {
                        if (tinymce.get('anchor_text_editor')) {
                            var editor = tinymce.get('anchor_text_editor');
                            editor.on('keyup change SetContent', function() {
                                setTimeout(updateStepStates, 100);
                            });
                        }
                    }, 1000);
                });
            }
        }
    }
    
    setupTinyMCETracking();

    // Initial step state update
    setTimeout(updateStepStates, 500);
    // Also update after a delay to catch any late-loading elements
    setTimeout(updateStepStates, 1500);

    // Form submit handler
    $('#add-post-form').on('submit', function(e) {
        e.preventDefault();

        var postTitles = $('#post-titles').val().trim();
        if (!postTitles) {
            aiautotool_alert_error('<?php echo esc_js(__('Please enter at least one post title.', 'ai-auto-tool')); ?>', '');
            return;
        }
        
        var titlesArray = postTitles.split('\n').filter(function(line) {
            return line.trim().length > 0;
        });
        
        if (titlesArray.length === 0) {
            aiautotool_alert_error('<?php echo esc_js(__('Please enter at least one post title.', 'ai-auto-tool')); ?>', '');
            return;
        }

        var autoGenerateTitle = $('#auto_change_title').prop('checked');
        var aiautotool_prompt = $('#aiautotool_prompt').val();
        var securityToken = aiautotool_js_setting.security;
        var batchSize = 10;
        var anchor_text = '';
        
        // Get anchor text from TinyMCE if available
        if (typeof tinymce !== 'undefined' && tinymce.get('anchor_text_editor')) {
            anchor_text = tinymce.get('anchor_text_editor').getContent();
        }
        
        // Check prompt selection mode
        var promptMode = $('input[name="prompt_selection_mode"]:checked').val();
        var multiplePromptContents = [];
        if (promptMode === 'multiple') {
            $('.prompt-content-textarea').each(function() {
                var promptId = $(this).data('prompt-id');
                var promptContent = $(this).val();
                if (promptId && promptContent) {
                    multiplePromptContents.push({
                        id: promptId,
                        content: promptContent
                    });
                }
            });
            if (multiplePromptContents.length === 0) {
                aiautotool_alert_error('<?php echo esc_js(__('Please select at least one prompt and wait for it to load for multiple prompt mode.', 'ai-auto-tool')); ?>', '');
                return;
            }
        }

        var $submitBtn = $('#btnSubmitaddpost');
        var $progressContainer = $('#progress-bar-container');
        var $progressBar = $('#progress-bar .progress-fill');
        var $progressText = $('#progress-text');
        var $progressPercent = $('#progress-percent');
        var $postList = $('#post-list');
        
        // Disable submit button and show progress
        $submitBtn.prop('disabled', true).addClass('loading');
        $progressContainer.slideDown(300);
        $postList.empty();

        function sendBatchAjaxRequest(startIndex) {
            var endIndex = Math.min(startIndex + batchSize, titlesArray.length);
            var batchData = titlesArray.slice(startIndex, endIndex).join('\n');

            // Get selected categories as array
            var selectedCategories = [];
            $('.post-category-checkbox:checked').each(function() {
                selectedCategories.push($(this).val());
            });

            // Get post author data
            var postAuthorMode = $('#post_author_mode').val();
            var postAuthorUser = $('#post_author_user').val();

            var data = {
                action: 'add_post',
                post_titles: batchData,
                post_category: selectedCategories,
                post_tags: $('#post_tags').val(),
                auto_change_title: autoGenerateTitle,
                auto_generate_tags: $('#auto_generate_tags').prop('checked') ? 1 : 0,
                post_language: $('#post_language').val(),
                anchor_text: anchor_text,
                prompt_selection_mode: promptMode,
                post_author_mode: postAuthorMode,
                post_author_user: postAuthorUser,
                security: securityToken
            };
            
            // Add prompt data based on mode
            if (promptMode === 'single') {
                if (aiautotool_prompt) {
                    data.aiautotool_prompt = aiautotool_prompt;
                }
            } else if (promptMode === 'multiple' && multiplePromptContents.length > 0) {
                data.multiple_prompt_contents = JSON.stringify(multiplePromptContents);
            }
            // Note: promptMode === 'auto' doesn't need any prompt data

            $.post(aiautotool_js_setting.ajax_url, data, function(response) {
                if (response.success) {
                    var posts = response.data;
                    var listHtml = $postList.html() || '';
                    
                    for (var i = 0; i < posts.length; i++) {
                        var post = posts[i];
                        var postNum = startIndex + i + 1;
                        listHtml += '<li><span class="post-number">' + postNum + '.</span> <a href="' + post.url_edit + '" target="_blank">' + post.title + '</a> <i class="fa-solid fa-external-link-alt" style="font-size: 11px; color: #999;"></i></li>';
                    }
                    
                    $postList.html(listHtml);

                    var progress = Math.min(((endIndex / titlesArray.length) * 100), 100);
                    $progressBar.css('width', progress + '%');
                    $progressPercent.text(Math.round(progress) + '%');
                    $progressText.text('<?php echo esc_js(__('Creating posts...', 'ai-auto-tool')); ?> ' + endIndex + ' / ' + titlesArray.length);

                    if (endIndex < titlesArray.length) {
                        sendBatchAjaxRequest(endIndex);
                    } else {
                        // All done
                        $submitBtn.prop('disabled', false).removeClass('loading');
                        $progressText.text('<?php echo esc_js(__('All posts created successfully!', 'ai-auto-tool')); ?>');
                        $progressPercent.text('100%');
                        
                        setTimeout(function() {
                            $progressContainer.slideUp(300);
                        }, 2000);
                    }
                } else {
                    $submitBtn.prop('disabled', false).removeClass('loading');
                    $progressContainer.slideUp(300);
                    var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('An error occurred while creating posts.', 'ai-auto-tool')); ?>';
                    aiautotool_alert_error(errorMsg, '');
                }
            }).fail(function() {
                $submitBtn.prop('disabled', false).removeClass('loading');
                $progressContainer.slideUp(300);
                aiautotool_alert_error('<?php echo esc_js(__('Network error. Please try again.', 'ai-auto-tool')); ?>', '');
            });
        }
        
        sendBatchAjaxRequest(0);
    });
});


</script>
        <?php
    }

    
    public function enqueue_scripts($hook) {
        // Chỉ enqueue scripts cho admin có quyền cao nhất
        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 add-post-draft page
        $screen = get_current_screen();
        $is_add_post_draft_page = false;
        
        // Check via hook (most reliable)
        if (strpos($hook, 'add-post-draft') !== false) {
            $is_add_post_draft_page = true;
        }
        
        // Check via screen ID
        if ($screen && (strpos($screen->id, 'add-post-draft') !== false)) {
            $is_add_post_draft_page = true;
        }
        
        // Check via GET parameter
        if (isset($_GET['page']) && $_GET['page'] === 'add-post-draft') {
            $is_add_post_draft_page = true;
        }
        
        // Enqueue CSS for add-post-draft page
        if ($is_add_post_draft_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 (contains showLoading, hideLoading functions)
            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 for aiautotool.js
            wp_localize_script('kct_cr_scriptx', '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
            ));
        } else {
            $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',
            );

            // Still localize for jQuery even if not on add-post-draft page
            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
            ));
        }
    }


    /**
     * Fix question prompt by replacing placeholders
     * @param string $prompt Original prompt
     * @param string $title Post title
     * @param string $lang Language
     * @param string $blog Blog name
     * @param string $cate Category
     * @param string $content Content
     * @return string Fixed prompt
     */
    public function aiautotool_fix_question($prompt, $title = '', $lang = '', $blog = '', $cate = '', $content = '') {
        $replacements = array(
            '%%title%%' => $title,
            '%%lang%%' => $lang,
            '%%blog%%' => $blog,
            '%%cate%%' => $cate,
            '%%content%%' => $content
        );

        $outprompt = str_replace(array_keys($replacements), array_values($replacements), $prompt);
        return $outprompt;
    }

    /**
     * Generate AI idea titles for posts
     * @return array Array of suggested titles
     */
    public function aiautotool_idea_title_post() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        // Check if AI Helper is available
        if (!class_exists('AIAutotool_AI_Helper')) {
            wp_send_json_error(array('message' => __('AI Helper not available. Please ensure AI Providers module is loaded.', 'ai-auto-tool')));
        }
        
        if (!AIAutotool_AI_Helper::is_available()) {
            wp_send_json_error(array('message' => __('No AI provider configured. Please configure an AI provider in settings.', 'ai-auto-tool')));
        }
        
        $default_language = get_option('aiautotool_default_language', 'vi');
        $lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
        
        // Get category if provided
        $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
        $category_name = isset($_POST['category_name']) ? sanitize_text_field($_POST['category_name']) : '';
        
        // If category is provided, get category name from WordPress
        if ($category_id > 0 && empty($category_name)) {
            $category = get_category($category_id);
            if ($category && !is_wp_error($category)) {
                $category_name = $category->name;
            }
        }
        
        // Generate idea titles using AI Helper
        $ideas = $this->generate_ideas_with_ai_helper($lang, 10, $category_name);
        
        if (!empty($ideas)) {
            wp_send_json_success(array('output' => $ideas));
        } else {
            wp_send_json_error('Failed to generate ideas');
        }
    }
    
    /**
     * Generate blog post idea titles using AI Helper
     * 
     * @param string $lang Language for generation
     * @param int $count Number of ideas to generate
     * @param string $category Category name (optional)
     * @return array Array of idea objects with 'title' property
     */
    private function generate_ideas_with_ai_helper($lang = 'Vietnamese', $count = 10, $category = '') {
        // Build simple prompt - chỉ yêu cầu danh sách title, mỗi title một dòng
        $prompt = "Tạo {$count} tiêu đề bài viết blog hấp dẫn và SEO-friendly";
        
        // Add category context if provided
        if (!empty($category)) {
            $prompt .= " về chủ đề: {$category}";
        }
        
        $prompt .= ". Mỗi tiêu đề một dòng, không đánh số, không ký tự đặc biệt. Viết bằng {$lang}.";
        
        // Use AI Helper to generate ideas
        $result = AIAutotool_AI_Helper::generate($prompt, array(
            'temperature' => 0.8,
            'max_tokens' => 1000
        ));
        
        // Check if generation was successful
        if (!$result['success']) {
            // Fallback: return default ideas
            return $this->get_default_ideas($lang, $count, $category);
        }
        
        $content = $result['content'];
        
        // Parse the result to extract titles - chỉ lấy mỗi dòng là một title
        $ideas = $this->parse_ideas_from_response($content, $count);
        
        // If we got enough ideas, return them
        if (!empty($ideas) && count($ideas) >= min(3, $count)) {
            return array_slice($ideas, 0, $count);
        }
        
        // Fallback if parsing didn't work well
        return $this->get_default_ideas($lang, $count, $category);
    }
    
    /**
     * Parse ideas from AI response
     * Chỉ lấy danh sách title, mỗi title một dòng
     * 
     * @param string $content AI response content
     * @param int $count Number of ideas needed
     * @return array Array of idea objects with 'title' property
     */
    private function parse_ideas_from_response($content, $count) {
        $ideas = array();
        
        // Remove HTML tags if any
        $content = strip_tags($content);
        
        // Normalize line breaks
        $content = str_replace(array("\r\n", "\r"), "\n", $content);
        
        // Split by newlines - mỗi dòng là một title
        $lines = explode("\n", $content);
        
        foreach ($lines as $line) {
            // Clean up the line
            $line = trim($line);
            
            // Remove numbering if AI still adds it (1., 2., etc.)
            $line = preg_replace('/^\d+[\.\)]\s*/', '', $line);
            // Remove bullet points if any
            $line = preg_replace('/^[\-\*\•\◦]\s*/', '', $line);
            $line = trim($line);
            
            // Skip empty lines or very short lines (less than 5 characters)
            if (!empty($line) && strlen($line) >= 5) {
                $ideas[] = array('title' => $line);
                if (count($ideas) >= $count) {
                    break;
                }
            }
        }
        
        return $ideas;
    }
    
    /**
     * Get default ideas as fallback
     * 
     * @param string $lang Language
     * @param int $count Number of ideas
     * @param string $category Category name
     * @return array Array of default idea objects
     */
    private function get_default_ideas($lang = 'Vietnamese', $count = 10, $category = '') {
        $categoryPrefix = !empty($category) ? $category . ': ' : '';
        $defaultIdeas = array(
            array('title' => $categoryPrefix . 'Cách bắt đầu với ' . $lang),
            array('title' => $categoryPrefix . 'Hướng dẫn chi tiết về ' . $lang),
            array('title' => $categoryPrefix . 'Tips và tricks cho ' . $lang),
            array('title' => $categoryPrefix . 'Những điều cần biết về ' . $lang),
            array('title' => $categoryPrefix . 'Best practices cho ' . $lang),
        );
        
        return array_slice($defaultIdeas, 0, min($count, count($defaultIdeas)));
    }

    /**
     * Add missing cron widget reference
     */
    private function get_cron_widget() {
        if (class_exists('AIAutoTool_Cron_Status_Widget')) {
            return AIAutoTool_Cron_Status_Widget::get_instance();
        }
        return null;
    }
    
    /**
     * Helper function to update cron status with incremental progress
     * This helps show progress during long-running operations
     */
    private function update_cron_progress($cron_widget, $current_task, $current_post_title, $progress, $cron_type = '', $is_running = true) {
        if ($cron_widget) {
            $cron_widget->update_cron_status(array(
                'is_running' => $is_running,
                'current_task' => $current_task,
                'current_post_title' => $current_post_title,
                'progress' => $progress,
                'cron_type' => $cron_type ? $cron_type : __('Auto Content', 'aiautotool-cron-widget')
            ));
        }
    }
    

    /**
     * Get configured AI Provider models for autoblogging.
     *
     * Values are saved as provider::model so cron can force a specific provider
     * without relying on legacy hardcoded model names.
     *
     * @return array Array of option value => label.
     */
    private function get_available_models() {
        $models = array(
            '' => __('Auto - use AI Provider settings', 'ai-auto-tool')
        );

        if (!class_exists('AIAutotool_AI_Provider_Manager')) {
            $manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_manager.php';
            if (file_exists($manager_file)) {
                require_once $manager_file;
            }
        }

        if (!class_exists('AIAutotool_AI_Provider_Manager')) {
            $models['__no_provider__'] = __('No configured AI Provider. Add API key first.', 'ai-auto-tool');
            return $models;
        }

        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $providers_info = $manager->get_providers_info();

        foreach ($providers_info as $provider_id => $provider_info) {
            if (empty($provider_info['configured']) || empty($provider_info['models']) || !is_array($provider_info['models'])) {
                continue;
            }

            $provider_name = !empty($provider_info['name']) ? $provider_info['name'] : $provider_id;
            foreach ($provider_info['models'] as $model_id => $model_name) {
                $model_id = (string) $model_id;
                if ($model_id === '') {
                    continue;
                }

                $models[$provider_id . '::' . $model_id] = sprintf(
                    '%s - %s',
                    $provider_name,
                    !empty($model_name) ? $model_name : $model_id
                );
            }
        }

        if (count($models) === 1) {
            $models['__no_provider__'] = __('No configured AI Provider. Add API key first.', 'ai-auto-tool');
        }

        return $models;
    }

    private function resolve_autoblogging_ai_selection($model_value, $provider_id = '') {
        $model_value = is_string($model_value) ? trim($model_value) : '';
        $provider_id = is_string($provider_id) ? trim($provider_id) : '';

        if ($model_value === '' || $model_value === '__no_provider__') {
            return array(
                'provider_id' => '',
                'model' => '',
                'auto' => true,
            );
        }

        if (strpos($model_value, '::') !== false) {
            $parts = explode('::', $model_value, 2);
            return array(
                'provider_id' => sanitize_key($parts[0]),
                'model' => sanitize_text_field($parts[1]),
                'auto' => false,
            );
        }

        return array(
            'provider_id' => $provider_id,
            'model' => sanitize_text_field($model_value),
            'auto' => false,
        );
    }

    private function is_auto_image_disabled() {
        return filter_var(get_option('aiautotool_draft_public_turnoff_auto_images', false), FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Generate full article from title (for cron usage, no SSE streaming)
     * This function uses the same logic as aiautotool_write_article_with_analysis_callback
     * but adapted for cron jobs - collects all content internally and returns final article
     * 
     * @param string $title Article title
     * @param string $lang Language (default: 'Vietnamese')
     * @param string $model AI provider/model selection. Empty means use AI Provider routing.
     * @param string $provider_id Provider ID (optional)
     * @return string|false Full article content in HTML format, or false on error
     */
    public function generate_article_from_title($title, $lang = 'Vietnamese', $model = '', $provider_id = '') {
        // Set execution time limit for long-running cron jobs
        @set_time_limit(600); // 10 minutes
        @ini_set('max_execution_time', 600);
        @ignore_user_abort(true);
        
        if (empty($title)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        // Load required files
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        
        // Load AI Helper and AI Agent for new AI Provider system
        if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php';
        }
        
        // Initialize BardGenContent for fallback
        $bardGenContent = new BardGenContent();

        $ai_selection = $this->resolve_autoblogging_ai_selection($model, $provider_id);
        $provider_id = $ai_selection['provider_id'];
        $model = $ai_selection['model'];
        $auto_ai_provider_selection = !empty($ai_selection['auto']);
        
        // Helper function to convert markdown to HTML
        $convert_markdown_to_html = function($text) {
            if (empty($text)) {
                return '';
            }
            
            // Check if content is already HTML (has HTML tags)
            $has_html = preg_match('/<[a-z][\s\S]*>/i', $text);
            if ($has_html) {
                return $text; // Already HTML, return as is
            }
            
            // Try Parsedown first
            $parsedown_loaded = false;
            if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php';
                $parsedown_loaded = class_exists('Parsedown');
            }
            
            if ($parsedown_loaded) {
                $parsedown = new Parsedown();
                return $parsedown->text($text);
            }
            
            // Try markdown parser function
            if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php';
                if (function_exists('markdown')) {
                    return markdown($text);
                }
            }
            
            // Fallback to simple inline parser
            $html = preg_replace('/^######\s+(.+)$/m', '<h6>$1</h6>', $text);
            $html = preg_replace('/^#####\s+(.+)$/m', '<h5>$1</h5>', $html);
            $html = preg_replace('/^####\s+(.+)$/m', '<h4>$1</h4>', $html);
            $html = preg_replace('/^###\s+(.+)$/m', '<h3>$1</h3>', $html);
            $html = preg_replace('/^##\s+(.+)$/m', '<h2>$1</h2>', $html);
            $html = preg_replace('/^#\s+(.+)$/m', '<h1>$1</h1>', $html);
            $html = preg_replace_callback('/```([\s\S]*?)```/m', function($matches) {
                return '<pre><code>' . esc_html(trim($matches[1])) . '</code></pre>';
            }, $html);
            $html = preg_replace('/`([^`]+)`/', '<code>$1</code>', $html);
            $html = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $html);
            $html = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $html);
            $html = preg_replace('/(?<!\*)\*([^*]+?)\*(?!\*)/', '<em>$1</em>', $html);
            $html = preg_replace('/(?<!_)_([^_]+?)_(?!_)/', '<em>$1</em>', $html);
            $html = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2" target="_blank" rel="nofollow">$1</a>', $html);
            $html = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '<img src="$2" alt="$1" style="max-width:100%;height:auto;" />', $html);
            $html = preg_replace('/^>\s+(.+)$/m', '<blockquote>$1</blockquote>', $html);
            $html = preg_replace('/^[\-\*]\s+(.+)$/m', '<li>$1</li>', $html);
            $html = preg_replace('/(<li>.*<\/li>\n?)+/s', '<ul>$0</ul>', $html);
            $html = preg_replace('/^\d+\.\s+(.+)$/m', '<li>$1</li>', $html);
            $html = preg_replace('/\n\n+/', '</p><p>', $html);
            $html = '<p>' . $html . '</p>';
            $html = preg_replace('/<p>\s*<\/p>/', '', $html);
            $html = preg_replace('/<p>(<[^>]+>)/', '$1<p>', $html);
            $html = preg_replace('/(<\/[^>]+>)<\/p>/', '$1', $html);
            
            return $html;
        };
        
        // Track last AI call time to ensure minimum 10 seconds between calls
        $last_ai_call_time = 0;
        $min_ai_call_interval = 10; // Minimum seconds between AI calls
        
        // Helper function to generate content using AI Agent with fallback
        $generate_with_agent = function($prompt, $lang, $model, $provider_id = '', $options = array()) use ($bardGenContent, &$last_ai_call_time, $min_ai_call_interval) {
            // Ensure minimum 10 seconds between AI calls
            $current_time = time();
            $time_since_last_call = $current_time - $last_ai_call_time;
            
            if ($last_ai_call_time > 0 && $time_since_last_call < $min_ai_call_interval) {
                $wait_time = $min_ai_call_interval - $time_since_last_call;
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                sleep($wait_time);
            }
            
            // Update last call time before making the call
            $last_ai_call_time = time();
            
            // Try AI Agent first if available
            if (class_exists('AIAutotool_AI_Agent')) {
                $agent = AIAutotool_AI_Agent::get_instance();
                
                // Determine use case based on prompt content
                $use_case = 'general';
                $prompt_lower = strtolower($prompt);
                if (stripos($prompt_lower, 'checklist') !== false || stripos($prompt_lower, 'danh sách') !== false) {
                    $use_case = 'fast';
                } elseif (stripos($prompt_lower, 'phân tích') !== false || stripos($prompt_lower, 'analyze') !== false) {
                    $use_case = 'reasoning';
                } elseif (strlen($prompt) > 2000) {
                    $use_case = 'long_context';
                }
                
                // Merge options - allow use_case override from options
                if (isset($options['use_case'])) {
                    $use_case = $options['use_case'];
                }
                
                $agent_options = array_merge(array(
                    'use_case' => $use_case,
                    'temperature' => 0.7,
                    'max_tokens' => isset($options['max_tokens']) ? $options['max_tokens'] : 2000
                ), $options);
                
                // If provider_id is specified, try that first
                if (!empty($provider_id)) {
                    $agent_options['provider'] = $provider_id;
                    if (!empty($model)) {
                        $agent_options['model'] = $model;
                    }
                }
                
                $result = $agent->generate($prompt, $agent_options);
                
                if ($result['success'] && !empty($result['content'])) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    return array(
                        'code' => '200',
                        'result' => $result['content'],
                        'provider' => $result['provider'],
                        'model' => $result['model']
                    );
                }
            }
            
            // Fallback to old method (bardcontentmore)
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            return $bardGenContent->bardcontentmore($prompt, $lang, $model);
        };
        
        // Helper function to generate language instruction
        $get_language_instruction = function($lang) {
            $lang_lower = strtolower(trim($lang));
            $lang_instruction = '';
            
            if (strpos($lang_lower, 'vietnamese') !== false || strpos($lang_lower, 'tiếng việt') !== false || 
                $lang_lower === 'vi' || $lang_lower === 'vie') {
                $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n";
                $lang_instruction .= "You MUST respond ONLY in Vietnamese (Tiếng Việt).\n";
                $lang_instruction .= "ALL your output MUST be in Vietnamese language only.\n";
                $lang_instruction .= "DO NOT use English or any other language.\n";
                $lang_instruction .= "Response language: Vietnamese (Tiếng Việt) ONLY.\n\n";
            } elseif (strpos($lang_lower, 'english') !== false || $lang_lower === 'en' || $lang_lower === 'eng') {
                $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n";
                $lang_instruction .= "You MUST respond ONLY in English.\n";
                $lang_instruction .= "ALL your output MUST be in English language only.\n";
                $lang_instruction .= "DO NOT use Vietnamese or any other language.\n";
                $lang_instruction .= "Response language: English ONLY.\n\n";
            } else {
                $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n";
                $lang_instruction .= "You MUST respond ONLY in {$lang} language.\n";
                $lang_instruction .= "ALL your output MUST be in {$lang} language only.\n";
                $lang_instruction .= "DO NOT use any other language.\n";
                $lang_instruction .= "Response language: {$lang} ONLY.\n\n";
            }
            
            return $lang_instruction;
        };
        
        try {
            // Get website information
            $site_name = get_bloginfo('name');
            $site_url = home_url();
            
            // Get author information (use first available author for cron)
            $authors = get_users(array('who' => 'authors', 'number' => 1));
            $author_name = !empty($authors) ? $authors[0]->display_name : 'Admin';
            $author_bio = !empty($authors) ? get_user_meta($authors[0]->ID, 'description', true) : '';
            
            // Step 1: Generate Checklist
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $checklist_prompt = $get_language_instruction($lang);
            $checklist_prompt .= "You are an SEO Content Author with deep understanding of user intent and search behavior.\n\n";
            $checklist_prompt .= "Your task: Analyze the topic based on the provided **title**.\n\n";
            $checklist_prompt .= "Input:\n\n";
            $checklist_prompt .= "- title: \"{$title}\"\n\n";
            $checklist_prompt .= "Output:\n\n";
            $checklist_prompt .= "Provide a structured analysis including:\n\n";
            $checklist_prompt .= "1. **User Intent Analysis**\n\n";
            $checklist_prompt .= "   - Người tìm kiếm với tiêu đề này đang muốn điều gì?\n\n";
            $checklist_prompt .= "   - Họ gặp vấn đề, nỗi đau, thắc mắc gì?\n\n";
            $checklist_prompt .= "   - Mục đích của họ là: tìm hiểu, so sánh, mua hàng, hay giải pháp?\n\n";
            $checklist_prompt .= "2. **Search Intent Classification**\n\n";
            $checklist_prompt .= "   - Phân loại theo 3 nhóm:\n\n";
            $checklist_prompt .= "     - Informational (tìm hiểu)\n\n";
            $checklist_prompt .= "     - Commercial Investigation (cân nhắc)\n\n";
            $checklist_prompt .= "     - Transactional (muốn mua)\n\n";
            $checklist_prompt .= "   - Giải thích lý do chọn loại này.\n\n";
            $checklist_prompt .= "3. **What Users Expect From This Article**\n\n";
            $checklist_prompt .= "   - Danh sách 5–10 thông tin, câu trả lời hoặc nội dung mà người dùng mong đợi.\n\n";
            $checklist_prompt .= "   - Điều gì khiến họ hài lòng sau khi đọc?\n\n";
            $checklist_prompt .= "4. **What We Should Provide**\n\n";
            $checklist_prompt .= "   - Những mục nội dung cần có trong bài viết để thoả mãn user intent.\n\n";
            $checklist_prompt .= "   - Insight đặc biệt mà đối thủ thường thiếu.\n\n";
            $checklist_prompt .= "   - Nội dung cần ưu tiên + về lý do.\n\n";
            $checklist_prompt .= "5. **SEO Opportunities**\n\n";
            $checklist_prompt .= "   - Gợi ý LSI keywords, entity liên quan.\n\n";
            $checklist_prompt .= "   - Gợi ý schema nên dùng.\n\n";
            $checklist_prompt .= "   - Định hướng cấu trúc bài chuẩn SEO.\n\n";
            $checklist_prompt .= "Hãy trình bày phân tích một cách logic, có chiều sâu, theo phong cách tác giả chuyên nghiệp.\n\n";
            $checklist_prompt .= "IMPORTANT: Return the analysis in JSON format only. Keep responses concise and structured. Use this JSON structure:\n";
            $checklist_prompt .= "{\n";
            $checklist_prompt .= "  \"user_intent\": {\"what_they_want\": \"\", \"problems\": \"\", \"purpose\": \"\"},\n";
            $checklist_prompt .= "  \"search_intent\": {\"type\": \"\", \"reason\": \"\"},\n";
            $checklist_prompt .= "  \"user_expectations\": [],\n";
            $checklist_prompt .= "  \"content_to_provide\": {\"required_sections\": [], \"unique_insights\": \"\", \"priorities\": \"\"},\n";
            $checklist_prompt .= "  \"seo_opportunities\": {\"lsi_keywords\": [], \"schema\": \"\", \"structure\": \"\"}\n";
            $checklist_prompt .= "}\n\n";
            if (!empty($author_bio)) {
                $checklist_prompt .= "Author description: {$author_bio}\n\n";
            }
            
            // Get provider_id from settings if not provided
            if (!$auto_ai_provider_selection && empty($provider_id) && class_exists('AIAutotool_AI_Provider_Manager')) {
                $manager = AIAutotool_AI_Provider_Manager::get_instance();
                $active_provider = $manager->get_active_provider();
                if ($active_provider) {
                    $provider_id = $active_provider->get_id();
                }
            }
            
            $checklist_result = $generate_with_agent($checklist_prompt, $lang, $model, $provider_id, array(
                'max_tokens' => 2000,
                'temperature' => 0.7,
                'use_case' => 'reasoning'
            ));
            
            if (is_array($checklist_result) && isset($checklist_result['code']) && $checklist_result['code'] != '200') {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return false;
            }
            
            $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result;
            $checklist_text = $convert_markdown_to_html($checklist_text);
            
            // Step 2: Generate Author Credibility Info
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $author_credibility_prompt = $get_language_instruction($lang);
            $author_credibility_prompt .= "Based on the checklist from step 1, create author credibility information to establish credibility for the article.\n";
            $author_credibility_prompt .= "ONLY RETURN THE NECESSARY INFORMATION, DO NOT WRITE ANYTHING ELSE.\n\n";
            $author_credibility_prompt .= "Checklist from step 1:\n{$checklist_text}\n\n";
            $author_credibility_prompt .= "Author name: {$author_name}\n";
            if (!empty($author_bio)) {
                $author_credibility_prompt .= "Current author description: {$author_bio}\n";
            }
            $author_credibility_prompt .= "\nONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n";
            
            $author_credibility_result = $generate_with_agent($author_credibility_prompt, $lang, $model, $provider_id, array(
                'max_tokens' => 500,
                'temperature' => 0.7
            ));
            
            if (is_array($author_credibility_result) && isset($author_credibility_result['code']) && $author_credibility_result['code'] != '200') {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return false;
            }
            
            $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result;
            $author_credibility_text = $convert_markdown_to_html($author_credibility_text);
            
            // Step 3: Analyze Keywords
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 150, 'UTF-8');
            $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 150, 'UTF-8');
            $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary));
            $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary));
            
            $keywords_prompt = $get_language_instruction($lang);
            $keywords_prompt .= "Based on the following information, create a list of necessary keywords for the article.\n";
            $keywords_prompt .= "ONLY RETURN KEYWORDS, DO NOT ADD ANY DESCRIPTION.\n\n";
            $keywords_prompt .= "Title: {$title}\n\n";
            $keywords_prompt .= "Checklist: {$checklist_summary}\n";
            $keywords_prompt .= "Author credibility information: {$author_credibility_summary}\n\n";
            $keywords_prompt .= "Requirements:\n";
            $keywords_prompt .= "1. 10-15 main keywords\n";
            $keywords_prompt .= "2. Secondary keywords and LSI\n\n";
            $keywords_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n";
            
            $keywords_analysis = $generate_with_agent($keywords_prompt, $lang, $model, $provider_id, array(
                'max_tokens' => 800,
                'temperature' => 0.7
            ));
            
            if (is_array($keywords_analysis) && isset($keywords_analysis['code']) && $keywords_analysis['code'] != '200') {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return false;
            }
            
            $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis;
            $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text);
            
            // Step 4: Determine Content Direction
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $checklist_final = mb_substr(strip_tags($checklist_text), 0, 200, 'UTF-8');
            $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 200, 'UTF-8');
            $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 300, 'UTF-8');
            
            $checklist_final = preg_replace('/\s+/', ' ', trim($checklist_final));
            $author_credibility_final = preg_replace('/\s+/', ' ', trim($author_credibility_final));
            $keywords_final = preg_replace('/\s+/', ' ', trim($keywords_final));
            
            $direction_prompt = $get_language_instruction($lang);
            $direction_prompt .= "Title: {$title}\n\n";
            $direction_prompt .= "Analysis summary:\n";
            $direction_prompt .= "- Checklist: {$checklist_final}\n";
            $direction_prompt .= "- Author credibility information: {$author_credibility_final}\n";
            $direction_prompt .= "- Keywords: {$keywords_final}\n\n";
            $direction_prompt .= "Requirements:\n";
            $direction_prompt .= "1. Article structure (number of sections, headings)\n";
            $direction_prompt .= "2. Content and main points\n";
            $direction_prompt .= "3. Style and tone\n";
            $direction_prompt .= "4. Length and format\n\n";
            $direction_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n";
            
            $direction_analysis = $generate_with_agent($direction_prompt, $lang, $model, $provider_id, array(
                'max_tokens' => 1000,
                'temperature' => 0.7
            ));
            
            if (is_array($direction_analysis) && isset($direction_analysis['code']) && $direction_analysis['code'] != '200') {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return false;
            }
            
            $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis;
            $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text);
            
            // Step 5: Parse checklist to extract required sections
            $article_sections = array();
            $checklist_plain = strip_tags($checklist_text);
            
            // Try to extract JSON from checklist_text
            if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) {
                $json_start = strpos($checklist_plain, '{');
                $json_end = strrpos($checklist_plain, '}');
                if ($json_start !== false && $json_end !== false && $json_end > $json_start) {
                    $json_str = substr($checklist_plain, $json_start, $json_end - $json_start + 1);
                    $checklist_json = json_decode($json_str, true);
                    if ($checklist_json && isset($checklist_json['content_to_provide']['required_sections'])) {
                        $article_sections = $checklist_json['content_to_provide']['required_sections'];
                    }
                }
            }
            
            // Fallback: create default sections
            if (empty($article_sections) || !is_array($article_sections)) {
                $article_sections = array('Introduction', 'Main Content', 'Conclusion');
            }
            
            // Step 6: Generate prompts for each section
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $lang_instruction_final = $get_language_instruction($lang);
            $article_end_marker = "<!--ARTICLE_COMPLETE_END-->";
            
            $common_requirements = "Requirements:\n";
            $common_requirements .= "- output with Language: {$lang}\n";
            $common_requirements .= "- Format: Markdown (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n";
            $common_requirements .= "- SEO: Optimize keywords\n";
            $common_requirements .= "- Quality: High, useful, professional\n";
            $common_requirements .= "- Style: According to analysis\n";
            $common_requirements .= "- Write for readers. The writing should be poetic.\n";
            
            $section_prompts = array();
            $total_sections = count($article_sections);
            
            for ($i = 0; $i < $total_sections; $i++) {
                $section_name = $article_sections[$i];
                $is_first_section = ($i === 0);
                $is_last_section = ($i === $total_sections - 1);
                
                $section_prompt = $lang_instruction_final;
                
                if ($is_first_section) {
                    $section_prompt .= "Write the first section of the article:\n\n";
                } else {
                    $section_prompt .= "Continue writing the next section of the article:\n\n";
                }
                
                $section_prompt .= "Title: {$title}\n\n";
                $section_prompt .= "Analysis:\n";
                $section_prompt .= "1. Checklist: {$checklist_final}\n";
                $section_prompt .= "2. Keywords: {$keywords_final}\n";
                $section_prompt .= "3. Content direction: " . mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8') . "\n\n";
                
                $section_prompt .= "Current Section to Write: {$section_name}\n";
                $section_prompt .= "Section Number: " . ($i + 1) . " of {$total_sections}\n\n";
                
                $section_prompt .= $common_requirements;
                
                if ($is_first_section) {
                    $section_prompt .= "\n- IMPORTANT: Write the article directly, DO NOT introduce your AI role, DO NOT say \"Excellent!\", \"As a...\", \"I believe I can...\" or any introductory phrases. Start writing the article immediately.\n";
                    $section_prompt .= "- Write the introduction section of the article. This should be engaging and hook the reader.\n";
                } else {
                    $section_prompt .= "\n- IMPORTANT: Continue writing seamlessly from the previous section.\n";
                    $section_prompt .= "- You will receive the last part of the previous section to continue from.\n";
                    $section_prompt .= "- Write the section: {$section_name}\n";
                    $section_prompt .= "- Make sure the transition is smooth and natural.\n";
                }
                
                if ($is_last_section) {
                    $section_prompt .= "\n- CRITICAL: When you finish writing this final section, you MUST add this exact marker at the very end: {$article_end_marker}\n";
                    $section_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n";
                    $section_prompt .= "- Make sure to write a proper conclusion that wraps up the article.\n";
                }
                
                $section_prompts[] = array(
                    'section_name' => $section_name,
                    'section_index' => $i,
                    'prompt' => $section_prompt,
                    'is_first' => $is_first_section,
                    'is_last' => $is_last_section
                );
            }
            
            // Step 7: Write Article section by section
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Build system prompt for article writing
            $author_info_for_system = '';
            if (!empty($author_credibility_text)) {
                $author_credibility_plain = strip_tags($author_credibility_text);
                $author_credibility_plain = preg_replace('/\s+/', ' ', trim($author_credibility_plain));
                $author_info_for_system = mb_substr($author_credibility_plain, 0, 500, 'UTF-8');
            }
            
            $system_prompt = "You are an expert content writer and SEO specialist with years of experience creating high-quality, engaging articles.\n\n";
            
            if (!empty($author_info_for_system)) {
                $system_prompt .= "Author Role and Credibility:\n";
                $system_prompt .= "You are writing as the article author with the following background and credibility:\n";
                $system_prompt .= $author_info_for_system . "\n\n";
                $system_prompt .= "IMPORTANT: Embody this author persona when writing. Write from this author's perspective, using their expertise, experience, and voice. ";
                $system_prompt .= "However, DO NOT explicitly mention or introduce this author information in the article content itself. ";
                $system_prompt .= "Instead, let your writing naturally reflect this author's expertise and perspective through the quality, depth, and style of the content.\n\n";
            }
            
            $system_prompt .= "Your role:\n";
            $system_prompt .= "- Write comprehensive, well-structured articles that provide real value to readers\n";
            $system_prompt .= "- Optimize content for SEO while maintaining natural, readable flow\n";
            $system_prompt .= "- Use proper markdown formatting (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n";
            $system_prompt .= "- Create content that is original, informative, and engaging\n\n";
            $system_prompt .= "Writing guidelines:\n";
            $system_prompt .= "- Write directly as the article author - DO NOT introduce yourself as AI\n";
            $system_prompt .= "- DO NOT use phrases like \"Excellent!\", \"As a...\", \"I believe I can...\", or any introductory phrases\n";
            $system_prompt .= "- Start writing the article content immediately\n";
            $system_prompt .= "- Integrate information naturally and organically, not mechanically\n";
            $system_prompt .= "- Write for readers first, ensuring the content is valuable and easy to understand\n";
            $system_prompt .= "- Use a poetic, engaging writing style when appropriate\n";
            $system_prompt .= "- Maintain consistency in tone and style throughout the article\n\n";
            $system_prompt .= "Quality standards:\n";
            $system_prompt .= "- High-quality, professional content\n";
            $system_prompt .= "- Accurate, up-to-date information\n";
            $system_prompt .= "- Well-structured with clear headings and subheadings\n";
            $system_prompt .= "- Natural keyword integration (1-2% keyword density)\n";
            $system_prompt .= "- Engaging introduction and strong conclusion with CTA when appropriate\n\n";
            $system_prompt .= "Article completion marker:\n";
            $system_prompt .= "- When you finish writing the complete article, you MUST add this exact marker at the very end: <!--ARTICLE_COMPLETE_END-->\n";
            $system_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n";
            $system_prompt .= "- Only add this marker when the article is truly finished with a proper conclusion.\n";
            
            $lang_instruction = $get_language_instruction($lang);
            if (!empty($lang_instruction)) {
                $system_prompt .= "\n" . $lang_instruction;
            }
            
            // Helper function to extract article content up to the end marker
            $extract_article_content = function($text) use (&$article_end_marker) {
                if (empty($text)) {
                    return $text;
                }
                
                $marker_pos = strpos($text, $article_end_marker);
                if ($marker_pos !== false) {
                    $extracted = substr($text, 0, $marker_pos);
                    return rtrim($extracted);
                }
                
                return $text;
            };
            
            // Write article section by section
            $article_text = '';
            $previous_section_ending = '';
            
            for ($section_idx = 0; $section_idx < $total_sections; $section_idx++) {
                $section_data = $section_prompts[$section_idx];
                $section_name = $section_data['section_name'];
                $section_prompt = $section_data['prompt'];
                $is_first = $section_data['is_first'];
                $is_last = $section_data['is_last'];
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                // If not first section, add previous section ending to prompt
                if (!$is_first && !empty($previous_section_ending)) {
                    $context_ending = mb_substr($previous_section_ending, -1500);
                    $section_prompt .= "\n\n---\n";
                    $section_prompt .= "Here is the ending of the previous section to continue from:\n\n";
                    $section_prompt .= $context_ending . "\n\n";
                    $section_prompt .= "---\n\n";
                    $section_prompt .= "IMPORTANT: Continue writing seamlessly from the last sentence above. ";
                    $section_prompt .= "Do NOT repeat what was already written. Maintain the same writing style and tone.\n";
                }
                
                // Generate section content
                $section_content = $generate_with_agent($section_prompt, $lang, $model, $provider_id, array(
                    'max_tokens' => 4000,
                    'temperature' => 0.8,
                    'use_case' => 'long_context',
                    'system' => $system_prompt
                ));
                
                if (is_array($section_content) && isset($section_content['code']) && $section_content['code'] != '200') {
                    $error_msg = $section_content['msg'] ?? 'Failed to generate section: ' . $section_name;
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    if ($is_last) {
                        break;
                    }
                    continue;
                }
                
                $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content;
                
                // Extract content up to the end marker (if marker exists in last section)
                if ($is_last) {
                    $section_text = $extract_article_content($section_text);
                }
                
                // If not first section, add a newline for separation
                if (!empty($article_text)) {
                    $article_text .= "\n\n";
                }
                
                // Append section_text to article_text
                $article_text .= $section_text;
                
                // Store the ending of this section for next iteration
                $previous_section_ending = mb_substr($section_text, -2000);
                
                // If this is the last section and we have the end marker, we're done
                if ($is_last && strpos($section_text, $article_end_marker) !== false) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    break;
                }
            }
            
            // Step 8: Generate introduction and conclusion summary (mobai and ketbai)
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $article_plain_text = $article_text;
            $article_plain_text = preg_replace('/#{1,6}\s+/', '', $article_plain_text);
            $article_plain_text = preg_replace('/\*\*(.*?)\*\*/', '$1', $article_plain_text);
            $article_plain_text = preg_replace('/\*(.*?)\*/', '$1', $article_plain_text);
            $article_plain_text = preg_replace('/\[([^\]]+)\]\([^\)]+\)/', '$1', $article_plain_text);
            $article_plain_text = preg_replace('/\s+/', ' ', $article_plain_text);
            $article_plain_text = trim($article_plain_text);
            
            $article_for_context = $article_plain_text;
            if (mb_strlen($article_for_context) > 4000) {
                $article_for_context = mb_substr($article_for_context, 0, 2000) . ' ... ' . mb_substr($article_for_context, -2000);
            }
            
            // Create prompt to generate both mobai and ketbai
            if (stripos($lang, 'vietnamese') !== false || stripos($lang, 'việt') !== false || $lang === 'vi' || $lang === 'Vietnamese') {
                $summary_prompt = "Dựa trên nội dung bài viết sau đây, hãy tạo 2 phần:\n\n";
                $summary_prompt .= "1. MỞ BÀI (mobai): Viết một đoạn mở bài giới thiệu ngắn gọn (3-5 câu) dựa trên các ý chính quan trọng của bài viết.\n";
                $summary_prompt .= "2. KẾT BÀI (ketbai): Viết một đoạn tóm tắt kết luận ngắn gọn (3-5 câu) các ý chính quan trọng nhất đã được trình bày trong bài viết.\n\n";
                $summary_prompt .= "Yêu cầu:\n";
                $summary_prompt .= "- Mỗi phần viết 3-5 câu, ngắn gọn, súc tích, dễ hiểu\n";
                $summary_prompt .= "- Tập trung vào những thông tin quan trọng nhất\n";
                $summary_prompt .= "- Viết tự nhiên, không cần tiêu đề 'Mở bài', 'Kết luận' hay 'Tóm tắt'\n";
                $summary_prompt .= "- TRẢ VỀ ĐỊNH DẠNG JSON CHÍNH XÁC với 2 key: 'mobai' và 'ketbai'\n";
                $summary_prompt .= "- Format JSON: {\"mobai\": \"nội dung mở bài\", \"ketbai\": \"nội dung kết bài\"}\n";
                $summary_prompt .= "- CHỈ trả về JSON, không có text thêm, không có markdown code block\n\n";
            } else {
                $summary_prompt = "Based on the following article content, create 2 parts:\n\n";
                $summary_prompt .= "1. INTRODUCTION (mobai): Write a brief introduction paragraph (3-5 sentences) based on the main important points of the article.\n";
                $summary_prompt .= "2. CONCLUSION (ketbai): Write a brief conclusion summary (3-5 sentences) of the main important points presented in the article.\n\n";
                $summary_prompt .= "Requirements:\n";
                $summary_prompt .= "- Each part should be 3-5 sentences, concise, clear, and easy to understand\n";
                $summary_prompt .= "- Focus on the most important information\n";
                $summary_prompt .= "- Write naturally, no need for 'Introduction', 'Conclusion' or 'Summary' headings\n";
                $summary_prompt .= "- RETURN EXACT JSON FORMAT with 2 keys: 'mobai' and 'ketbai'\n";
                $summary_prompt .= "- JSON format: {\"mobai\": \"introduction content\", \"ketbai\": \"conclusion content\"}\n";
                $summary_prompt .= "- RETURN ONLY JSON, no additional text, no markdown code block\n\n";
            }
            
            $summary_prompt .= "Article content:\n" . $article_for_context;
            
            $summary_result = $generate_with_agent($summary_prompt, $lang, $model, $provider_id, array(
                'max_tokens' => 800,
                'temperature' => 0.7,
                'use_case' => 'fast'
            ));
            
            if (is_array($summary_result) && isset($summary_result['code']) && $summary_result['code'] == '200') {
                $summary_response = is_array($summary_result) ? ($summary_result['result'] ?? '') : $summary_result;
                $summary_response = trim($summary_response);
                
                // Try to extract JSON from response
                if (preg_match('/\{[\s\S]*"mobai"[\s\S]*"ketbai"[\s\S]*\}/', $summary_response, $json_match)) {
                    $summary_response = $json_match[0];
                }
                
                $summary_response = preg_replace('/```json\s*/', '', $summary_response);
                $summary_response = preg_replace('/```\s*/', '', $summary_response);
                $summary_response = trim($summary_response);
                
                $summary_data = json_decode($summary_response, true);
                
                if ($summary_data && isset($summary_data['mobai']) && isset($summary_data['ketbai'])) {
                    $mobai = trim($summary_data['mobai']);
                    $ketbai = trim($summary_data['ketbai']);
                    
                    $mobai = trim($mobai, ' "\'');
                    $ketbai = trim($ketbai, ' "\'');
                    
                    if (!empty($mobai) && !empty($ketbai)) {
                        // Add mobai at the beginning of article
                        if (preg_match('/^(#{1,6}\s+.+?\n\n)/', $article_text, $matches)) {
                            $article_text = preg_replace('/^(#{1,6}\s+.+?\n\n)/', '$1' . $mobai . "\n\n", $article_text, 1);
                        } else {
                            $article_text = $mobai . "\n\n" . $article_text;
                        }
                        
                        // Add ketbai at the end of article
                        $article_text .= "\n\n" . $ketbai;
                    }
                }
            }
            
            // Convert final article to HTML
            $article_text = $convert_markdown_to_html($article_text);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            return $article_text;
            
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
    }

} // End of AI_AutoTool_Autoblogging class
} // End of class_exists check
