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

if (!class_exists('AIAutoToolsinglepost')) {
class AIAutoToolsinglepost  extends rendersetting{

    public  $active = true;
    public  $active_option_name = 'AIAutoToolsinglepost_active';
     public  $usage_option_name = 'AI_post_usage';
    public  $settings_option_name = 'aiautotool_singleai_settings';
    public  $icon = '<i class="fa-solid fa-robot"></i>';

    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool ;
    public $name_plan ;
    public $config = array();
    public $notice ;
    
    // Track last AI call time to ensure minimum 10 seconds between calls
    private static $last_ai_call_time = 0;
    
    /**
     * Update AI_post_usage counter after successful article generation
     * This increments the usage counter for the "AI Posts" feature
     */
    private function aiautotool_update_ai_post_usage() {
        // Get current usage value
        $current_value = get_option('AI_post_usage', 0);
        
        // Increment by 1
        $new_value = $current_value + 1;
        
        // Update the option (autoload = 'no' for better performance)
        update_option('AI_post_usage', $new_value, 'no');
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return $new_value;
    }

    private function aiautotool_get_ai_provider_model_options($include_auto = true) {
        $options = array();

        if ($include_auto) {
            $options[] = array(
                'value' => '',
                'label' => __('Auto - use AI Provider settings', 'ai-auto-tool'),
                'selected' => true,
            );
        }

        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')) {
            return $options;
        }

        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $providers_info = $manager->get_providers_info();
        $active_provider = $manager->get_active_provider();
        $active_provider_id = $active_provider ? $active_provider->get_id() : '';
        $active_model = $manager->get_active_model();

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

                $is_active = !$include_auto && $provider_id === $active_provider_id && $model_id === $active_model;
                $options[] = array(
                    'value' => $provider_id . '::' . $model_id,
                    'label' => sprintf('%s - %s', $provider_name, $model_name ? $model_name : $model_id),
                    'selected' => $is_active,
                );
            }
        }

        if (count($options) === ($include_auto ? 1 : 0)) {
            $options[] = array(
                'value' => '',
                'label' => __('No configured AI Provider. Add API key first.', 'ai-auto-tool'),
                'selected' => !$include_auto,
            );
        }

        return $options;
    }

    private function aiautotool_render_ai_provider_model_options($include_auto = true) {
        foreach ($this->aiautotool_get_ai_provider_model_options($include_auto) as $option) {
            printf(
                '<option value="%s"%s>%s</option>',
                esc_attr($option['value']),
                !empty($option['selected']) ? ' selected' : '',
                esc_html($option['label'])
            );
        }
    }

    public function aiautotool_get_ai_provider_js_settings() {
        $settings = array(
            'ai_providers' => array(),
            'ai_image_providers' => array(),
            'active_ai_provider' => '',
            'active_ai_model' => '',
            'ai_provider_routing_mode' => 'single',
            'ai_voice' => array(),
        );

        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')) {
            return $settings;
        }

        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $active_provider = $manager->get_active_provider();

        $settings['ai_providers'] = $manager->get_providers_info();
        $settings['ai_image_providers'] = method_exists($manager, 'get_image_providers_info') ? $manager->get_image_providers_info() : array();
        $settings['active_ai_provider'] = $active_provider ? $active_provider->get_id() : '';
        $settings['active_ai_model'] = $manager->get_active_model();
        $settings['ai_provider_routing_mode'] = method_exists($manager, 'get_provider_routing_mode') ? $manager->get_provider_routing_mode() : 'single';

        if (class_exists('AIAutotool_AI_Voice_Manager')) {
            $settings['ai_voice'] = AIAutotool_AI_Voice_Manager::get_instance()->get_config();
        } else {
            $voice_manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_voice_manager.php';
            if (file_exists($voice_manager_file)) {
                require_once $voice_manager_file;
                if (class_exists('AIAutotool_AI_Voice_Manager')) {
                    $settings['ai_voice'] = AIAutotool_AI_Voice_Manager::get_instance()->get_config();
                }
            }
        }

        return $settings;
    }

    private function aiautotool_resolve_provider_model_selection($model_value, $provider_id = '') {
        $model_value = sanitize_text_field((string) $model_value);
        $provider_id = sanitize_text_field((string) $provider_id);

        if (strpos($model_value, '::') !== false) {
            list($provider_id, $model_value) = array_pad(explode('::', $model_value, 2), 2, '');
            $provider_id = sanitize_text_field($provider_id);
            $model_value = sanitize_text_field($model_value);
        }

        if ($model_value === 'auto' || $model_value === 'provider-default' || $model_value === 'gemini' || $model_value === 'chatgpt') {
            $model_value = '';
        }

        return array(
            'provider_id' => $provider_id,
            'model' => $model_value,
        );
    }
    private static $min_ai_call_interval = 10; // Minimum seconds between AI calls
    public function __construct() {
        $this->name_plan =  __('Ai Post','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 'true' if not exists
         $active_option = get_option($this->active_option_name);
         if ($active_option === false) {
             // Option doesn't exist, set it to 'true' to auto-activate
             update_option($this->active_option_name, 'true');
             $this->active = 'true';
         } else {
             $this->active = $active_option;
         }
         
        // Check if active (handle both string 'true' and boolean true)
        if ($this->active === 'true' || $this->active === true) {
            $this->init();
            
            // Initialize AI Agent to ensure hooks are registered
            if (class_exists('AIAutotool_AI_Agent')) {
                AIAutotool_AI_Agent::get_instance();
            }
        }
        add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback'));
        
        add_action( 'wp_ajax_aiautotool_write_article_with_google_search', array( $this, 'aiautotool_write_article_with_google_search_callback' ));
        add_action( 'wp_ajax_aiautotool_write_article_with_analysis', array( $this, 'aiautotool_write_article_with_analysis_callback' ));
        add_action( 'wp_ajax_aiautotool_write_article_with_auto_writer', array( $this, 'aiautotool_write_article_with_auto_writer_callback' ));
            
        // Register settings
        add_action('admin_init', array($this, 'register_singleai_settings'));

        // Register assets using Asset Manager (tối ưu hóa)
        $this->register_assets();
        
        // Enqueue aiautotool.css and js on edit post pages
        add_action('admin_enqueue_scripts', array($this, 'enqueue_aiautotool_assets'), 5);
    }
    
    /**
     * Enqueue aiautotool.css and aiautotool.js on edit post pages
     */
    public function enqueue_aiautotool_assets($hook) {
        // Check if we're on edit post/page screens
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }
        
        // Get enabled post types from settings
        $settings = $this->get_singleai_settings();
        $enabled_post_types = $settings['post_types'];
        
        // Check if current screen is an edit post screen for enabled post types
        $is_edit_screen = in_array($screen->base, array('post', 'page', 'post-new', 'page-new'));
        $is_enabled_post_type = isset($screen->post_type) && in_array($screen->post_type, $enabled_post_types);
        
        // Also check for ai_single_post page
        $is_ai_post_page = strpos($screen->id, 'ai_single_post') !== false;
        
        if (($is_edit_screen && $is_enabled_post_type) || $is_ai_post_page) {
            $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(__FILE__)));
            
            // Enqueue Font Awesome if not already enqueued
            if (!wp_style_is('font-awesome', 'enqueued')) {
                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 SweetAlert2 CSS if not already enqueued
            if (!wp_style_is('sweetalert2', 'enqueued')) {
                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 if not already enqueued
            if (!wp_script_is('sweetalert2', 'enqueued')) {
                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 main aiautotool.css if not already enqueued
            if (!wp_style_is('aiautotool', 'enqueued')) {
                wp_enqueue_style(
                    'aiautotool',
                    $plugin_url . 'css/aiautotool.css',
                    array('font-awesome'),
                    defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0'
                );
            }
            
            // Enqueue aiautotool.js if not already enqueued (contains check_aipost_premium function)
            if (!wp_script_is('kct_cr_scriptx', 'enqueued')) {
                // Load rendersetting class if needed for JS settings
                if (!class_exists('rendersetting')) {
                    $rendersetting_file = plugin_dir_path(dirname(dirname(__FILE__))) . 'lib/setting.php';
                    if (file_exists($rendersetting_file)) {
                        require_once $rendersetting_file;
                    }
                }
                
                // Get JS settings (same logic as asset manager)
                $setting = class_exists('rendersetting') ? new rendersetting() : null;
                $langcodedefault = get_option('aiautotool_default_language', 'vi');
                global $post;
                $settingseditornumberline = '';
                $freemius_access = function_exists('aiautotool_get_freemius_access_status') ? aiautotool_get_freemius_access_status() : array(
                    'can_use_pro_features' => false,
                    'is_free' => true,
                    'is_trial' => false,
                    'trial_days_remaining' => null,
                    'trial_ends' => null,
                    'reason' => 'freemius_unavailable',
                );
                
	                $js_setting = array(
	                    'ajax_url' => admin_url('admin-ajax.php'),
	                    'security' => wp_create_nonce('aiautotool_nonce'),
	                    'media_search_base_url' => $this->get_media_search_base_url(),
	                    'languageCodes' => $setting ? $setting->languageCodes : array(),
                    'langcodedefault' => $langcodedefault,
                    'fsdata' => $setting ? rendersetting::aiautotool_getdata() : array(),
                    'freemius_access' => $freemius_access,
                    'aiautotool_premium' => ! empty($freemius_access['can_use_pro_features']),
                    'code_mirrror' => $settingseditornumberline,
                    'gemini_api' => defined('AIAUTOTOOL_API_GEM') ? AIAUTOTOOL_API_GEM : '',
                    'prompt' => get_option('aiautotool_prompt_options', array())
                );

                if (class_exists('AIAutotool_AI_Provider_Manager')) {
                    $provider_manager = AIAutotool_AI_Provider_Manager::get_instance();
                    $providers_info = $provider_manager->get_providers_info();
                    $js_setting['ai_providers'] = $providers_info;
                    $js_setting['ai_image_providers'] = method_exists($provider_manager, 'get_image_providers_info') ? $provider_manager->get_image_providers_info() : array();
                    $js_setting['active_ai_provider'] = ($provider_manager->get_active_provider()) ? $provider_manager->get_active_provider()->get_id() : '';
                    $js_setting['active_ai_model'] = $provider_manager->get_active_model();
                    $js_setting['ai_provider_routing_mode'] = method_exists($provider_manager, 'get_provider_routing_mode') ? $provider_manager->get_provider_routing_mode() : 'single';
                } else {
                    $js_setting['ai_providers'] = array();
                    $js_setting['ai_image_providers'] = array();
                    $js_setting['active_ai_provider'] = '';
                    $js_setting['active_ai_model'] = '';
                    $js_setting['ai_provider_routing_mode'] = 'single';
                }
                
                if (isset($post->ID)) {
                    $js_setting['postID'] = $post->ID;
                    $js_setting['postTitle'] = $post->post_title;
                }
                
                // Register and enqueue aiautotool.js
                wp_register_script(
                    'kct_cr_scriptx',
                    $plugin_url . 'js/aiautotool.js',
                    array('jquery'),
                    defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0',
                    true
                );
                
                // Localize script with settings
                wp_localize_script('kct_cr_scriptx', 'aiautotool_js_setting', $js_setting);
                wp_enqueue_script('kct_cr_scriptx');
            }
            
            // Enqueue AI Agent JavaScript
            if (class_exists('AIAutotool_AI_Agent')) {
                AIAutotool_AI_Agent::enqueue_assets();
            }
        }
    }
    
    /**
     * Register settings for Single AI
     */
    public function register_singleai_settings() {
        register_setting(
            'aiautotool_singleai_settings_group',
            $this->settings_option_name,
            array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_singleai_settings'),
                'default' => array('post_types' => array('post', 'page'))
            )
        );
    }
    
    /**
     * Sanitize settings
     */
    public function sanitize_singleai_settings($input) {
        $sanitized = array();
        
        if (isset($input['post_types']) && is_array($input['post_types'])) {
            $sanitized['post_types'] = array_map('sanitize_text_field', $input['post_types']);
        } else {
            $sanitized['post_types'] = array('post', 'page');
        }
        
        return $sanitized;
    }
    
    /**
     * Get settings
     */
    public function get_singleai_settings() {
        $defaults = array('post_types' => array('post', 'page'));
        $settings = get_option($this->settings_option_name, $defaults);
        
        // Ensure post_types is an array
        if (!isset($settings['post_types']) || !is_array($settings['post_types'])) {
            $settings['post_types'] = $defaults['post_types'];
        }
        
        return $settings;
    }

    private function get_media_search_base_url() {
        $base_url = defined('AIAUTOTOOL_MEDIA_SEARCH_SERVER') ? AIAUTOTOOL_MEDIA_SEARCH_SERVER : getenv('AIAUTOTOOL_MEDIA_SEARCH_SERVER');
        if (empty($base_url)) {
            $base_url = 'https://aplugin.aiautotool.com';
        }

        return untrailingslashit(esc_url_raw($base_url));
    }
    
    /**
     * Register assets using Asset Manager
     */
    private function register_assets() {
        // Ensure Asset Manager is loaded
        if (!function_exists('aiautotool_register_assets')) {
            return;
        }
        
        // Use closure to lazy load config when assets are actually enqueued
        $feature = $this;
        aiautotool_register_assets('single-ai', array(
            'scripts' => array(
                'kct_aipost' => array(
                    'src' => plugin_dir_url(__FILE__) . 'assets/js/aipost.js',
                    'deps' => array('jquery', 'kct_cr_scriptx', 'aiautotool-ai-agent'), // Depend on aiautotool.js for check_aipost_premium function
                    'version' => (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.2') . '-voice-video-v1',
                    'in_footer' => true,
                    'localize' => array(
                        'object_name' => 'aipost',
                        'data' => function() use ($feature) {
                            $ai_provider_data = $feature->aiautotool_get_ai_provider_js_settings();

                            // Lazy load config when actually enqueuing
                            return array_merge(array(
                                'ajax_url' => admin_url('admin-ajax.php'),
                                'config' => isset($feature->config) ? $feature->config : array(),
                                'media_search_base_url' => $feature->get_media_search_base_url(),
                                'security' => wp_create_nonce('aiautotool_aipost_nonce')
                            ), $ai_provider_data);
                        }
                    )
                )
            ),
            'styles' => array(
                'aiautotool-singleai-modern' => array(
                    'src' => plugin_dir_url(__FILE__) . 'assets/css/singleai-modern.css',
                    'deps' => array('aiautotool'),
                    'version' => defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0',
                    'media' => 'all'
                )
            ),
            'pages' => array('ai_single_post', 'post', 'page', 'post-new', 'page-new'), // Load on single AI post page and edit post/page screens
            'conditions' => array(
                function($hook) {
                    $screen = get_current_screen();
                    if (!$screen) {
                        return false;
                    }
                    // Load on ai_single_post page
                    if (strpos($screen->id, 'ai_single_post') !== false) {
                        return true;
                    }
                    // Load on edit post/page screens
                    if (in_array($screen->base, array('post', 'page', 'post-new', 'page-new'))) {
                        return true;
                    }
                    // Load on custom post type edit screens if enabled
                    $settings = get_option('aiautotool_singleai_settings', array('post_types' => array('post', 'page')));
                    $enabled_post_types = isset($settings['post_types']) ? $settings['post_types'] : array('post', 'page');
                    if (isset($screen->post_type) && in_array($screen->post_type, $enabled_post_types)) {
                        return true;
                    }
                    return false;
                }
            )
        ));
    }

    public function aiautotool_meta_box() {
        // Get enabled post types from settings
        $settings = $this->get_singleai_settings();
        $enabled_post_types = $settings['post_types'];
        
        // Add meta box only for enabled post types
        if (!empty($enabled_post_types)) {
                add_meta_box(
                    'aiautotool-meta-box', 
                    'Ai Auto Tool', 
                    array($this, 'aiautotool_meta_box_callback'), 
                $enabled_post_types, 
                'side', 
                'high' 
            );

            add_meta_box(
                'aiautotool-aireview-meta-box', 
                'Ai Review', 
                array($this,'aiautotool_aireview_meta_box_callback'), 
                $enabled_post_types,
                'side', 
                'high' 
            );
        }
        }

        public function aiautotool_aireview_meta_box_callback($post) {
            // Retrieve any saved meta box data
            $custom_data = get_post_meta($post->ID, 'custom_data_key', true);
            ?>
            <span class=" aiautotool_btn_v1 aiautotool_btn_v15 btn_bardWriter btn_summary" id="seoreview"  ><span class="icon"><i class="fa-solid fa-list-check"></i>  </span><span>SEO Review by AI </span></span>
            <table id="vertical-table"></table>
            <div id="table-container">
                
            </div>
            <script type="text/javascript">
                 jQuery(document).ready(function($) {
    $('#seoreview').click(function() {
        // Lấy tiêu đề bài viết
        var postTitle = $('#title').val();
        var post_language = get_lang();
        if (languageCodes.hasOwnProperty(post_language)) {
            langcheck = languageCodes[post_language];
        }
        // Kiểm tra xem có sử dụng trình soạn thảo TinyMCE không
        if (typeof tinyMCE !== "undefined") {
            var editor = tinyMCE.activeEditor;
            if (editor) {
                console.log('Có trình soạn thảo TinyMCE');
                // Lấy nội dung từ trình soạn thảo
                var postContent = editor.getContent();
                // Kiểm tra xem tiêu đề và nội dung có rỗng không
                if (postTitle.trim() !== '' && postContent.trim() !== '') {
                    // Tiến hành gọi API bằng AJAX
                    showLoading('Bot Analyzing....');
                    $.ajax({
                        type: 'POST',
                        url: aiautotool_js_setting.ajax_url,
                        data: {
                            action: 'seoreview_ajax',
                            security: aiautotool_js_setting.security, // Sử dụng nonce tương ứng
                            title: postTitle,
                            content: postContent,
                            lang:langcheck
                        },
                        dataType: 'json',
                        success: function(response) {
                            // Xử lý kết quả từ API nếu cần
                            console.log(response);
                            if(response.data){
                                jQuery('#table-container').html(response.data);
                            }
                            
                            hideLoading();

                        },
                        error: function(xhr, status, error) {
                            hideLoading();
                            console.error('Error ' + error);
                        }
                    });
                } else {
                    if(Swal){
                         Swal.fire({
                                  title: 'Error!',
                                  text: 'Title and Content is Null!!.',
                                  icon: 'error',
                                  confirmButtonText: 'Close'
                                });
                     }else{
                        alert('Title and Content is Null!!.');
                     }
                    console.log('Title and Content is Null!!.');
                }
            } else {
                if(Swal){
                         Swal.fire({
                                  title: 'Error!',
                                  text: 'No TinyMCE!.',
                                  icon: 'error',
                                  confirmButtonText: 'Close'
                                });
                     }else{
                        alert('No TinyMCE.');
                     }
                console.log('No TinyMCE ');
            }
        } else {
            if(Swal){
                         Swal.fire({
                                  title: 'Error!',
                                  text: 'TinyMCE not work.',
                                  icon: 'error',
                                  confirmButtonText: 'Close'
                                });
                     }else{
                        alert('TinyMCE not work!!.');
                     }
            console.log('TinyMCE not work.');
        }
    });

     });
   
            </script>
            <?php
        }
        public function aiautotool_meta_box_callback($post) {
            // Retrieve any saved meta box data
            $custom_data = get_post_meta($post->ID, 'custom_data_key', true);

            // Output the HTML markup for your custom meta box
            ?>
            <div class="aiautotool-modal-container">
        <div class="aiautotool-modal-overlay"></div>
        <div class="aiautotool-modal-content">
            <h2><?php echo wp_kses_post(__('All tool for AI Post','ai-auto-tool'));  ?></h2>
            <p>
                <span class=" aiautotool_btn_v1 aiautotool_btn_v16 btn_bardWriter btnoutline" id="btn_outline"  onclick="changeType('Outline')"><span class="icon"><i class="fa-solid fa-lightbulb"></i>  </span><span>Outline </span></span>
                
                <span class=" aiautotool_btn_v1 aiautotool_btn_v11 btn_bardWriter btn_intro" id=""  onclick="changeType('Introduction')"><span class="icon"><i class="fa-solid fa-info"></i>  </span><span>Introduction </span></span>
                <span class=" aiautotool_btn_v1 aiautotool_btn_v13 btn_bardWriter btn_conclusion" id=""  onclick="changeType('Conclusion')"><span class="icon"><i class="fa-solid fa-check-double"></i>  </span><span>Conclusion </span></span>
                <span class=" aiautotool_btn_v1 aiautotool_btn_v12 btn_bardWriter btn_faq" id=""  onclick="changeType('FAQ')"><span class="icon"><i class="fa-solid fa-question"></i>  </span><span>Create FAQ </span></span>
                
            </p>
            <div class=" aiautotool_container aiautotool_modal_content">
                <div id="outline">
                    <h3 id="current_type">Suggest Outline By Ai Auto Tool</h3>
                        <input type="hidden" name="type" id="type" value="Outline">
                    <div class="aiautotool_input2">
                      <input type="text" name="moretool" class="aiautotool_input2_input" placeholder="Enter your Keyword for ">
                      <button class="aiautotool_input2_button" id="moretool" type="submit">Create </button>  

                    </div>
                </div>
                <div id="Summary" style="display:none">
                    <div class="aiautotool_input2">
                      <input type="text" class="aiautotool_input2_input" placeholder="Enter your Keyword for ">
                      <button class="aiautotool_input2_button" type="submit" id="createButton">Create </button>  
                    </div>
                </div>
                
                <div id="Summary"></div>
                <div id="Introduction"></div>
                <div id="Conclusion"></div>
                <div id="Create FAQ"></div>
                <script type="text/javascript">

                  



                    function changeType(newType) {
                        document.getElementById('current_type').innerText = newType;
                        document.getElementsByName('type')[0].value = newType;
                        const createButton = document.getElementById('moretool');
                        createButton.innerText = 'Create ' + newType;
                    }
                    jQuery(document).ready(function(){
                        jQuery("#moretool").click(function(){
                            var type = document.getElementsByName('type')[0].value;
                            var moretoolText = jQuery("input[name='moretool']").val();
                            var post_language = get_lang();
                            var langcheck = '';
                            if(moretoolText.trim() === "") {
                                if(Swal){
                                     Swal.fire({
                                              title: 'Error!',
                                              text: 'Please fill Keyword in request.',
                                              icon: 'error',
                                              confirmButtonText: 'Close'
                                            });
                                 }else{
                                    alert('Please fill Keyword in request.');
                                 }
                            } else {


                                open_box_aiautotool();
                            jQuery('.aiautotool-modal-close').click();

                            if (languageCodes.hasOwnProperty(post_language)) {
                               langcheck = languageCodes[post_language];
                              
                            } 
                            var divId = "outbard";

                            switch(type) {
                                case "Outline":
                                    text = 'Create an outline for a {'+moretoolText+'} , with main topics and subtopics organized in a hierarchical numbered list format.'; 
                                    

                                    sendbardToServer(text, divId,'writemore',langcheck);
                                    break;
                                case "Summary":
                                    // Xử lý khi type là Summary
                                    sendbardToServer(moretoolText, divId, langcheck); // Điều chỉnh hàm và tham số phù hợp
                                    break;
                                case "Introduction":
                                    text = 'Write an introduction for the article title ['+moretoolText+'] , Include an introduction of 50 to 100 words.'; 
                                    sendbardToServer(text, divId,'writemore', langcheck); // Điều chỉnh hàm và tham số phù hợp
                                    break;
                                case "Conclusion":
                                    // Xử lý khi type là Conclusion
                                    text = 'Viết phần kết bài cho bài viết ['+moretoolText+']. ';
                                    sendbardToServer(text , divId,'writemore', langcheck); // Điều chỉnh hàm và tham số phù hợp
                                    break;
                                case "FAQ":
                                    // Xử lý khi type là Create FAQ
                                    text = 'I want to create an FAQ section for my ['+moretoolText+']. Can you help me come up with a list of frequently asked questions and answers that will provide helpful information for my customers?';
                                    sendbardToServer(text, divId,'writemore', langcheck); // Điều chỉnh hàm và tham số phù hợp
                                    break;
                                default:
                                    // Xử lý khi type không khớp với bất kỳ trường hợp nào
                                    console.error("Unknown type: " + type);
                            }
                            
                            
                            }
                        });
                    });
                </script>
            </div>
            <button class="aiautotool-modal-close"><i class="fa-regular fa-rectangle-xmark"></i></button>
        </div>
    </div>
            <div class="aiautotool_box1 aiautotool-ai-post-panel">
                        <div class="aiautotool_box_head">
                               <img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)); ?>" width="16px" height="16px">
                            <?php echo wp_kses_post($this->icon . ' ' . esc_html($this->name_plan)); ?> </div>
                                <style type="text/css">
                                    /* Ask Assistant Container - Modern Style */
                                    .aiautotool_box1 .askassistant,
                                    .aiautotool_box .askassistant {
                                        background: #ffffff;
                                        border: 2px solid #e5e7eb;
                                        border-radius: 24px;
                                        padding: 8px;
                                        margin-bottom: 16px;
                                        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
                                        transition: all 0.3s ease;
                                    }
                                    
                                    .aiautotool_box1 .askassistant:hover,
                                    .aiautotool_box .askassistant:hover {
                                        border-color: #d1d5db;
                                        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
                                    }
                                    
                                    .aiautotool_box1 .askassistant:focus-within,
                                    .aiautotool_box .askassistant:focus-within {
                                        border-color: #667eea;
                                        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
                                    }
                                    
                                    /* Textarea - Full Width on Top */
                                    .aiautotool_box1 .askassistant textarea,
                                    .aiautotool_box .askassistant textarea {
                                        width: 100%;
                                        border: none;
                                        background: transparent;
                                        padding: 12px 16px;
                                        font-size: 15px;
                                        line-height: 1.5;
                                        resize: none;
                                        min-height: 50px;
                                        color: #1f2937;
                                        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
                                        margin-bottom: 8px;
                                    }
                                    
                                    .aiautotool_box1 .askassistant textarea:focus,
                                    .aiautotool_box .askassistant textarea:focus {
                                        outline: none;
                                    }
                                    
                                    .aiautotool_box1 .askassistant textarea::placeholder,
                                    .aiautotool_box .askassistant textarea::placeholder {
                                        color: #9ca3af;
                                        font-weight: 400;
                                    }
                                    
                                    /* Bottom Row: Select + Button */
                                    .aiautotool_box1 .askassistant .select-and-button,
                                    .aiautotool_box .askassistant .select-and-button {
                                        display: flex;
                                        align-items: center;
                                        gap: 8px;
                                        padding: 0 8px;
                                    }
                                    
                                    /* Select Dropdown - Pill Shape */
                                    .aiautotool_box1 .askassistant .select-and-button select,
                                    .aiautotool_box .askassistant .select-and-button select {
                                        width: 50%;
                                        flex: 0 0 50%;
                                        border: none;
                                        background: #f3f4f6;
                                        padding: 10px 36px 10px 16px;
                                        border-radius: 20px;
                                        cursor: pointer;
                                        font-size: 14px;
                                        font-weight: 500;
                                        color: #4b5563;
                                        appearance: none;
                                        transition: all 0.2s ease;
                                        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath fill='%234b5563' d='M4.5 6L8 9.5L11.5 6'/%3E%3C/svg%3E");
                                        background-repeat: no-repeat;
                                        background-position: right 12px center;
                                        background-size: 16px;
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button select:hover,
                                    .aiautotool_box .askassistant .select-and-button select:hover {
                                        background: #e5e7eb;
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button select:focus,
                                    .aiautotool_box .askassistant .select-and-button select:focus {
                                        outline: none;
                                        background: #dbeafe;
                                        color: #2563eb;
                                    }
                                    
                                    /* Send Button - Square with Rounded Corners */
                                    .aiautotool_box1 .askassistant .select-and-button button,
                                    .aiautotool_box .askassistant .select-and-button button {
                                        border: none;
                                        background: #10b981;
                                        color: white;
                                        width: 50%;
                                        flex: 0 0 50%;
                                        height: 40px;
                                        border-radius: 12px;
                                        cursor: pointer;
                                        transition: all 0.2s ease;
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3);
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button button:hover,
                                    .aiautotool_box .askassistant .select-and-button button:hover {
                                        background: #059669;
                                        transform: translateY(-1px);
                                        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button button:active,
                                    .aiautotool_box .askassistant .select-and-button button:active {
                                        transform: translateY(0);
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button button i,
                                    .aiautotool_box .askassistant .select-and-button button i {
                                        font-size: 18px;
                                    }
                                    
                                    /* Hide text in button, show only icon */
                                    .aiautotool_box1 .askassistant .select-and-button button,
                                    .aiautotool_box .askassistant .select-and-button button {
                                        font-size: 0;
                                    }
                                    
                                    .aiautotool_box1 .askassistant .select-and-button button i,
                                    .aiautotool_box .askassistant .select-and-button button i {
                                        font-size: 18px !important;
                                    }
                                    
                                    
                                    /* Responsive adjustments */
                                    @media (max-width: 600px) {
                                        .aiautotool_box1 .askassistant .select-and-button {
                                            flex-direction: row;
                                        }
                                        
                                        .aiautotool_box1 .askassistant .select-and-button select,
                                        .aiautotool_box1 .askassistant .select-and-button button {
                                            width: 50%;
                                            flex: 0 0 50%;
                                        }
                                    }
                                    
                                    /* Ask AI Modal Styles */
                                    #ask-ai-modal {
                                        display: none;
                                        position: fixed;
                                        top: 0;
                                        left: 0;
                                        width: 100%;
                                        height: 100%;
                                        z-index: 999999;
                                        align-items: center;
                                        justify-content: center;
                                    }
                                    
                                    #ask-ai-modal.active {
                                        display: flex;
                                    }
                                    
                                    #ask-ai-modal-overlay {
                                        position: absolute;
                                        top: 0;
                                        left: 0;
                                        width: 100%;
                                        height: 100%;
                                        background: rgba(0, 0, 0, 0.5);
                                        backdrop-filter: blur(4px);
                                    }
                                    
                                    #ask-ai-modal-content {
                                        position: relative;
                                        background: white;
                                        border-radius: 16px;
                                        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                                        width: 90%;
                                        max-width: 600px;
                                        max-height: 90vh;
                                        overflow: hidden;
                                        display: flex;
                                        flex-direction: column;
                                        z-index: 1;
                                    }
                                    
                                    #ask-ai-modal-header {
                                        display: flex;
                                        align-items: center;
                                        justify-content: space-between;
                                        padding: 20px 24px;
                                        border-bottom: 1px solid #e5e7eb;
                                    }
                                    
                                    #ask-ai-modal-header h3 {
                                        margin: 0;
                                        font-size: 20px;
                                        font-weight: 600;
                                        color: #1f2937;
                                    }
                                    
                                    #ask-ai-modal-close {
                                        background: none;
                                        border: none;
                                        font-size: 24px;
                                        color: #6b7280;
                                        cursor: pointer;
                                        padding: 4px 8px;
                                        border-radius: 8px;
                                        transition: all 0.2s ease;
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                    }
                                    
                                    #ask-ai-modal-close:hover {
                                        background: #f3f4f6;
                                        color: #1f2937;
                                    }
                                    
                                    #ask-ai-modal-body {
                                        padding: 24px;
                                        overflow-y: auto;
                                    }
                                    
                                    /* Open Ask AI Button */
                                    .aiautotool-ai-post-panel {
                                        overflow: hidden;
                                        border-radius: 12px;
                                        background: #ffffff;
                                        box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
                                    }

                                    .aiautotool-ai-post-panel > .aiautotool_box_head {
                                        min-height: 56px;
                                        padding: 14px 18px;
                                        align-items: center;
                                        gap: 10px;
                                        font-size: 20px;
                                        line-height: 1.2;
                                        border-radius: 0;
                                    }

                                    .aiautotool-ai-post-panel > .aiautotool_box_head img {
                                        width: 26px !important;
                                        height: 26px !important;
                                        flex: 0 0 auto;
                                    }

                                    .aiautotool-ai-post-actions {
                                        padding: 14px 18px 10px;
                                        background: #ffffff;
                                    }

                                    .open-ask-ai-btn {
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        gap: 8px;
                                        width: 100%;
                                        min-height: 44px;
                                        padding: 10px 14px;
                                        background: linear-gradient(135deg, #009b72 0%, #08b989 100%);
                                        color: white;
                                        border: none;
                                        border-radius: 8px;
                                        font-size: 14px;
                                        font-weight: 700;
                                        cursor: pointer;
                                        transition: all 0.3s ease;
                                        box-shadow: 0 8px 18px rgba(0, 155, 114, 0.22);
                                        margin: 0;
                                    }
                                    
                                    .open-ask-ai-btn:hover {
                                        transform: translateY(-2px);
                                        box-shadow: 0 10px 24px rgba(0, 155, 114, 0.3);
                                    }
                                    
                                    .open-ask-ai-btn:active {
                                        transform: translateY(0);
                                    }
                                    
                                    .open-ask-ai-btn i {
                                        font-size: 17px;
                                    }

                                    .aiautotool-ai-post-panel .aiautotool_form {
                                        padding: 0 18px 18px;
                                    }

                                    .aiautotool-ai-post-panel .aiautotool-segmented-tabs {
                                        width: 100%;
                                        max-width: 100%;
                                        box-sizing: border-box;
                                        margin: 6px 0 14px;
                                        padding: 4px;
                                        gap: 4px;
                                        border-radius: 10px;
                                        overflow: hidden;
                                    }

                                    .aiautotool-ai-post-panel .aiautotool-tab-item {
                                        min-width: 0;
                                        flex: 1 1 0;
                                        padding: 9px 8px;
                                        border-radius: 8px;
                                        font-size: 13px;
                                        line-height: 1.1;
                                        white-space: nowrap;
                                    }

                                    .aiautotool-ai-post-panel .aiautotool-tab-item i {
                                        font-size: 15px;
                                        flex: 0 0 auto;
                                    }

                                    .aiautotool-ai-post-panel .aiautotool-tab-item span {
                                        overflow: hidden;
                                        text-overflow: ellipsis;
                                    }

                                    @media (max-width: 420px) {
                                        .aiautotool-ai-post-panel > .aiautotool_box_head {
                                            min-height: 50px;
                                            padding: 12px 14px;
                                            font-size: 18px;
                                        }

                                        .aiautotool-ai-post-actions,
                                        .aiautotool-ai-post-panel .aiautotool_form {
                                            padding-left: 14px;
                                            padding-right: 14px;
                                        }

                                        .aiautotool-ai-post-panel .aiautotool-tab-item {
                                            font-size: 12px;
                                            padding-left: 6px;
                                            padding-right: 6px;
                                            gap: 5px;
                                        }
                                    }

                                    .aiautotool-editor-writing-panel {
                                        border: 1px solid #d8e4dc;
                                        border-radius: 8px;
                                        background: #f7faf8;
                                        margin: 0 0 16px;
                                        overflow: hidden;
                                    }

                                    .aiautotool-editor-writing-header {
                                        padding: 14px;
                                        background: #ffffff;
                                        border-bottom: 1px solid #d8e4dc;
                                    }

                                    .aiautotool-editor-writing-title {
                                        display: flex;
                                        align-items: center;
                                        gap: 8px;
                                        margin: 0 0 4px;
                                        color: #173b2f;
                                        font-size: 14px;
                                        font-weight: 700;
                                    }

                                    .aiautotool-editor-writing-note {
                                        margin: 0;
                                        color: #5d6f68;
                                        font-size: 12px;
                                        line-height: 1.45;
                                    }

                                    .aiautotool-editor-writing-source {
                                        padding: 12px;
                                        display: grid;
                                        gap: 8px;
                                    }

                                    .aiautotool-editor-writing-source textarea {
                                        width: 100%;
                                        min-height: 86px;
                                        resize: vertical;
                                        border: 1px solid #cbd8d0;
                                        border-radius: 6px;
                                        padding: 9px 10px;
                                        font-size: 13px;
                                        line-height: 1.45;
                                        box-sizing: border-box;
                                    }

                                    .aiautotool-editor-writing-source textarea:focus {
                                        border-color: #00875c;
                                        box-shadow: 0 0 0 2px rgba(0, 135, 92, 0.12);
                                        outline: none;
                                    }

                                    .aiautotool-editor-writing-actions {
                                        padding: 0 12px 12px;
                                        display: grid;
                                        gap: 10px;
                                    }

                                    .aiautotool-editor-writing-group {
                                        background: #ffffff;
                                        border: 1px solid #d8e4dc;
                                        border-radius: 8px;
                                        padding: 10px;
                                    }

                                    .aiautotool-editor-writing-group-title {
                                        display: flex;
                                        align-items: center;
                                        gap: 7px;
                                        color: #173b2f;
                                        font-size: 12px;
                                        font-weight: 700;
                                        margin-bottom: 8px;
                                    }

                                    .aiautotool-editor-writing-buttons {
                                        display: grid;
                                        grid-template-columns: 1fr 1fr;
                                        gap: 7px;
                                    }

                                    .aiautotool-editor-writing-button {
                                        min-height: 36px;
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        gap: 6px;
                                        border: 1px solid #cbd8d0;
                                        border-radius: 6px;
                                        background: #ffffff;
                                        color: #173b2f;
                                        font-size: 12px;
                                        font-weight: 650;
                                        cursor: pointer;
                                    }

                                    .aiautotool-editor-writing-button:hover {
                                        border-color: #00875c;
                                        color: #006b49;
                                        background: #f0faf5;
                                    }

                                    .aiautotool-editor-writing-button.primary {
                                        grid-column: 1 / -1;
                                        background: #00875c;
                                        border-color: #00875c;
                                        color: #ffffff;
                                    }

                                    .aiautotool-editor-writing-button.primary:hover {
                                        background: #006b49;
                                        color: #ffffff;
                                    }
                                    
                                    @media (max-width: 600px) {
                                        #ask-ai-modal-content {
                                            width: 95%;
                                            max-height: 85vh;
                                        }
                                        
                                        #ask-ai-modal-header {
                                            padding: 16px 20px;
                                        }
                                        
                                        #ask-ai-modal-body {
                                            padding: 20px;
                                        }
                                    }
                                </style>
                                <div class="aiautotool-ai-post-actions">
                                    <button class="open-ask-ai-btn" id="open-ask-ai-modal" aria-label="<?php echo esc_attr(__('Ask AI', 'ai-auto-tool')); ?>">
                                        <i class="fa-solid fa-comments"></i>
                                        <span><?php echo wp_kses_post(__('Ask AI', 'ai-auto-tool')); ?></span>
                                    </button>
                                </div>

                                <?php if (false) : ?>
                                <div class="aiautotool-editor-writing-panel" id="aiautotool-editor-writing-panel">
                                    <div class="aiautotool-editor-writing-header">
                                        <p class="aiautotool-editor-writing-title">
                                            <i class="fa-solid fa-pen-nib"></i>
                                            <?php echo esc_html__('Writing Tool', 'ai-auto-tool'); ?>
                                        </p>
                                        <p class="aiautotool-editor-writing-note">
                                            <?php echo esc_html__('Draft from title, improve selected/source content, or generate SEO assets.', 'ai-auto-tool'); ?>
                                        </p>
                                    </div>

                                    <div class="aiautotool-editor-writing-source">
                                        <textarea id="aiautotool_editor_writing_source" placeholder="<?php echo esc_attr__('Optional source content. If empty, the tool uses the post title/editor content.', 'ai-auto-tool'); ?>"></textarea>
                                    </div>

                                    <div class="aiautotool-editor-writing-actions">
                                        <div class="aiautotool-editor-writing-group">
                                            <div class="aiautotool-editor-writing-group-title">
                                                <i class="fa-solid fa-file-pen"></i>
                                                <?php echo esc_html__('Create Draft', 'ai-auto-tool'); ?>
                                            </div>
                                            <div class="aiautotool-editor-writing-buttons">
                                                <button type="button" class="aiautotool-editor-writing-button primary" data-editor-writing-special="write-with-agent">
                                                    <i class="fa-solid fa-robot"></i>
                                                    <?php echo esc_html__('Write Full Article', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="Outline">
                                                    <i class="fa-solid fa-list-ol"></i>
                                                    <?php echo esc_html__('Outline', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="Introduction">
                                                    <i class="fa-solid fa-arrow-right-to-bracket"></i>
                                                    <?php echo esc_html__('Intro', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="aiautotool-editor-writing-group">
                                            <div class="aiautotool-editor-writing-group-title">
                                                <i class="fa-solid fa-wand-magic-sparkles"></i>
                                                <?php echo esc_html__('Improve Content', 'ai-auto-tool'); ?>
                                            </div>
                                            <div class="aiautotool-editor-writing-buttons">
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="ContentRewrite">
                                                    <i class="fa-solid fa-rotate"></i>
                                                    <?php echo esc_html__('Rewrite', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="ContentSummary">
                                                    <i class="fa-solid fa-compress"></i>
                                                    <?php echo esc_html__('Summarize', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-prompt="expand">
                                                    <i class="fa-solid fa-up-right-and-down-left-from-center"></i>
                                                    <?php echo esc_html__('Expand', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-prompt="clarity">
                                                    <i class="fa-solid fa-wand-magic-sparkles"></i>
                                                    <?php echo esc_html__('Clarity', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="aiautotool-editor-writing-group">
                                            <div class="aiautotool-editor-writing-group-title">
                                                <i class="fa-solid fa-chart-line"></i>
                                                <?php echo esc_html__('SEO Assets', 'ai-auto-tool'); ?>
                                            </div>
                                            <div class="aiautotool-editor-writing-buttons">
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-special="btn_suggettitle">
                                                    <i class="fa-solid fa-heading"></i>
                                                    <?php echo esc_html__('Titles', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="MetaDescription">
                                                    <i class="fa-solid fa-tags"></i>
                                                    <?php echo esc_html__('Meta', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="FAQ">
                                                    <i class="fa-solid fa-question-circle"></i>
                                                    <?php echo esc_html__('FAQ', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="KeywordResearch">
                                                    <i class="fa-solid fa-magnifying-glass-chart"></i>
                                                    <?php echo esc_html__('Keywords', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="aiautotool-editor-writing-group">
                                            <div class="aiautotool-editor-writing-group-title">
                                                <i class="fa-solid fa-sliders"></i>
                                                <?php echo esc_html__('Advanced', 'ai-auto-tool'); ?>
                                            </div>
                                            <div class="aiautotool-editor-writing-buttons">
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-special="custom-prompt-write">
                                                    <i class="fa-solid fa-keyboard"></i>
                                                    <?php echo esc_html__('Prompt', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="BlogPostIdeas">
                                                    <i class="fa-solid fa-lightbulb"></i>
                                                    <?php echo esc_html__('Ideas', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="SocialMedia">
                                                    <i class="fa-solid fa-share-nodes"></i>
                                                    <?php echo esc_html__('Social', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" class="aiautotool-editor-writing-button" data-editor-writing-action="ContentCalendar">
                                                    <i class="fa-solid fa-calendar-days"></i>
                                                    <?php echo esc_html__('Calendar', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Ask AI Modal -->
                                <div id="ask-ai-modal" aria-hidden="true">
                                    <div id="ask-ai-modal-overlay"></div>
                                    <div id="ask-ai-modal-content">
                                        <div id="ask-ai-modal-header">
                                            <h3><?php echo wp_kses_post(__('Ask AI Assistant', 'ai-auto-tool')); ?></h3>
                                            <button id="ask-ai-modal-close" aria-label="<?php echo esc_attr(__('Close', 'ai-auto-tool')); ?>">
                                                <i class="fa-solid fa-times"></i>
                                            </button>
                                        </div>
                                        <div id="ask-ai-modal-body">
                                            <div class="askassistant">
                                                <textarea id="promptask" rows="4" placeholder="<?php echo wp_kses_post(__('Ask AI...','ai-auto-tool'));?>"></textarea>
                                               <div class="select-and-button">
                                                    <select class="aiautotool-ai-select" data-aiautotool-ai-select="ask">
                                                        <?php $this->aiautotool_render_ai_provider_model_options(true); ?>
                                                    </select>
                                                    <button id="askprompt" aria-label="Send" title="Send">
                                                        <i class="fa-solid fa-paper-plane"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <script>
                                    jQuery(document).ready(function($) {
                                        var $modal = $('#ask-ai-modal');
                                        var $overlay = $('#ask-ai-modal-overlay');
                                        var $closeBtn = $('#ask-ai-modal-close');
                                        var $openBtn = $('#open-ask-ai-modal');
                                        
                                        // Function to open modal
                                        function openAskAIModal() {
                                            $modal.addClass('active').attr('aria-hidden', 'false');
                                            $('body').css('overflow', 'hidden');
                                            // Focus on textarea when modal opens
                                            setTimeout(function() {
                                                $('#promptask').focus();
                                            }, 100);
                                        }
                                        
                                        // Function to close modal
                                        function closeAskAIModal() {
                                            $modal.removeClass('active').attr('aria-hidden', 'true');
                                            $('body').css('overflow', '');
                                        }
                                        
                                        // Open modal button click
                                        $openBtn.on('click', function(e) {
                                            e.preventDefault();
                                            openAskAIModal();
                                        });
                                        
                                        // Close modal button click
                                        $closeBtn.on('click', function(e) {
                                            e.preventDefault();
                                            closeAskAIModal();
                                        });
                                        
                                        // Close modal when clicking overlay
                                        $overlay.on('click', function(e) {
                                            if (e.target === this) {
                                                closeAskAIModal();
                                            }
                                        });
                                        
                                        // Close modal on Escape key
                                        $(document).on('keydown', function(e) {
                                            if (e.key === 'Escape' && $modal.hasClass('active')) {
                                                closeAskAIModal();
                                            }
                                        });
                                        
                                        // Allow Enter to send, Shift+Enter for new line
                                        $('#promptask').on('keydown', function(e) {
                                            if (e.key === 'Enter' && !e.shiftKey) {
                                                e.preventDefault();
                                                $('#askprompt').click();
                                            }
                                        });
                                        
                                        // Click handler for Ask AI button - Integrate with AI Agent
                                        $('#askprompt').on('click', function(e) {
                                            e.preventDefault();
                                            
                                            // Get prompt value
                                            var prompt = $('#promptask').val().trim();
                                            
                                            // Validate prompt
                                            if (!prompt) {
                                                if (typeof Swal !== 'undefined') {
                                                    Swal.fire({
                                                        title: '<?php echo esc_js(__('Error!', 'ai-auto-tool')); ?>',
                                                        text: '<?php echo esc_js(__('Please enter a question or request for AI.', 'ai-auto-tool')); ?>',
                                                        icon: 'error',
                                                        confirmButtonText: '<?php echo esc_js(__('OK', 'ai-auto-tool')); ?>'
                                                    });
                                                } else {
                                                    alert('<?php echo esc_js(__('Please enter a question or request for AI.', 'ai-auto-tool')); ?>');
                                                }
                                                return;
                                            }
                                            
                                            // Switch to AI Content tab
                                            if (typeof openTab === 'function') {
                                                openTab('aiContentTab');
                                            } else {
                                                // Fallback: manually switch tabs
                                                $('.aiautotool-tab-item').removeClass('active');
                                                $('.aiautotool-tab-item[data-tab="aiContentTab"]').addClass('active');
                                                $('.tabcontent').hide();
                                                $('#aiContentTab').show();
                                            }
                                            
                                            // Execute AI Agent with SSE
                                            if (typeof executePromptWithAgent === 'function') {
                                                executePromptWithAgent(prompt, 'outbard')
                                                    .then(function() {
                                                        console.log('AI Agent completed successfully');
                                                        // Clear the prompt textarea
                                                        $('#promptask').val('');
                                                        // Close modal after successful submission
                                                        closeAskAIModal();
                                                    })
                                                    .catch(function(error) {
                                                        console.error('AI Agent error:', error);
                                                        if (typeof Swal !== 'undefined') {
                                                            Swal.fire({
                                                                title: '<?php echo esc_js(__('Error!', 'ai-auto-tool')); ?>',
                                                                text: '<?php echo esc_js(__('AI Agent error:', 'ai-auto-tool')); ?> ' + error.message,
                                                                icon: 'error',
                                                                confirmButtonText: '<?php echo esc_js(__('Close', 'ai-auto-tool')); ?>'
                                                            });
                                                        }
                                                    });
                                            } else {
                                                console.error('executePromptWithAgent function not found');
                                                if (typeof Swal !== 'undefined') {
                                                    Swal.fire({
                                                        title: '<?php echo esc_js(__('Error!', 'ai-auto-tool')); ?>',
                                                        text: '<?php echo esc_js(__('AI Agent not available. Please refresh the page.', 'ai-auto-tool')); ?>',
                                                        icon: 'error',
                                                        confirmButtonText: '<?php echo esc_js(__('OK', 'ai-auto-tool')); ?>'
                                                    });
                                                }
                                            }
                                        });

                                        function getEditorWritingText() {
                                            var source = $('#aiautotool_editor_writing_source').val().trim();
                                            var title = $('#title').val() ? $('#title').val().trim() : '';
                                            var editorContent = '';

                                            if (typeof tinymce !== 'undefined' && tinymce.activeEditor) {
                                                editorContent = tinymce.activeEditor.getContent({ format: 'text' }).trim();
                                            } else if ($('#content').length) {
                                                editorContent = $('#content').val().trim();
                                            }

                                            return source || editorContent || title;
                                        }

                                        function runEditorToolAction(actionType) {
                                            var inputText = getEditorWritingText();

                                            if (!inputText) {
                                                if (typeof showError === 'function') {
                                                    showError('<?php echo esc_js(__('Please enter a title or source content first.', 'ai-auto-tool')); ?>');
                                                } else {
                                                    alert('<?php echo esc_js(__('Please enter a title or source content first.', 'ai-auto-tool')); ?>');
                                                }
                                                return;
                                            }

                                            var tempId = 'aiautotool_editor_writing_temp_' + Date.now();
                                            var $tempInput = $('<input type="hidden">').attr('id', tempId).val(inputText);
                                            var $tempButton = $('<button type="button" style="display:none;">Run</button>');
                                            $('body').append($tempInput, $tempButton);

                                            if (window.processToolRequest) {
                                                window.processToolRequest(actionType, tempId);
                                            } else if (typeof showError === 'function') {
                                                showError('<?php echo esc_js(__('AI tool handler is not available. Please refresh the page.', 'ai-auto-tool')); ?>');
                                            }

                                            setTimeout(function() {
                                                $tempInput.remove();
                                                $tempButton.remove();
                                            }, 2000);
                                        }

                                        function runEditorPromptTool(promptType) {
                                            var inputText = getEditorWritingText();
                                            var prompts = {
                                                expand: 'Expand the following content into a more complete, useful, and well-structured section while preserving the meaning. Use clear headings if helpful:\n\n',
                                                clarity: 'Improve the clarity, flow, grammar, and readability of the following content. Keep the meaning accurate and avoid adding unsupported facts:\n\n'
                                            };

                                            if (!inputText || !prompts[promptType]) {
                                                if (typeof showError === 'function') {
                                                    showError('<?php echo esc_js(__('Please enter source content first.', 'ai-auto-tool')); ?>');
                                                }
                                                return;
                                            }

                                            if (typeof open_box_aiautotool === 'function') {
                                                open_box_aiautotool();
                                            }
                                            if (typeof openTab === 'function') {
                                                openTab('aiContentTab');
                                            }

                                            var postLanguage = typeof get_lang === 'function' ? get_lang() : 'vi';
                                            var resolvedLang = postLanguage;
                                            if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(postLanguage)) {
                                                resolvedLang = languageCodes[postLanguage];
                                            }

                                            var sendFn = window.sendbardToServer || (typeof sendbardToServer !== 'undefined' ? sendbardToServer : null);
                                            if (!sendFn) {
                                                if (typeof showError === 'function') {
                                                    showError('<?php echo esc_js(__('AI function is not available. Please refresh the page.', 'ai-auto-tool')); ?>');
                                                }
                                                return;
                                            }

                                            sendFn(prompts[promptType] + inputText, 'outbard', 'writemore', resolvedLang);
                                        }

                                        function runEditorSpecialTool(toolId) {
                                            var configMap = {
                                                'write-with-agent': {
                                                    id: 'write-with-agent',
                                                    text: 'Write Full Article',
                                                    action: 'write-with-agent',
                                                    premium: true
                                                },
                                                'btn_suggettitle': {
                                                    id: 'btn_suggettitle',
                                                    text: 'SEO Titles',
                                                    action: 'TitleSuggestion',
                                                    premium: true
                                                },
                                                'custom-prompt-write': {
                                                    id: 'custom-prompt-write',
                                                    text: 'Custom Prompt',
                                                    action: 'CustomPrompt',
                                                    premium: true
                                                }
                                            };

                                            if (toolId === 'write-with-agent' && !$('#title').val().trim()) {
                                                var source = $('#aiautotool_editor_writing_source').val().trim();
                                                if (source) {
                                                    $('#title').val(source.split(/\r?\n/)[0].slice(0, 120)).trigger('change');
                                                }
                                            }

                                            if (typeof handleSpecialButton === 'function' && configMap[toolId]) {
                                                handleSpecialButton(configMap[toolId], null);
                                                return;
                                            }

                                            if (toolId === 'custom-prompt-write' && typeof showCustomPromptModal === 'function') {
                                                showCustomPromptModal();
                                            } else if (toolId === 'btn_suggettitle') {
                                                runEditorToolAction('TitleSuggestion');
                                            }
                                        }

                                        $(document).off('click.aiautotoolEditorWriting', '.aiautotool-editor-writing-button').on('click.aiautotoolEditorWriting', '.aiautotool-editor-writing-button', function(e) {
                                            e.preventDefault();
                                            var actionType = $(this).data('editor-writing-action');
                                            var promptType = $(this).data('editor-writing-prompt');
                                            var specialTool = $(this).data('editor-writing-special');

                                            if (actionType) {
                                                runEditorToolAction(actionType);
                                            } else if (promptType) {
                                                runEditorPromptTool(promptType);
                                            } else if (specialTool) {
                                                runEditorSpecialTool(specialTool);
                                            }
                                        });
                                    });
                                </script>
                                <div class="aiautotool_form">
                                    <!-- Modern Segmented Tab Control -->
                                    <div class="aiautotool-segmented-tabs">
                                        <div class="aiautotool-tab-item active" data-tab="aiContentTab">
                                            <i class="fa-solid fa-wand-magic-sparkles"></i>
                                            <span><?php echo wp_kses_post(__('AI Content','ai-auto-tool')); ?></span>
                                        </div>
                                        <div class="aiautotool-tab-item" data-tab="imagesTab">
                                            <i class="fa-solid fa-image"></i>
                                            <span><?php echo wp_kses_post(__('Images','ai-auto-tool')); ?></span>
                                        </div>
                                        <div class="aiautotool-tab-item" data-tab="videoTab">
                                            <i class="fa-brands fa-youtube"></i>
                                            <span><?php echo wp_kses_post(__('Videos','ai-auto-tool')); ?></span>
                                        </div>
                                    </div>
                                    
                                    <style>
                                        /* Modern Segmented Tab Control */
                                        .aiautotool-segmented-tabs {
                                            display: flex;
                                            background: #f3f4f6;
                                            padding: 4px;
                                            border-radius: 12px;
                                            margin-bottom: 20px;
                                            gap: 4px;
                                            box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
                                            overflow-x: auto;
                                            overflow-y: hidden;
                                            scroll-behavior: smooth;
                                            -webkit-overflow-scrolling: touch;
                                        }
                                        
                                        /* Hide scrollbar but keep functionality */
                                        .aiautotool-segmented-tabs::-webkit-scrollbar {
                                            height: 0px;
                                        }
                                        
                                        .aiautotool-segmented-tabs::-webkit-scrollbar-track {
                                            background: transparent;
                                        }
                                        
                                        .aiautotool-segmented-tabs::-webkit-scrollbar-thumb {
                                            background: transparent;
                                        }
                                        
                                        /* For Firefox */
                                        .aiautotool-segmented-tabs {
                                            scrollbar-width: none;
                                        }
                                        
                                        /* Drag cursor */
                                        .aiautotool-segmented-tabs.dragging {
                                            cursor: grabbing;
                                            cursor: -webkit-grabbing;
                                        }
                                        
                                        .aiautotool-segmented-tabs.dragging .aiautotool-tab-item {
                                            pointer-events: none;
                                        }
                                        
                                        .aiautotool-tab-item {
                                            flex: 1 0 auto;
                                            display: flex;
                                            align-items: center;
                                            justify-content: center;
                                            gap: 8px;
                                            padding: 10px 5px;
                                            border-radius: 8px;
                                            cursor: pointer;
                                            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                                            font-size: 14px;
                                            font-weight: 500;
                                            color: #6b7280;
                                            background: transparent;
                                            position: relative;
                                            user-select: none;
                                            white-space: nowrap;
                                            min-width: fit-content;
                                        }
                                        
                                        .aiautotool-tab-item i {
                                            font-size: 16px;
                                            transition: all 0.3s ease;
                                        }
                                        
                                        .aiautotool-tab-item:hover {
                                            color: #374151;
                                            background: rgba(255, 255, 255, 0.5);
                                        }
                                        
                                        .aiautotool-tab-item.active {
                                            background: #ffffff;
                                            color: #2563eb;
                                            box-shadow: 
                                                0 1px 3px rgba(0, 0, 0, 0.1),
                                                0 1px 2px rgba(0, 0, 0, 0.06);
                                            font-weight: 600;
                                        }
                                        
                                        .aiautotool-tab-item.active i {
                                            color: #2563eb;
                                            transform: scale(1.1);
                                        }
                                        
                                        /* Responsive */
                                        @media (max-width: 640px) {
                                            .aiautotool-tab-item span {
                                                display: none;
                                            }
                                            
                                            .aiautotool-tab-item {
                                                padding: 10px;
                                            }
                                            
                                            .aiautotool-tab-item i {
                                                font-size: 18px;
                                            }
                                        }
                                    </style>
                                    
                                    <script>
                                        jQuery(document).ready(function($) {
                                            // Modern Tab Switching
                                            $('.aiautotool-tab-item').on('click', function() {
                                                var targetTab = $(this).data('tab');
                                                
                                                // Remove active class from all tabs
                                                $('.aiautotool-tab-item').removeClass('active');
                                                
                                                // Add active class to clicked tab
                                                $(this).addClass('active');
                                                
                                                // Hide all tab contents
                                                $('.tabcontent').hide();
                                                
                                                // Show target tab content
                                                $('#' + targetTab).fadeIn(200);
                                            });
                                            
                                            // Show first tab by default
                                            $('.tabcontent').hide();
                                            $('#aiContentTab').show();
                                            
                                            // Drag to scroll functionality
                                            $('.aiautotool-segmented-tabs').each(function() {
                                                const slider = this;
                                                let isDown = false;
                                                let startX;
                                                let scrollLeft;
                                                
                                                $(slider).on('mousedown', function(e) {
                                                    // Don't interfere with tab clicks
                                                    if ($(e.target).closest('.aiautotool-tab-item').length) {
                                                        return;
                                                    }
                                                    isDown = true;
                                                    $(slider).addClass('dragging');
                                                    startX = e.pageX - slider.offsetLeft;
                                                    scrollLeft = slider.scrollLeft;
                                                    e.preventDefault();
                                                });
                                                
                                                $(slider).on('mouseleave mouseup', function() {
                                                    isDown = false;
                                                    $(slider).removeClass('dragging');
                                                });
                                                
                                                $(slider).on('mousemove', function(e) {
                                                    if (!isDown) return;
                                                    e.preventDefault();
                                                    const x = e.pageX - slider.offsetLeft;
                                                    const walk = (x - startX) * 2;
                                                    slider.scrollLeft = scrollLeft - walk;
                                                });
                                            });
                                        });
                                    </script>

                                    <!-- AI Content Tab -->
                                    <div id="aiContentTab" class="tabcontent">
                                        <div id="info_content" placeholdertext="<?php echo wp_kses_post(__('Input title for post Then Click gen Article,Select a phrase and click the Write button to use this feature','ai-auto-tool')); ?>"  ></div>
                                        
                                        <div class="loadingprocess p-5 aiautotool-text-center div_proccess_1 d-none div_proccess">
                                        <div id="loading-icon" class="loader" style="display:block"></div> <?php echo wp_kses_post(__('Start socket','ai-auto-tool')); ?> <span id="proccess_1" class="process_loading badge badge-soft-primary"></span>
                                        </div>
                                        <div class="div_proccess_error aiautotool-text-center div_proccess d-none">
                                        <div class="aiautotool-pt-5"> <span><?php echo wp_kses_post(__('Start socket Error, Please F5 to reload.','ai-auto-tool')); ?></span></div>
                                        
                                        </div>
                                        <!-- Content for AI Content tab goes here -->
                                        <div id="outbard">
                                            
                                            <br>
                                            <img src="<?php echo esc_url(plugins_url('assets/images/find1.png', __FILE__)); ?>" width="150px"  /></center></div>
                                        <button class="btn btnaddpost aiautotool_button" style="display:none" ><?php echo wp_kses_post(__('Add To Post','ai-auto-tool')); ?></button>
                                    </div>

                                    <!-- Images Tab -->
                                    <div id="imagesTab" class="tabcontent">
                                        <div class="infodiv">
                                        <div id="info_img" placeholdertext="<?php echo wp_kses_post(__('Select a phrase and click the Find Image button to use this feature','ai-auto-tool')); ?>"  ></div>
                                        <center>
                                            
                                            <br>
                                            <img src="<?php echo esc_url(plugins_url('assets/images/find1.png', __FILE__)); ?>" width="150px"  /></center>
                                        </div>
                                        
                                        <div id="img_list_find" class="img_list_find"></div>
                                        <!-- Content for Images tab goes here -->
                                    </div>

                                    <!-- Images Tab -->
                                    <div id="videoTab" class="tabcontent">
                                        <div class="infodiv">
                                        <div id="info_img" placeholdertext="<?php echo wp_kses_post(__('Select a phrase and click the Find Image button to use this feature','ai-auto-tool')); ?>"  ></div>
                                        <center>
                                            <br>
                                            <img src="<?php echo esc_url(plugins_url('assets/images/find1.png', __FILE__)); ?>" width="150px"  /></center>
                                        </div>
                                        
                                        <div id="video_list_find" class="video_list_find"></div>
                                        <!-- Content for Images tab goes here -->
                                    </div>

                                    
                                </div>
                            </div>
            <?php
        }
    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'])) {
            // Nếu đã qua một tháng, đặt lại số lượng bài đăng và ngày bắt đầu

            $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 ($config['number_post'] !== -1 && $config['number_post'] >= $config['usage']) || $config['number_post'] === -1;
            return $this->check_quota();
    }

    public function aiautotool__update_usage() {
        $this->aiautotool_check_post_limit();
        // Get the current usage value
        $current_value = get_option($this->usage_option_name, 0);

        // Increment the value by 1
        $new_value = $current_value + 1;

        // Update the option with the new value and set autoload to 'no'
        update_option($this->usage_option_name, $new_value, 'no');

        // Optionally, return the updated value
        return $new_value;
    }
    
    /**
     * Legacy method - kept for backward compatibility
     * Assets are now handled by Asset Manager via register_assets()
     * 
     * @deprecated Assets are now managed by Asset Manager
     */
    public function add_aiautotool_aipost_js() {
        // Assets are now managed by Asset Manager
        // This method is kept for backward compatibility only
        // If Asset Manager didn't load assets, fallback to old method
        if (!wp_script_is('kct_aipost', 'enqueued')) {
            wp_register_script('kct_aipost', plugin_dir_url( __FILE__ ) .'assets/js/aipost.js', array('jquery'), '1.2'.rand(), true);
	            wp_localize_script( 'kct_aipost', 'aipost', array_merge(array( 'ajax_url' => admin_url( 'admin-ajax.php'),'config'=>$this->config,'media_search_base_url' => $this->get_media_search_base_url(),'security' => wp_create_nonce('aiautotool_aipost_nonce') ), $this->aiautotool_get_ai_provider_js_settings()) );
            wp_enqueue_script('kct_aipost');
        }
        
        // Enqueue modern CSS for single post page
        $current_screen = get_current_screen();
        if ($current_screen && (strpos($current_screen->id, 'ai_single_post') !== false)) {
            if (!wp_style_is('aiautotool-singleai-modern', 'enqueued')) {
                wp_enqueue_style('aiautotool-singleai-modern', plugin_dir_url( __FILE__ ) .'assets/css/singleai-modern.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0');
            }
        }
    }
    
    public function aiautotool_update_usage() {
        $this->aiautotool_check_post_limit();
        
        // Get the current usage value
        $current_value = get_option($this->usage_option_name, 0);

        // Increment the value by 1
        $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']);
            update_option($this->active_option_name, $active,null, 'no');
            print_r($active);
        }

        wp_die();
    }

    function init(){
        $configs = get_option($this->plan_limit_aiautotool, array());
         

        
        if (!$this->aiautotool_has_plugin_data()) {
            $this->aiautotool_initialize_plugin_data();
            $configs = get_option($this->plan_limit_aiautotool, array());
        }
        if(isset($configs['expiration'])){
            $this->config  = array(
                'number_post'=>$this->limit,
                'usage'=>get_option($this->usage_option_name, 0, 'no'),
                'time_exprice'=>$configs['expiration']
            );
        }else{
            $this->config  = array(
                'number_post'=>$this->limit,
                'usage'=>get_option($this->usage_option_name, 0, 'no'),
                'time_exprice'=>''
            );
        }
        

        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;
            if (is_object($license) && isset($license->expiration)) {
                $this->config = array(
                    'number_post' => -1,
                    'usage' => get_option($this->usage_option_name, 0, 'no'),
                    'time_exprice' => $license->expiration
                );
            } else {
                $this->config = array(
                    'number_post' => -1,
                    'usage' => get_option($this->usage_option_name, 0, 'no'),
                    'time_exprice' => ''
                );
            }
        }
        add_action('admin_menu', array($this, 'add_menu'));

        add_action('admin_init', array($this, 'aiautotool_check_post_limit'));
        
        add_action('wp_ajax_aiautotool_get_slug', array($this, 'aiautotool_get_slug'));

        add_action('wp_ajax_bard_content', array($this, 'bard_content_callback'));


        add_action('wp_ajax_save_post_data', array($this, 'save_post_data'));

         add_action( 'admin_footer', array( $this, 'add_aiautotool_aipost_js' ) );

        add_action('wp_ajax_update_usage', array($this, 'aiautotool_update_usage_callback'));


             add_action('wp_ajax_seoreview_ajax', array($this, 'aiautotool_seoreview_ajax_callback'));
        add_action('add_meta_boxes', array( $this, 'aiautotool_meta_box' ));

        add_action('wp_ajax_aiautotool_suggest_tag', array($this, 'aiautotool_suggest_tag_callback'));
        
        // AJAX handlers for image generation features
        add_action('wp_ajax_aiautotool_save_draft', array($this, 'aiautotool_save_draft_callback'));
        add_action('wp_ajax_aiautotool_set_featured_image', array($this, 'aiautotool_set_featured_image_callback'));
        add_action('wp_ajax_aiautotool_generate_ai_image', array($this, 'aiautotool_generate_ai_image_callback'));
        add_action('wp_ajax_aiautotool_generate_tts_audio', array($this, 'aiautotool_generate_tts_audio_callback'));
        add_action('wp_ajax_aiautotool_save_tts_audio', array($this, 'aiautotool_save_tts_audio_callback'));
        add_action('wp_ajax_aiautotool_fetch_remote_content', array($this, 'aiautotool_fetch_remote_content_callback'));
        add_action('wp_ajax_aiautotool_analyze_image_positions', array($this, 'aiautotool_analyze_image_positions_callback'));
        add_action('wp_ajax_aiautotool_generate_english_prompt', array($this, 'aiautotool_generate_english_prompt_callback'));
        add_action('transition_post_status', array($this, 'aiautotool_maybe_queue_auto_tts'), 10, 3);
        add_action('aiautotool_generate_post_tts_event', array($this, 'aiautotool_generate_post_tts_event'));
        add_action('rest_api_init', array($this, 'aiautotool_register_voice_video_rest_routes'));
        
        // AJAX handler for article writing with Google search (SSE streaming)
        //add_action('wp_ajax_aiautotool_write_article_with_google_search', array($this, 'aiautotool_write_article_with_google_search_callback'));

    }
      public function aiautotool_suggest_tag_callback() {
            // Kiểm tra nonce
            if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'aiautotool_nonce' ) ) {
                wp_send_json_error( 'Invalid nonce' );
            }
            
            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
            $lang = isset($_POST['lang']) ? sanitize_text_field($_POST['lang']) : $this->setting['lang'];
            
            $tag = $this->aiautotool_AIprecreatetagname($title,$lang);
            if(isset($tag)){
                wp_send_json_success( $tag );
            }else{
                wp_send_json_error( 'no tag' );
            }
            
        }

    public function aiautotool_AIprecreatetagname($title, $lang) {
        $bardGenContent = new BardGenContent();
        $question = "The most important: The results must only be in JSON format, the response must be in the SAME LANGUAGE as the original text (text between \"======\").
    Create %%NUMMBERCOMMENT%% tag for the article.
    tag only 2 or 3 word
    tag must have a ====== %%TITLTE%%  ======  intellectual level.
    The post\'s content is between \"=========\". 
    The results must only be in JSON format, with this exact format, you have to fill empty values,Each item in tag has the form { \"tag\": \"\" }
    ";
        $question = str_replace('%%TITLTE%%', $title, $question);
        $question = str_replace('%%NUMMBERCOMMENT%%', rand(8, 15), $question);

        $json = $bardGenContent->bardcontentmore($question, $lang);

        return $this->aiautotool_fixjsonreturn($json);
    }
    
     public function aiautotool_seoreview_ajax_callback() {
        // Kiểm tra xác thực nonce để đảm bảo an toàn
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        // Lấy dữ liệu gửi từ client
        $post_title = sanitize_text_field($_POST['title']);
        $post_content = wp_kses_post($_POST['content']);
        
        $lang = $_POST['lang'];

        $question = '
        Tên của bạn bây giờ sẽ là AIAutoTool.
        Mở đầu kết quả trả về bạn phải tự giới thiệu về mình là : AIAutoTool, sau đây là phần đánh giá bài viết của bạn.
        Ngôn ngữ trả về phải giống với ngôn ngữ có trong nội dung (Nội dung bài viết nằm giữa =======)
        hãy thống kê từ khoá chính, từ khoá phụ, dự đoán từ khoá cùng vị trí có thể lên top google trong tương lai đối với nội dung bài viết có trong nội dung bài viết sau.
        Dựa vào bảng checklist dưới đây, đánh giá bài viết có (nội dung bài viết nằm giữa =======)
    - title Chứa từ khóa chính (khoảng 5-7 từ)
    - tiêu đề Dưới 70 ký tự (bao gồm cả khoảng trắng)
    - Sử dụng giọng văn Thu hút và khơi gợi sự tò mò
    - Sử dụng chữ hoa và số đếm hợp lý, các con số thống kê nên được đưa ra.
    - Mô tả ngắn của bài viết nên Chứa từ khóa chính (khoảng 10-15 từ).Dưới 160 ký tự (bao gồm cả khoảng trắng)
    - Tóm tắt nội dung bài viết một cách súc tích và hấp dẫn
    - Sử dụng Call to Action (CTA)
    - Cung cấp thông tin hữu ích và giá trị cho người đọc
    - Đáp ứng đúng ý định tìm kiếm của người dùng
    - Sử dụng từ khóa chính một cách tự nhiên và mật độ phù hợp (khoảng 1-2%)
    - Chia bài viết thành các đoạn ngắn, sử dụng headings và subheadings hợp lý
    - Bổ sung hình ảnh, video và infographic để minh họa cho nội dung
    - Sử dụng các liên kết nội bộ và liên kết ngoài chất lượng
    - Chứa từ khóa chính và biến thể của từ khóa mục tiêu.
    - Có tổ chức logic, dễ đọc và dễ tiếp cận.
    - Chứa thông tin giá trị và hữu ích cho người đọc.
    - Sử dụng các tiêu đề con (H2, H3) để phân đoạn nội dung.
    - Bài viết cần được kiểm tra lỗi chính tả và ngữ pháp
Trên đây là những yêu cầu tối thiểu cho một bài viết blog, bạn hãy đóng vai trò người SEOER đánh giá nội dung sau đây có được bao nhiêu điều thoả mãi checklist seo ở trên. Nội dung có trong bài viết sau:. ======= %%CONTENT%% =======';
       
                $question = str_replace('%%CONTENT%%',$post_content,$question);
                 $bardGenContent = new BardGenContent();
                 $json = $bardGenContent->bardcontentmore($question,$lang);
                 
                 if ($json) {
                    
                     wp_send_json_success($json);
                       wp_die(); 
                     
                 }
       
                 wp_send_json_error($newcontent);
        wp_die(); 
    }

    public function aiautotool_fixjsonreturn($result){
        $pattern = '/\{(?:[^{}]|(?R))*\}/'; 
        preg_match_all($pattern, $result, $matches);
        $arritem = array();
       
        foreach ($matches[0] as $jsonString) {
            
            $decodedJson = json_decode($jsonString, true);
            
            
            if ($decodedJson !== null) {
                if(isset($decodedJson['tags']))
                {
                    foreach($decodedJson['tags'] as $item){
                        $arritem[] = $item;
                    }
                }else{
                    $arritem[] = $decodedJson;
                }
            } else {
                return null;
            }
        }
       
        return $arritem;
    }

    function aiautotool_update_usage_callback() {
        
        check_ajax_referer('aiautotool_aipost_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $this->aiautotool_update_usage();
        wp_send_json_success(array('success'=>true));
        wp_die();
    }

    function save_post_data() {
       
        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;
        
        $title = sanitize_text_field($_POST['aiautotool_title']);
        $slug = sanitize_text_field($_POST['aiautotool_slug']);
        $categories = array_map('absint', $_POST['post_category']); // Ensure categories are integers
        $tags = sanitize_text_field($_POST['aiautotool_tags']);
        $content = wp_kses_post($_POST['aiautotool_content']);

        //xu ly time 
        $publish_year = sanitize_text_field($_POST['publish_year']);
        $publish_month = sanitize_text_field($_POST['publish_month']);
        $publish_day = sanitize_text_field($_POST['publish_day']);
        $publish_hour = sanitize_text_field($_POST['publish_hour']);
        $publish_minute = sanitize_text_field($_POST['publish_minute']);
        $attachThumbnail = sanitize_text_field($_POST['custom-thumbnail-id']);

        $post_language = sanitize_text_field($_POST['post_language']);

        $publish_timestamp = strtotime("$publish_year-$publish_month-$publish_day $publish_hour:$publish_minute");

        $current_time = current_time('timestamp');
        if ($publish_timestamp <= $current_time) {
            
            $post_status = 'publish';
            $post_date = date('Y-m-d H:i:s', $publish_timestamp);
        } else {
            
            $post_status = 'future'; 
            $post_date = date('Y-m-d H:i:s', $publish_timestamp);
        }

        $post_data = array(
        'post_title' => $title,
        'post_name' => $slug,
        'post_content' => $content, 
        'post_status' => $post_status,
        'post_date' => $post_date,
        'post_category' => $categories,
        'tags_input' => $tags,
    );

        $post_id = wp_insert_post($post_data);

        $selectedLanguageName = 'Vietnamese';
             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);


        $html = stripslashes($content);
                    preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
                    $listimg1 =  $matches[1]; 
                    $imgUploaded = array();
                    
                     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){
                        $content = str_replace($img['url'],$img['baseurl'],$content);
                    }
                            
                    
                    if ($attachThumbnail != 0) {
                        set_post_thumbnail($post_id, $attachThumbnail);
                    }
                    $post_data = array(
                        'ID' => $post_id,
                        'post_title'=>$title,
                        'post_content' => $content,
                        'post_status'=>'publish'
                    );

                    $post_id = wp_update_post($post_data);

        if ($post_id) {
            $post_url = get_permalink($post_id);
            $edit_url = get_edit_post_link($post_id);
            // Post successfully created, send success response
             wp_send_json_success(array(
                'post_id' => $post_id,
                'post_url' => $post_url,
                'edit_url' => $edit_url,
                'message' => 'Post successfully saved and published!',
            ));
        } else {
            // Error in creating the post, send error response
            wp_send_json_error(array(
                'message' => 'Error saving and publishing the post.',
            ));
        }

        // Perform your data saving logic here (example: save to database)

        // Send a response back to the client
        wp_send_json_success(array('content' => $_POST));
        // or wp_send_json_error('Error saving data!'); in case of an error
    }

    public function kct_aiautotool_save_image($imgURL,$post_title){
            $image_name = basename( $imgURL );
            $filetype  = wp_check_filetype($image_name);
            $upload_dir = wp_upload_dir();
            
            $extension = $filetype['ext']?$filetype['ext']:"jpg";
            if (empty($extension)) $extension = "jpg";
            $unique_file_name = sanitize_title($post_title)."-".uniqid().".".$extension;
            $filename = $upload_dir['path'] . '/' . $unique_file_name;
            $baseurl = $upload_dir['baseurl'] .$upload_dir['subdir']. '/' . $unique_file_name;
            $ch = curl_init($imgURL);
            $fp = fopen($filename, 'wb');
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_exec($ch);
            $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
            curl_close($ch);
            fclose($fp);
            if ($rescode == 200  && filesize($filename) > 100){

                 $wp_filetype = wp_check_filetype(basename($filename), null);
                
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => sanitize_file_name($post_title),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                
                $attach_id    = wp_insert_attachment($attachment, $filename);
                $imagenew     = get_post($attach_id);
                $fullsizepath = get_attached_file($imagenew->ID);
                
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                $attach_data = wp_generate_attachment_metadata($attach_id, $fullsizepath);
                wp_update_attachment_metadata($attach_id, $attach_data);
                


                $output['url'] = $imgURL;
                $output['file_name'] = $unique_file_name;
                $output['path'] = $filename;
                $output['baseurl'] = $baseurl;
                $output['attach_id'] = $attach_id;
                $output['url_out'] = $baseurl;
                return $output;
            }else{
                return null;
            }
        }
    public function bard_content_callback(){
        // Verify nonce for security
        if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            return;
        }

    	$languageCodes = $this->languageCodes;
        $bardGenContent = new BardGenContent();
        
        // Get parameters with fallbacks
        $question = isset($_POST['question']) ? sanitize_textarea_field($_POST['question']) : '';
        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : $question;
        $option = isset($_POST['option']) ? sanitize_text_field($_POST['option']) : '';
        $ac = isset($_POST['ac']) ? sanitize_text_field($_POST['ac']) : $option;
        $post_language = isset($_POST['lang']) ? sanitize_text_field($_POST['lang']) : '';
        $tone = isset($_POST['tone']) ? sanitize_text_field($_POST['tone']) : '';
        $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection(
            isset($_POST['model']) ? $_POST['model'] : '',
            isset($_POST['provider_id']) ? $_POST['provider_id'] : ''
        );
        $model = $resolved_ai_selection['model'];
        $provider_id = $resolved_ai_selection['provider_id'];
        
        // Handle old parameter name for compatibility
        if (empty($post_language) && isset($_POST['post_language'])) {
            $post_language = sanitize_text_field($_POST['post_language']);
        }
        
        // Resolve language code
        $lang = 'English';
        if (!empty($post_language)) {
            if(array_key_exists($post_language, $languageCodes)) {
                $lang = $languageCodes[$post_language];
            } else {
                $lang = $post_language;
            }
        }
        
        $newcontent = '';
        $prompt = '';
        
        try {
            // Handle different action types
    	    switch($ac){
    	 	    case 'bardcontent':
    	 		    $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id);
    	 		    break;
    	 		    
                case 'bard_content':
                    $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id);
                    break;
                    
                case 'writemore':
                case 'bardcontentmore':
                    // For Remote Rewrite and content expansion
                    if (!empty($question)) {
                        $newcontent = $bardGenContent->bardcontentmore($question, $lang, $model, $provider_id);
                    } else {
                        $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id);
                    }
                    break;
                    
                case 'bardrewrite':
                    // For content rewriting
                    if (!empty($question)) {
                        $newcontent = $bardGenContent->bardrewrite($question, $lang, $tone, $model, $provider_id);
                    } elseif (!empty($title)) {
                        $newcontent = $bardGenContent->bardrewrite($title, $lang, $tone, $model, $provider_id);
                    }
                    break;
                    
                case 'writefull':
                    // For full article writing
                    if (!empty($question)) {
                        $newcontent = $bardGenContent->bardcontentfull($question, $lang, $model, $provider_id);
                    } else {
                        $newcontent = $bardGenContent->bardcontentfull($title, $lang, $model, $provider_id);
                    }
                    break;
                    
                case 'writebard':
                    // For basic content generation
                    if (!empty($question)) {
                        $newcontent = $bardGenContent->bardcontent($question, $lang, $model, $provider_id);
                    } else {
                        $newcontent = $bardGenContent->bardcontent($title, $lang, $model, $provider_id);
                    }
                    break;
                    
    	 	    case 'suggettitle':
                    $allprompt = get_option('aiautotool_prompt_options', array());
                    if (!isset($allprompt['aiautotool_prompt_suggest_title']) || empty($allprompt['aiautotool_prompt_suggest_title'])) {
                        $prompt_suggest_title = "Generate 5 SEO-friendly titles for the following topic: {title}. Each title should be between 50-70 characters and include the main keyword. Format the response as a numbered list.";
                    } else {
                        $prompt_suggest_title = $allprompt['aiautotool_prompt_suggest_title'];
                    }
                    
                    $content = '';
                    $cate = '';
                    $blogtitle = '';
                    
                    // Add number of titles to generate
                    $num_titles = 5;
                    $prompt = $this->aiautotool_fix_question($prompt_suggest_title, $title, $lang, $cate, $blogtitle, $content);
                    $prompt = str_replace('{num_titles}', $num_titles, $prompt);
                    
                    $newcontent = $bardGenContent->gentitle($prompt, $lang, $model, $provider_id);
                    
                    // Format the response as a numbered list if not already formatted
                    if (strpos($newcontent, '1.') === false) {
                        $titles = explode("\n", trim($newcontent));
                        $formatted_titles = array();
                        foreach ($titles as $index => $t) {
                            if (!empty(trim($t))) {
                                $formatted_titles[] = ($index + 1) . '. ' . trim($t);
                            }
                        }
                        $newcontent = implode("\n", $formatted_titles);
                    }
                    break;
                    
    	 	    default:
    	 		    // Default to content generation
    	 		    if (!empty($question)) {
                        $newcontent = $bardGenContent->bardcontentmore($question, $lang, $model, $provider_id);
                    } else {
                        $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id);
                    }
    	 		    break;
    	    }
    	    
    	    // Check if content was generated
    	    if (empty($newcontent)) {
    	        wp_send_json_error(array(
    	            'message' => 'AI failed to generate content. Please try again.',
    	            'code' => 'empty_content'
    	        ));
    	        return;
    	    }
    	    
    	    // Return success with generated content
	        wp_send_json_success(array(
	            'content' => $newcontent,
	            'result' => $newcontent,
	            'lang' => $lang,
	            'lg' => $post_language,
	            'prompt' => $prompt,
	            'option' => $ac
	        ));
	        
	    } catch (Exception $e) {
	        wp_send_json_error(array(
	            'message' => 'Error generating content: ' . $e->getMessage(),
	            'code' => 'exception'
	        ));
	    }
	    
	    wp_die();
    }
    public function aiautotool_get_slug() {
		    check_ajax_referer('aiautotool_nonce', 'security');
		    
		    if (!current_user_can('edit_posts')) {
		        wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
		    }
		    
		    $title = sanitize_title($_POST['title']);
		    wp_send_json_success(array('slug' => $title));
		    wp_die();
		}

    public function add_menu() {
        // add_submenu_page(
        //     MENUSUBPARRENT,
        //     '<i class="fa-solid fa-robot"></i> AI Single Post',
        //     '<i class="fa-solid fa-robot"></i> AI Single Post',
        //     'manage_options',
        //     'ai_single_post',
        //     array($this, 'render_form')
        // );
        add_submenu_page(
            'edit.php',
            '<i class="fa-solid fa-robot"></i> AI Post',
            '<i class="fa-solid fa-robot"></i> AI Post',
            'manage_options',
            'ai_post',
            array($this, 'render_form')
        );
    }
    public function render_setting() {
        // Get current config
        $configs = get_option($this->plan_limit_aiautotool, array());
        $usage = get_option($this->usage_option_name, 0);
        $limit = $this->limit;
        $expiration = isset($configs['expiration']) ? $configs['expiration'] : '';
        
        // Check if premium or active trial - verify with Freemius access helper
        $is_premium = false;
        $plan_name = '';
        if (function_exists('aiautotool_can_use_pro_features') && aiautotool_can_use_pro_features()) {
            $premium_obj = $this->is_premium();
            $is_premium = true;
            $limit = -1; // Unlimited
            if ($premium_obj && is_object($premium_obj) && method_exists($premium_obj, '_get_license')) {
                $license = $premium_obj->_get_license();
                if ($license && isset($license->expiration)) {
                    $expiration = $license->expiration;
                }
            }
        }
        
        // Calculate remaining
        $remaining = ($limit == -1) ? __('Unlimited', 'ai-auto-tool') : max(0, $limit - $usage);
        $usage_percentage = ($limit == -1 || $limit == 0) ? 0 : min(100, ($usage / $limit) * 100);
        
        ?>
        <div id="tab-single-ai-setting" class="tab-content sotab-box ftbox" style="display:none;">
            <h2><i class="fa-solid fa-pen-nib"></i> <?php esc_html_e('Writing Tool', 'ai-auto-tool'); ?></h2>

            <div class="ft-card" style="margin-bottom: 20px;">
                <h3><?php esc_html_e('Writing Workflow', 'ai-auto-tool'); ?></h3>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Use this feature to draft from a title, improve existing content, and prepare SEO assets with the active AI provider.', 'ai-auto-tool'); ?>
                </p>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; margin-top: 18px;">
                    <div style="padding: 16px; background: #f7faf8; border: 1px solid #d8e4dc; border-radius: 8px;">
                        <div style="font-weight: 700; color: #173b2f; margin-bottom: 8px;"><i class="fa-solid fa-file-pen"></i> <?php esc_html_e('Create Draft', 'ai-auto-tool'); ?></div>
                        <div style="color: #5d6f68; font-size: 13px; line-height: 1.5;"><?php esc_html_e('Generate outline, introduction, and full article from a title or keyword.', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="padding: 16px; background: #f7faf8; border: 1px solid #d8e4dc; border-radius: 8px;">
                        <div style="font-weight: 700; color: #173b2f; margin-bottom: 8px;"><i class="fa-solid fa-wand-magic-sparkles"></i> <?php esc_html_e('Improve Content', 'ai-auto-tool'); ?></div>
                        <div style="color: #5d6f68; font-size: 13px; line-height: 1.5;"><?php esc_html_e('Rewrite, expand, summarize, or improve clarity from selected or pasted content.', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="padding: 16px; background: #f7faf8; border: 1px solid #d8e4dc; border-radius: 8px;">
                        <div style="font-weight: 700; color: #173b2f; margin-bottom: 8px;"><i class="fa-solid fa-chart-line"></i> <?php esc_html_e('SEO Assets', 'ai-auto-tool'); ?></div>
                        <div style="color: #5d6f68; font-size: 13px; line-height: 1.5;"><?php esc_html_e('Create SEO titles, meta descriptions, FAQ, keywords, and related content ideas.', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="padding: 16px; background: #f7faf8; border: 1px solid #d8e4dc; border-radius: 8px;">
                        <div style="font-weight: 700; color: #173b2f; margin-bottom: 8px;"><i class="fa-solid fa-sliders"></i> <?php esc_html_e('Advanced', 'ai-auto-tool'); ?></div>
                        <div style="color: #5d6f68; font-size: 13px; line-height: 1.5;"><?php esc_html_e('Use custom prompts, social posts, content calendars, and bulk/automation shortcuts.', 'ai-auto-tool'); ?></div>
                    </div>
                </div>
            </div>
            
            <!-- Usage Statistics -->
            <div class="ft-card" style="margin-bottom: 20px;">
                <h3><?php esc_html_e('Writing Usage', 'ai-auto-tool'); ?></h3>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px;">
                    <div style="text-align: center; padding: 20px; background: #f7faf8; border-radius: 8px; border-left: 4px solid #00875c;">
                        <div style="font-size: 32px; font-weight: bold; color: #00875c;"><?php echo esc_html($usage); ?></div>
                        <div style="color: #5d6f68; margin-top: 5px; font-size: 14px;"><?php esc_html_e('Drafts Created', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 20px; background: #f7faf8; border-radius: 8px; border-left: 4px solid #2f7d5c;">
                        <div style="font-size: 32px; font-weight: bold; color: #2f7d5c;"><?php echo esc_html($limit == -1 ? __('∞', 'ai-auto-tool') : $limit); ?></div>
                        <div style="color: #5d6f68; margin-top: 5px; font-size: 14px;"><?php esc_html_e('Plan Limit', 'ai-auto-tool'); ?></div>
                    </div>
                    <div style="text-align: center; padding: 20px; background: #f7faf8; border-radius: 8px; border-left: 4px solid #7b8f84;">
                        <div style="font-size: 32px; font-weight: bold; color: #54685f;"><?php echo esc_html($remaining); ?></div>
                        <div style="color: #5d6f68; margin-top: 5px; font-size: 14px;"><?php esc_html_e('Remaining', 'ai-auto-tool'); ?></div>
                    </div>
                </div>
                
                <?php if ($limit != -1 && $limit > 0): ?>
                <div style="margin-top: 20px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                        <span style="font-weight: 600;"><?php esc_html_e('Usage Progress', 'ai-auto-tool'); ?></span>
                        <span style="color: #6c757d;"><?php echo esc_html(number_format($usage_percentage, 1)); ?>%</span>
                    </div>
                    <div style="background: #e9ecef; border-radius: 10px; height: 25px; overflow: hidden;">
                        <div style="background: #00875c; height: 100%; width: <?php echo esc_attr($usage_percentage); ?>%; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 600;">
                            <?php if ($usage_percentage > 10): ?>
                                <?php echo esc_html($usage); ?> / <?php echo esc_html($limit); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Plan Information -->
            <div class="ft-card" style="margin-bottom: 20px;">
                <h3><?php esc_html_e('Access', 'ai-auto-tool'); ?></h3>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php esc_html_e('Plan Type', 'ai-auto-tool'); ?></th>
                        <td>
                            <?php if ($is_premium): ?>
                                <span style="color: #28a745; font-weight: 600;">
                                    <i class="fa-solid fa-crown"></i> <?php echo esc_html(ucfirst($plan_name)); ?>
                                </span>
                            <?php else: ?>
                                <span style="color: #6c757d;">
                                    <i class="fa-solid fa-user"></i> <?php esc_html_e('Free', 'ai-auto-tool'); ?>
                                </span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Post Limit', 'ai-auto-tool'); ?></th>
                        <td>
                            <?php if ($limit == -1): ?>
                                <span style="color: #28a745; font-weight: 600;">
                                    <i class="fa-solid fa-infinity"></i> <?php esc_html_e('Unlimited', 'ai-auto-tool'); ?>
                                </span>
                            <?php else: ?>
                                <span><?php echo esc_html($limit); ?> <?php esc_html_e('posts', 'ai-auto-tool'); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if ($expiration): ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Expiration Date', 'ai-auto-tool'); ?></th>
                        <td>
                            <?php 
                            $exp_date = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($expiration));
                            echo esc_html($exp_date);
                            ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
            
            <!-- Post Types Configuration -->
            <div class="ft-card" style="margin-bottom: 20px;">
                <h3><?php esc_html_e('Editor Availability', 'ai-auto-tool'); ?></h3>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Select which post types should show the Writing Tool panel inside the editor.', 'ai-auto-tool'); ?>
                </p>
                
                <form method="post" action="options.php">
                    <?php
                    settings_fields('aiautotool_singleai_settings_group');
                    $settings = $this->get_singleai_settings();
                    $enabled_post_types = $settings['post_types'];
                    $available_post_types = get_post_types(array('public' => true), 'objects');
                    ?>
                    
                    <div style="margin-top: 20px;">
                        <?php foreach ($available_post_types as $post_type): 
                            $checked = in_array($post_type->name, $enabled_post_types) ? 'checked' : '';
                            ?>
                            <p style="margin-bottom: 10px;">
                                <label class="nut-switch">
                                    <input type="checkbox" name="<?php echo esc_attr($this->settings_option_name); ?>[post_types][]" value="<?php echo esc_attr($post_type->name); ?>" <?php echo $checked; ?> />
                                    <span class="slider"></span>
                                </label>
                                <label style="margin-left: 10px; font-weight: 500;">
                                    <?php echo esc_html($post_type->label); ?>
                                    <span style="color: #6c757d; font-weight: normal; font-size: 12px;">(<?php echo esc_html($post_type->name); ?>)</span>
                                </label>
                            </p>
                        <?php endforeach; ?>
                    </div>
                    
                    <?php submit_button(__('Save Writing Tool Settings', 'ai-auto-tool'), 'ft-submit', 'submit', false); ?>
                </form>
            </div>
            
            <!-- Feature Information -->
            <div class="ft-card">
                <h3><?php esc_html_e('How To Use', 'ai-auto-tool'); ?></h3>
                <p class="ft-note">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Open a post editor, enter a title or paste source notes, then use the Writing Tool panel to draft, improve, and optimize content.', 'ai-auto-tool'); ?>
                </p>
                <ul style="list-style: disc; margin-left: 20px; margin-top: 10px;">
                    <li><?php esc_html_e('Create a full draft from title or keyword.', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Rewrite, expand, summarize, or polish existing content.', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Generate SEO titles, meta descriptions, FAQ, and keyword ideas.', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Use custom prompts for advanced writing cases.', 'ai-auto-tool'); ?></li>
                </ul>
                <p style="margin-top: 15px;">
                    <a href="<?php echo esc_url(admin_url('post-new.php')); ?>" class="button button-primary">
                        <i class="fa-solid fa-plus"></i> <?php esc_html_e('Open Post Editor', 'ai-auto-tool'); ?>
                    </a>
                    <a href="https://doc.aiautotool.com/features/ai-content-editor" target="_blank" class="button">
                        <i class="fa-solid fa-book"></i> <?php esc_html_e('View Documentation', 'ai-auto-tool'); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php
    }
    
    public function render_tab_setting() {
        if ($this->active == 'true' || $this->active === true) {
            echo '<button href="#tab-single-ai-setting" class="nav-tab sotab"><i class="fa-solid fa-pen-nib"></i> ' . esc_html__('Writing Tool', 'ai-auto-tool') . '</button>';
        }
    }

    public function render_feature(){
        // Load feature descriptions
        require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            $this->icon.' '.$this->name_plan,
            AiAutoTool_Feature_Descriptions::get('single_ai'),
            "https://doc.aiautotool.com/features/ai-content-editor",
            $this->active_option_name,
            $this->active,
            defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)
        );
    echo $autoToolBox->generateHTML();

    }


    
   

    public function render_form() {
        $current_time = current_time('mysql');
        $datetime = new DateTime($current_time);
        $year = $datetime->format('Y');  // Lấy năm
        $month = $datetime->format('m'); // Lấy tháng
        $day = $datetime->format('d');   // Lấy ngày
        $hour = $datetime->format('H');  // Lấy giờ
        $minute = $datetime->format('i'); // Lấy phút

       

        $language_code = explode('_',get_locale());
        $language_code = $language_code[0];
            // Mảng mã ngôn ngữ và tên tương ứng
            $languages = $this->languageCodes;

           
            // $post = new SinglePost('','vi');
            // print_r($post->getPost());
        ?>
        <style>
            .aiautotool-modern-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 30px;
                border-radius: 12px;
                margin-bottom: 30px;
                box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
                display: flex;
                align-items: center;
                gap: 20px;
            }
            
            .aiautotool-modern-header img {
                width: 48px;
                height: 48px;
                filter: brightness(0) invert(1);
            }
            
            .aiautotool-modern-header h1 {
                color: white;
                margin: 0;
                font-size: 32px;
                font-weight: 700;
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            .aiautotool_container {
                display: grid;
                grid-template-columns: 1fr 380px;
                gap: 30px;
                max-width: 1600px;
                margin: 0 auto;
            }
            
            .aiautotool_left {
                width: 100%;
            }
            
            .aiautotool_box {
                background: white;
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.08);
                padding: 0;
                margin-bottom: 30px;
                overflow: hidden;
                transition: all 0.3s ease;
            }
            
            .aiautotool_box:hover {
                box-shadow: 0 8px 30px rgba(0,0,0,0.12);
                transform: translateY(-2px);
            }
            
            .aiautotool_box_head {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px 30px;
                font-size: 18px;
                font-weight: 600;
                display: flex;
                align-items: center;
                gap: 12px;
                border-bottom: none;
            }
            
            .aiautotool_box_head img {
                filter: brightness(0) invert(1);
                width: 24px;
                height: 24px;
            }
            
            .aiautotool_box_content {
                padding: 30px;
            }
            
            .aiautotool-form-group {
                margin-bottom: 25px;
            }
            
            .aiautotool-form-label {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 14px;
                font-weight: 600;
                color: #374151;
                margin-bottom: 10px;
            }
            
            .aiautotool-form-label i {
                color: #667eea;
                font-size: 16px;
            }
            
            .aiautotool-input {
                width: 100%;
                padding: 12px 16px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 15px;
                transition: all 0.3s ease;
                background: #f9fafb;
            }
            
            .aiautotool-input:focus {
                outline: none;
                border-color: #667eea;
                background: white;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }
            
            .aiautotool-select {
                width: 100%;
                padding: 12px 16px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 15px;
                background: #f9fafb;
                cursor: pointer;
                transition: all 0.3s ease;
            }
            
            .aiautotool-select:focus {
                outline: none;
                border-color: #667eea;
                background: white;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }
            
            .aiautotool_categories {
                background: #f9fafb;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                padding: 15px;
                max-height: 200px;
                overflow-y: auto;
            }
            
            .aiautotool_categories::-webkit-scrollbar {
                width: 8px;
            }
            
            .aiautotool_categories::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 4px;
            }
            
            .aiautotool_categories::-webkit-scrollbar-thumb {
                background: #667eea;
                border-radius: 4px;
            }
            
            #custom-thumbnail-preview {
                background: #f9fafb;
                border: 2px dashed #e5e7eb;
                border-radius: 8px;
                padding: 20px;
                text-align: center;
                min-height: 150px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 15px;
                transition: all 0.3s ease;
            }
            
            #custom-thumbnail-preview:hover {
                border-color: #667eea;
                background: white;
            }
            
            #custom-thumbnail-preview img {
                max-width: 100%;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }
            
            #upload-custom-thumbnail {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 8px;
                font-size: 15px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                width: 100%;
            }
            
            #upload-custom-thumbnail:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            }
            
            .aiautotool_right {
                width: 100%;
            }
            
            .aiautotool-fixed {
                position: sticky;
                top: 32px;
            }
            
            .aiautotool_navpublic {
                background: white;
                border-radius: 12px;
                padding: 25px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.08);
                margin-bottom: 20px;
            }
            
            .aiautotool_navpublic label {
                display: block;
                font-weight: 600;
                color: #374151;
                margin-bottom: 15px;
                font-size: 14px;
            }
            
            .publish-date-time-row {
                display: grid;
                grid-template-columns: 2fr 1fr 1fr;
                gap: 10px;
                margin-bottom: 15px;
            }
            
            .aiautotool_box_time_select,
            .aiautotool_box_time_input {
                padding: 10px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 14px;
                background: #f9fafb;
                transition: all 0.3s ease;
            }
            
            .aiautotool_box_time_select:focus,
            .aiautotool_box_time_input:focus {
                outline: none;
                border-color: #667eea;
                background: white;
            }
            
            .save-single-generation {
                background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                color: white;
                border: none;
                padding: 16px;
                border-radius: 8px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                width: 100%;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
            }
            
            .save-single-generation:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
            }
            
            .save-single-generation:before {
                content: "\\f0c7";
                font-family: "Font Awesome 7 Free";
                font-weight: 900;
            }
            
            #aiautotool-meta-box .aiautotool_box_head {
                background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            }
            
            .askassistant {
                padding: 20px;
                background: linear-gradient(135deg, #f9fafb 0%, #e5e7eb 100%);
                border-radius: 8px;
                margin-bottom: 20px;
            }
            
            .askassistant {
                position: relative;
            }
            
            .askassistant textarea {
                width: 100%;
                padding: 12px 12px 12px 40px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                resize: vertical;
                min-height: 80px;
                font-size: 14px;
                margin-bottom: 12px;
                transition: all 0.3s ease;
            }
            
            .askassistant::before {
                content: "\f075";
                font-family: "Font Awesome 6 Free";
                font-weight: 400;
                position: absolute;
                left: 32px;
                top: 32px;
                color: #9ca3af;
                pointer-events: none;
                z-index: 1;
                font-size: 16px;
                transition: color 0.3s ease;
            }
            
            .askassistant:has(textarea:focus)::before {
                color: #f59e0b;
            }
            
            .askassistant textarea:focus {
                outline: none;
                border-color: #f59e0b;
                box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
            }
            
            .select-and-button {
                display: flex;
                gap: 10px;
                position: relative;
            }
            
            .select-and-button select {
                width: 50%;
                flex: 0 0 50%;
                padding: 8px 30px 8px 32px;
                border: 2px solid #e5e7eb;
                border-radius: 6px;
                background: white;
                cursor: pointer;
                font-size: 13px;
                appearance: none;
                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
                background-repeat: no-repeat;
                background-position: right 10px center;
                background-size: 12px;
                transition: all 0.3s ease;
            }
            
            .select-and-button::after {
                content: "\f0d7";
                font-family: "Font Awesome 6 Free";
                font-weight: 400;
                position: absolute;
                left: 12px;
                top: 50%;
                transform: translateY(-50%);
                color: #9ca3af;
                pointer-events: none;
                z-index: 1;
                font-size: 12px;
                transition: color 0.3s ease;
            }
            
            .select-and-button:has(select:focus)::after {
                color: #f59e0b;
            }
            
            .select-and-button select:focus {
                outline: none;
                border-color: #f59e0b;
            }
            
            .select-and-button button {
                width: 50%;
                flex: 0 0 50%;
                background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                font-weight: 600;
                font-size: 13px;
                cursor: pointer;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 6px;
            }
            
            .select-and-button button i {
                font-size: 14px;
                transition: transform 0.3s ease;
            }
            
            .select-and-button button:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4);
            }
            
            .select-and-button button:hover i {
                transform: scale(1.1) rotate(5deg);
            }
            
            .aiautotool_tab {
                display: flex;
                gap: 8px;
                margin-bottom: 20px;
                background: #f9fafb;
                padding: 8px;
                border-radius: 8px;
            }
            
            .aiautotool_tab button {
                flex: 1;
                padding: 12px;
                background: transparent;
                border: none;
                border-radius: 6px;
                cursor: pointer;
                font-weight: 600;
                color: #6b7280;
                transition: all 0.3s ease;
            }
            
            .aiautotool_tab button:hover {
                background: white;
                color: #667eea;
            }
            
            .aiautotool_tab button.active {
                background: white;
                color: #667eea;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            
            .tabcontent {
                padding: 20px;
                background: white;
                border-radius: 8px;
            }

            .aiautotool-writing-panel {
                border: 1px solid #d8e4dc;
                border-radius: 8px;
                background: #f7faf8;
                margin-bottom: 20px;
                overflow: hidden;
            }

            #aiautotool_bar_right #aiautotool-writing-panel {
                display: none !important;
            }

            .aiautotool-writing-panel {
                display: none !important;
            }

            .aiautotool-writing-panel__header {
                padding: 16px 18px;
                background: #ffffff;
                border-bottom: 1px solid #d8e4dc;
            }

            .aiautotool-writing-panel__title {
                display: flex;
                align-items: center;
                gap: 8px;
                color: #173b2f;
                font-size: 15px;
                font-weight: 700;
                margin: 0 0 4px;
            }

            .aiautotool-writing-panel__note {
                color: #5d6f68;
                font-size: 12px;
                line-height: 1.45;
                margin: 0;
            }

            .aiautotool-writing-source {
                padding: 14px;
                display: grid;
                gap: 10px;
            }

            .aiautotool-writing-source textarea {
                min-height: 92px;
                width: 100%;
                resize: vertical;
                border: 1px solid #cbd8d0;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 13px;
                line-height: 1.45;
                background: #ffffff;
                box-sizing: border-box;
            }

            .aiautotool-writing-source textarea:focus {
                border-color: #00875c;
                box-shadow: 0 0 0 2px rgba(0, 135, 92, 0.12);
                outline: none;
            }

            .aiautotool-writing-source__row {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
            }

            .aiautotool-writing-source select {
                width: 100%;
                min-height: 36px;
                border-color: #cbd8d0;
                border-radius: 6px;
                color: #173b2f;
                font-size: 13px;
            }

            .aiautotool-writing-workflows {
                padding: 0 14px 14px;
                display: grid;
                gap: 10px;
            }

            .aiautotool-writing-group {
                background: #ffffff;
                border: 1px solid #d8e4dc;
                border-radius: 8px;
                padding: 12px;
            }

            .aiautotool-writing-group__head {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 10px;
                color: #173b2f;
                font-size: 13px;
                font-weight: 700;
            }

            .aiautotool-writing-actions {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
            }

            .aiautotool-writing-action {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 7px;
                min-height: 38px;
                padding: 8px 10px;
                border: 1px solid #cbd8d0;
                border-radius: 6px;
                background: #ffffff;
                color: #173b2f;
                font-size: 12px;
                font-weight: 650;
                cursor: pointer;
                transition: all 0.16s ease;
            }

            .aiautotool-writing-action:hover {
                border-color: #00875c;
                color: #006b49;
                background: #f0faf5;
            }

            .aiautotool-writing-action--primary {
                grid-column: 1 / -1;
                background: #00875c;
                border-color: #00875c;
                color: #ffffff;
            }

            .aiautotool-writing-action--primary:hover {
                background: #006b49;
                color: #ffffff;
            }
            
            .infodiv {
                text-align: center;
                padding: 30px;
                color: #6b7280;
            }
            
            .infodiv img {
                opacity: 0.6;
                margin-top: 15px;
            }
            
            @media (max-width: 1280px) {
                .aiautotool_container {
                    grid-template-columns: 1fr;
                }
                
                .aiautotool-fixed {
                    position: relative;
                    top: 0;
                }
            }

            @media (max-width: 782px) {
                .aiautotool-writing-source__row,
                .aiautotool-writing-actions {
                    grid-template-columns: 1fr;
                }
            }
            
            .ft-input-big {
                width: 100%;
                padding: 12px 16px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 15px;
                transition: all 0.3s ease;
                background: #f9fafb;
            }
            
            .ft-input-big:focus {
                outline: none;
                border-color: #667eea;
                background: white;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }
            
            hr {
                border: none;
                border-top: 2px solid #e5e7eb;
                margin: 25px 0;
            }
        </style>
        
        <div class="aiautotool-modern-header">
            <img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)); ?>" alt="AI Autotool" />
            <h1><?php echo wp_kses_post(__('AI Content Generator','ai-auto-tool')); ?></h1>
        </div>
        
        <div>
            <form method="post" action="" id="aiautotool_post_form" class="aiautotool_container">
                <div class="aiautotool_left">
                	<div class="aiautotool_box">
                		<div class="aiautotool_box_head">
                            <img src="<?php echo esc_url(defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)); ?>" />
			                <span id="titlehead"><?php echo wp_kses_post(__('Post Content','ai-auto-tool')); ?></span>  
			            </div>
			            <div class="aiautotool_box_content">
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-language"></i>
                                    <?php echo wp_kses_post(__('Language','ai-auto-tool')); ?>
                                </label>
                                <select name="post_language" id="post_language" class="aiautotool-select">
                                <?php
                                foreach ($languages as $code => $name) {
                                    $is_selected = selected($language_code, $code, false);
                                    echo '<option value="' . esc_attr($code) . '" ' . esc_attr($is_selected ). '>' . esc_attr($name ). '</option>';
                                }
                                ?>
                                </select>
                            </div>
                            
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-heading"></i>
                                    <?php echo wp_kses_post(__('Post Title','ai-auto-tool')); ?>
                                </label>
    	                        <input placeholder="<?php echo esc_attr(__('Enter your post title here...','ai-auto-tool')); ?>" type="text" id="aiautotool_title" class="aiautotool-input" name="aiautotool_title">
                            </div>
                            
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-link"></i>
                                    <?php echo wp_kses_post(__('URL Slug','ai-auto-tool')); ?>
                                </label>
    	                        <input placeholder="<?php echo esc_attr(__('post-url-slug','ai-auto-tool')); ?>" type="text" id="aiautotool_slug" class="aiautotool-input" name="aiautotool_slug">
                            </div>
                            
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-folder"></i>
                                    <?php echo wp_kses_post(__('Categories','ai-auto-tool')); ?>
                                </label>
    		                    <div class="aiautotool_categories">
    		                        <?php wp_category_checklist(); ?>
    		                    </div>
                            </div>
                            
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-tags"></i>
                                    <?php echo wp_kses_post(__('Tags','ai-auto-tool')); ?>
                                </label>
    		                    <input placeholder="<?php echo esc_attr(__('tag1, tag2, tag3...','ai-auto-tool')); ?>" type="text" id="aiautotool_tags" class="aiautotool-input" name="aiautotool_tags">
    		                </div>
    		                
                            <?php 
                            $thumbnail_id = 0;
                            $thumbnail_url = wp_get_attachment_image_url($thumbnail_id, 'thumbnail');
                            ?>
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-image"></i>
                                    <?php echo wp_kses_post(__('Featured Image','ai-auto-tool')); ?>
                                </label>
                                <input type="hidden" id="custom-thumbnail-id" name="custom-thumbnail-id" value="<?php echo esc_attr($thumbnail_id); ?>">
                                <div id="custom-thumbnail-preview">
                                    <?php if ($thumbnail_url): ?>
                                        <img src="<?php echo esc_url($thumbnail_url); ?>" />
                                    <?php else: ?>
                                        <div style="color: #9ca3af;">
                                            <i class="fa-solid fa-cloud-arrow-up" style="font-size: 48px; margin-bottom: 10px;"></i>
                                            <p><?php echo wp_kses_post(__('No image selected','ai-auto-tool')); ?></p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <button type="button" id="upload-custom-thumbnail">
                                    <i class="fa-solid fa-upload"></i>
                                    <?php echo wp_kses_post(__('Upload Featured Image','ai-auto-tool')); ?>
                                </button>
                            </div>
                            
                            <div class="aiautotool-form-group">
                                <label class="aiautotool-form-label">
                                    <i class="fa-solid fa-file-lines"></i>
                                    <?php echo wp_kses_post(__('Post Content','ai-auto-tool')); ?>
                                </label>
    	                        <?php wp_editor('', 'aiautotool_content', array('textarea_name' => 'aiautotool_content')); ?>
                            </div>
                        </div>


	                   
               		 </div>
                </div>

                <div class="aiautotool_right">
                	<div class="aiautotool-fixed">
                		<div class="aiautotool_navpublic">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                                <i class="fa-solid fa-calendar-days" style="color: #667eea; font-size: 18px;"></i>
                                <label for="publish_datetime" style="margin: 0; font-size: 15px;">
                                    <?php echo wp_kses_post(__('Publish Schedule','ai-auto-tool')); ?>
                                </label>
                            </div>
                            
                            <div class="publish-date-time-row">
                                <select id="publish_month" name="publish_month" class="aiautotool_box_time_select">
                                    <option <?php selected($month, '01'); ?> value="01"><?php echo wp_kses_post(__('January','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '02'); ?> value="02"><?php echo wp_kses_post(__('February','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '03'); ?> value="03"><?php echo wp_kses_post(__('March','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '04'); ?> value="04"><?php echo wp_kses_post(__('April','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '05'); ?> value="05"><?php echo wp_kses_post(__('May','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '06'); ?> value="06"><?php echo wp_kses_post(__('June','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '07'); ?> value="07"><?php echo wp_kses_post(__('July','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '08'); ?> value="08"><?php echo wp_kses_post(__('August','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '09'); ?> value="09"><?php echo wp_kses_post(__('September','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '10'); ?> value="10"><?php echo wp_kses_post(__('October','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '11'); ?> value="11"><?php echo wp_kses_post(__('November','ai-auto-tool')); ?></option>
                                    <option <?php selected($month, '12'); ?> value="12"><?php echo wp_kses_post(__('December','ai-auto-tool')); ?></option>
                                </select>
                                
                                <input value="<?php echo esc_attr($day); ?>" type="text" id="publish_day" name="publish_day" class="aiautotool_box_time_input" placeholder="<?php echo esc_attr(__('Day','ai-auto-tool')); ?>">
                                
                                <input value="<?php echo esc_attr($year); ?>" type="text" id="publish_year" name="publish_year" class="aiautotool_box_time_input" placeholder="<?php echo esc_attr(__('Year','ai-auto-tool')); ?>">
                            </div>
                            
                            <div style="display: grid; grid-template-columns: 1fr auto 1fr; gap: 10px; align-items: center;">
                                <input value="<?php echo esc_attr($hour); ?>" type="text" id="publish_hour" name="publish_hour" class="aiautotool_box_time_input" placeholder="<?php echo esc_attr(__('Hour','ai-auto-tool')); ?>">
                                
                                <span style="color: #6b7280; font-weight: 600;">:</span>
                                
                                <input value="<?php echo esc_attr($minute); ?>" type="text" id="publish_minute" name="publish_minute" class="aiautotool_box_time_input" placeholder="<?php echo esc_attr(__('Min','ai-auto-tool')); ?>">
                            </div>
                            
                    		<button type="submit" class="save-single-generation">
                                <?php echo wp_kses_post(__('Publish Post','ai-auto-tool')); ?>
                            </button>
			           </div>
	                	
					<!-- AI Assistant Box -->
					<div id="aiautotool-meta-box" class="aiautotool_box">
			            <div class="aiautotool_box_head">
					        <img src="<?php echo esc_url(plugins_url('../../images/logo.svg', __FILE__)); ?>" />
					        <span><?php echo wp_kses_post(__('AI Assistant','ai-auto-tool')); ?></span>
			            </div>
			            <div style="padding: 20px;">
                            <div class="askassistant">
                                <textarea id="promptask" rows="2" placeholder="<?php echo esc_attr(__('Ask AI anything about your content...','ai-auto-tool'));?>" aria-label="<?php echo esc_attr(__('AI Prompt Input','ai-auto-tool'));?>"></textarea>
                                <div class="select-and-button">
                                    <select class="aiautotool-ai-select" data-aiautotool-ai-select="ask">
                                        <?php $this->aiautotool_render_ai_provider_model_options(true); ?>
                                    </select>
                                    <button id="askprompt" aria-label="Send" title="Send">
                                        <i class="fa-solid fa-paper-plane"></i>
                                    </button>
                                </div>
                            </div>

                            <?php if (false) : ?>
                            <div class="aiautotool-writing-panel" id="aiautotool-writing-panel">
                                <div class="aiautotool-writing-panel__header">
                                    <p class="aiautotool-writing-panel__title">
                                        <i class="fa-solid fa-pen-nib"></i>
                                        <?php echo esc_html__('Writing Tool', 'ai-auto-tool'); ?>
                                    </p>
                                    <p class="aiautotool-writing-panel__note">
                                        <?php echo esc_html__('Generate from title, improve existing content, and prepare SEO assets with the active AI provider.', 'ai-auto-tool'); ?>
                                    </p>
                                </div>

                                <div class="aiautotool-writing-source">
                                    <textarea id="aiautotool_writing_source" placeholder="<?php echo esc_attr__('Optional: paste existing content, source notes, or URL context. If empty, the tool uses the post title/editor content.', 'ai-auto-tool'); ?>"></textarea>
                                    <div class="aiautotool-writing-source__row">
                                        <select id="aiautotool_writing_tone" aria-label="<?php echo esc_attr__('Tone', 'ai-auto-tool'); ?>">
                                            <option value=""><?php echo esc_html__('Tone: auto', 'ai-auto-tool'); ?></option>
                                            <option value="professional"><?php echo esc_html__('Professional', 'ai-auto-tool'); ?></option>
                                            <option value="friendly"><?php echo esc_html__('Friendly', 'ai-auto-tool'); ?></option>
                                            <option value="persuasive"><?php echo esc_html__('Persuasive', 'ai-auto-tool'); ?></option>
                                            <option value="concise"><?php echo esc_html__('Concise', 'ai-auto-tool'); ?></option>
                                        </select>
                                        <select id="aiautotool_writing_length" aria-label="<?php echo esc_attr__('Length', 'ai-auto-tool'); ?>">
                                            <option value=""><?php echo esc_html__('Length: auto', 'ai-auto-tool'); ?></option>
                                            <option value="short"><?php echo esc_html__('Short', 'ai-auto-tool'); ?></option>
                                            <option value="standard"><?php echo esc_html__('Standard', 'ai-auto-tool'); ?></option>
                                            <option value="long"><?php echo esc_html__('Long form', 'ai-auto-tool'); ?></option>
                                        </select>
                                    </div>
                                </div>

                                <div class="aiautotool-writing-workflows">
                                    <div class="aiautotool-writing-group">
                                        <div class="aiautotool-writing-group__head">
                                            <i class="fa-solid fa-file-pen"></i>
                                            <?php echo esc_html__('Create Draft', 'ai-auto-tool'); ?>
                                        </div>
                                        <div class="aiautotool-writing-actions">
                                            <button type="button" class="aiautotool-writing-action aiautotool-writing-action--primary" data-writing-special="write-with-agent">
                                                <i class="fa-solid fa-robot"></i>
                                                <?php echo esc_html__('Write Full Article', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="Outline">
                                                <i class="fa-solid fa-list-ol"></i>
                                                <?php echo esc_html__('Outline', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="Introduction">
                                                <i class="fa-solid fa-arrow-right-to-bracket"></i>
                                                <?php echo esc_html__('Intro', 'ai-auto-tool'); ?>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="aiautotool-writing-group">
                                        <div class="aiautotool-writing-group__head">
                                            <i class="fa-solid fa-wand-magic-sparkles"></i>
                                            <?php echo esc_html__('Improve Content', 'ai-auto-tool'); ?>
                                        </div>
                                        <div class="aiautotool-writing-actions">
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="ContentRewrite">
                                                <i class="fa-solid fa-rotate"></i>
                                                <?php echo esc_html__('Rewrite', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="ContentSummary">
                                                <i class="fa-solid fa-compress"></i>
                                                <?php echo esc_html__('Summarize', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-prompt="expand">
                                                <i class="fa-solid fa-up-right-and-down-left-from-center"></i>
                                                <?php echo esc_html__('Expand', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-prompt="clarity">
                                                <i class="fa-solid fa-sparkles"></i>
                                                <?php echo esc_html__('Improve Clarity', 'ai-auto-tool'); ?>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="aiautotool-writing-group">
                                        <div class="aiautotool-writing-group__head">
                                            <i class="fa-solid fa-chart-line"></i>
                                            <?php echo esc_html__('SEO Assets', 'ai-auto-tool'); ?>
                                        </div>
                                        <div class="aiautotool-writing-actions">
                                            <button type="button" class="aiautotool-writing-action" data-writing-special="btn_suggettitle">
                                                <i class="fa-solid fa-heading"></i>
                                                <?php echo esc_html__('SEO Titles', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="MetaDescription">
                                                <i class="fa-solid fa-tags"></i>
                                                <?php echo esc_html__('Meta', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="FAQ">
                                                <i class="fa-solid fa-question-circle"></i>
                                                <?php echo esc_html__('FAQ', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="KeywordResearch">
                                                <i class="fa-solid fa-magnifying-glass-chart"></i>
                                                <?php echo esc_html__('Keywords', 'ai-auto-tool'); ?>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="aiautotool-writing-group">
                                        <div class="aiautotool-writing-group__head">
                                            <i class="fa-solid fa-sliders"></i>
                                            <?php echo esc_html__('Advanced', 'ai-auto-tool'); ?>
                                        </div>
                                        <div class="aiautotool-writing-actions">
                                            <button type="button" class="aiautotool-writing-action" data-writing-special="custom-prompt-write">
                                                <i class="fa-solid fa-keyboard"></i>
                                                <?php echo esc_html__('Custom Prompt', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="BlogPostIdeas">
                                                <i class="fa-solid fa-lightbulb"></i>
                                                <?php echo esc_html__('Ideas', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="SocialMedia">
                                                <i class="fa-solid fa-share-nodes"></i>
                                                <?php echo esc_html__('Social', 'ai-auto-tool'); ?>
                                            </button>
                                            <button type="button" class="aiautotool-writing-action" data-writing-action="ContentCalendar">
                                                <i class="fa-solid fa-calendar-days"></i>
                                                <?php echo esc_html__('Calendar', 'ai-auto-tool'); ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="aiautotool_form">
                                <!-- Modern Segmented Tab Control -->
                                <div class="aiautotool-segmented-tabs">
                                    <div class="aiautotool-tab-item active" data-tab="aiContentTab">
                                        <i class="fa-solid fa-wand-magic-sparkles"></i>
                                        <span><?php echo wp_kses_post(__('AI Content','ai-auto-tool')); ?></span>
                                    </div>
                                    <div class="aiautotool-tab-item" data-tab="imagesTab">
                                        <i class="fa-solid fa-image"></i>
                                        <span><?php echo wp_kses_post(__('Images','ai-auto-tool')); ?></span>
                                    </div>
                                </div>

                                <!-- AI Content Tab -->
                                <div id="aiContentTab" class="tabcontent" style="display: block;">
                                    <div id="info_content"></div>
                                    
                                    <div class="loadingprocess p-5 text-center div_proccess_1 d-none div_proccess">
                                        <div id="loading-icon" class="loader" style="display:block"></div>
                                        <p style="margin-top: 15px; color: #667eea; font-weight: 600;">
                                            <?php echo wp_kses_post(__('AI is generating content...','ai-auto-tool')); ?>
                                        </p>
                                        <span id="proccess_1" class="process_loading badge badge-soft-primary"></span>
                                    </div>
                                    
                                    <div class="div_proccess_error text-center div_proccess d-none">
                                        <div style="padding-top: 20px; color: #ef4444;">
                                            <i class="fa-solid fa-triangle-exclamation" style="font-size: 32px; margin-bottom: 10px;"></i>
                                            <p><?php echo wp_kses_post(__('Connection Error. Please refresh (F5) to reload.','ai-auto-tool')); ?></p>
                                        </div>
                                    </div>
                                    
                                    <div id="outbard">
                                        <div class="infodiv">
                                            <i class="fa-solid fa-wand-magic-sparkles" style="font-size: 48px; color: #667eea; margin-bottom: 15px;"></i>
                                            <p><?php echo wp_kses_post(__('Select text and click <b>Write</b> button to generate AI content','ai-auto-tool')); ?></p>
                                            <img src="<?php echo esc_url(plugins_url('../images/find1.png', __FILE__)); ?>" width="150px" style="margin-top: 10px;" />
                                        </div>
                                    </div>
                                    
                                    <button class="btn btnaddpost aiautotool_button" style="display:none;">
                                        <i class="fa-solid fa-plus"></i>
                                        <?php echo wp_kses_post(__('Add To Post','ai-auto-tool')); ?>
                                    </button>
                                </div>

                                <!-- Images Tab -->
                                <div id="imagesTab" class="tabcontent" style="display: none;">
                                    <div class="infodiv">
                                        <div id="info_img"></div>
                                        <i class="fa-solid fa-image" style="font-size: 48px; color: #667eea; margin-bottom: 15px;"></i>
                                        <p><?php echo wp_kses_post(__('Select text and click <b>Find Image</b> button to search images','ai-auto-tool')); ?></p>
                                        <img src="<?php echo esc_url(plugins_url('../images/find1.png', __FILE__)); ?>" width="150px" style="margin-top: 10px;" />
                                    </div>
                                    
                                    <div id="img_list_find" class="img_list_find"></div>
                                </div>
                            </div>
                        </div>
		            </div>
		        </div>
                    
                </div>
                <!-- end right -->
            </form>
            <div class="aiautotool-modal-container">
        <div class="aiautotool-modal-overlay"></div>
        <div class="aiautotool-modal-content">
            <h2><?php echo wp_kses_post(__('All tool for AI Post','ai-auto-tool'));  ?></h2>
            
            <!-- Status Indicator -->
            <div class="aiautotool-status-indicator">
                <div class="status-badge" id="current-status">
                    <i class="fa-solid fa-lightbulb"></i>
                    <span>Outline Tool</span>
                </div>
                <div class="status-description" id="status-description">
                    Create comprehensive outlines with main topics and subtopics
                </div>
            </div>
            
            <p class="aiautotool-tool-buttons">
                <span class="aiautotool_btn_v1 aiautotool_btn_v16 btn_bardWriter btnoutline active" id="btn_outline" onclick="changeType('Outline')" data-tooltip="Create structured outlines for better content organization">
                    <span class="icon"><i class="fa-solid fa-lightbulb"></i></span>
                    <span>Outline</span>
                    <span class="tool-indicator">Active</span>
                </span>
                
                <span class="aiautotool_btn_v1 aiautotool_btn_v11 btn_bardWriter btn_intro" id="btn_intro" onclick="changeType('Introduction')" data-tooltip="Generate engaging introductions that hook readers">
                    <span class="icon"><i class="fa-solid fa-info"></i></span>
                    <span>Introduction</span>
                    <span class="tool-indicator">Click to use</span>
                </span>
                
                <span class="aiautotool_btn_v1 aiautotool_btn_v13 btn_bardWriter btn_conclusion" id="btn_conclusion" onclick="changeType('Conclusion')" data-tooltip="Write compelling conclusions that summarize key points">
                    <span class="icon"><i class="fa-solid fa-check-double"></i></span>
                    <span>Conclusion</span>
                    <span class="tool-indicator">Click to use</span>
                </span>
                
                <span class="aiautotool_btn_v1 aiautotool_btn_v12 btn_bardWriter btn_faq" id="btn_faq" onclick="changeType('FAQ')" data-tooltip="Create helpful FAQ sections with relevant questions">
                    <span class="icon"><i class="fa-solid fa-question"></i></span>
                    <span>Create FAQ</span>
                    <span class="tool-indicator">Click to use</span>
                </span>
            </p>
            
            <div class="aiautotool_container aiautotool_modal_content">
                <div id="outline" class="tool-content active">
                    <div class="tool-header">
                        <h3 id="current_type">
                            <i class="fa-solid fa-lightbulb"></i>
                            Suggest Outline By AI Auto Tool
                        </h3>
                        <div class="tool-badge outline-badge">Active Tool</div>
                    </div>
                    <input type="hidden" name="type" id="type" value="Outline">
                    <div class="aiautotool_input2">
                        <input type="text" name="moretool" class="aiautotool_input2_input" id="moretool_input" placeholder="Enter your topic or keyword for outline">
                        <button class="aiautotool_input2_button" id="moretool" type="submit">
                            <i class="fa-solid fa-magic"></i>
                            Create Outline
                        </button>
                    </div>
                    <div class="tool-description">
                        <p><i class="fa-solid fa-info-circle"></i> Create a comprehensive outline with main topics and subtopics organized in a hierarchical structure.</p>
                    </div>
                </div>
                
                <div id="introduction" class="tool-content" style="display:none">
                    <div class="tool-header">
                        <h3>
                            <i class="fa-solid fa-info"></i>
                            Write Introduction
                        </h3>
                        <div class="tool-badge intro-badge">Active Tool</div>
                    </div>
                    <input type="hidden" name="type" id="type_intro" value="Introduction">
                    <div class="aiautotool_input2">
                        <input type="text" name="moretool_intro" class="aiautotool_input2_input" id="moretool_input_intro" placeholder="Enter your article title or topic">
                        <button class="aiautotool_input2_button" id="moretool_intro" type="submit">
                            <i class="fa-solid fa-magic"></i>
                            Create Introduction
                        </button>
                    </div>
                    <div class="tool-description">
                        <p><i class="fa-solid fa-info-circle"></i> Generate an engaging introduction of 50-100 words that hooks readers and introduces your topic.</p>
                    </div>
                </div>
                
                <div id="conclusion" class="tool-content" style="display:none">
                    <div class="tool-header">
                        <h3>
                            <i class="fa-solid fa-check-double"></i>
                            Write Conclusion
                        </h3>
                        <div class="tool-badge conclusion-badge">Active Tool</div>
                    </div>
                    <input type="hidden" name="type" id="type_conclusion" value="Conclusion">
                    <div class="aiautotool_input2">
                        <input type="text" name="moretool_conclusion" class="aiautotool_input2_input" id="moretool_input_conclusion" placeholder="Enter your article title or topic">
                        <button class="aiautotool_input2_button" id="moretool_conclusion" type="submit">
                            <i class="fa-solid fa-magic"></i>
                            Create Conclusion
                        </button>
                    </div>
                    <div class="tool-description">
                        <p><i class="fa-solid fa-info-circle"></i> Create a compelling conclusion that summarizes key points and provides a strong ending.</p>
                    </div>
                </div>
                
                <div id="faq" class="tool-content" style="display:none">
                    <div class="tool-header">
                        <h3>
                            <i class="fa-solid fa-question"></i>
                            Create FAQ Section
                        </h3>
                        <div class="tool-badge faq-badge">Active Tool</div>
                    </div>
                    <input type="hidden" name="type" id="type_faq" value="FAQ">
                    <div class="aiautotool_input2">
                        <input type="text" name="moretool_faq" class="aiautotool_input2_input" id="moretool_input_faq" placeholder="Enter your topic or product name">
                        <button class="aiautotool_input2_button" id="moretool_faq" type="submit">
                            <i class="fa-solid fa-magic"></i>
                            Create FAQ
                        </button>
                    </div>
                    <div class="tool-description">
                        <p><i class="fa-solid fa-info-circle"></i> Generate frequently asked questions and answers to help your audience understand your topic better.</p>
                    </div>
                </div>
                
                <script type="text/javascript">
                    // Tool descriptions for status updates
                    const toolDescriptions = {
                        'Outline': {
                            title: 'Outline Tool',
                            description: 'Create comprehensive outlines with main topics and subtopics',
                            icon: 'fa-solid fa-lightbulb'
                        },
                        'Introduction': {
                            title: 'Introduction Tool',
                            description: 'Generate engaging introductions that hook readers',
                            icon: 'fa-solid fa-info'
                        },
                        'Conclusion': {
                            title: 'Conclusion Tool',
                            description: 'Write compelling conclusions that summarize key points',
                            icon: 'fa-solid fa-check-double'
                        },
                        'FAQ': {
                            title: 'FAQ Tool',
                            description: 'Create helpful FAQ sections with relevant questions',
                            icon: 'fa-solid fa-question'
                        }
                    };

                    function changeType(newType) {
                        // Update status indicator
                        const statusBadge = document.getElementById('current-status');
                        const statusDescription = document.getElementById('status-description');
                        const toolInfo = toolDescriptions[newType];
                        
                        if (statusBadge && statusDescription && toolInfo) {
                            statusBadge.innerHTML = `<i class="${toolInfo.icon}"></i><span>${toolInfo.title}</span>`;
                            statusDescription.textContent = toolInfo.description;
                        }
                        
                        // Update active button
                        document.querySelectorAll('.aiautotool-tool-buttons span').forEach(btn => {
                            btn.classList.remove('active');
                            const indicator = btn.querySelector('.tool-indicator');
                            if (indicator) {
                                indicator.textContent = 'Click to use';
                            }
                        });
                        
                        const activeButton = document.getElementById('btn_' + newType.toLowerCase().replace(' ', '_'));
                        if (activeButton) {
                            activeButton.classList.add('active');
                            const indicator = activeButton.querySelector('.tool-indicator');
                            if (indicator) {
                                indicator.textContent = 'Active';
                            }
                        }
                        
                        // Update content sections
                        document.querySelectorAll('.tool-content').forEach(content => {
                            content.style.display = 'none';
                            content.classList.remove('active');
                        });
                        
                        // Show appropriate content section
                        let targetContent;
                        switch(newType) {
                            case 'Outline':
                                targetContent = document.getElementById('outline');
                                document.getElementById('current_type').innerHTML = '<i class="fa-solid fa-lightbulb"></i> Suggest Outline By AI Auto Tool';
                                break;
                            case 'Introduction':
                                targetContent = document.getElementById('introduction');
                                break;
                            case 'Conclusion':
                                targetContent = document.getElementById('conclusion');
                                break;
                            case 'FAQ':
                                targetContent = document.getElementById('faq');
                                break;
                        }
                        
                        if (targetContent) {
                            targetContent.style.display = 'block';
                            setTimeout(() => {
                                targetContent.classList.add('active');
                            }, 10);
                        }
                        
                        // Update hidden input
                        document.getElementById('type').value = newType;
                        
                        // Add visual feedback
                        showToolChangeFeedback(newType);
                    }
                    
                    function showToolChangeFeedback(toolType) {
                        // Create a temporary notification
                        const notification = document.createElement('div');
                        notification.className = 'tool-change-notification';
                        notification.innerHTML = `
                            <i class="${toolDescriptions[toolType].icon}"></i>
                            <span>Switched to ${toolType} Tool</span>
                        `;
                        
                        document.body.appendChild(notification);
                        
                        // Remove after animation
                        setTimeout(() => {
                            notification.remove();
                        }, 2000);
                    }
                    
                    jQuery(document).ready(function(){
                        // Add tooltips
                        document.querySelectorAll('[data-tooltip]').forEach(element => {
                            element.addEventListener('mouseenter', function() {
                                const tooltip = document.createElement('div');
                                tooltip.className = 'tooltip';
                                tooltip.textContent = this.getAttribute('data-tooltip');
                                document.body.appendChild(tooltip);
                                
                                const rect = this.getBoundingClientRect();
                                tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
                                tooltip.style.top = rect.top - tooltip.offsetHeight - 10 + 'px';
                            });
                            
                            element.addEventListener('mouseleave', function() {
                                const tooltip = document.querySelector('.tooltip');
                                if (tooltip) {
                                    tooltip.remove();
                                }
                            });
                        });
                        
                        // Outline button
                        jQuery("#moretool").click(function(){
                            processToolRequest('Outline', 'moretool_input');
                        });
                        
                        // Introduction button
                        jQuery("#moretool_intro").click(function(){
                            processToolRequest('Introduction', 'moretool_input_intro');
                        });
                        
                        // Conclusion button
                        jQuery("#moretool_conclusion").click(function(){
                            processToolRequest('Conclusion', 'moretool_input_conclusion');
                        });
                        
                        // FAQ button
                        jQuery("#moretool_faq").click(function(){
                            processToolRequest('FAQ', 'moretool_input_faq');
                        });
                        
                        function processToolRequest(type, inputId) {
                            var inputText = jQuery("#" + inputId).val();
                            var post_language = get_lang();
                            var langcheck = '';
                            
                            if(inputText.trim() === "") {
                                if(Swal){
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'Please enter a topic or keyword.',
                                        icon: 'error',
                                        confirmButtonText: 'Close'
                                    });
                                } else {
                                    alert('Please enter a topic or keyword.');
                                }
                                return;
                            }
                            
                            // Check premium status
                            if(!check_aipost_premium()) {
                                if(Swal){
                                    Swal.fire({
                                        title: 'Error!',
                                        text: 'AI Post Limit Quota. Please Upgrade Pro.',
                                        icon: 'error',
                                        confirmButtonText: 'Close'
                                    });
                                } else {
                                    alert('AI Post Limit Quota. Please Upgrade Pro.');
                                }
                                return;
                            }
                            
                            open_box_aiautotool();
                            jQuery('.aiautotool-modal-close').click();
                            
                            if (languageCodes.hasOwnProperty(post_language)) {
                                langcheck = languageCodes[post_language];
                            }
                            
                            var divId = "outbard";
                            var text = '';
                            
                            switch(type) {
                                case "Outline":
                                    text = 'Create a comprehensive and well-structured outline for an article about "' + inputText + '". Include main topics and subtopics organized in a hierarchical numbered list format. Make it SEO-friendly and engaging for readers.';
                                    break;
                                case "Introduction":
                                    text = 'Write an engaging and compelling introduction for an article titled "' + inputText + '". The introduction should be 50-100 words, hook the reader\'s attention, clearly state the topic, and provide a preview of what the article will cover. Make it professional and engaging.';
                                    break;
                                case "Conclusion":
                                    text = 'Write a strong and compelling conclusion for an article about "' + inputText + '". The conclusion should summarize the key points, reinforce the main message, and provide a memorable ending that encourages reader engagement. Make it professional and impactful.';
                                    break;
                                case "FAQ":
                                    text = 'Create a comprehensive FAQ section for "' + inputText + '". Generate 5-8 frequently asked questions and detailed answers that would be helpful for your audience. Make the questions relevant, specific, and the answers informative and easy to understand. Format it clearly with Q&A structure.';
                                    break;
                                default:
                                    console.error("Unknown type: " + type);
                                    return;
                            }
                            
                            sendbardToServer(text, divId, 'writemore', langcheck);
                        }
                    });
                </script>
            </div>
            <button class="aiautotool-modal-close"><i class="fa-regular fa-rectangle-xmark"></i></button>
        </div>
    </div>
        </div>
        <script>
            jQuery(document).ready(function($) {
                // Tab switching functionality
                $('.aiautotool_tab button').on('click', function() {
                    var tabId = $(this).data('tab');
                    
                    // Remove active class from all tabs
                    $('.aiautotool_tab button').removeClass('active');
                    $(this).addClass('active');
                    
                    // Hide all tab contents
                    $('.tabcontent').hide();
                    
                    // Show selected tab content
                    $('#' + tabId).fadeIn(300);
                });
                
                // Auto-generate slug from title
                $('#aiautotool_title').on('blur', function() {
                    var title = $(this).val();
                    if (title && !$('#aiautotool_slug').val()) {
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'aiautotool_get_slug',
                                title: title
                            },
                            success: function(response) {
                                if (response.success) {
                                    $('#aiautotool_slug').val(response.data.slug);
                                }
                            }
                        });
                    }
                });
                
                // Add loading state to publish button
                $('#aiautotool_post_form').on('submit', function() {
                    var $btn = $('.save-single-generation');
                    $btn.prop('disabled', true);
                    $btn.html('<i class="fa-solid fa-spinner fa-spin"></i> Publishing...');
                });
                
                // Add hover effects to form inputs
                $('.aiautotool-input, .aiautotool-select').on('focus', function() {
                    $(this).parent().addClass('focused');
                }).on('blur', function() {
                    $(this).parent().removeClass('focused');
                });

                function aiautotoolGetEditorText() {
                    if (typeof tinymce !== 'undefined' && tinymce.get('aiautotool_content')) {
                        return tinymce.get('aiautotool_content').getContent({ format: 'text' }).trim();
                    }

                    return $('#aiautotool_content').val() ? $('#aiautotool_content').val().trim() : '';
                }

                function aiautotoolGetWritingInput() {
                    var source = $('#aiautotool_writing_source').val().trim();
                    var title = $('#aiautotool_title').val().trim();
                    var editorText = aiautotoolGetEditorText();
                    var tone = $('#aiautotool_writing_tone').val();
                    var length = $('#aiautotool_writing_length').val();
                    var input = source || editorText || title;

                    if (tone) {
                        input += "\n\nTone: " + tone + ".";
                    }

                    if (length) {
                        input += "\nLength: " + length + ".";
                    }

                    return input.trim();
                }

                function aiautotoolRunToolAction(actionType) {
                    var inputText = aiautotoolGetWritingInput();

                    if (!inputText) {
                        if (typeof showError === 'function') {
                            showError('<?php echo esc_js(__('Please enter a title or source content first.', 'ai-auto-tool')); ?>');
                        } else {
                            alert('<?php echo esc_js(__('Please enter a title or source content first.', 'ai-auto-tool')); ?>');
                        }
                        $('#aiautotool_title').focus();
                        return;
                    }

                    var tempId = 'aiautotool_writing_temp_' + Date.now();
                    var $tempInput = $('<input type="hidden">').attr('id', tempId).val(inputText);
                    var $tempButton = $('<button type="button" style="display:none;">Run</button>');
                    $('body').append($tempInput, $tempButton);

                    if (window.processToolRequest) {
                        window.processToolRequest(actionType, tempId);
                    } else if (typeof processToolRequest === 'function') {
                        processToolRequest(actionType, tempId);
                    } else if (typeof showError === 'function') {
                        showError('<?php echo esc_js(__('AI tool handler is not available. Please refresh the page.', 'ai-auto-tool')); ?>');
                    }

                    setTimeout(function() {
                        $tempInput.remove();
                        $tempButton.remove();
                    }, 2000);
                }

                function aiautotoolRunPromptTool(promptType) {
                    var inputText = aiautotoolGetWritingInput();
                    var prompts = {
                        expand: 'Expand the following content into a more complete, useful, and well-structured section while preserving the meaning. Use clear headings if helpful:\\n\\n',
                        clarity: 'Improve the clarity, flow, grammar, and readability of the following content. Keep the meaning accurate and avoid adding unsupported facts:\\n\\n'
                    };

                    if (!inputText || !prompts[promptType]) {
                        if (typeof showError === 'function') {
                            showError('<?php echo esc_js(__('Please enter source content first.', 'ai-auto-tool')); ?>');
                        }
                        return;
                    }

                    open_box_aiautotool();
                    openTab('aiContentTab');

                    var postLanguage = $('#post_language').val();
                    var resolvedLang = postLanguage;
                    if (typeof languageCodes !== 'undefined' && languageCodes.hasOwnProperty(postLanguage)) {
                        resolvedLang = languageCodes[postLanguage];
                    }

                    var sendFn = window.sendbardToServer || (typeof sendbardToServer !== 'undefined' ? sendbardToServer : null);
                    if (!sendFn) {
                        if (typeof showError === 'function') {
                            showError('<?php echo esc_js(__('AI function is not available. Please refresh the page.', 'ai-auto-tool')); ?>');
                        }
                        return;
                    }

                    sendFn(prompts[promptType] + inputText, 'outbard', 'writemore', resolvedLang);
                }

                function aiautotoolRunSpecialTool(toolId) {
                    var configMap = {
                        'write-with-agent': {
                            id: 'write-with-agent',
                            text: 'Write Full Article',
                            action: 'write-with-agent',
                            premium: true
                        },
                        'btn_suggettitle': {
                            id: 'btn_suggettitle',
                            text: 'SEO Titles',
                            action: 'TitleSuggestion',
                            premium: true
                        },
                        'custom-prompt-write': {
                            id: 'custom-prompt-write',
                            text: 'Custom Prompt',
                            action: 'CustomPrompt',
                            premium: true
                        }
                    };

                    if (toolId === 'write-with-agent' && !$('#aiautotool_title').val().trim()) {
                        var source = $('#aiautotool_writing_source').val().trim();
                        if (source) {
                            $('#aiautotool_title').val(source.split(/\r?\n/)[0].slice(0, 120));
                        }
                    }

                    if (typeof handleSpecialButton === 'function' && configMap[toolId]) {
                        handleSpecialButton(configMap[toolId], null);
                        return;
                    }

                    if (toolId === 'custom-prompt-write' && typeof showCustomPromptModal === 'function') {
                        showCustomPromptModal();
                    } else if (toolId === 'btn_suggettitle') {
                        aiautotoolRunToolAction('TitleSuggestion');
                    }
                }

                $(document).off('click.aiautotoolWritingPanel', '.aiautotool-writing-action').on('click.aiautotoolWritingPanel', '.aiautotool-writing-action', function(e) {
                    e.preventDefault();
                    var actionType = $(this).data('writing-action');
                    var promptType = $(this).data('writing-prompt');
                    var specialTool = $(this).data('writing-special');

                    if (actionType) {
                        aiautotoolRunToolAction(actionType);
                    } else if (promptType) {
                        aiautotoolRunPromptTool(promptType);
                    } else if (specialTool) {
                        aiautotoolRunSpecialTool(specialTool);
                    }
                });
                
                // Initialize first tab as active
                $('.aiautotool_tab button:first').addClass('active');
                $('.tabcontent:first').show();
            });
        </script>
        <?php
    }
    
    // ===== AJAX Handlers for Image Generation Features =====
    
    /**
     * AJAX callback to save draft and get post ID
     */
    public function aiautotool_save_draft_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $title = sanitize_text_field($_POST['title']);
        $content = wp_kses_post($_POST['content']);
        
        if (empty($title) || empty($content)) {
            wp_send_json_error('Title and content are required');
        }
        
        $post_data = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => 'draft',
            'post_type' => 'post',
            'post_author' => get_current_user_id()
        );
        
        $post_id = wp_insert_post($post_data);
        
        if ($post_id && !is_wp_error($post_id)) {
            wp_send_json_success(array(
                'post_id' => $post_id,
                'message' => 'Draft saved successfully'
            ));
        } else {
            wp_send_json_error('Failed to save draft');
        }
    }

    /**
     * AJAX callback to generate an image through configured AI image providers.
     */
    public function aiautotool_generate_ai_image_callback() {
        check_ajax_referer('aiautotool_aipost_nonce', 'security');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : '';
        if ($prompt === '') {
            wp_send_json_error(array('message' => __('Image prompt is required', 'ai-auto-tool')));
        }

        if (!class_exists('AIAutotool_AI_Helper')) {
            $helper_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php';
            if (file_exists($helper_file)) {
                require_once $helper_file;
            }
        }

        if (!class_exists('AIAutotool_AI_Helper')) {
            wp_send_json_error(array('message' => __('AI Provider module is not available', 'ai-auto-tool')));
        }

        $provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : '';
        $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
        $width = isset($_POST['width']) ? absint($_POST['width']) : 1024;
        $height = isset($_POST['height']) ? absint($_POST['height']) : 1024;
        $seed = isset($_POST['seed']) ? sanitize_text_field(wp_unslash($_POST['seed'])) : '';
        $negative_prompt = isset($_POST['negative_prompt']) ? sanitize_text_field(wp_unslash($_POST['negative_prompt'])) : 'worst quality, blurry';
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        $result = AIAutotool_AI_Helper::generate_image($prompt, array(
            'provider' => $provider,
            'model' => $model,
            'width' => $width,
            'height' => $height,
            'seed' => $seed,
            'negative_prompt' => $negative_prompt,
            'timeout' => 120,
        ));

        if (empty($result['success'])) {
            $message = !empty($result['error']) ? $result['error'] : __('Image generation failed', 'ai-auto-tool');
            wp_send_json_error(array('message' => $message, 'result' => $result));
        }

        if (!empty($result['data_url'])) {
            $saved = $this->aiautotool_save_generated_image_data_url($result['data_url'], $prompt, $post_id);
            if (empty($saved['success'])) {
                wp_send_json_error(array('message' => $saved['message']));
            }

            $result['url'] = $saved['url'];
            $result['attachment_id'] = $saved['attachment_id'];
            unset($result['data_url']);
        }

        if (empty($result['url'])) {
            wp_send_json_error(array('message' => __('Image provider did not return an image URL', 'ai-auto-tool')));
        }

        wp_send_json_success($result);
    }

    private function aiautotool_save_generated_image_data_url($data_url, $prompt, $post_id = 0) {
        if (!preg_match('/^data:image\/(png|jpe?g|webp);base64,(.+)$/i', $data_url, $matches)) {
            return array('success' => false, 'message' => __('Invalid generated image data', 'ai-auto-tool'));
        }

        $extension = strtolower($matches[1]);
        if ($extension === 'jpeg') {
            $extension = 'jpg';
        }

        $image_data = base64_decode($matches[2]);
        if ($image_data === false || $image_data === '') {
            return array('success' => false, 'message' => __('Failed to decode generated image', 'ai-auto-tool'));
        }

        $filename = sanitize_file_name(substr(sanitize_title($prompt), 0, 80));
        if ($filename === '') {
            $filename = 'ai-generated-image';
        }
        $filename .= '-' . time() . '.' . $extension;

        $upload = wp_upload_bits($filename, null, $image_data);
        if (!empty($upload['error'])) {
            return array('success' => false, 'message' => $upload['error']);
        }

        $file_path = $upload['file'];
        $file_url = $upload['url'];
        $filetype = wp_check_filetype($filename, null);
        $attachment = array(
            'post_mime_type' => !empty($filetype['type']) ? $filetype['type'] : 'image/' . $extension,
            'post_title' => sanitize_text_field(wp_trim_words($prompt, 12, '')),
            'post_content' => '',
            'post_status' => 'inherit',
        );

        $attach_id = wp_insert_attachment($attachment, $file_path, $post_id);
        if (is_wp_error($attach_id)) {
            return array('success' => false, 'message' => $attach_id->get_error_message());
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
        wp_update_attachment_metadata($attach_id, $attach_data);

        return array(
            'success' => true,
            'url' => $file_url,
            'attachment_id' => $attach_id,
        );
    }
    
    /**
     * AJAX callback to set featured image
     */
    public function aiautotool_set_featured_image_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        $image_url = esc_url_raw($_POST['image_url']);
        $post_id = intval($_POST['post_id']);
        
        if (empty($image_url) || empty($post_id)) {
            wp_send_json_error('Image URL and post ID are required');
        }
        
        // Check if post exists
        $post = get_post($post_id);
        if (!$post) {
            wp_send_json_error('Post not found');
        }
        
        // Check permission to edit post
        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error('Permission denied');
        }
        
        try {
            // Download and upload image to media library
            $upload_dir = wp_upload_dir();
            $image_data = file_get_contents($image_url);
            
            if ($image_data === false) {
                wp_send_json_error('Failed to download image');
            }
            
            $filename = 'ai-generated-' . time() . '.jpg';
            $file_path = $upload_dir['path'] . '/' . $filename;
            
            if (file_put_contents($file_path, $image_data) === false) {
                wp_send_json_error('Failed to save image to server');
            }
            
            // Create attachment
            $wp_filetype = wp_check_filetype($filename, null);
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => sanitize_file_name($filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            
            $attach_id = wp_insert_attachment($attachment, $file_path, $post_id);
            
            if (is_wp_error($attach_id)) {
                wp_send_json_error('Failed to create attachment');
            }
            
            // Generate attachment metadata
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
            wp_update_attachment_metadata($attach_id, $attach_data);
            
            // Set as featured image
            $result = set_post_thumbnail($post_id, $attach_id);
            
            if ($result) {
                wp_send_json_success(array(
                    'success' => true,
                    'attachment_id' => $attach_id,
                    'message' => 'Featured image set successfully'
                ));
            } else {
                wp_send_json_error('Failed to set featured image');
            }
            
        } catch (Exception $e) {
            wp_send_json_error('Error: ' . $e->getMessage());
        }
    }
    
    /**
     * AJAX callback to fetch remote content for Remote Rewrite feature
     */
    public function aiautotool_fetch_remote_content_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        
        if (empty($url)) {
            wp_send_json_error(array(
                'message' => 'URL is required',
                'code' => 'missing_url'
            ));
        }
        
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            wp_send_json_error(array(
                'message' => 'Invalid URL format',
                'code' => 'invalid_url'
            ));
        }
        
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            wp_send_json_error(array(
                'message' => 'URL must use HTTP or HTTPS protocol',
                'code' => 'invalid_protocol'
            ));
        }
        
        try {
            $response = wp_remote_get($url, array(
                'timeout' => 30,
                'redirection' => 5,
                'httpversion' => '1.1',
                'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'headers' => array(
                    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language' => 'en-US,en;q=0.5',
                )
            ));
            
            if (is_wp_error($response)) {
                wp_send_json_error(array(
                    'message' => 'Failed to fetch remote content: ' . $response->get_error_message(),
                    'code' => 'fetch_error'
                ));
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            
            if ($response_code !== 200) {
                wp_send_json_error(array(
                    'message' => 'Remote server returned error code: ' . $response_code,
                    'code' => 'http_error'
                ));
            }
            
            $content = wp_remote_retrieve_body($response);
            
            if (empty($content)) {
                wp_send_json_error(array(
                    'message' => 'Remote content is empty',
                    'code' => 'empty_content'
                ));
            }
            
            wp_send_json_success(array(
                'html' => $content,
                'content' => $content,
                'url' => $url,
                'message' => 'Content fetched successfully'
            ));
            
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => 'Exception: ' . $e->getMessage(),
                'code' => 'exception'
            ));
        }
    }

    public function aiautotool_save_tts_audio_callback() {
        check_ajax_referer('aiautotool_aipost_nonce', 'security');

        $audio_url = isset($_POST['audio_url']) ? esc_url_raw(wp_unslash($_POST['audio_url'])) : '';
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : __('Article narration', 'ai-auto-tool');

        if (empty($audio_url)) {
            wp_send_json_error(array('message' => __('Audio URL is required', 'ai-auto-tool')));
        }

        if ($post_id > 0 && !current_user_can('edit_post', $post_id)) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        if ($post_id <= 0 && !current_user_can('upload_files')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp_file = download_url($audio_url, 60);
        if (is_wp_error($tmp_file)) {
            wp_send_json_error(array('message' => $tmp_file->get_error_message()));
        }

        $path = wp_parse_url($audio_url, PHP_URL_PATH);
        $source_name = $path ? basename($path) : '';
        if (empty($source_name) || false === strpos($source_name, '.')) {
            $source_name = sanitize_title($title) . '-' . time() . '.mp3';
        }

        $file_array = array(
            'name' => sanitize_file_name($source_name),
            'tmp_name' => $tmp_file,
        );

        $filetype = wp_check_filetype($file_array['name']);
        if (empty($filetype['type']) || 'audio/mpeg' !== $filetype['type']) {
            @unlink($tmp_file);
            wp_send_json_error(array('message' => __('Only MP3 audio can be saved', 'ai-auto-tool')));
        }

        $attachment_id = media_handle_sideload($file_array, $post_id, $title);
        if (is_wp_error($attachment_id)) {
            @unlink($tmp_file);
            wp_send_json_error(array('message' => $attachment_id->get_error_message()));
        }

        wp_send_json_success(array(
            'attachment_id' => $attachment_id,
            'url' => wp_get_attachment_url($attachment_id),
            'title' => get_the_title($attachment_id),
        ));
    }

    private function aiautotool_get_voice_manager() {
        if (!class_exists('AIAutotool_AI_Voice_Manager')) {
            $voice_manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_voice_manager.php';
            if (file_exists($voice_manager_file)) {
                require_once $voice_manager_file;
            }
        }

        return class_exists('AIAutotool_AI_Voice_Manager') ? AIAutotool_AI_Voice_Manager::get_instance() : null;
    }

    public function aiautotool_generate_tts_audio_callback() {
        check_ajax_referer('aiautotool_aipost_nonce', 'security');

        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        if ($post_id > 0 && !current_user_can('edit_post', $post_id)) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        if ($post_id <= 0 && !current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }

        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : __('Article narration', 'ai-auto-tool');
        $text = isset($_POST['text']) ? wp_unslash($_POST['text']) : '';
        $provider = isset($_POST['provider']) ? sanitize_key($_POST['provider']) : '';
        $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
        $voice = isset($_POST['voice']) ? sanitize_text_field(wp_unslash($_POST['voice'])) : '';

        $voice_manager = $this->aiautotool_get_voice_manager();
        if (!$voice_manager) {
            wp_send_json_error(array('message' => __('AI Voice manager is not available', 'ai-auto-tool')));
        }

        if ($post_id > 0 && empty($text)) {
            $result = $voice_manager->generate_from_post($post_id, array(
                'provider' => $provider,
                'model' => $model,
                'voice' => $voice,
                'skip_urls' => true,
            ));
        } else {
            $result = $voice_manager->generate_audio($text, array(
                'post_id' => $post_id,
                'title' => $title,
                'provider' => $provider,
                'model' => $model,
                'voice' => $voice,
                'skip_urls' => true,
            ));
        }

        if (empty($result['success'])) {
            wp_send_json_error(array('message' => isset($result['error']) ? $result['error'] : __('Could not generate MP3', 'ai-auto-tool')));
        }

        wp_send_json_success(array(
            'attachment_id' => $result['attachment_id'],
            'audio_url' => $result['url'],
            'local_audio_url' => $result['url'],
            'provider' => $result['provider'],
            'model' => $result['model'],
            'voice' => $result['voice'],
            'characters' => $result['characters'],
            'bytes' => $result['bytes'],
        ));
    }

    public function aiautotool_maybe_queue_auto_tts($new_status, $old_status, $post) {
        if ($new_status !== 'publish' || $old_status === 'publish' || empty($post->ID)) {
            return;
        }

        if (get_option('aiautotool_tts_auto_generate_on_publish', '0') !== '1') {
            return;
        }

        if (wp_is_post_revision($post->ID) || get_post_meta($post->ID, '_aiautotool_tts_audio', true)) {
            return;
        }

        if (!wp_next_scheduled('aiautotool_generate_post_tts_event', array((int) $post->ID))) {
            wp_schedule_single_event(time() + 30, 'aiautotool_generate_post_tts_event', array((int) $post->ID));
        }
    }

    public function aiautotool_generate_post_tts_event($post_id) {
        $post_id = (int) $post_id;
        if ($post_id <= 0 || get_post_status($post_id) !== 'publish') {
            return;
        }

        $voice_manager = $this->aiautotool_get_voice_manager();
        if (!$voice_manager) {
            return;
        }

        $result = $voice_manager->generate_from_post($post_id, array(
            'skip_urls' => true,
        ));

        if (empty($result['success'])) {
            update_post_meta($post_id, '_aiautotool_tts_last_error', isset($result['error']) ? $result['error'] : 'TTS generation failed');
        } else {
            delete_post_meta($post_id, '_aiautotool_tts_last_error');
        }
    }

    public function aiautotool_register_voice_video_rest_routes() {
        register_rest_route('aitool/v1', '/tts', array(
            'methods' => 'POST',
            'callback' => array($this, 'aiautotool_rest_generate_tts'),
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ));

        register_rest_route('aitool/v1', '/providers', array(
            'methods' => 'GET',
            'callback' => array($this, 'aiautotool_rest_get_voice_providers'),
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ));

        register_rest_route('aitool/v1', '/voices', array(
            'methods' => 'GET',
            'callback' => array($this, 'aiautotool_rest_get_voices'),
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ));

        register_rest_route('aitool/v1', '/status', array(
            'methods' => 'GET',
            'callback' => array($this, 'aiautotool_rest_get_media_status'),
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            },
        ));

        foreach (array('video', 'subtitle', 'publish') as $route) {
            register_rest_route('aitool/v1', '/' . $route, array(
                'methods' => 'POST',
                'callback' => array($this, 'aiautotool_rest_media_placeholder'),
                'permission_callback' => function() {
                    return current_user_can('edit_posts');
                },
            ));
        }
    }

    public function aiautotool_rest_generate_tts($request) {
        $post_id = (int) $request->get_param('post_id');
        if ($post_id > 0 && !current_user_can('edit_post', $post_id)) {
            return new WP_Error('aiautotool_permission_denied', __('Permission denied', 'ai-auto-tool'), array('status' => 403));
        }

        $voice_manager = $this->aiautotool_get_voice_manager();
        if (!$voice_manager) {
            return new WP_Error('aiautotool_voice_unavailable', __('AI Voice manager is not available', 'ai-auto-tool'), array('status' => 500));
        }

        $options = array(
            'provider' => sanitize_key($request->get_param('provider')),
            'model' => sanitize_text_field((string) $request->get_param('model')),
            'voice' => sanitize_text_field((string) $request->get_param('voice')),
            'skip_urls' => true,
        );

        if ($post_id > 0) {
            $result = $voice_manager->generate_from_post($post_id, $options);
        } else {
            $text = (string) $request->get_param('text');
            $options['title'] = sanitize_text_field((string) $request->get_param('title'));
            $result = $voice_manager->generate_audio($text, $options);
        }

        if (empty($result['success'])) {
            return new WP_Error('aiautotool_tts_failed', isset($result['error']) ? $result['error'] : __('Could not generate MP3', 'ai-auto-tool'), array('status' => 500));
        }

        return rest_ensure_response($result);
    }

    public function aiautotool_rest_get_voice_providers() {
        $voice_manager = $this->aiautotool_get_voice_manager();
        if (!$voice_manager) {
            return rest_ensure_response(array('providers' => array()));
        }

        return rest_ensure_response($voice_manager->get_config());
    }

    public function aiautotool_rest_get_voices() {
        return rest_ensure_response(array(
            'voices' => array(
                array('provider' => 'openai', 'voice_id' => 'alloy', 'language' => 'multi', 'gender' => 'neutral', 'name' => 'Alloy'),
                array('provider' => 'openai', 'voice_id' => 'nova', 'language' => 'multi', 'gender' => 'female', 'name' => 'Nova'),
                array('provider' => 'openai', 'voice_id' => 'onyx', 'language' => 'multi', 'gender' => 'male', 'name' => 'Onyx'),
                array('provider' => 'elevenlabs', 'voice_id' => '21m00Tcm4TlvDq8ikWAM', 'language' => 'multi', 'gender' => 'female', 'name' => 'Rachel'),
            ),
        ));
    }

    public function aiautotool_rest_get_media_status() {
        $voice_manager = $this->aiautotool_get_voice_manager();
        return rest_ensure_response(array(
            'tts' => $voice_manager ? $voice_manager->get_usage_stats() : array(),
            'video' => array('status' => 'planned', 'message' => 'Short video queue and renderer are prepared for the next implementation phase.'),
            'subtitle' => array('status' => 'planned'),
            'publish' => array('status' => 'planned'),
        ));
    }

    public function aiautotool_rest_media_placeholder($request) {
        return rest_ensure_response(array(
            'success' => false,
            'status' => 'planned',
            'message' => __('This workflow endpoint is registered. Queue/render implementation will be added in the next phase.', 'ai-auto-tool'),
        ));
    }
    
    /**
     * AJAX callback to analyze image positions in content
     */
    public function aiautotool_analyze_image_positions_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $content = isset($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : '';
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : '';
        
        if (empty($content)) {
            wp_send_json_error('Content is required');
            return;
        }
        
        try {
            $ai_response = $this->call_ai_api_for_image_analysis($prompt);
            
            if ($ai_response) {
                wp_send_json_success($ai_response);
            } else {
                wp_send_json_error('Failed to analyze content with AI');
            }
            
        } catch (Exception $e) {
            wp_send_json_error('Error: ' . $e->getMessage());
        }
    }
    
    /**
     * AJAX callback to generate English image prompt
     */
    public function aiautotool_generate_english_prompt_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
        $paragraph = isset($_POST['paragraph']) ? sanitize_textarea_field(wp_unslash($_POST['paragraph'])) : '';
        $ai_analysis = isset($_POST['ai_analysis']) ? json_decode(stripslashes(wp_unslash($_POST['ai_analysis'])), true) : array();
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : '';
        
        if (empty($title) || empty($paragraph)) {
            wp_send_json_error('Title and paragraph are required');
            return;
        }
        
        try {
            $english_prompt = str_replace("\n", " ", strip_tags($this->call_ai_api_for_english_prompt($prompt)));
            if ($english_prompt) {
                wp_send_json_success($english_prompt);
            } else {
                wp_send_json_error('Failed to generate English prompt with AI');
            }
            
        } catch (Exception $e) {
            wp_send_json_error('Error: ' . $e->getMessage());
        }
    }
    
    /**
     * Call AI API for English prompt generation
     */
    private function call_ai_api_for_english_prompt($prompt) {
        return $this->call_ai_provider_for_suggest_images($prompt, array(
            'temperature' => 0.4,
            'max_tokens' => 700,
            'timeout' => 75,
        ));
    }
    
    /**
     * Call AI API for image analysis
     */
    private function call_ai_api_for_image_analysis($prompt) {
        return $this->call_ai_provider_for_suggest_images($prompt, array(
            'temperature' => 0.2,
            'max_tokens' => 1400,
            'timeout' => 90,
        ));
    }

    /**
     * Call the configured AI Provider for Suggest Image planning.
     */
    private function call_ai_provider_for_suggest_images($prompt, $options = array()) {
        if (!class_exists('AIAutotool_AI_Helper')) {
            $helper_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php';
            if (file_exists($helper_file)) {
                require_once $helper_file;
            }
        }

        if (!class_exists('AIAutotool_AI_Helper')) {
            return false;
        }

        $result = AIAutotool_AI_Helper::generate($prompt, $options);
        if (!empty($result['success']) && isset($result['content'])) {
            return trim((string) $result['content']);
        }

        return false;
    }
    
    /**
     * Helper function to search Google using Custom Search API
     * 
     * @param string $query Search query
     * @param string $lang Language code
     * @return array|false Search results or false on error
     */
    private function search_google_custom_search($query, $lang = 'en') {
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        // Get Google Custom Search API settings
        $api_key = get_option('aiautotool_google_search_api_key', '');
        $cx_id = get_option('aiautotool_google_search_cx_id', '');
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        // If no API key or CX ID, try to get from general settings
        if (empty($api_key) || empty($cx_id)) {
            // Try to get from WordPress options directly
            if (empty($api_key)) {
                $api_key = get_option('google_search_api_key', '');
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
            }
            if (empty($cx_id)) {
                $cx_id = get_option('google_search_cx_id', '');
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
            }
        }
        
        // If still no API key or CX ID, use scraping fallback
        if (empty($api_key) || empty($cx_id)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            $scrape_result = $this->search_google_scrape($query, $lang);
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return $scrape_result;
        }
        
        // Build search URL
        $search_url = 'https://www.googleapis.com/customsearch/v1';
        $search_url .= '?key=' . urlencode(trim($api_key));
        $search_url .= '&cx=' . urlencode(trim($cx_id));
        $search_url .= '&q=' . urlencode($query);
        $search_url .= '&num=10'; // Get 10 results
        
        // Add language parameter if available
        if (!empty($lang)) {
            $lang_map = array(
                'vietnamese' => 'lang_vi',
                'vi' => 'lang_vi',
                'english' => 'lang_en',
                'en' => 'lang_en'
            );
            $lang_lower = strtolower($lang);
            if (isset($lang_map[$lang_lower])) {
                $search_url .= '&lr=' . $lang_map[$lang_lower];
            }
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        // Make request using wp_remote_get
        $response = wp_remote_get($search_url, array(
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                $error_data = $response->get_error_data();
                if ($error_data) {
                }
            }
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $status_code = wp_remote_retrieve_response_code($response);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        if ($status_code !== 200) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        $data = json_decode($body, true);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            if (json_last_error() !== JSON_ERROR_NONE) {
            } else {
            }
        }
        
        if (isset($data['error'])) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                if (isset($data['error']['message'])) {
                }
                if (isset($data['error']['code'])) {
                }
            }
            return false;
        }
        
        // Format results
        $results = array();
        if (isset($data['items']) && is_array($data['items'])) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            foreach ($data['items'] as $index => $item) {
                $results[] = array(
                    'title' => isset($item['title']) ? $item['title'] : '',
                    'link' => isset($item['link']) ? $item['link'] : '',
                    'snippet' => isset($item['snippet']) ? $item['snippet'] : '',
                    'displayLink' => isset($item['displayLink']) ? $item['displayLink'] : ''
                );
            }
        } else {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                if (isset($data['items'])) {
                }
            }
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return !empty($results) ? $results : false;
    }
    
    /**
     * Scrape Google search results (fallback when API is not available)
     * WARNING: CHỈ DÙNG ĐỂ TEST – Google sẽ chặn IP sau vài lần
     * 
     * @param string $query Search query
     * @param string $lang Language code
     * @return array|false Array of search results or false on error
     */
    private function search_google_scrape($query, $lang = 'en') {
        // Map language codes to Google language codes
        $lang_map = array(
            'vietnamese' => 'vi',
            'vi' => 'vi',
            'english' => 'en',
            'en' => 'en'
        );
        $lang_lower = strtolower($lang);
        $hl_param = isset($lang_map[$lang_lower]) ? $lang_map[$lang_lower] : 'en';
        
        // Build search URL
        $encoded_query = urlencode($query);
        $url = "https://www.google.com/search?q=" . $encoded_query . "&hl=" . $hl_param . "&num=10";
        
        // Use wp_remote_get instead of curl for WordPress compatibility
        $response = wp_remote_get($url, array(
            'timeout' => 15,
            'sslverify' => true,
            'headers' => array(
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            ),
            'redirection' => 5
        ));
        
        if (is_wp_error($response)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        $html = wp_remote_retrieve_body($response);
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code !== 200 || empty($html)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        $results = array();
        $links = array();
        
        // Method 1: Try to extract links from /url?q= pattern (matching user's example)
        preg_match_all('/<a href="\/url\?q=(.*?)&amp;/', $html, $link_matches);
        
        if (!empty($link_matches[1])) {
            foreach ($link_matches[1] as $link) {
                $decoded_link = urldecode($link);
                // Filter out Google internal links
                if (strpos($decoded_link, 'webcache.googleusercontent') === false && 
                    strpos($decoded_link, 'google') === false) {
                    $links[] = $decoded_link;
                }
            }
            $links = array_slice(array_unique($links), 0, 10);
            
            // Try to extract titles and snippets for each link
            foreach ($links as $link) {
                $title = '';
                $snippet = '';
                $displayLink = parse_url($link, PHP_URL_HOST);
                
                // Try to find title and snippet near the link in HTML
                $escaped_link = preg_quote($link, '/');
                // Look for title in h3 tags
                if (preg_match('/' . $escaped_link . '.*?<h3[^>]*>(.*?)<\/h3>/is', $html, $title_match)) {
                    $title = trim(strip_tags($title_match[1]));
                }
                
                // Look for snippet in various patterns
                if (preg_match('/' . $escaped_link . '.*?<span[^>]*class="[^"]*[sS][^"]*"[^>]*>(.*?)<\/span>/is', $html, $snippet_match)) {
                    $snippet = trim(strip_tags($snippet_match[1]));
                } elseif (preg_match('/' . $escaped_link . '.*?<div[^>]*class="[^"]*[sS][^"]*"[^>]*>(.*?)<\/div>/is', $html, $snippet_match)) {
                    $snippet = trim(strip_tags($snippet_match[1]));
                }
                
                if (!empty($link)) {
                    $results[] = array(
                        'title' => $title ?: ($displayLink ?: $link),
                        'link' => $link,
                        'snippet' => $snippet,
                        'displayLink' => $displayLink ?: ''
                    );
                }
            }
        }
        
        // Method 2: If no results, try alternative pattern (Google's newer structure)
        if (empty($results)) {
            // Try to match result blocks
            if (preg_match_all('/<div[^>]*class="[^"]*g[^"]*"[^>]*>(.*?)<\/div>/is', $html, $result_blocks)) {
                foreach ($result_blocks[1] as $block) {
                    $result_item = array();
                    
                    // Extract link
                    if (preg_match('/<a[^>]+href="([^"]+)"/', $block, $link_match)) {
                        $link = $link_match[1];
                        if (strpos($link, '/url?q=') === 0) {
                            $link = urldecode(substr($link, 7));
                        }
                        
                        // Filter out Google internal links
                        if (strpos($link, 'webcache.googleusercontent') === false && 
                            strpos($link, 'google.com') === false) {
                            $result_item['link'] = $link;
                            $result_item['displayLink'] = parse_url($link, PHP_URL_HOST) ?: '';
                        }
                    }
                    
                    // Extract title
                    if (preg_match('/<h3[^>]*>(.*?)<\/h3>/is', $block, $title_match)) {
                        $result_item['title'] = strip_tags($title_match[1]);
                    }
                    
                    // Extract snippet
                    if (preg_match('/<span[^>]*class="[^"]*[sS][^"]*"[^>]*>(.*?)<\/span>/is', $block, $snippet_match)) {
                        $result_item['snippet'] = strip_tags($snippet_match[1]);
                    }
                    
                    if (!empty($result_item['link']) && count($results) < 10) {
                        $results[] = array(
                            'title' => isset($result_item['title']) ? $result_item['title'] : '',
                            'link' => $result_item['link'],
                            'snippet' => isset($result_item['snippet']) ? $result_item['snippet'] : '',
                            'displayLink' => isset($result_item['displayLink']) ? $result_item['displayLink'] : ''
                        );
                    }
                }
            }
        }
        
        // If still no results, return at least the links we found
        if (empty($results) && !empty($links)) {
            foreach ($links as $link) {
                $results[] = array(
                    'title' => parse_url($link, PHP_URL_HOST) ?: $link,
                    'link' => $link,
                    'snippet' => '',
                    'displayLink' => parse_url($link, PHP_URL_HOST) ?: ''
                );
            }
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return !empty($results) ? $results : false;
    }
    
    public function aiautotool_write_article_with_google_search_callback() {
        // Verify nonce for AJAX requests
        if (defined('DOING_AJAX') && DOING_AJAX) {
            if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) {
                // For SSE, we need to send error via stream
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Security check failed. Please refresh the page and try again.');
                $stream->close();
                return;
            }
            
            if (!current_user_can('edit_posts')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Permission denied');
                $stream->close();
                return;
            }
        }
        
        // Check if user has active Pro license or trial access.
        if (!function_exists('aiautotool_can_use_pro_features') || !aiautotool_can_use_pro_features()) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('This feature requires a Pro account. Please upgrade to Pro to use this feature.');
            $stream->close();
            return;
        }
        
        // Load rendersetting class if not already loaded
        if (!class_exists('rendersetting')) {
            $rendersetting_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/setting.php';
            if (file_exists($rendersetting_file)) {
                require_once $rendersetting_file;
            }
        }
        
        // Get data from POST
        $data = array();
        if (isset($_POST['data']) && is_string($_POST['data'])) {
            $data = json_decode(stripslashes($_POST['data']), true);
        } else {
            $raw_data = file_get_contents('php://input');
            $data = json_decode($raw_data, true);
        }
        
        if (!$data || !is_array($data)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Invalid JSON data');
            $stream->close();
            return;
        }
        
        // Extract parameters
        $title = isset($data['title']) ? sanitize_text_field($data['title']) : '';
        $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese';
        $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection(
            isset($data['model']) ? $data['model'] : '',
            isset($data['provider_id']) ? $data['provider_id'] : ''
        );
        $model = $resolved_ai_selection['model'];
        $provider_id = $resolved_ai_selection['provider_id'];
        $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : '';
        
        // Extract article settings
        $target_audience = isset($data['targetAudience']) ? sanitize_text_field($data['targetAudience']) : '';
        $tone = isset($data['tone']) ? sanitize_text_field($data['tone']) : '';
        $length_type = isset($data['lengthType']) ? sanitize_text_field($data['lengthType']) : '';
        $competitors = isset($data['competitors']) && is_array($data['competitors']) 
            ? array_map('esc_url_raw', array_filter($data['competitors'])) 
            : array();
        $brand_voice_rules = isset($data['brandVoiceRules']) ? sanitize_textarea_field($data['brandVoiceRules']) : '';
        
        if (empty($title)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Title parameter is required');
            $stream->close();
            return;
        }
        
        // Load SSE Stream class
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
        
        // Load Google Search class
        if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/google-search.php')) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/google-search.php';
        }
        
        // Load AI Helper and AI Agent for new AI Provider system
        if (file_exists(plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php')) {
            require_once plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php';
        }
        
        // Initialize BardGenContent for fallback
        $bardGenContent = new BardGenContent();
        
        // Helper function to convert markdown to HTML (same as original function)
        $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) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                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();
                $html = $parsedown->text($text);
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return $html;
            }
            
            // 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')) {
                    $html = markdown($text);
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    return $html;
                }
            }
            
            // 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);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return $html;
        };
        
        // Track last AI call time to ensure minimum 10 seconds between calls
        $last_ai_call_time_2 = 0;
        $min_ai_call_interval_2 = 10; // Minimum seconds between AI calls
        
        // Helper function to generate content using AI Agent with fallback (same as original)
        $generate_with_agent = function($prompt, $lang, $model, $provider_id = '', $options = array()) use ($bardGenContent, &$last_ai_call_time_2, $min_ai_call_interval_2) {
            // Ensure minimum 10 seconds between AI calls
            $current_time = time();
            $time_since_last_call = $current_time - $last_ai_call_time_2;
            
            if ($last_ai_call_time_2 > 0 && $time_since_last_call < $min_ai_call_interval_2) {
                $wait_time = $min_ai_call_interval_2 - $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_2 = 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';
                }
                
                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 (!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']
                    );
                } else {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            return $bardGenContent->bardcontentmore($prompt, $lang, $model);
        };
        
        // Helper function to generate language instruction (same as original)
        $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;
        };
        
        // Helper function to find related posts (same as original)
        $find_related_posts_for_internal_linking = function($title, $keywords_text, $lang, $article_text = '', $limit = 5) {
            $related_posts = array();
            
            $keywords_summary = mb_substr(strip_tags($keywords_text), 0, 200, 'UTF-8');
            $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary));
            
            $keywords_array = array();
            $lines = explode("\n", $keywords_text);
            foreach ($lines as $line) {
                $line = trim(strip_tags($line));
                if (!empty($line) && strlen($line) > 3) {
                    $line = preg_replace('/^[\d\-\*\.\s]+/', '', $line);
                    if (!empty($line)) {
                        $keywords_array[] = $line;
                        if (count($keywords_array) >= 5) break;
                    }
                }
            }
            
            if (empty($keywords_array)) {
                $title_words = explode(' ', $title);
                $keywords_array = array_slice($title_words, 0, 3);
            }
            
            $search_query = implode(' ', array_slice($keywords_array, 0, 3));
            
            $args_by_keywords = array(
                'post_type' => 'post',
                'posts_per_page' => $limit * 2,
                'post_status' => 'publish',
                's' => $search_query,
                'orderby' => 'relevance',
                'order' => 'DESC',
            );
            
            if (function_exists('pll_get_post_language')) {
                $args_by_keywords['lang'] = $lang;
            }
            
            $query_by_keywords = new WP_Query($args_by_keywords);
            
            if ($query_by_keywords->have_posts()) {
                while ($query_by_keywords->have_posts()) {
                    $query_by_keywords->the_post();
                    $post_id = get_the_ID();
                    $post_title = get_the_title();
                    $post_url = get_permalink();
                    $post_excerpt = get_the_excerpt();
                    
                    $relevance_score = 0;
                    $title_lower = mb_strtolower($title, 'UTF-8');
                    $post_title_lower = mb_strtolower($post_title, 'UTF-8');
                    
                    foreach ($keywords_array as $keyword) {
                        $keyword_lower = mb_strtolower($keyword, 'UTF-8');
                        if (mb_strpos($post_title_lower, $keyword_lower) !== false) {
                            $relevance_score += 3;
                        }
                        if (mb_strpos($post_excerpt, $keyword_lower) !== false) {
                            $relevance_score += 1;
                        }
                    }
                    
                    similar_text($title_lower, $post_title_lower, $similarity);
                    $relevance_score += $similarity / 10;
                    
                    $related_posts[] = array(
                        'id' => $post_id,
                        'title' => $post_title,
                        'url' => $post_url,
                        'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'),
                        'relevance_score' => $relevance_score
                    );
                }
                wp_reset_postdata();
            }
            
            if (!empty($keywords_array)) {
                $tag_names = array_slice($keywords_array, 0, 3);
                
                $args_by_tags = array(
                    'post_type' => 'post',
                    'posts_per_page' => $limit,
                    'post_status' => 'publish',
                    'tag_slug__in' => array_map(function($tag) {
                        return sanitize_title($tag);
                    }, $tag_names),
                    'orderby' => 'date',
                    'order' => 'DESC',
                );
                
                if (function_exists('pll_get_post_language')) {
                    $args_by_tags['lang'] = $lang;
                }
                
                $query_by_tags = new WP_Query($args_by_tags);
                
                if ($query_by_tags->have_posts()) {
                    while ($query_by_tags->have_posts()) {
                        $query_by_tags->the_post();
                        $post_id = get_the_ID();
                        $post_title = get_the_title();
                        $post_url = get_permalink();
                        $post_excerpt = get_the_excerpt();
                        
                        $exists = false;
                        foreach ($related_posts as $existing) {
                            if ($existing['id'] == $post_id) {
                                $exists = true;
                                break;
                            }
                        }
                        
                        if (!$exists) {
                            $relevance_score = 2;
                            $related_posts[] = array(
                                'id' => $post_id,
                                'title' => $post_title,
                                'url' => $post_url,
                                'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'),
                                'relevance_score' => $relevance_score
                            );
                        }
                    }
                    wp_reset_postdata();
                }
            }
            
            usort($related_posts, function($a, $b) {
                return $b['relevance_score'] <=> $a['relevance_score'];
            });
            
            return array_slice($related_posts, 0, $limit);
        };
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        $stream = new AIAutoTool_SSE_Stream();
        $stream->start();
        if (!empty($message_id)) {
            $stream->set_message_id($message_id);
        }
        
        try {
            // Step 1: Search Google for latest content and fetch URLs content
            $stream->send_step_start(1, 'search_google', 'Searching Google for latest content...');
            
            $google_search_results = array();
            $google_search_text = '';
            $urls_content = array();
            $search_debug_info = array();
            
            // Debug: Check if new class exists
            $has_new_class = class_exists('AIAutoTool_Google_Search');
            if (defined('WP_DEBUG') && WP_DEBUG) {
                $search_debug_info[] = 'AIAutoTool_Google_Search class: ' . ($has_new_class ? 'Available' : 'Not available');
            }
            
            // Try using new Google Search class first
            if ($has_new_class) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                // Try method 1: Use get_simple_results() first (simplest method like in test file)
                $search_options = array(
                    'timeout' => 30,
                    'params' => array(
                        'hl' => ($lang === 'Vietnamese' || strpos(strtolower($lang), 'vi') !== false) ? 'vi' : 'en',
                        'gl' => ($lang === 'Vietnamese' || strpos(strtolower($lang), 'vi') !== false) ? 'vn' : 'us'
                    )
                );
                
                $simple_results = AIAutoTool_Google_Search::get_simple_results($title, $search_options);
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    if (is_wp_error($simple_results)) {
                    } elseif (is_array($simple_results)) {
                    }
                }
                
                // Check if error is due to missing Jina AI API key
                if (is_wp_error($simple_results) && $simple_results->get_error_code() === 'no_api_key') {
                    $error_message = $simple_results->get_error_message();
                    $stream->send_error($error_message);
                    $stream->close();
                    return;
                }
                
                // Check if blocked by Google
                if (is_wp_error($simple_results) && $simple_results->get_error_code() === 'blocked') {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        $search_debug_info[] = 'Google blocked request - Trying fallbacks';
                    }
                    
                    // Try Custom Search API first
                    $google_search_results = $this->search_google_custom_search($title, $lang);
                    if ($google_search_results !== false && is_array($google_search_results) && !empty($google_search_results)) {
                        $search_debug_info[] = 'Custom Search API: Success - ' . count($google_search_results) . ' results';
                    } else {
                        // Try Jina AI Search as fallback
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                            $search_debug_info[] = 'Custom Search API: Failed - Trying Jina AI Search';
                        }
                        
                        $jina_result = AIAutoTool_Google_Search::search_jina_ai($title, $search_options);
                        
                        // Check if error is due to missing API key
                        if (is_wp_error($jina_result) && $jina_result->get_error_code() === 'no_api_key') {
                            $error_message = $jina_result->get_error_message();
                            $stream->send_error($error_message);
                            $stream->close();
                            return;
                        }
                        
                        if (!is_wp_error($jina_result) && isset($jina_result['results']['organic']) && !empty($jina_result['results']['organic'])) {
                            // Format Jina AI results
                            foreach ($jina_result['results']['organic'] as $index => $item) {
                                $result_item = array(
                                    'title' => isset($item['title']) ? $item['title'] : 'No title',
                                    'link' => isset($item['url']) ? $item['url'] : '',
                                    'snippet' => isset($item['snippet']) ? $item['snippet'] : '',
                                    'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : ''
                                );
                                $google_search_results[] = $result_item;
                            }
                            $search_debug_info[] = 'Jina AI Search: Success - ' . count($google_search_results) . ' results';
                        } else {
                            $search_debug_info[] = 'All fallbacks failed - ' . (is_wp_error($jina_result) ? $jina_result->get_error_message() : ($simple_results->get_error_message() ?: 'No results'));
                        }
                    }
                } elseif (!is_wp_error($simple_results) && is_array($simple_results) && !empty($simple_results)) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    // Format results from simple_results
                    foreach ($simple_results as $index => $item) {
                        $result_item = array(
                            'title' => isset($item['title']) ? $item['title'] : 'No title',
                            'link' => isset($item['url']) ? $item['url'] : '',
                            'snippet' => isset($item['snippet']) ? $item['snippet'] : '',
                            'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : ''
                        );
                        $google_search_results[] = $result_item;
                    }
                    
                    $search_debug_info[] = 'get_simple_results: Success - ' . count($google_search_results) . ' results';
                    
                } else {
                    // Try method 2: Use search() directly
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    $search_result = AIAutoTool_Google_Search::search($title, $search_options);
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        if (is_wp_error($search_result)) {
                            $search_debug_info[] = 'search() error: ' . $search_result->get_error_message();
                            
                            // If blocked, try Custom Search API
                            if ($search_result->get_error_code() === 'blocked') {
                                $google_search_results = $this->search_google_custom_search($title, $lang);
                                if ($google_search_results !== false && is_array($google_search_results) && !empty($google_search_results)) {
                                    $search_debug_info[] = 'Custom Search API fallback: Success - ' . count($google_search_results) . ' results';
                                }
                            }
                        } elseif (is_array($search_result)) {
                            if (isset($search_result['results']['organic'])) {
                            }
                        }
                    }
                    
                    if (!is_wp_error($search_result) && isset($search_result['results']['organic']) && is_array($search_result['results']['organic']) && !empty($search_result['results']['organic'])) {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        
                        // Format results from search() organic results
                        foreach ($search_result['results']['organic'] as $index => $item) {
                            $result_item = array(
                                'title' => isset($item['title']) ? $item['title'] : 'No title',
                                'link' => isset($item['url']) ? $item['url'] : '',
                                'snippet' => isset($item['snippet']) ? $item['snippet'] : '',
                                'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : ''
                            );
                            $google_search_results[] = $result_item;
                        }
                        
                        $search_debug_info[] = 'search() method: Success - ' . count($google_search_results) . ' results';
                        
                    } else {
                        // Try method 3: Use search_and_get_content (may fail if no URLs, but try anyway)
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        
                        $search_limit = 5;
                        $search_content_options = array_merge($search_options, array(
                            'format' => 'markdown',
                            'delay' => 2
                        ));
                        
                        $search_content_result = AIAutoTool_Google_Search::search_and_get_content($title, $search_limit, $search_content_options);
                        
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                            if (is_wp_error($search_content_result)) {
                                $search_debug_info[] = 'search_and_get_content error: ' . $search_content_result->get_error_message();
                            } elseif (is_array($search_content_result)) {
                                if (isset($search_content_result['results'])) {
                                }
                            }
                        }
                        
                        if (!is_wp_error($search_content_result) && isset($search_content_result['results']) && is_array($search_content_result['results']) && !empty($search_content_result['results'])) {
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                            
                            // Format results from search_and_get_content
                            foreach ($search_content_result['results'] as $index => $item) {
                                $result_item = array(
                                    'title' => isset($item['search_title']) ? $item['search_title'] : 'No title',
                                    'link' => isset($item['url']) ? $item['url'] : '',
                                    'snippet' => isset($item['search_snippet']) ? $item['search_snippet'] : '',
                                    'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : ''
                                );
                                
                                // If we got content from Jina AI, add it
                                if (!empty($item['content']) && isset($item['content']['content'])) {
                                    $urls_content[] = array(
                                        'url' => $item['url'],
                                        'title' => $item['search_title'],
                                        'content' => $item['content']['content'],
                                        'length' => isset($item['content']['length']) ? $item['content']['length'] : strlen($item['content']['content'])
                                    );
                                    
                                    // Add content preview to snippet
                                    $content_preview = mb_substr(strip_tags($item['content']['content']), 0, 300, 'UTF-8');
                                    $result_item['snippet'] = $content_preview . '...';
                                    $result_item['has_content'] = true;
                                } else if (!empty($item['error'])) {
                                    $result_item['error'] = $item['error'];
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                }
                                
                                $google_search_results[] = $result_item;
                            }
                            
                            $search_debug_info[] = 'search_and_get_content: Success - ' . count($google_search_results) . ' results';
                            
                        } else {
                            // All methods failed, use fallback
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                $search_debug_info[] = 'All new class methods failed - Using fallback';
                            }
                            
                            $google_search_results = $this->search_google_custom_search($title, $lang);
                            
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                if ($google_search_results === false) {
                                    $search_debug_info[] = 'Fallback method: Failed';
                                } elseif (is_array($google_search_results)) {
                                    $search_debug_info[] = 'Fallback method: Success - ' . count($google_search_results) . ' results';
                                }
                            }
                        }
                    }
                }
            } else {
                // Fallback to old method if class not available
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    $search_debug_info[] = 'New class not available - Using fallback directly';
                }
                
                $google_search_results = $this->search_google_custom_search($title, $lang);
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    if ($google_search_results === false) {
                        $search_debug_info[] = 'Direct fallback: Failed';
                    } elseif (is_array($google_search_results)) {
                        $search_debug_info[] = 'Direct fallback: Success - ' . count($google_search_results) . ' results';
                    }
                }
            }
            
            // Step 1.1: Extract full content from all URLs found in search results
            if ($google_search_results && is_array($google_search_results) && !empty($google_search_results)) {
                $stream->send_status('Extracting content from the URLs found...');
                
                // Collect all URLs from search results
                $urls_to_fetch = array();
                $urls_already_fetched = array();
                
                // Check which URLs already have content
                foreach ($urls_content as $existing_content) {
                    $urls_already_fetched[] = $existing_content['url'];
                }
                
                // Collect URLs that need content extraction
                foreach ($google_search_results as $result) {
                    $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : '');
                    if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
                        // Skip if already fetched or if marked as has_content
                        if (!in_array($url, $urls_already_fetched) && (!isset($result['has_content']) || !$result['has_content'])) {
                            $urls_to_fetch[] = array(
                                'url' => $url,
                                'title' => isset($result['title']) ? $result['title'] : ''
                            );
                        }
                    }
                }
                
                // Initialize failed URLs tracking array
                $failed_urls = array();
                
                // Extract content from URLs that don't have it yet
                if (!empty($urls_to_fetch) && $has_new_class) {
                    $stream->send_status('Extracting content from ' . count($urls_to_fetch) . ' URLs...');
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    $content_extraction_options = array(
                        'format' => 'markdown',
                        'delay' => 2, // Delay between requests to avoid rate limiting
                        'timeout' => 60
                    );
                    
                    // Get API key if available
                    if (class_exists('AIAutotool_AI_Provider_API_Keys')) {
                        $jina_api_key = AIAutotool_AI_Provider_API_Keys::get_jina_key();
                        if (!empty($jina_api_key)) {
                            $content_extraction_options['api_key'] = $jina_api_key;
                            $content_extraction_options['jina_api_key'] = $jina_api_key;
                        }
                    }
                    
                    // Extract content from URLs
                    $urls_only = array_column($urls_to_fetch, 'url');
                    $stream->send_status('Extracting content from ' . count($urls_only) . ' URLs...');
                   
                    $content_results = AIAutoTool_Google_Search::get_multiple_urls_content($urls_only, $content_extraction_options);
                    
                    // Process extracted content - track failed URLs to skip them
                    if (is_array($content_results)) {
                        foreach ($content_results as $index => $content_result) {
                            $url = $content_result['url'];
                            $result_data = $content_result['result'];
                            
                            if (!is_wp_error($result_data)) {
                                $extracted_content = isset($result_data['content']) ? $result_data['content'] : '';
                                $extracted_title = isset($result_data['title']) ? $result_data['title'] : 
                                    (isset($urls_to_fetch[$index]['title']) ? $urls_to_fetch[$index]['title'] : '');
                                
                                if (!empty($extracted_content)) {
                                    $urls_content[] = array(
                                        'url' => $url,
                                        'title' => $extracted_title,
                                        'content' => $extracted_content,
                                        'length' => strlen($extracted_content),
                                        'source' => 'jina_ai'
                                    );
                                    $stream->send_status('Content:  ' . count($urls_content) . ' ...');
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                } else {
                                    // Content is empty, mark as failed
                                    $failed_urls[] = array(
                                        'url' => $url,
                                        'reason' => 'Content is empty'
                                    );
                                    $stream->send_status('Content:  Content is empty: ' . $url . ' ...');
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                }
                            } else {
                                // Error occurred, mark as failed and skip
                                $error_msg = $result_data->get_error_message();
                                $failed_urls[] = array(
                                    'url' => $url,
                                    'reason' => $error_msg
                                );
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                            }
                        }
                    }
                    
                    // Log skipped URLs info
                    if (!empty($failed_urls) && defined('WP_DEBUG') && WP_DEBUG) {
                        foreach ($failed_urls as $failed) {
                        }
                    }
                }
                
                // Format search results text
                $google_search_text = "Latest information from Google search:\n\n";
                
                // Track which URLs were successfully extracted
                $extracted_urls = array();
                foreach ($urls_content as $content_item) {
                    $extracted_urls[] = $content_item['url'];
                }
                
                foreach ($google_search_results as $index => $result) {
                    $google_search_text .= ($index + 1) . ". " . (isset($result['title']) ? $result['title'] : 'No title') . "\n";
                    $google_search_text .= "   " . (isset($result['snippet']) ? $result['snippet'] : '') . "\n";
                    $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : '');
                    if (!empty($url)) {
                        $google_search_text .= "   Source: " . $url . "\n";
                    }
                    
                    // Check if we have full content for this URL
                    $has_full_content = false;
                    if (in_array($url, $extracted_urls) || (isset($result['has_content']) && $result['has_content'])) {
                        $has_full_content = true;
                        $google_search_text .= "   ✓ Full content fetched\n";
                    } else {
                        $google_search_text .= "   ✗ Content extraction failed - skipped\n";
                    }
                    $google_search_text .= "\n";
                }
                
                // Add info about skipped URLs if any
                if (!empty($failed_urls)) {
                    $google_search_text .= "\n=== URLs Đã Bỏ Qua (không trích xuất được) ===\n\n";
                    foreach ($failed_urls as $idx => $failed) {
                        $google_search_text .= ($idx + 1) . ". " . $failed['url'] . "\n";
                        $google_search_text .= "   Lý do: " . $failed['reason'] . "\n\n";
                    }
                    $google_search_text .= "Tổng cộng: " . count($failed_urls) . " URL đã bỏ qua\n\n";
                }
                
                // Add full extracted content (this will be used for article writing)
                if (!empty($urls_content)) {
                    $google_search_text .= "\n=== Full Content from Sources (for article writing) ===\n\n";
                    $google_search_text .= "Đã trích xuất thành công nội dung từ " . count($urls_content) . " URL:\n\n";
                    foreach ($urls_content as $idx => $content_item) {
                        $google_search_text .= "--- Source " . ($idx + 1) . ": " . $content_item['url'] . " ---\n";
                        $google_search_text .= "Title: " . $content_item['title'] . "\n";
                        $google_search_text .= "Content length: " . $content_item['length'] . " characters\n\n";
                        $google_search_text .= $content_item['content'] . "\n\n";
                        $google_search_text .= "=== End of Source " . ($idx + 1) . " ===\n\n\n";
                    }
                }
                
                // Prepare display message
                $display_message = "Kết quả tìm kiếm Google và nội dung đã trích xuất:\n\n";
                $display_message .= "✓ Đã trích xuất thành công: " . count($urls_content) . " URL\n";
                if (!empty($failed_urls)) {
                    $display_message .= "✗ Đã bỏ qua: " . count($failed_urls) . " URL (không trích xuất được)\n";
                }
                $display_message .= "\nNội dung đầy đủ sẽ được sử dụng trong các bước tiếp theo.\n";
                
                $stream->send_step_output(1, '<div class="google-search-results"><h4>' . esc_html($display_message) . '</h4><pre>' . esc_html(mb_substr($google_search_text, 0, 2000, 'UTF-8')) . (strlen($google_search_text) > 2000 ? '... (nội dung đầy đủ sẽ được sử dụng trong các bước tiếp theo)' : '') . '</pre></div>');
                $stream->send_step_complete(1, 'success');
                
                // CRITICAL VALIDATION: Check if we have at least ONE extracted content - MUST have content to continue
                if (empty($urls_content) || !is_array($urls_content) || count($urls_content) == 0) {
                    $error_message = "Lỗi: Không thể trích xuất nội dung từ BẤT KỲ URL nào trong số các URL tìm được.\n\n";
                    $error_message .= "Bài viết CHỈ được viết dựa trên nội dung đã crawl được từ các URL.\n";
                    $error_message .= "Vui lòng thử lại hoặc kiểm tra cấu hình API (Jina AI API key).\n\n";
                    
                    if (!empty($google_search_results)) {
                        $error_message .= "Đã tìm thấy " . count($google_search_results) . " kết quả tìm kiếm, nhưng không thể trích xuất nội dung từ bất kỳ URL nào.\n\n";
                        $error_message .= "Các URL đã thử:\n";
                        foreach (array_slice($google_search_results, 0, 10) as $idx => $result) {
                            $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : '');
                            $error_message .= ($idx + 1) . ". " . $url . "\n";
                        }
                    }
                    
                    if (!empty($failed_urls)) {
                        $error_message .= "\nChi tiết lỗi:\n";
                        foreach ($failed_urls as $idx => $failed) {
                            $error_message .= ($idx + 1) . ". " . $failed['url'] . " - " . $failed['reason'] . "\n";
                        }
                    }
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    $stream->send_error($error_message);
                    $stream->close();
                    return;
                }
                
                // Log success with info about skipped URLs
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    if (!empty($failed_urls)) {
                    }
                    foreach ($urls_content as $idx => $content_item) {
                    }
                }
                
                // Send info about skipped URLs if any (as status, not error)
                if (!empty($failed_urls)) {
                    $skip_message = "Lưu ý: Đã bỏ qua " . count($failed_urls) . " URL không trích xuất được. Sẽ tiếp tục với " . count($urls_content) . " URL đã trích xuất thành công.";
                    $stream->send_status($skip_message);
                }
                
            } else {
                // If search fails, STOP - we cannot write article without search results and extracted content
                $error_message = "Lỗi: Không thể tìm kiếm trên Google hoặc không có kết quả.\n\n";
                $error_message .= "QUAN TRỌNG: Bài viết CHỈ được viết dựa trên nội dung đã crawl được từ các URL tìm kiếm.\n";
                $error_message .= "Không thể tiếp tục viết bài mà không có nội dung từ kết quả tìm kiếm.\n\n";
                
                if (defined('WP_DEBUG') && WP_DEBUG && !empty($search_debug_info)) {
                    $error_message .= "Thông tin debug:\n";
                    foreach ($search_debug_info as $info) {
                        $error_message .= "- " . $info . "\n";
                    }
                    $error_message .= "\n";
                }
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    if (!empty($search_debug_info)) {
                    }
                    
                    // Check API configuration
                    $api_key = get_option('aiautotool_google_search_api_key', '');
                    $cx_id = get_option('aiautotool_google_search_cx_id', '');
                }
                
                $stream->send_step_output(1, '<div class="google-search-results"><h4>Lỗi Tìm Kiếm Google:</h4><p>' . nl2br(esc_html($error_message)) . '</p></div>');
                $stream->send_error($error_message);
                $stream->close();
                return;
            }
            
            // Step 2: Generate Checklist (same as original but with Google search context)
            $stream->send_step_start(2, 'generate_checklist', 'Generating checklist...');
            
            // Get website information
            $site_name = get_bloginfo('name');
            $site_url = home_url();
            
            // Get author information
            $current_user = wp_get_current_user();
            $author_name = $current_user->display_name;
            $author_bio = get_user_meta($current_user->ID, 'description', true);
            
            $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** and the extracted content from Google search results.\n\n";
            $checklist_prompt .= "Input:\n\n";
            $checklist_prompt .= "- title: \"{$title}\"\n\n";
            
            // Add Google search results if available - emphasize using extracted content
            if (!empty($google_search_text)) {
                $checklist_prompt .= "Extracted content from Google search results (this is the ONLY content source - do not suggest creating new content):\n{$google_search_text}\n\n";
                
                // Add emphasis if we have extracted content
                if (!empty($urls_content)) {
                    $checklist_prompt .= "IMPORTANT: The above content has been fully extracted from the search result URLs. ";
                    $checklist_prompt .= "Your analysis should be based ONLY on this extracted content. Do not suggest creating new content or adding information that is not present in the extracted content.\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";
            }
            
            // Generate Checklist
            $checklist_text = '';
            
            // Lấy provider_id từ settings nếu không có trong request
            if (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();
                }
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $stream->send_error($checklist_result['msg'] ?: 'Failed to generate checklist');
                $stream->close();
                return;
            }
            
            $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result;
            
            if (defined('WP_DEBUG') && WP_DEBUG && isset($checklist_result['provider'])) {
            }
            
            // Convert markdown to HTML
            $checklist_text = $convert_markdown_to_html($checklist_text);
            
            $stream->send_step_output(2, $checklist_text);
            $stream->send_step_complete(2, 'success');
            
            // Step 3: Generate Author Credibility Info (same as original)
            $stream->send_step_start(3, 'generate_author_credibility', 'Generating author credibility information...');
            
            $author_credibility_prompt = $get_language_instruction($lang);
            $author_credibility_prompt .= "Based on the checklist from step 2, 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 2:\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";
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $stream->send_error($author_credibility_result['msg'] ?: 'Failed to generate author credibility info');
                $stream->close();
                return;
            }
            
            $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result;
            
            // Convert markdown to HTML
            $author_credibility_text = $convert_markdown_to_html($author_credibility_text);
            
            $stream->send_step_output(3, $author_credibility_text);
            $stream->send_step_complete(3, 'success');
            
            // Step 4: Analyze Keywords (same as original but with Google search context)
            $stream->send_step_start(4, 'analyze_keywords', 'Analyzing required keywords...');
            
            $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";
            
            // Add Google search results if available
            if (!empty($google_search_text)) {
                $google_search_summary = mb_substr($google_search_text, 0, 500, 'UTF-8');
                $keywords_prompt .= "Latest information from Google: {$google_search_summary}\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";
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $error_msg = $keywords_analysis['msg'] ?: 'Failed to analyze keywords';
                $stream->send_error($error_msg);
                $stream->close();
                return;
            }
            
            $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis;
            
            // Convert markdown to HTML
            $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text);
            
            $stream->send_step_output(4, $keywords_analysis_text);
            $stream->send_step_complete(4, 'success');
            
            // Step 5: Analyze Writing Direction (same as original but with Google search context)
            $stream->send_step_start(5, 'analyze_direction', 'Analyzing writing direction...');
            
            $direction_prompt = $get_language_instruction($lang);
            $direction_prompt .= "Based on the following information, analyze and determine the writing direction for the article.\n";
            $direction_prompt .= "ONLY RETURN THE ANALYSIS, DO NOT ADD ANY DESCRIPTION.\n\n";
            $direction_prompt .= "Title: {$title}\n\n";
            
            // Add Google search results if available
            if (!empty($google_search_text)) {
                $google_search_summary = mb_substr($google_search_text, 0, 800, 'UTF-8');
                $direction_prompt .= "Latest information from Google: {$google_search_summary}\n\n";
            }
            
            $direction_prompt .= "Checklist: {$checklist_summary}\n";
            $direction_prompt .= "Keywords: " . mb_substr(strip_tags($keywords_analysis_text), 0, 200, 'UTF-8') . "\n\n";
            $direction_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n";
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $error_msg = $direction_analysis['msg'] ?: 'Failed to analyze direction';
                $stream->send_error($error_msg);
                $stream->close();
                return;
            }
            
            $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis;
            
            // Convert markdown to HTML
            $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text);
            
            $stream->send_step_output(5, $direction_analysis_text);
            $stream->send_step_complete(5, 'success');
            
            // Step 5.5: Find Related Posts & Internal Linking Strategy (moved before writing article)
            // Check if auto internal links is enabled
            $auto_internal_links = isset($data['autoInternalLinks']) 
                ? filter_var($data['autoInternalLinks'], FILTER_VALIDATE_BOOLEAN) 
                : true; // Default to true if not set
            
            $related_posts = array();
            
            if ($auto_internal_links) {
                $stream->send_step_start(5.5, 'find_related_posts', 'Finding related posts for internal linking...');
                
                // Find related posts (before writing article, so we can include them in the prompt)
                $related_posts = $find_related_posts_for_internal_linking($title, $keywords_analysis_text, $lang, '', 5);
            }
            
            $related_posts_info_for_prompt = '';
            $related_posts_display = '';
            
            if ($auto_internal_links && !empty($related_posts)) {
                // Prepare related posts information for prompt
                $related_posts_info_for_prompt = "\n\nRelated Posts for Internal Linking:\n";
                foreach ($related_posts as $index => $post) {
                    $related_posts_info_for_prompt .= ($index + 1) . ". Title: {$post['title']}\n";
                    $related_posts_info_for_prompt .= "   URL: {$post['url']}\n";
                    $related_posts_info_for_prompt .= "   Excerpt: {$post['excerpt']}\n";
                    $related_posts_info_for_prompt .= "   Relevance: " . round($post['relevance_score'], 2) . "\n\n";
                }
                $related_posts_info_for_prompt .= "IMPORTANT: Naturally insert internal links to these related posts in your article where relevant. Use markdown format: [anchor text](url). Make sure links are contextually relevant and add value to readers.\n";
                
                // Prepare for display
                $related_posts_display = "<h3>Related Posts Found for Internal Linking:</h3>\n<ul>\n";
                foreach ($related_posts as $post) {
                    $related_posts_display .= "<li><a href=\"{$post['url']}\" target=\"_blank\">{$post['title']}</a> (Relevance: " . round($post['relevance_score'], 2) . ")</li>\n";
                }
                $related_posts_display .= "</ul>\n<p><strong>These related posts will be included in the writing prompt so AI can naturally insert internal links while writing the article.</strong></p>";
            } elseif ($auto_internal_links && empty($related_posts)) {
                $related_posts_display = "<p>No related posts found for internal linking. This might be because:</p><ul><li>This is one of the first posts on the site</li><li>No posts match the keywords or categories</li><li>Try adding more content to enable internal linking</li></ul>";
            } else {
                $related_posts_display = "<p><strong>Auto Internal Links is disabled.</strong> Internal links will not be automatically inserted.</p>";
            }
            
            if ($auto_internal_links) {
                $stream->send_step_output(5.5, $related_posts_display);
                $stream->send_step_complete(5.5, 'success');
            } else {
                // Skip step 5.5 if auto internal links is disabled
                $stream->send_step_start(5.5, 'find_related_posts', 'Auto Internal Links is disabled...');
                $stream->send_step_output(5.5, $related_posts_display);
                $stream->send_step_complete(5.5, 'success');
            }
            
            // Step 6: Generate Multiple Prompts (one for each section from step 2)
            $stream->send_step_start(6, 'generate_prompt', 'Generating optimized prompts for AI...');
            
            // Define article end marker (used in both step 6 and step 7)
            $article_end_marker = "<!--ARTICLE_COMPLETE_END-->";
            
            // Get the original prompt template if available
            $original_prompt = '';
            if (isset($data['original_prompt']) && !empty($data['original_prompt'])) {
                $original_prompt = mb_substr(strip_tags($data['original_prompt']), 0, 500, 'UTF-8');
            }
            
            // Parse checklist to extract required sections
            $article_sections = array();
            $checklist_json = null;
            
            // Try to extract JSON from checklist_text
            $checklist_plain = strip_tags($checklist_text);
            // Try to find JSON in the text
            if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) {
                // Try to find full JSON structure
                $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 JSON parsing failed, try to extract sections from text
            if (!$checklist_json || !isset($checklist_json['content_to_provide']['required_sections'])) {
                // Fallback: try to extract sections from text format
                if (preg_match('/required_sections["\']?\s*:\s*\[(.*?)\]/s', $checklist_plain, $sections_match)) {
                    $sections_text = $sections_match[1];
                    // Try to extract quoted strings
                    preg_match_all('/["\']([^"\']+)["\']/', $sections_text, $section_matches);
                    if (!empty($section_matches[1])) {
                        $article_sections = $section_matches[1];
                    }
                }
                
                // If still no sections, create default sections based on direction analysis
                if (empty($article_sections)) {
                    // Create default sections: Introduction, Main Content, Conclusion
                    $article_sections = array('Introduction', 'Main Content', 'Conclusion');
                }
            } else {
                // Extract sections from JSON
                $article_sections = $checklist_json['content_to_provide']['required_sections'];
                if (empty($article_sections) || !is_array($article_sections)) {
                    $article_sections = array('Introduction', 'Main Content', 'Conclusion');
                }
            }
            
            // Ensure we have at least one section
            if (empty($article_sections)) {
                $article_sections = array('Introduction', 'Main Content', 'Conclusion');
            }
            
            // Tối ưu hóa final prompt: giới hạn độ dài các phân tích
            $checklist_final = mb_substr(strip_tags($checklist_text), 0, 300, 'UTF-8');
            $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 300, 'UTF-8');
            $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 400, 'UTF-8');
            $direction_final = mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8');
            
            // Làm sạch text
            $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_final = preg_replace('/\s+/', ' ', trim($direction_final));
            
            // Add language instruction to final prompt FIRST
            $lang_instruction_final = $get_language_instruction($lang);
            
            // Build common requirements that will be used in all section prompts
            $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";
            
            // Add extracted content from Google search - CRITICAL: AI must ONLY use this content
            if (!empty($urls_content) && is_array($urls_content)) {
                $common_requirements .= "\n=== CRITICAL WRITING INSTRUCTION ===\n\n";
                $common_requirements .= "You have been provided with FULL EXTRACTED CONTENT from Google search results below.\n";
                $common_requirements .= "YOUR TASK: Write the article by REWRITING, REORGANIZING, and SYNTHESIZING this extracted content ONLY.\n";
                $common_requirements .= "DO NOT create new content, DO NOT add information that is not in the extracted content below.\n";
                $common_requirements .= "DO NOT invent facts, statistics, or information.\n";
                $common_requirements .= "You can:\n";
                $common_requirements .= "- Rewrite the content in your own words\n";
                $common_requirements .= "- Reorganize and restructure the information\n";
                $common_requirements .= "- Combine and synthesize information from multiple sources\n";
                $common_requirements .= "- Improve the flow, clarity, and readability\n";
                $common_requirements .= "- Optimize for SEO while keeping the original information\n";
                $common_requirements .= "You CANNOT:\n";
                $common_requirements .= "- Add new facts or information not present in the extracted content\n";
                $common_requirements .= "- Create new examples or case studies not mentioned in the sources\n";
                $common_requirements .= "- Invent statistics, numbers, or data not found in the sources\n\n";
                $common_requirements .= "=== EXTRACTED CONTENT FROM SOURCES ===\n\n";
                
                // Add full extracted content (limit each to reasonable size but include key information)
                foreach ($urls_content as $idx => $content_item) {
                    $content_preview = $content_item['content'];
                    // Limit each source to 3000 chars to avoid token limits, but include as much as possible
                    if (strlen($content_preview) > 3000) {
                        $content_preview = mb_substr($content_preview, 0, 3000, 'UTF-8') . "\n... (content truncated, use the available portion)";
                    }
                    
                    $common_requirements .= "--- SOURCE " . ($idx + 1) . " ---\n";
                    $common_requirements .= "URL: " . $content_item['url'] . "\n";
                    $common_requirements .= "Title: " . $content_item['title'] . "\n";
                    $common_requirements .= "Content:\n" . $content_preview . "\n\n";
                    $common_requirements .= "=== END OF SOURCE " . ($idx + 1) . " ===\n\n\n";
                }
                
                $common_requirements .= "Remember: Use ONLY the information from the sources above. Rewrite and reorganize it, but do not add new information.\n\n";
            } else {
                // This should never happen due to validation, but add safety check
                $common_requirements .= "\nERROR: No extracted content available. Article cannot be written without crawled content.\n";
                $common_requirements .= "The article writing process requires extracted content from Google search URLs.\n\n";
            }
            
            // Add article settings if provided
            if (!empty($target_audience)) {
                $common_requirements .= "\nTarget Audience: {$target_audience}\n";
                $common_requirements .= "IMPORTANT: Write this article specifically for {$target_audience}. Tailor the content, examples, and language to resonate with this audience.\n";
            }
            
            if (!empty($tone)) {
                $tone_descriptions = array(
                    'professional' => 'professional, authoritative, and business-like',
                    'friendly' => 'friendly, warm, and approachable',
                    'humorous' => 'humorous, light-hearted, and entertaining',
                    'formal' => 'formal, respectful, and traditional',
                    'casual' => 'casual, relaxed, and conversational',
                    'authoritative' => 'authoritative, expert, and confident',
                    'conversational' => 'conversational, engaging, and personable'
                );
                $tone_desc = isset($tone_descriptions[$tone]) ? $tone_descriptions[$tone] : $tone;
                $common_requirements .= "\nTone: Write in a {$tone_desc} tone throughout the article.\n";
            }
            
            if (!empty($length_type)) {
                $length_instructions = array(
                    'short-form' => 'Keep the article concise and to the point (500-800 words). Focus on key information without extensive detail.',
                    'long-form' => 'Write a comprehensive, detailed article (2000+ words). Include in-depth explanations, examples, and thorough coverage of the topic.',
                    'comparison' => 'Structure the article as a comparison. Compare different options, approaches, or solutions with clear pros and cons.'
                );
                if (isset($length_instructions[$length_type])) {
                    $common_requirements .= "\nLength Type: {$length_instructions[$length_type]}\n";
                }
            }
            
            if (!empty($competitors)) {
                $common_requirements .= "\nCompetitor Analysis:\n";
                $common_requirements .= "The following are top competitor articles on similar topics:\n";
                foreach ($competitors as $index => $competitor_url) {
                    $common_requirements .= ($index + 1) . ". {$competitor_url}\n";
                }
                $common_requirements .= "IMPORTANT: Analyze these competitor articles and create content that is:\n";
                $common_requirements .= "- More comprehensive and valuable\n";
                $common_requirements .= "- Better structured and easier to read\n";
                $common_requirements .= "- More up-to-date and accurate\n";
                $common_requirements .= "- Unique in perspective and approach\n";
            }
            
            if (!empty($brand_voice_rules)) {
                $common_requirements .= "\nBrand Voice Rules:\n";
                $common_requirements .= "Follow these brand voice guidelines when writing:\n";
                $common_requirements .= $brand_voice_rules . "\n";
                $common_requirements .= "IMPORTANT: Strictly adhere to these brand voice rules throughout the entire article.\n";
            }
            
            // Add internal linking requirements if related posts found
            if ($auto_internal_links && !empty($related_posts)) {
                $common_requirements .= $related_posts_info_for_prompt;
                $common_requirements .= "- Insert 3-5 internal links directly and naturally within the paragraphs of the article, using appropriate keywords in context. Do NOT place links on separate lines; links must be inside the main text, not as standalone items.\n";
                $common_requirements .= "- Each related post/link should appear only ONCE in the entire article. Do NOT insert the same link multiple times.\n";
                $common_requirements .= "- Use natural anchor text (not exact post titles) that fits the context and the keywords.\n";
                $common_requirements .= "- Don't over-link: maximum 1 link per 200 words.\n";
                $common_requirements .= "- Links should be contextually relevant to the surrounding paragraph and enhance the reader's experience.\n\n";
            }
            
            // Generate prompts for each section
            $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: {$direction_final}\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";
                }
                
                if (!empty($original_prompt) && $is_first_section) {
                    $section_prompt .= "\nAdditional: {$original_prompt}\n";
                }
                
                if ($is_first_section) {
                    $section_prompt .= "\nWrite the first section of the article now.";
                } else {
                    $section_prompt .= "\nYou will receive the previous section's ending to continue from. Write the next section.";
                }
                
                $section_prompts[] = array(
                    'section_name' => $section_name,
                    'section_index' => $i,
                    'prompt' => $section_prompt,
                    'is_first' => $is_first_section,
                    'is_last' => $is_last_section
                );
            }
            
            // Display all prompts
            $prompts_display = "Generated " . count($section_prompts) . " prompts for article sections:\n\n";
            foreach ($section_prompts as $idx => $sp) {
                $prompts_display .= "Section " . ($idx + 1) . ": {$sp['section_name']}\n";
            }
            $prompts_display .= "\n" . str_repeat("=", 50) . "\n\n";
            $prompts_display .= "First section prompt preview:\n\n";
            $prompts_display .= mb_substr($section_prompts[0]['prompt'], 0, 1000, 'UTF-8') . "...";
            
            $stream->send_step_output(6, $prompts_display);
            $stream->send_step_complete(6, 'success');
            
            // Step 7: Write Article
            $stream->send_step_start(7, 'write_article', 'Writing article...');
            $stream->send_status('Generating article content with AI...');
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Build system prompt for article writing
            // Prepare author information for system prompt
            $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));
                // Limit to reasonable length for system prompt
                $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";
            
            // Add author role information to system prompt
            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";
            
            // Add language requirement to system prompt
            $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;
                }
                
                // Check if marker exists in the text
                $marker_pos = strpos($text, $article_end_marker);
                if ($marker_pos !== false) {
                    // Extract content before the marker
                    $extracted = substr($text, 0, $marker_pos);
                    // Remove any trailing whitespace
                    $extracted = rtrim($extracted);
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    return $extracted;
                }
                
                // Marker not found, return original text
                return $text;
            };
            
            // Write article section by section
            $article_text = '';
            $previous_section_ending = '';
            
            // Check if section_prompts exists (from step 6)
            if (!isset($section_prompts) || empty($section_prompts)) {
                // Fallback: if section_prompts not available, use old method
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                // Create a basic prompt if section_prompts not available
                $fallback_prompt = $lang_instruction_final . "Write a complete article about: {$title}\n\n";
                $fallback_prompt .= "Requirements:\n";
                $fallback_prompt .= "- Language: {$lang}\n";
                $fallback_prompt .= "- Format: Markdown\n";
                $fallback_prompt .= "- Write directly, DO NOT introduce yourself.\n";
                
                // Add Google search results if available
                if (!empty($google_search_text)) {
                    $fallback_prompt .= "\nIMPORTANT: Use the following latest information from Google search:\n\n";
                    $fallback_prompt .= $google_search_text . "\n\n";
                }
                
                $article_content = $generate_with_agent($fallback_prompt, $lang, $model, $provider_id, array(
                    'max_tokens' => 4000,
                    'temperature' => 0.8,
                    'use_case' => 'long_context',
                    'system' => $system_prompt
                ));
                
                if (is_array($article_content) && isset($article_content['code']) && $article_content['code'] != '200') {
                    $stream->send_error($article_content['msg'] ?: 'Failed to generate article');
                    $stream->close();
                    return;
                }
                
                $article_text = is_array($article_content) ? ($article_content['result'] ?? '') : $article_content;
                $article_text = $extract_article_content($article_text);
            } else {
                // Write section by section using section_prompts
                $total_sections = count($section_prompts);
                
                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) {
                    }
                    
                    $stream->send_status('Writing section ' . ($section_idx + 1) . ' of ' . $total_sections . ': ' . $section_name . '...');
                    
                    // If not first section, add previous section ending to prompt
                    if (!$is_first && !empty($previous_section_ending)) {
                        // Get last 1500 characters of previous section for context
                        $context_ending = mb_substr($previous_section_ending, -1500);
                        
                        // Modify prompt to include previous section ending
                        $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) {
                        }
                        $stream->send_error($error_msg);
                        // Continue with next section or break
                        if ($is_last) {
                            break;
                        }
                        continue;
                    }
                    
                    $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG && isset($section_content['provider'])) {
                    }
                    
                    // Extract content up to the end marker (if marker exists in last section)
                    if ($is_last) {
                        $section_text = $extract_article_content($section_text);
                    }
                    
                    // Check if this section has a main heading (h2/h3) in markdown and search for image BEFORE adding to article_text
                    if (!empty($section_text)) {
                        $section_has_main_heading = false;
                        $main_heading_title = '';
                        $main_heading_markdown_pos = -1;
                        
                        // Check for h2 heading in markdown (## heading)
                        if (preg_match('/^##\s+(.+)$/m', $section_text, $h2_match, PREG_OFFSET_CAPTURE)) {
                            $section_has_main_heading = true;
                            $main_heading_title = trim($h2_match[1][0]);
                            $main_heading_markdown_pos = $h2_match[0][1] + strlen($h2_match[0][0]);
                        } elseif (preg_match('/^###\s+(.+)$/m', $section_text, $h3_match, PREG_OFFSET_CAPTURE)) {
                            // Fallback to h3 if no h2
                            $section_has_main_heading = true;
                            $main_heading_title = trim($h3_match[1][0]);
                            $main_heading_markdown_pos = $h3_match[0][1] + strlen($h3_match[0][0]);
                        }
                        
                        // If section has main heading, search and insert image into markdown
                        if ($section_has_main_heading && !empty($main_heading_title) && strlen($main_heading_title) > 3) {
                            $stream->send_status('Đang tìm hình ảnh cho section: ' . $main_heading_title . '...');
                            
                            // Get section content for better search query
                            $section_content_plain = strip_tags($section_text);
                            $section_content_plain = mb_substr($section_content_plain, 0, 500, 'UTF-8');
                            
                            // Generate search query using AI
                            $image_search_query = $main_heading_title;
                            
                            if (!empty($section_content_plain) && strlen($section_content_plain) > 20) {
                                $query_prompt = $get_language_instruction($lang);
                                $query_prompt .= "Tạo một từ khóa tìm kiếm hình ảnh ngắn gọn (3-5 từ) phù hợp với section sau:\n\n";
                                $query_prompt .= "Tiêu đề section: {$main_heading_title}\n";
                                $query_prompt .= "Nội dung section: " . mb_substr($section_content_plain, 0, 300, 'UTF-8') . "\n\n";
                                $query_prompt .= "Yêu cầu:\n";
                                $query_prompt .= "- Chỉ trả về từ khóa tìm kiếm, không có giải thích\n";
                                $query_prompt .= "- Từ khóa phải phù hợp để tìm hình ảnh minh họa\n";
                                $query_prompt .= "- Tối đa 5 từ\n\n";
                                $query_prompt .= "Chỉ trả về từ khóa tìm kiếm:";
                                
                                $query_result = $generate_with_agent($query_prompt, $lang, $model, $provider_id, array(
                                    'max_tokens' => 50,
                                    'temperature' => 0.7,
                                    'use_case' => 'fast'
                                ));
                                
                                if (is_array($query_result) && isset($query_result['code']) && $query_result['code'] == '200') {
                                    $generated_query = is_array($query_result) ? trim($query_result['result'] ?? '') : trim($query_result);
                                    $generated_query = strip_tags($generated_query);
                                    $generated_query = preg_replace('/["\']/', '', $generated_query);
                                    if (!empty($generated_query) && strlen($generated_query) > 3) {
                                        $image_search_query = $generated_query;
                                    }
                                }
                            }
                            
                            // Search for image
                            try {
                                $image_results = $bardGenContent->searchimg($image_search_query);
                                
                                // Handle both cases: direct array or object with 'result' key
                                $image_array = null;
                                if (is_array($image_results) && !empty($image_results)) {
                                    // Direct array case (sendPostRequest returns $decoded->result)
                                    $image_array = $image_results;
                                } elseif (is_object($image_results) && isset($image_results->result) && is_array($image_results->result) && !empty($image_results->result)) {
                                    // Object with 'result' key case
                                    $image_array = $image_results->result;
                                } elseif (isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) {
                                    // Array with 'result' key case
                                    $image_array = $image_results['result'];
                                }
                                
                                if ($image_array && !empty($image_array)) {
                                    $selected_image = $image_array[0];
                                    
                                    // Create image markdown format
                                    $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n";
                                    
                                    // Insert image after heading in section_text (markdown)
                                    $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0);
                                    
                                    $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title);
                                    
                                    // Stream section content immediately after inserting image (especially for section 1)
                                    if ($is_first || $section_idx === 0) {
                                        $section_html = $convert_markdown_to_html($section_text);
                                        if (!empty($section_html)) {
                                            $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                                            $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                                            $section_footer = '</div>';
                                            $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                                        }
                                    }
                                    
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                } else {
                                    // Fallback: try with section title only
                                    if ($image_search_query !== $main_heading_title) {
                                        $image_results = $bardGenContent->searchimg($main_heading_title);
                                        if ($image_results && isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) {
                                            $selected_image = $image_results['result'][0];
                                            $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n";
                                            $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0);
                                            
                                            $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title);
                                            
                                            // Stream section content immediately after inserting image (especially for section 1)
                                            if ($is_first || $section_idx === 0) {
                                                $section_html = $convert_markdown_to_html($section_text);
                                                if (!empty($section_html)) {
                                                    $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                                                    $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                                                    $section_footer = '</div>';
                                                    $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception $img_ex) {
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                            }
                            
                            // Small delay
                            usleep(300000); // 0.3 second delay
                        }
                        
                        // If not first section, add a newline for separation
                        if (!empty($article_text)) {
                            $article_text .= "\n\n";
                        }
                        // Append section_text (which now includes image if found) to article_text
                        $article_text .= $section_text;
                        
                        // Store the ending of this section for next iteration
                        // Take last 2000 characters for context
                        $previous_section_ending = mb_substr($section_text, -2000);
                        
                        // Convert section to HTML and display the entire section at once
                        $section_html = $convert_markdown_to_html($section_text);
                        if (!empty($section_html)) {
                            // Add section header for clarity
                            $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                            $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                            $section_footer = '</div>';
                            
                            // Send the complete section at once (with image if found)
                            $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                        }
                    }
                    
                    // 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;
                    }
                }
            }
            
            // Convert final article to HTML (for final output)
            $article_text = $convert_markdown_to_html($article_text);
            
            $stream->send_step_complete(7, 'success', array('content' => $article_text));
            
            // Update AI_post_usage counter
            $this->aiautotool_update_ai_post_usage();
            
            // Send completion
            $stream->send_complete($article_text, array(
                'google_search_results' => $google_search_results,
                'checklist' => $checklist_text,
                'author_credibility' => $author_credibility_text,
                'keywords_analysis' => $keywords_analysis_text,
                'direction_analysis' => $direction_analysis_text,
                'final_prompt' => $final_prompt,
                'article' => $article_text,
                'related_posts' => $related_posts
            ), $message_id);
            
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            if (!$stream) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
            }
            
            $stream->send_error($error_msg, array(
                'exception' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ), $message_id);
        } catch (Error $e) {
            $error_msg = 'Fatal Error: ' . $e->getMessage();
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            if (!isset($stream) || !$stream) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
            }
            
            $stream->send_error($error_msg, array(
                'exception' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ), $message_id);
        }
        
        if (isset($stream) && $stream) {
            $stream->close();
        } else {
            exit;
        }
    }
    
    public function aiautotool_write_article_with_analysis_callback() {
        // Verify nonce for AJAX requests
        if (defined('DOING_AJAX') && DOING_AJAX) {
            if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) {
                // For SSE, we need to send error via stream
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Security check failed. Please refresh the page and try again.');
                $stream->close();
                return;
            }
            
            if (!current_user_can('edit_posts')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Permission denied');
                $stream->close();
                return;
            }
        }
        
        // Check if user has active Pro license or trial access.
        if (!function_exists('aiautotool_can_use_pro_features') || !aiautotool_can_use_pro_features()) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('This feature requires a Pro account. Please upgrade to Pro to use this feature.');
            $stream->close();
            return;
        }
        
        // Load rendersetting class if not already loaded
        if (!class_exists('rendersetting')) {
            $rendersetting_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/setting.php';
            if (file_exists($rendersetting_file)) {
                require_once $rendersetting_file;
            }
        }
        
        // Get data from POST
        $data = array();
        if (isset($_POST['data']) && is_string($_POST['data'])) {
            $data = json_decode(stripslashes($_POST['data']), true);
        } else {
            $raw_data = file_get_contents('php://input');
            $data = json_decode($raw_data, true);
        }
        
        if (!$data || !is_array($data)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Invalid JSON data');
            $stream->close();
            return;
        }
        
        // Extract parameters
        $title = isset($data['title']) ? sanitize_text_field($data['title']) : '';
        $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese';
        $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection(
            isset($data['model']) ? $data['model'] : '',
            isset($data['provider_id']) ? $data['provider_id'] : ''
        );
        $model = $resolved_ai_selection['model'];
        $provider_id = $resolved_ai_selection['provider_id'];
        $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : '';
        
        // Extract article settings
        $target_audience = isset($data['targetAudience']) ? sanitize_text_field($data['targetAudience']) : '';
        $tone = isset($data['tone']) ? sanitize_text_field($data['tone']) : '';
        $length_type = isset($data['lengthType']) ? sanitize_text_field($data['lengthType']) : '';
        $competitors = isset($data['competitors']) && is_array($data['competitors']) 
            ? array_map('esc_url_raw', array_filter($data['competitors'])) 
            : array();
        $brand_voice_rules = isset($data['brandVoiceRules']) ? sanitize_textarea_field($data['brandVoiceRules']) : '';
        
        if (empty($title)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Title parameter is required');
            $stream->close();
            return;
        }
        
        // Load SSE Stream class
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
        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(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php')) {
            require_once plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php';
        }
        
        // Initialize BardGenContent for fallback
        $bardGenContent = new BardGenContent();
        
        // 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) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                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();
                $html = $parsedown->text($text);
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                return $html;
            }
            
            // 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')) {
                    $html = markdown($text);
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    return $html;
                }
            }
            
            // Fallback to simple inline parser (inline implementation)
            // Convert headers (h1-h6)
            $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);
            
            // Convert code blocks (```code```)
            $html = preg_replace_callback('/```([\s\S]*?)```/m', function($matches) {
                return '<pre><code>' . esc_html(trim($matches[1])) . '</code></pre>';
            }, $html);
            
            // Convert inline code (`code`)
            $html = preg_replace('/`([^`]+)`/', '<code>$1</code>', $html);
            
            // Convert bold (**text** or __text__)
            $html = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $html);
            $html = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $html);
            
            // Convert italic (*text* or _text_)
            $html = preg_replace('/(?<!\*)\*([^*]+?)\*(?!\*)/', '<em>$1</em>', $html);
            $html = preg_replace('/(?<!_)_([^_]+?)_(?!_)/', '<em>$1</em>', $html);
            
            // Convert links [text](url)
            $html = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2" target="_blank" rel="nofollow">$1</a>', $html);
            
            // Convert images ![alt](url)
            $html = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '<img src="$2" alt="$1" style="max-width:100%;height:auto;" />', $html);
            
            // Convert blockquotes (> text)
            $html = preg_replace('/^>\s+(.+)$/m', '<blockquote>$1</blockquote>', $html);
            
            // Convert unordered lists (- item or * item)
            $html = preg_replace('/^[\-\*]\s+(.+)$/m', '<li>$1</li>', $html);
            $html = preg_replace('/(<li>.*<\/li>\n?)+/s', '<ul>$0</ul>', $html);
            
            // Convert ordered lists (1. item)
            $html = preg_replace('/^\d+\.\s+(.+)$/m', '<li>$1</li>', $html);
            
            // Convert line breaks (double newline = paragraph break)
            $html = preg_replace('/\n\n+/', '</p><p>', $html);
            $html = '<p>' . $html . '</p>';
            
            // Clean up empty paragraphs
            $html = preg_replace('/<p>\s*<\/p>/', '', $html);
            $html = preg_replace('/<p>(<[^>]+>)/', '$1<p>', $html);
            $html = preg_replace('/(<\/[^>]+>)<\/p>/', '$1', $html);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            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'; // Checklist is a simple task
                } elseif (stripos($prompt_lower, 'phân tích') !== false || stripos($prompt_lower, 'analyze') !== false) {
                    $use_case = 'reasoning'; // Analysis requires reasoning
                } elseif (strlen($prompt) > 2000) {
                    $use_case = 'long_context'; // Long prompts need long context models
                }
                
                // 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']
                    );
                } else {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
            
            // 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 = '';
            
            // Check for Vietnamese (more specific patterns first)
            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";
            } 
            // Check for English
            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";
            } 
            // For other languages
            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;
        };
        
        // Helper function to find related posts for internal linking
        $find_related_posts_for_internal_linking = function($title, $keywords_text, $lang, $article_text = '', $limit = 5) {
            $related_posts = array();
            
            // Extract main keywords from keywords analysis
            $keywords_summary = mb_substr(strip_tags($keywords_text), 0, 200, 'UTF-8');
            $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary));
            
            // Extract keywords array (first 3-5 keywords)
            $keywords_array = array();
            $lines = explode("\n", $keywords_text);
            foreach ($lines as $line) {
                $line = trim(strip_tags($line));
                if (!empty($line) && strlen($line) > 3) {
                    // Remove numbering and bullets
                    $line = preg_replace('/^[\d\-\*\.\s]+/', '', $line);
                    if (!empty($line)) {
                        $keywords_array[] = $line;
                        if (count($keywords_array) >= 5) break;
                    }
                }
            }
            
            // If no keywords extracted, use title words
            if (empty($keywords_array)) {
                $title_words = explode(' ', $title);
                $keywords_array = array_slice($title_words, 0, 3);
            }
            
            // Build search query from keywords
            $search_query = implode(' ', array_slice($keywords_array, 0, 3));
            
            // Find posts by keywords (search)
            $args_by_keywords = array(
                'post_type' => 'post',
                'posts_per_page' => $limit * 2, // Get more to filter later
                'post_status' => 'publish',
                's' => $search_query,
                'orderby' => 'relevance',
                'order' => 'DESC',
            );
            
            // Add language filter if Polylang is active
            if (function_exists('pll_get_post_language')) {
                $args_by_keywords['lang'] = $lang;
            }
            
            $query_by_keywords = new WP_Query($args_by_keywords);
            
            if ($query_by_keywords->have_posts()) {
                while ($query_by_keywords->have_posts()) {
                    $query_by_keywords->the_post();
                    $post_id = get_the_ID();
                    $post_title = get_the_title();
                    $post_url = get_permalink();
                    $post_excerpt = get_the_excerpt();
                    
                    // Calculate relevance score (simple: based on keyword matches)
                    $relevance_score = 0;
                    $title_lower = mb_strtolower($title, 'UTF-8');
                    $post_title_lower = mb_strtolower($post_title, 'UTF-8');
                    
                    foreach ($keywords_array as $keyword) {
                        $keyword_lower = mb_strtolower($keyword, 'UTF-8');
                        if (mb_strpos($post_title_lower, $keyword_lower) !== false) {
                            $relevance_score += 3;
                        }
                        if (mb_strpos($post_excerpt, $keyword_lower) !== false) {
                            $relevance_score += 1;
                        }
                    }
                    
                    // Check title similarity
                    similar_text($title_lower, $post_title_lower, $similarity);
                    $relevance_score += $similarity / 10;
                    
                    $related_posts[] = array(
                        'id' => $post_id,
                        'title' => $post_title,
                        'url' => $post_url,
                        'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'),
                        'relevance_score' => $relevance_score
                    );
                }
                wp_reset_postdata();
            }
            
            // Also find by tags if available (tags are more flexible than categories)
            // Try to find posts with similar tags based on keywords
            if (!empty($keywords_array)) {
                $tag_names = array_slice($keywords_array, 0, 3); // Use first 3 keywords as potential tags
                
                $args_by_tags = array(
                    'post_type' => 'post',
                    'posts_per_page' => $limit,
                    'post_status' => 'publish',
                    'tag_slug__in' => array_map(function($tag) {
                        return sanitize_title($tag);
                    }, $tag_names),
                    'orderby' => 'date',
                    'order' => 'DESC',
                );
                
                if (function_exists('pll_get_post_language')) {
                    $args_by_tags['lang'] = $lang;
                }
                
                $query_by_tags = new WP_Query($args_by_tags);
                
                if ($query_by_tags->have_posts()) {
                    while ($query_by_tags->have_posts()) {
                        $query_by_tags->the_post();
                        $post_id = get_the_ID();
                        $post_title = get_the_title();
                        $post_url = get_permalink();
                        $post_excerpt = get_the_excerpt();
                        
                        // Check if already in related_posts
                        $exists = false;
                        foreach ($related_posts as $existing) {
                            if ($existing['id'] == $post_id) {
                                $exists = true;
                                break;
                            }
                        }
                        
                        if (!$exists) {
                            $relevance_score = 2; // Lower score for tag matches
                            $related_posts[] = array(
                                'id' => $post_id,
                                'title' => $post_title,
                                'url' => $post_url,
                                'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'),
                                'relevance_score' => $relevance_score
                            );
                        }
                    }
                    wp_reset_postdata();
                }
            }
            
            // Sort by relevance score and limit
            usort($related_posts, function($a, $b) {
                return $b['relevance_score'] <=> $a['relevance_score'];
            });
            
            return array_slice($related_posts, 0, $limit);
        };
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        $stream = new AIAutoTool_SSE_Stream();
        $stream->start();
        if (!empty($message_id)) {
            $stream->set_message_id($message_id);
        }
        
        try {
            
            
            // Step 1: Generate Checklist
            $stream->send_step_start(1, 'generate_checklist', 'Generating checklist...');
            
            // Get website information
            $site_name = get_bloginfo('name');
            $site_url = home_url();
            
            // Get author information
            $current_user = wp_get_current_user();
            $author_name = $current_user->display_name;
            $author_bio = get_user_meta($current_user->ID, 'description', true);
            
            $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";
            }
            
            // Step 1: Generate Checklist - Sử dụng AI Agent với tự động fallback
            $checklist_text = '';
            
            // Lấy provider_id từ settings nếu không có trong request
            if (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();
                }
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $stream->send_error($checklist_result['msg'] ?: 'Failed to generate checklist');
                $stream->close();
                return;
            }
            
            $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result;
            
            if (defined('WP_DEBUG') && WP_DEBUG && isset($checklist_result['provider'])) {
            }
            
            // Convert markdown to HTML
            $checklist_text = $convert_markdown_to_html($checklist_text);
            
            $stream->send_step_output(1, $checklist_text);
            $stream->send_step_complete(1, 'success');
            
            // Step 2: Generate Author Credibility Info - Sử dụng AI Agent
            $stream->send_step_start(2, 'generate_author_credibility', 'Generating author credibility information...');
            
            $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";
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $stream->send_error($author_credibility_result['msg'] ?: 'Failed to generate author credibility info');
                $stream->close();
                return;
            }
            
            $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result;
            
            // Convert markdown to HTML
            $author_credibility_text = $convert_markdown_to_html($author_credibility_text);
            
            $stream->send_step_output(2, $author_credibility_text);
            $stream->send_step_complete(2, 'success');
            
            // Step 3: Analyze Keywords
            $stream->send_step_start(3, 'analyze_keywords', 'Analyzing required keywords...');
            
            // Tối ưu hóa prompt: giới hạn độ dài và làm sạch text
            $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');
            
            // Làm sạch và rút gọn text
            $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";
            
            // Log prompt length for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $error_msg = $keywords_analysis['msg'] ?: 'Failed to analyze keywords';
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                $stream->send_error('Step 3 - Keywords analysis failed: ' . $error_msg . ' (Error code: ' . (isset($keywords_analysis['code']) ? $keywords_analysis['code'] : 'N/A') . ')');
                $stream->close();
                return;
            }
            
            $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis;
            
            // Convert markdown to HTML
            $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text);
            
            $stream->send_step_output(3, $keywords_analysis_text);
            $stream->send_step_complete(3, 'success');
            
            // Step 4: Determine Content Direction
            $stream->send_step_start(4, 'determine_direction', 'Determining article content direction...');
            
            // Tối ưu hóa prompt: giới hạn độ dài các phân tích
            $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 200, 'UTF-8');
            $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 200, 'UTF-8');
            $keywords_summary = mb_substr(strip_tags($keywords_analysis_text), 0, 300, 'UTF-8');
            
            // Làm sạch text
            $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary));
            $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary));
            $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary));
            
            $direction_prompt = $get_language_instruction($lang);
            $direction_prompt .= "Title: {$title}\n\n";
            $direction_prompt .= "Analysis summary:\n";
            $direction_prompt .= "- Checklist: {$checklist_summary}\n";
            $direction_prompt .= "- Author credibility information: {$author_credibility_summary}\n";
            $direction_prompt .= "- Keywords: {$keywords_summary}\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";
            
            // Log prompt length for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            $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') {
                $stream->send_error($direction_analysis['msg'] ?: 'Failed to determine content direction');
                $stream->close();
                return;
            }
            
            $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis;
            
            // Convert markdown to HTML
            $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text);
            
            $stream->send_step_output(4, $direction_analysis_text);
            $stream->send_step_complete(4, 'success');
            
            // Step 5: Find Related Posts & Internal Linking Strategy (moved before writing article)
            // Check if auto internal links is enabled
            $auto_internal_links = isset($data['autoInternalLinks']) 
                ? filter_var($data['autoInternalLinks'], FILTER_VALIDATE_BOOLEAN) 
                : true; // Default to true if not set
            
            $related_posts = array();
            
            if ($auto_internal_links) {
                $stream->send_step_start(5, 'find_related_posts', 'Finding related posts for internal linking...');
                
                // Find related posts (before writing article, so we can include them in the prompt)
                $related_posts = $find_related_posts_for_internal_linking($title, $keywords_analysis_text, $lang, '', 5);
            }
            
            $related_posts_info_for_prompt = '';
            $related_posts_display = '';
            
            if ($auto_internal_links && !empty($related_posts)) {
                // Prepare related posts information for prompt
                $related_posts_info_for_prompt = "\n\nRelated Posts for Internal Linking:\n";
                foreach ($related_posts as $index => $post) {
                    $related_posts_info_for_prompt .= ($index + 1) . ". Title: {$post['title']}\n";
                    $related_posts_info_for_prompt .= "   URL: {$post['url']}\n";
                    $related_posts_info_for_prompt .= "   Excerpt: {$post['excerpt']}\n";
                    $related_posts_info_for_prompt .= "   Relevance: " . round($post['relevance_score'], 2) . "\n\n";
                }
                $related_posts_info_for_prompt .= "IMPORTANT: Naturally insert internal links to these related posts in your article where relevant. Use markdown format: [anchor text](url). Make sure links are contextual and add value to readers.\n";
                
                // Prepare for display
                $related_posts_display = "<h3>Related Posts Found for Internal Linking:</h3>\n<ul>\n";
                foreach ($related_posts as $post) {
                    $related_posts_display .= "<li><a href=\"{$post['url']}\" target=\"_blank\">{$post['title']}</a> (Relevance: " . round($post['relevance_score'], 2) . ")</li>\n";
                }
                $related_posts_display .= "</ul>\n<p><strong>These related posts will be included in the writing prompt so AI can naturally insert internal links while writing the article.</strong></p>";
            } elseif ($auto_internal_links && empty($related_posts)) {
                $related_posts_display = "<p>No related posts found for internal linking. This might be because:</p><ul><li>This is one of the first posts on the site</li><li>No posts match the keywords or categories</li><li>Try adding more content to enable internal linking</li></ul>";
            } else {
                $related_posts_display = "<p><strong>Auto Internal Links is disabled.</strong> Internal links will not be automatically inserted.</p>";
            }
            
            if ($auto_internal_links) {
                $stream->send_step_output(5, $related_posts_display);
                $stream->send_step_complete(5, 'success');
            } else {
                // Skip step 5 if auto internal links is disabled
                $stream->send_step_start(5, 'find_related_posts', 'Auto Internal Links is disabled...');
                $stream->send_step_output(5, $related_posts_display);
                $stream->send_step_complete(5, 'success');
            }
            
            // Step 6: Generate Multiple Prompts (one for each section from step 1)
            $stream->send_step_start(6, 'generate_prompt', 'Generating optimized prompts for AI...');
            
            // Define article end marker (used in both step 6 and step 7)
            $article_end_marker = "<!--ARTICLE_COMPLETE_END-->";
            
            // Get the original prompt template if available
            $original_prompt = '';
            if (isset($data['original_prompt']) && !empty($data['original_prompt'])) {
                $original_prompt = mb_substr(strip_tags($data['original_prompt']), 0, 500, 'UTF-8');
            }
            
            // Parse checklist to extract required sections
            $article_sections = array();
            $checklist_json = null;
            
            // Try to extract JSON from checklist_text
            $checklist_plain = strip_tags($checklist_text);
            // Try to find JSON in the text
            if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) {
                // Try to find full JSON structure
                $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 JSON parsing failed, try to extract sections from text
            if (!$checklist_json || !isset($checklist_json['content_to_provide']['required_sections'])) {
                // Fallback: try to extract sections from text format
                if (preg_match('/required_sections["\']?\s*:\s*\[(.*?)\]/s', $checklist_plain, $sections_match)) {
                    $sections_text = $sections_match[1];
                    // Try to extract quoted strings
                    preg_match_all('/["\']([^"\']+)["\']/', $sections_text, $section_matches);
                    if (!empty($section_matches[1])) {
                        $article_sections = $section_matches[1];
                    }
                }
                
                // If still no sections, create default sections based on direction analysis
                if (empty($article_sections)) {
                    // Create default sections: Introduction, Main Content, Conclusion
                    $article_sections = array('Introduction', 'Main Content', 'Conclusion');
                }
            } else {
                // Extract sections from JSON
                $article_sections = $checklist_json['content_to_provide']['required_sections'];
                if (empty($article_sections) || !is_array($article_sections)) {
                    $article_sections = array('Introduction', 'Main Content', 'Conclusion');
                }
            }
            
            // Ensure we have at least one section
            if (empty($article_sections)) {
                $article_sections = array('Introduction', 'Main Content', 'Conclusion');
            }
            
            // Tối ưu hóa final prompt: giới hạn độ dài các phân tích
            $checklist_final = mb_substr(strip_tags($checklist_text), 0, 300, 'UTF-8');
            $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 300, 'UTF-8');
            $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 400, 'UTF-8');
            $direction_final = mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8');
            
            // Làm sạch text
            $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_final = preg_replace('/\s+/', ' ', trim($direction_final));
            
            // Add language instruction to final prompt FIRST
            $lang_instruction_final = $get_language_instruction($lang);
            
            // Build common requirements that will be used in all section prompts
            $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";
            
            // Add article settings if provided
            if (!empty($target_audience)) {
                $common_requirements .= "\nTarget Audience: {$target_audience}\n";
                $common_requirements .= "IMPORTANT: Write this article specifically for {$target_audience}. Tailor the content, examples, and language to resonate with this audience.\n";
            }
            
            if (!empty($tone)) {
                $tone_descriptions = array(
                    'professional' => 'professional, authoritative, and business-like',
                    'friendly' => 'friendly, warm, and approachable',
                    'humorous' => 'humorous, light-hearted, and entertaining',
                    'formal' => 'formal, respectful, and traditional',
                    'casual' => 'casual, relaxed, and conversational',
                    'authoritative' => 'authoritative, expert, and confident',
                    'conversational' => 'conversational, engaging, and personable'
                );
                $tone_desc = isset($tone_descriptions[$tone]) ? $tone_descriptions[$tone] : $tone;
                $common_requirements .= "\nTone: Write in a {$tone_desc} tone throughout the article.\n";
            }
            
            if (!empty($length_type)) {
                $length_instructions = array(
                    'short-form' => 'Keep the article concise and to the point (500-800 words). Focus on key information without extensive detail.',
                    'long-form' => 'Write a comprehensive, detailed article (2000+ words). Include in-depth explanations, examples, and thorough coverage of the topic.',
                    'comparison' => 'Structure the article as a comparison. Compare different options, approaches, or solutions with clear pros and cons.'
                );
                if (isset($length_instructions[$length_type])) {
                    $common_requirements .= "\nLength Type: {$length_instructions[$length_type]}\n";
                }
            }
            
            if (!empty($competitors)) {
                $common_requirements .= "\nCompetitor Analysis:\n";
                $common_requirements .= "The following are top competitor articles on similar topics:\n";
                foreach ($competitors as $index => $competitor_url) {
                    $common_requirements .= ($index + 1) . ". {$competitor_url}\n";
                }
                $common_requirements .= "IMPORTANT: Analyze these competitor articles and create content that is:\n";
                $common_requirements .= "- More comprehensive and valuable\n";
                $common_requirements .= "- Better structured and easier to read\n";
                $common_requirements .= "- More up-to-date and accurate\n";
                $common_requirements .= "- Unique in perspective and approach\n";
            }
            
            if (!empty($brand_voice_rules)) {
                $common_requirements .= "\nBrand Voice Rules:\n";
                $common_requirements .= "Follow these brand voice guidelines when writing:\n";
                $common_requirements .= $brand_voice_rules . "\n";
                $common_requirements .= "IMPORTANT: Strictly adhere to these brand voice rules throughout the entire article.\n";
            }
            
            // Add internal linking requirements if related posts found
            if ($auto_internal_links && !empty($related_posts)) {
                $common_requirements .= $related_posts_info_for_prompt;
                $common_requirements .= "- Insert 3-5 internal links directly and naturally within the paragraphs of the article, using appropriate keywords in context. Do NOT place links on separate lines; links must be inside the main text, not as standalone items.\n";
                $common_requirements .= "- Each related post/link should appear only ONCE in the entire article. Do NOT insert the same link multiple times.\n";
                $common_requirements .= "- Use natural anchor text (not exact post titles) that fits the context and the keywords.\n";
                $common_requirements .= "- Don't over-link: maximum 1 link per 200 words.\n";
                $common_requirements .= "- Links should be contextually relevant to the surrounding paragraph and enhance the reader's experience.\n\n";
            }
            
            // Generate prompts for each section
            $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: {$direction_final}\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";
                }
                
                if (!empty($original_prompt) && $is_first_section) {
                    $section_prompt .= "\nAdditional: {$original_prompt}\n";
                }
                
                if ($is_first_section) {
                    $section_prompt .= "\nWrite the first section of the article now.";
                } else {
                    $section_prompt .= "\nYou will receive the previous section's ending to continue from. Write the next section.";
                }
                
                $section_prompts[] = array(
                    'section_name' => $section_name,
                    'section_index' => $i,
                    'prompt' => $section_prompt,
                    'is_first' => $is_first_section,
                    'is_last' => $is_last_section
                );
            }
            
            // Display all prompts
            $prompts_display = "Generated " . count($section_prompts) . " prompts for article sections:\n\n";
            foreach ($section_prompts as $idx => $sp) {
                $prompts_display .= "Section " . ($idx + 1) . ": {$sp['section_name']}\n";
            }
            $prompts_display .= "\n" . str_repeat("=", 50) . "\n\n";
            $prompts_display .= "First section prompt preview:\n\n";
            $prompts_display .= mb_substr($section_prompts[0]['prompt'], 0, 1000, 'UTF-8') . "...";
            
            $stream->send_step_output(6, $prompts_display);
            $stream->send_step_complete(6, 'success');
            
            // Step 7: Write Article
            $stream->send_step_start(7, 'write_article', 'Writing article...');
            $stream->send_status('Generating article content with AI...');
            
            // Log final prompt length before writing article
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Build system prompt for article writing
            // Prepare author information for system prompt
            $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));
                // Limit to reasonable length for system prompt
                $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";
            
            // Add author role information to system prompt
            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";
            
            // Add language requirement to system prompt
            $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;
                }
                
                // Check if marker exists in the text
                $marker_pos = strpos($text, $article_end_marker);
                if ($marker_pos !== false) {
                    // Extract content before the marker
                    $extracted = substr($text, 0, $marker_pos);
                    // Remove any trailing whitespace
                    $extracted = rtrim($extracted);
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    return $extracted;
                }
                
                // Marker not found, return original text
                return $text;
            };
            
            // Helper function to check if article is incomplete
            $is_article_incomplete = function($text, $length_type) use (&$article_end_marker) {
                if (empty($text)) {
                    return true;
                }
                
                // First check: if marker exists, article is complete
                if (strpos($text, $article_end_marker) !== false) {
                    return false; // Article is complete (has marker)
                }
                
                // Remove HTML tags for accurate length checking
                $plain_text = strip_tags($text);
                $plain_text = preg_replace('/\s+/', ' ', $plain_text); // Normalize whitespace
                $char_count = mb_strlen($plain_text);
                
                // For long-form articles, check character/word count - MUST be at least 2000 words
                if ($length_type === 'long-form') {
                    // Estimate word count: approximately 5 characters per word (works for most languages)
                    $estimated_words = $char_count / 5;
                    // Long-form articles MUST be at least 2000 words (approximately 10000 characters)
                    // If less than 2000 words, article is definitely incomplete
                    if ($char_count < 10000 || $estimated_words < 2000) {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        return true; // Must continue writing
                    }
                }
                
                // Check if article ends abruptly (no conclusion, ends mid-sentence)
                $text_trimmed = trim($plain_text);
                if (empty($text_trimmed)) {
                    return true;
                }
                
                $last_chars = mb_substr($text_trimmed, -10); // Last 10 characters
                $last_sentence = mb_substr($text_trimmed, -200); // Last 200 characters for context
                
                // Check for proper ending punctuation
                $proper_endings = array('.', '!', '?', '。', '！', '？', '…');
                $ends_properly = false;
                foreach ($proper_endings as $ending) {
                    if (mb_substr($text_trimmed, -1) === $ending) {
                        $ends_properly = true;
                        break;
                    }
                }
                
                // Check for conclusion keywords
                $conclusion_keywords = array(
                    'kết luận', 'conclusion', 'tóm lại', 'tổng kết', 'summary', 'tổng hợp',
                    'tổng kết lại', 'kết luận lại', 'tóm tắt', 'tổng hợp lại'
                );
                $has_conclusion = false;
                $last_sentence_lower = mb_strtolower($last_sentence);
                foreach ($conclusion_keywords as $keyword) {
                    if (mb_stripos($last_sentence_lower, $keyword) !== false) {
                        $has_conclusion = true;
                        break;
                    }
                }
                
                // For long-form articles: if doesn't end properly and no conclusion, likely incomplete
                if ($length_type === 'long-form') {
                    // Even if ends properly, if no conclusion section, might be incomplete
                    if (!$has_conclusion && $char_count < 12000) {
                        // If less than 12000 chars and no conclusion, likely incomplete
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        return true;
                    }
                    // If doesn't end properly, definitely incomplete
                    if (!$ends_properly && !$has_conclusion) {
                        return true;
                    }
                }
                
                return false;
            };
            
            // Write article section by section
            $article_text = '';
            $previous_section_ending = '';
            
            // Check if section_prompts exists (from step 6)
            if (!isset($section_prompts) || empty($section_prompts)) {
                // Fallback: if section_prompts not available, use old method
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                // Use final_prompt if available, otherwise create a basic one
                if (!isset($final_prompt) || empty($final_prompt)) {
                    $final_prompt = $lang_instruction_final . "Write a complete article about: {$title}\n\n";
                    $final_prompt .= "Requirements:\n";
                    $final_prompt .= "- Language: {$lang}\n";
                    $final_prompt .= "- Format: Markdown\n";
                    $final_prompt .= "- Write directly, DO NOT introduce yourself.\n";
                }
                
                $article_content = $generate_with_agent($final_prompt, $lang, $model, $provider_id, array(
                    'max_tokens' => 4000,
                    'temperature' => 0.8,
                    'use_case' => 'long_context',
                    'system' => $system_prompt
                ));
                
                if (is_array($article_content) && isset($article_content['code']) && $article_content['code'] != '200') {
                    $stream->send_error($article_content['msg'] ?: 'Failed to generate article');
                    $stream->close();
                    return;
                }
                
                $article_text = is_array($article_content) ? ($article_content['result'] ?? '') : $article_content;
                $article_text = $extract_article_content($article_text);
            } else {
                // Write section by section using section_prompts
                $total_sections = count($section_prompts);
                
                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) {
                    }
                    
                    $stream->send_status('Writing section ' . ($section_idx + 1) . ' of ' . $total_sections . ': ' . $section_name . '...');
                    
                    // If not first section, add previous section ending to prompt
                    if (!$is_first && !empty($previous_section_ending)) {
                        // Get last 1500 characters of previous section for context
                        $context_ending = mb_substr($previous_section_ending, -1500);
                        
                        // Modify prompt to include previous section ending
                        $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) {
                        }
                        $stream->send_error($error_msg);
                        // Continue with next section or break
                        if ($is_last) {
                            break;
                        }
                        continue;
                    }
                    
                    $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG && isset($section_content['provider'])) {
                    }
                    
                    // Extract content up to the end marker (if marker exists in last section)
                    if ($is_last) {
                        $section_text = $extract_article_content($section_text);
                    }
                    
                    // Check if this section has a main heading (h2/h3) in markdown and search for image BEFORE adding to article_text
                    if (!empty($section_text)) {
                        $section_has_main_heading = false;
                        $main_heading_title = '';
                        $main_heading_markdown_pos = -1;
                        
                        // Check for h2 heading in markdown (## heading)
                        if (preg_match('/^##\s+(.+)$/m', $section_text, $h2_match, PREG_OFFSET_CAPTURE)) {
                            $section_has_main_heading = true;
                            $main_heading_title = trim($h2_match[1][0]);
                            $main_heading_markdown_pos = $h2_match[0][1] + strlen($h2_match[0][0]);
                        } elseif (preg_match('/^###\s+(.+)$/m', $section_text, $h3_match, PREG_OFFSET_CAPTURE)) {
                            // Fallback to h3 if no h2
                            $section_has_main_heading = true;
                            $main_heading_title = trim($h3_match[1][0]);
                            $main_heading_markdown_pos = $h3_match[0][1] + strlen($h3_match[0][0]);
                        }
                        
                        // If section has main heading, search and insert image into markdown
                        if ($section_has_main_heading && !empty($main_heading_title) && strlen($main_heading_title) > 3) {
                            $stream->send_status('Đang tìm hình ảnh cho section: ' . $main_heading_title . '...');
                            
                            // Get section content for better search query
                            $section_content_plain = strip_tags($section_text);
                            $section_content_plain = mb_substr($section_content_plain, 0, 500, 'UTF-8');
                            
                            // Generate search query using AI
                            $image_search_query = $main_heading_title;
                            
                            if (!empty($section_content_plain) && strlen($section_content_plain) > 20) {
                                $query_prompt = $get_language_instruction($lang);
                                $query_prompt .= "Tạo một từ khóa tìm kiếm hình ảnh ngắn gọn (3-5 từ) phù hợp với section sau:\n\n";
                                $query_prompt .= "Tiêu đề section: {$main_heading_title}\n";
                                $query_prompt .= "Nội dung section: " . mb_substr($section_content_plain, 0, 300, 'UTF-8') . "\n\n";
                                $query_prompt .= "Yêu cầu:\n";
                                $query_prompt .= "- Chỉ trả về từ khóa tìm kiếm, không có giải thích\n";
                                $query_prompt .= "- Từ khóa phải phù hợp để tìm hình ảnh minh họa\n";
                                $query_prompt .= "- Tối đa 5 từ\n\n";
                                $query_prompt .= "Chỉ trả về từ khóa tìm kiếm:";
                                
                                $query_result = $generate_with_agent($query_prompt, $lang, $model, $provider_id, array(
                                    'max_tokens' => 50,
                                    'temperature' => 0.7,
                                    'use_case' => 'fast'
                                ));
                                
                                if (is_array($query_result) && isset($query_result['code']) && $query_result['code'] == '200') {
                                    $generated_query = is_array($query_result) ? trim($query_result['result'] ?? '') : trim($query_result);
                                    $generated_query = strip_tags($generated_query);
                                    $generated_query = preg_replace('/["\']/', '', $generated_query);
                                    if (!empty($generated_query) && strlen($generated_query) > 3) {
                                        $image_search_query = $generated_query;
                                    }
                                }
                            }
                            
                            // Search for image
                            try {
                                $image_results = $bardGenContent->searchimg($image_search_query);
                                
                                // Handle both cases: direct array or object with 'result' key
                                $image_array = null;
                                if (is_array($image_results) && !empty($image_results)) {
                                    // Direct array case (sendPostRequest returns $decoded->result)
                                    $image_array = $image_results;
                                } elseif (is_object($image_results) && isset($image_results->result) && is_array($image_results->result) && !empty($image_results->result)) {
                                    // Object with 'result' key case
                                    $image_array = $image_results->result;
                                } elseif (isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) {
                                    // Array with 'result' key case
                                    $image_array = $image_results['result'];
                                }
                                
                                if ($image_array && !empty($image_array)) {
                                    $selected_image = $image_array[0];
                                    
                                    // Create image markdown format
                                    $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n";
                                    
                                    // Insert image after heading in section_text (markdown)
                                    $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0);
                                    
                                    $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title);
                                    
                                    // Stream section content immediately after inserting image (especially for section 1)
                                    if ($is_first || $section_idx === 0) {
                                        $section_html = $convert_markdown_to_html($section_text);
                                        if (!empty($section_html)) {
                                            $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                                            $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                                            $section_footer = '</div>';
                                            $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                                        }
                                    }
                                    
                                    if (defined('WP_DEBUG') && WP_DEBUG) {
                                    }
                                } else {
                                    // Fallback: try with section title only
                                    if ($image_search_query !== $main_heading_title) {
                                        $image_results = $bardGenContent->searchimg($main_heading_title);
                                        if ($image_results && isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) {
                                            $selected_image = $image_results['result'][0];
                                            $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n";
                                            $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0);
                                            
                                            $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title);
                                            
                                            // Stream section content immediately after inserting image (especially for section 1)
                                            if ($is_first || $section_idx === 0) {
                                                $section_html = $convert_markdown_to_html($section_text);
                                                if (!empty($section_html)) {
                                                    $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                                                    $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                                                    $section_footer = '</div>';
                                                    $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception $img_ex) {
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                            }
                            
                            // Small delay
                            usleep(300000); // 0.3 second delay
                        }
                        
                        // If not first section, add a newline for separation
                        if (!empty($article_text)) {
                            $article_text .= "\n\n";
                        }
                        // Append section_text (which now includes image if found) to article_text
                        $article_text .= $section_text;
                        
                        // Store the ending of this section for next iteration
                        // Take last 2000 characters for context
                        $previous_section_ending = mb_substr($section_text, -2000);
                        
                        // Convert section to HTML and display the entire section at once
                        $section_html = $convert_markdown_to_html($section_text);
                        if (!empty($section_html)) {
                            // Add section header for clarity
                            $section_header = '<div class="article-section" data-section="' . ($section_idx + 1) . '" data-section-name="' . esc_attr($section_name) . '">';
                            $section_header .= '<div class="section-header"><strong>Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '</strong></div>';
                            $section_footer = '</div>';
                            
                            // Send the complete section at once (with image if found)
                            $stream->send_step_output(7, $section_header . $section_html . $section_footer);
                        }
                    }
                    
                    // 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;
                    }
                }
            }
            
            // Check if article is incomplete and continue writing if needed (fallback for edge cases)
            // For long-form articles, allow more continuation attempts to ensure minimum length
            $max_continuations = ($length_type === 'long-form') ? 3 : 1;
            $continuation_count = 0;
            
            while ($is_article_incomplete($article_text, $length_type) && $continuation_count < $max_continuations) {
                $continuation_count++;
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                }
                
                $stream->send_status('Continuing article writing... (part ' . ($continuation_count + 1) . ')');
                
                // Get the last part of the article to continue from
                // Take last 2000 characters to maintain context
                $context_text = mb_substr($article_text, -2000);
                
                // Create continuation prompt
                $continue_prompt = "Continue writing the article from where it left off. Here is the incomplete part:\n\n";
                $continue_prompt .= $context_text . "\n\n";
                $continue_prompt .= "IMPORTANT:\n";
                $continue_prompt .= "- Continue seamlessly from the last sentence\n";
                $continue_prompt .= "- Do NOT repeat what was already written\n";
                $continue_prompt .= "- Maintain the same writing style and tone\n";
                $continue_prompt .= "- Complete the article with a proper conclusion if this is the final part\n";
                $continue_prompt .= "- Write directly, DO NOT introduce yourself or add any meta-commentary\n";
                $continue_prompt .= "\nCRITICAL: When you finish writing the complete article, you MUST add this exact marker at the very end: {$article_end_marker}\n";
                $continue_prompt .= "This marker indicates that the article is complete. Do NOT add any content after this marker.\n";
                
                // Add original requirements for consistency
                if (!empty($length_type) && $length_type === 'long-form') {
                    // Calculate current word count to inform AI
                    $plain_text = strip_tags($article_text);
                    $plain_text = preg_replace('/\s+/', ' ', $plain_text);
                    $current_chars = mb_strlen($plain_text);
                    $current_words = round($current_chars / 5);
                    
                    $continue_prompt .= "\nLENGTH REQUIREMENT (CRITICAL):\n";
                    $continue_prompt .= "- Current article length: approximately {$current_words} words\n";
                    $continue_prompt .= "- REQUIRED: You MUST write at least 2000+ words total (currently at {$current_words} words)\n";
                    $continue_prompt .= "- Continue writing substantial content to reach the minimum requirement\n";
                    $continue_prompt .= "- Add the end marker ONLY when you have written at least 2000 words total\n";
                    $continue_prompt .= "- If you haven't reached 2000 words yet, continue writing more content\n";
                }
                
                // Generate continuation
                $continue_content = $generate_with_agent($continue_prompt, $lang, $model, $provider_id, array(
                    'max_tokens' => 4000,
                    'temperature' => 0.8,
                    'use_case' => 'long_context',
                    'system' => $system_prompt
                ));
                
                if (is_array($continue_content) && isset($continue_content['code']) && $continue_content['code'] != '200') {
                    // If continuation fails, break and use what we have
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    break;
                }
                
                $continue_text = is_array($continue_content) ? ($continue_content['result'] ?? '') : $continue_content;
                
                // Extract content up to the end marker (if marker exists)
                $continue_text = $extract_article_content($continue_text);
                
                if (!empty($continue_text)) {
                    // Remove any potential overlap by finding where the continuation starts
                    // Check if continuation begins with content that's already in article_text
                    $continue_trimmed = trim($continue_text);
                    $overlap_found = false;
                    
                    // Check for overlap in first 200 characters
                    if (strlen($continue_trimmed) > 200) {
                        $continue_start = substr($continue_trimmed, 0, 200);
                        if (strpos($article_text, $continue_start) !== false) {
                            $overlap_found = true;
                            // Find where this content appears in article_text and start from after it
                            $pos = strpos($article_text, $continue_start);
                            if ($pos !== false) {
                                $continue_text = substr($continue_trimmed, strlen($continue_start));
                            }
                        }
                    }
                    
                    // Append continuation
                    if (!empty(trim($continue_text))) {
                        $article_text .= "\n\n" . $continue_text;
                        
                        // Convert continuation to HTML and stream it
                        $continue_html = $convert_markdown_to_html($continue_text);
                        if (!empty($continue_html)) {
                            $chunk_size = 100;
                            $continue_length = strlen($continue_html);
                            for ($i = 0; $i < $continue_length; $i += $chunk_size) {
                                $chunk = substr($continue_html, $i, $chunk_size);
                                $stream->send_step_output(7, $chunk);
                                usleep(50000); // Small delay for streaming effect
                            }
                        }
                        
                        // For long-form: check if continuation added enough content
                        if ($length_type === 'long-form' && $continuation_count < $max_continuations) {
                            $plain_text_check = strip_tags($article_text);
                            $plain_text_check = preg_replace('/\s+/', ' ', $plain_text_check);
                            $current_chars = mb_strlen($plain_text_check);
                            $current_words = round($current_chars / 5);
                            
                            // If still too short and we have more attempts, log it
                            if ($current_chars < 10000 && $continuation_count < $max_continuations - 1) {
                                if (defined('WP_DEBUG') && WP_DEBUG) {
                                }
                                $stream->send_status('Article length: ~' . $current_words . ' words. Continuing to reach 2000+ words...');
                            }
                        }
                    } else {
                        // Continuation text is empty, but for long-form we should try again
                        if ($length_type === 'long-form' && $continuation_count < $max_continuations - 1) {
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                            }
                            // Don't break, continue to next iteration
                        } else {
                            // No continuation content, break
                            break;
                        }
                    }
                } else {
                    // No continuation content, but for long-form we should try again
                    if ($length_type === 'long-form' && $continuation_count < $max_continuations - 1) {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        // Don't break, continue to next iteration
                    } else {
                        // No continuation content, break
                        break;
                    }
                }
                
                // Small delay before checking again
                usleep(100000); // 100ms
            }
            
            // Final check for long-form articles
            if ($length_type === 'long-form') {
                $plain_text_final = strip_tags($article_text);
                $plain_text_final = preg_replace('/\s+/', ' ', $plain_text_final);
                $final_chars = mb_strlen($plain_text_final);
                $final_words = round($final_chars / 5);
                
                if ($final_chars < 10000) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    $stream->send_status('Warning: Article length is ~' . $final_words . ' words. Target was 2000+ words.');
                } else {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
            
            if ($continuation_count > 0 && defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Step 8: Generate introduction and conclusion summary (mobai and ketbai)
            $stream->send_status('writing introduction and conclusion...');
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Prepare article text for summary
            // Since $article_text is still in markdown format, we'll convert it to plain text for summary
            // Remove markdown formatting for cleaner summary context
            $article_plain_text = $article_text;
            $article_plain_text = preg_replace('/#{1,6}\s+/', '', $article_plain_text); // Remove headers
            $article_plain_text = preg_replace('/\*\*(.*?)\*\*/', '$1', $article_plain_text); // Remove bold
            $article_plain_text = preg_replace('/\*(.*?)\*/', '$1', $article_plain_text); // Remove italic
            $article_plain_text = preg_replace('/\[([^\]]+)\]\([^\)]+\)/', '$1', $article_plain_text); // Remove links
            $article_plain_text = preg_replace('/\s+/', ' ', $article_plain_text); // Normalize whitespace
            $article_plain_text = trim($article_plain_text);
            
            // Get full article for better context (but limit to avoid token limits)
            $article_for_context = $article_plain_text;
            if (mb_strlen($article_for_context) > 4000) {
                // Take first 2000 and last 2000 characters for better context
                $article_for_context = mb_substr($article_for_context, 0, 2000) . ' ... ' . mb_substr($article_for_context, -2000);
            }
            
            // Create prompt to generate both mobai (introduction) and ketbai (conclusion) in JSON format
            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. Phần này sẽ được dùng để giới thiệu 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. This will be used to introduce 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;
            
            // Generate summary using AI
            $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 (in case it's wrapped in markdown code block or has extra text)
                $json_match = null;
                if (preg_match('/\{[\s\S]*"mobai"[\s\S]*"ketbai"[\s\S]*\}/', $summary_response, $json_match)) {
                    $summary_response = $json_match[0];
                }
                
                // Remove markdown code blocks if present
                $summary_response = preg_replace('/```json\s*/', '', $summary_response);
                $summary_response = preg_replace('/```\s*/', '', $summary_response);
                $summary_response = trim($summary_response);
                
                // Parse JSON
                $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']);
                    
                    // Remove quotes if present
                    $mobai = trim($mobai, ' "\'');
                    $ketbai = trim($ketbai, ' "\'');
                    
                    if (!empty($mobai) && !empty($ketbai)) {
                        // Add mobai at the beginning of article (after title if exists, or at the start)
                        // Check if article starts with a heading (markdown ## or #)
                        if (preg_match('/^(#{1,6}\s+.+?\n\n)/', $article_text, $matches)) {
                            // Article starts with heading, add mobai after first heading
                            $article_text = preg_replace('/^(#{1,6}\s+.+?\n\n)/', '$1' . $mobai . "\n\n", $article_text, 1);
                        } else {
                            // No heading at start, add mobai at the beginning
                            $article_text = $mobai . "\n\n" . $article_text;
                        }
                        
                        // Add ketbai at the end of article
                        $article_text .= "\n\n" . $ketbai;
                        
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                        
                        // Stream the mobai and ketbai
                        $mobai_html = $convert_markdown_to_html($mobai);
                        $ketbai_html = $convert_markdown_to_html($ketbai);
                        
                        if (!empty($mobai_html)) {
                            $stream->send_step_output(7, "\n\n" . $mobai_html);
                        }
                        if (!empty($ketbai_html)) {
                            $stream->send_step_output(7, "\n\n" . $ketbai_html);
                        }
                    } else {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                        }
                    }
                } else {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        if (json_last_error() !== JSON_ERROR_NONE) {
                        }
                    }
                }
            } else {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    $error_msg = isset($summary_result['msg']) ? $summary_result['msg'] : 'Unknown error';
                }
                // Continue without summary if generation fails
            }
            
            // Convert final article to HTML (for final output)
            $article_text = $convert_markdown_to_html($article_text);
            
            $stream->send_step_complete(7, 'success', array('content' => $article_text));
            
            // Update AI_post_usage counter after successful article generation
            $this->aiautotool_update_ai_post_usage();
            
            // Send completion
            $stream->send_complete($article_text, array(
                'checklist' => $checklist_text,
                'author_credibility' => $author_credibility_text,
                'keywords_analysis' => $keywords_analysis_text,
                'direction_analysis' => $direction_analysis_text,
                'final_prompt' => $final_prompt,
                'article' => $article_text,
                'related_posts' => $related_posts
            ), $message_id);
            
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Make sure stream is started before sending error
            if (!$stream) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
            }
            
            $stream->send_error($error_msg, array(
                'exception' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ), $message_id);
        } catch (Error $e) {
            $error_msg = 'Fatal Error: ' . $e->getMessage();
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            
            // Make sure stream is started before sending error
            if (!isset($stream) || !$stream) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
            }
            
            $stream->send_error($error_msg, array(
                'exception' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ), $message_id);
        }
        
        if (isset($stream) && $stream) {
            $stream->close();
        } else {
            // If stream was never created, exit cleanly
            exit;
        }
    }
    
    /**
     * AJAX callback for writing article with AI Auto Writer (SSE streaming)
     */
    private function aiautotool_is_provider_retryable_error($error) {
        if (empty($error)) {
            return false;
        }

        $error = (string) $error;
        $retryable_patterns = array(
            '401',
            '403',
            '404',
            '408',
            '409',
            '422',
            '429',
            '500',
            '502',
            '503',
            '504',
            'permission_denied',
            'unauthorized',
            'forbidden',
            'invalid api key',
            'invalid_api_key',
            'invalid key',
            'api key',
            'quota',
            'rate limit',
            'too many requests',
            'resource has been exhausted',
            'billing',
            'credits',
            'credit',
            'license',
            'licenses',
            'doesn\'t have any credits',
            'does not have any credits',
            'purchase',
            'insufficient',
            'balance',
            'no balance',
            'no credits',
            'no active subscription',
            'subscription',
            'plan',
            'team doesn\'t have',
            'team does not have',
            'invalid response structure',
            'missing message content',
            'failed to create outline',
            'failed to parse outline',
            'failed to write introduction',
            'failed to write section',
            'failed to write conclusion',
            'incomplete article',
            'empty response',
            'timeout',
            'timed out',
            'connection error',
            'network response was not ok',
        );

        foreach ($retryable_patterns as $pattern) {
            if (stripos($error, $pattern) !== false) {
                return true;
            }
        }

        return false;
    }

    public function aiautotool_write_article_with_auto_writer_callback() {
        if (function_exists('ignore_user_abort')) {
            ignore_user_abort(true);
        }
        if (function_exists('set_time_limit')) {
            @set_time_limit(300);
        }
        @ini_set('max_execution_time', '300');
        @ini_set('hard_timeout', '30');
        @ini_set('default_socket_timeout', '300');

        // Verify nonce for AJAX requests
        if (defined('DOING_AJAX') && DOING_AJAX) {
            if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Security check failed. Please refresh the page and try again.');
                $stream->close();
                return;
            }
            
            if (!current_user_can('edit_posts')) {
                require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
                $stream = new AIAutoTool_SSE_Stream();
                $stream->start();
                $stream->send_error('Permission denied');
                $stream->close();
                return;
            }
        }
        
        // Get data from POST
        $data = array();
        if (isset($_POST['data']) && is_string($_POST['data'])) {
            $data = json_decode(stripslashes($_POST['data']), true);
        } else {
            $raw_data = file_get_contents('php://input');
            $data = json_decode($raw_data, true);
        }
        
        if (!$data || !is_array($data)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Invalid JSON data');
            $stream->close();
            return;
        }
        
        // Extract parameters
        $title = isset($data['title']) ? sanitize_text_field($data['title']) : '';
        $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'vi';
        $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : '';
        $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection(
            isset($data['model']) ? $data['model'] : '',
            isset($data['provider_id']) ? $data['provider_id'] : ''
        );
        $requested_provider_id = $resolved_ai_selection['provider_id'];
        $requested_model = $resolved_ai_selection['model'];
        $article_settings = (isset($data['article_settings']) && is_array($data['article_settings'])) ? $data['article_settings'] : array();
        
        if (empty($title)) {
            require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('Title parameter is required');
            $stream->close();
            return;
        }
        
        // Load SSE Stream class
        $sse_stream_path = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php';
        if (!file_exists($sse_stream_path)) {
            // Try alternative path
            $sse_stream_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/lib/aiautotool-sse-stream.php';
        }
        if (!file_exists($sse_stream_path)) {
            wp_die('SSE Stream class not found');
        }
        require_once $sse_stream_path;
        
        // Load AI Auto Writer
        $auto_writer_path = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_auto_writer.php';
        if (!file_exists($auto_writer_path)) {
            // Try alternative path
            $auto_writer_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/inc/ai-providers/aiautotool_ai_auto_writer.php';
        }
        if (!file_exists($auto_writer_path)) {
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('AI Auto Writer class not found at: ' . $auto_writer_path);
            $stream->close();
            return;
        }
        require_once $auto_writer_path;
        
        // Check if class exists
        if (!class_exists('AIAutotool_AI_Auto_Writer')) {
            $stream = new AIAutoTool_SSE_Stream();
            $stream->start();
            $stream->send_error('AI Auto Writer class not loaded');
            $stream->close();
            return;
        }
        
        // Initialize stream
        $stream = new AIAutoTool_SSE_Stream();
        $stream->start();
        
        if (!empty($message_id)) {
            $stream->set_message_id($message_id);
        }
        
        // Get auto writer instance
        try {
            $auto_writer = AIAutotool_AI_Auto_Writer::get_instance();
        } catch (Exception $e) {
            $stream->send_error('Failed to get AI Auto Writer instance: ' . $e->getMessage());
            $stream->close();
            return;
        }
        
        // Load AI Provider Manager to check available providers
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_manager.php';
        require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_api_keys.php';

        $provider_manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider_manager->refresh_providers();
        $routing_mode = method_exists($provider_manager, 'get_provider_routing_mode') ? $provider_manager->get_provider_routing_mode() : 'single';
        $route = false;
        if (!empty($requested_provider_id)) {
            $requested_provider = $provider_manager->get_provider($requested_provider_id);
            if (!$requested_provider || !$requested_provider->is_configured()) {
                $stream->send_error('Selected AI provider is not configured. Please choose another provider or update AI Provider settings.');
                $stream->close();
                return;
            }

            $available_models = $requested_provider->get_available_models();
            if (empty($requested_model) || !isset($available_models[$requested_model])) {
                $requested_model = $requested_provider->get_default_model();
            }

            $route = array(
                'provider' => $requested_provider,
                'provider_id' => $requested_provider_id,
                'model' => $requested_model,
                'routing_mode' => 'editor_override',
            );
        } else {
            $route = method_exists($provider_manager, 'get_provider_for_request') ? $provider_manager->get_provider_for_request() : false;
        }
        $active_provider = $provider_manager->get_active_provider();
        $active_provider_id = $active_provider ? $active_provider->get_id() : '';
        $active_model = $provider_manager->get_active_model();

        if ($active_provider && empty($active_model)) {
            $active_model = $active_provider->get_default_model();
        }

        // Active or routed provider from AI Provider settings must be tried first.
        $providers_to_try = array();
        if ($route && !empty($route['provider_id'])) {
            $providers_to_try[] = array(
                'provider' => $route['provider_id'],
                'model' => !empty($route['model']) ? $route['model'] : $route['provider']->get_default_model(),
                'source' => !empty($requested_provider_id) ? 'editor' : ($routing_mode === 'rotate' ? 'rotate' : 'active'),
            );
        } elseif ($active_provider) {
            $providers_to_try[] = array(
                'provider' => $active_provider_id,
                'model' => $active_model ? $active_model : $active_provider->get_default_model(),
                'source' => 'active',
            );
        }

        // Fallback providers are only used in rotate mode. In single/editor mode,
        // respect the user's explicit provider choice and fail fast if it cannot complete.
        if ($routing_mode === 'rotate' && empty($requested_provider_id)) {
            $fallback_priority = method_exists($provider_manager, 'get_provider_priority') ? $provider_manager->get_provider_priority() : array(
                'pollinations',
                'llm7',
                'gemini',
                'groq',
                'openrouter',
                'huggingface',
                'deepseek',
                'mistral',
                'together',
                'fireworks',
                'perplexity',
                'xai',
                'anthropic',
                'openai',
                'azure_openai',
                'ollama',
            );

            foreach ($fallback_priority as $provider_id) {
                if (!empty($providers_to_try[0]['provider']) && $provider_id === $providers_to_try[0]['provider']) {
                    continue;
                }

                $provider = $provider_manager->get_provider($provider_id);
                if (!$provider || !$provider->is_configured()) {
                    continue;
                }

                $providers_to_try[] = array(
                    'provider' => $provider_id,
                    'model' => $provider->get_default_model(),
                    'source' => 'fallback',
                );
            }
        }

        if (empty($providers_to_try)) {
            $stream->send_error('No AI provider is configured. Please add an API key and select an active provider in AI Provider settings.');
            $stream->close();
            return;
        }
        
        // Prepare base options
        $base_options = array(
            'language' => $lang === 'vi' || $lang === 'Vietnamese' ? 'vi' : 'en',
            'industry' => 'auto',
            'min_sections' => 5,
            'max_sections' => 10,
            'words_per_section' => 300,
            'include_intro' => true,
            'include_conclusion' => true,
            'detailed_level' => 'high',
            'max_retries' => 1,
            'retry_delay' => 0,
            'suppress_internal_errors' => true,
            'debug' => false,
        );

        if (!empty($article_settings['tone'])) {
            $base_options['tone'] = sanitize_text_field($article_settings['tone']);
        }

        if (!empty($article_settings['targetAudience'])) {
            $base_options['target_audience'] = sanitize_text_field($article_settings['targetAudience']);
        }

        if (!empty($article_settings['lengthType'])) {
            $length_type = sanitize_text_field($article_settings['lengthType']);
            if ($length_type === 'short') {
                $base_options['min_sections'] = 3;
                $base_options['max_sections'] = 5;
                $base_options['words_per_section'] = 220;
                $base_options['detailed_level'] = 'medium';
            } elseif ($length_type === 'standard') {
                $base_options['min_sections'] = 4;
                $base_options['max_sections'] = 7;
                $base_options['words_per_section'] = 300;
                $base_options['detailed_level'] = 'high';
            } elseif ($length_type === 'long') {
                $base_options['min_sections'] = 6;
                $base_options['max_sections'] = 10;
                $base_options['words_per_section'] = 450;
                $base_options['detailed_level'] = 'high';
            }
        }
        
        // Try each provider until one succeeds
        $result = null;
        $last_error = '';
        $attempted_providers = array();
        $provider_errors = array();
        
        foreach ($providers_to_try as $provider_config) {
            $attempted_providers[] = $provider_config['provider'] . '/' . $provider_config['model'];
            if ($provider_config['source'] === 'rotate') {
                $try_label = 'provider xoay vòng';
            } elseif ($provider_config['source'] === 'editor') {
                $try_label = 'provider chọn trong bài viết';
            } else {
                $try_label = $provider_config['source'] === 'active' ? 'provider đã chọn' : 'provider dự phòng';
            }
            $stream->send_status("Đang thử với {$try_label}: {$provider_config['provider']} - {$provider_config['model']}...");
            
            // Merge provider/model into options
            $options = array_merge($base_options, array(
                'provider' => $provider_config['provider'],
                'model' => $provider_config['model']
            ));
            
            // Call auto writer with streaming
            try {
                $result = $auto_writer->write_article_from_title_with_stream($title, $stream, $options);
                
                if ($result && isset($result['success']) && $result['success']) {
                    // Success! Send complete event
                    $stream->send_complete($result['full_content'], array(
                        'title' => isset($result['title']) ? $result['title'] : $title,
                        'word_count' => isset($result['word_count']) ? $result['word_count'] : 0,
                        'execution_time' => isset($result['execution_time']) ? $result['execution_time'] : 0,
                        'provider' => $provider_config['provider'],
                        'model' => $provider_config['model']
                    ));
                    $stream->close();
                    return; // Exit successfully
                } else {
                    $error = isset($result['error']) ? $result['error'] : 'Failed to write article';
                    $last_error = $error;
                    $provider_errors[] = $provider_config['provider'] . ': ' . $error;
                    
                    if ($this->aiautotool_is_provider_retryable_error($error)) {
                        $stream->send_status("Provider {$provider_config['provider']} failed: " . substr($error, 0, 100) . "... Đang thử provider khác...");
                        continue; // Try next provider
                    } else {
                        // Other error, might be fatal
                        break;
                    }
                }
            } catch (Exception $e) {
                error_log('AI Auto Writer Error with ' . $provider_config['provider'] . ': ' . $e->getMessage());
                $last_error = $e->getMessage();
                $provider_errors[] = $provider_config['provider'] . ': ' . $e->getMessage();
                
                if ($this->aiautotool_is_provider_retryable_error($e->getMessage())) {
                    $stream->send_status("Provider {$provider_config['provider']} error: " . substr($e->getMessage(), 0, 100) . "... Đang thử provider khác...");
                    continue; // Try next provider
                } else {
                    // Other error, might be fatal
                    break;
                }
            } catch (Error $e) {
                error_log('AI Auto Writer Fatal Error with ' . $provider_config['provider'] . ': ' . $e->getMessage());
                $last_error = $e->getMessage();
                break; // Fatal error, stop trying
            }
        }
        
        // All providers failed
        if (empty($last_error)) {
            $last_error = 'Tất cả providers đều thất bại. Vui lòng kiểm tra API keys trong Settings.';
        } elseif (!empty($provider_errors)) {
            if ($routing_mode === 'rotate' && empty($requested_provider_id)) {
                $last_error = 'Tất cả AI providers đã thử đều chưa tạo được bài hoàn chỉnh. Đã thử: ' . implode(', ', $attempted_providers) . '. Lỗi cuối: ' . $last_error;
            } else {
                $last_error = 'Provider đã chọn chưa tạo được bài hoàn chỉnh. Đã thử: ' . implode(', ', $attempted_providers) . '. Lỗi: ' . $last_error;
            }
        }
        $stream->send_error($last_error);
        
        // Close stream
        $stream->close();
    }
    
    
} // End of AIAutoToolsinglepost class
} // End of class_exists check
