<?php
/**
 * AI Auto Tool Bot Assistant
 * 
 * Intelligent assistant that monitors, analyzes, and provides insights
 * for your WordPress site. Acts as a central hub for all AI tools.
 * 
 * @package AI Auto Tool
 * @version 1.0.0
 */

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

// Load AI Providers module (if not already loaded)
$ai_providers_path = plugin_dir_path(dirname(__FILE__)) . 'ai-providers/index.php';
if (file_exists($ai_providers_path) && !class_exists('AIAutotool_AI_Helper')) {
    require_once $ai_providers_path;
}

// Load AI Agent Tools
require_once plugin_dir_path(__FILE__) . 'aiautotool_agent_tools.php';
require_once plugin_dir_path(__FILE__) . 'aiautotool_bot_assistant_advanced_settings.php';
require_once plugin_dir_path(__FILE__) . 'tools/tool-loader.php';

// Load Cursor-style AI Agent System
require_once plugin_dir_path(__FILE__) . 'aiautotool_agent_bootstrap.php';

// Load Floating Robot Widget
// Note: This file may have already been loaded early in plugin initialization
// Check to avoid duplicate loading
if (!class_exists('AIautotool_Floating_Robot_Widget') && !class_exists('AIautotool_Floating_Robot_Widget_Instance')) {
    require_once plugin_dir_path(__FILE__) . 'aiautotool_floating_robot_widget.php';
    // Widget will auto-initialize via AIautotool_Floating_Robot_Widget_Instance::get_instance() at end of file
}

// Load Tasks System
require_once plugin_dir_path(__FILE__) . 'tasks/index.php';

class AIautotool_bot_assistant extends rendersetting {
    
    public $active = true;
    public $active_option_name = 'aiautotool_bot_assistant_active';
    public $icon = '<i class="fa-solid fa-robot"></i>';
    public $name_plan;
    private $option_name = 'aiautotool_bot_assistant_settings';
    private $tools_monitor = [];
    
    public function __construct() {
        $this->name_plan = __('AI Bot Assistant', 'ai-auto-tool');
        // Enable by default - always active
        $this->active = get_option($this->active_option_name, true);
        
        // Hook vào admin menu - always show in menu (priority 10 to ensure parent menu exists)
        add_action('admin_menu', array($this, 'add_admin_menu'), 10);
        
        // Enqueue scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // AJAX handlers
        add_action('wp_ajax_bot_assistant_query', array($this, 'handle_query'));
        add_action('wp_ajax_bot_assistant_get_insights', array($this, 'get_insights'));
        add_action('wp_ajax_bot_assistant_get_stats', array($this, 'get_statistics'));
        add_action('wp_ajax_bot_assistant_search_content', array($this, 'search_content'));
        add_action('wp_ajax_bot_assistant_get_alerts', array($this, 'get_alerts'));
        add_action('wp_ajax_save_bot_assistant_ai_settings', array($this, 'save_ai_settings'));
        add_action('wp_ajax_bot_assistant_execute_action', array($this, 'execute_action'));
        add_action('wp_ajax_bot_assistant_execute_tool', array($this, 'execute_tool'));
        add_action('wp_ajax_bot_assistant_get_task_progress', array($this, 'get_task_progress'));
        add_action('wp_ajax_bot_assistant_execute_plan', array($this, 'execute_plan_from_chat'));
        add_action('wp_ajax_bot_assistant_get_execution_progress', array($this, 'get_execution_progress'));
        
        // Smart Analysis Workflow handlers
        add_action('wp_ajax_bot_assistant_smart_analysis', array($this, 'handle_smart_analysis'));
        add_action('wp_ajax_bot_assistant_check_resources', array($this, 'handle_check_resources'));
        add_action('wp_ajax_bot_assistant_build_execution_plan', array($this, 'handle_build_execution_plan'));
        
        // Step-by-step execution handlers
        add_action('wp_ajax_bot_assistant_start_session', array($this, 'start_step_session'));
        add_action('wp_ajax_bot_assistant_execute_step', array($this, 'execute_single_step'));
        
        // Agentic Workflow handlers
        add_action('wp_ajax_bot_assistant_agentic_start', array($this, 'agentic_start'));
        add_action('wp_ajax_bot_assistant_agentic_execute', array($this, 'agentic_execute'));
        add_action('wp_ajax_bot_assistant_agentic_reflect', array($this, 'agentic_reflect'));
        add_action('wp_ajax_bot_assistant_agentic_execute_plan', array($this, 'agentic_execute_plan'));
        
        // 🤖 NEW: AI Agent Core integration
        add_action('wp_ajax_bot_assistant_agent_execute', array($this, 'handle_agent_execution'));
        add_action('wp_ajax_bot_assistant_get_step_progress', array($this, 'get_step_progress'));
        
        // AJAX handler for standalone chat interface
        add_action('wp_ajax_render_standalone_chat', array($this, 'render_standalone_chat_html'));
        
        // Dashboard widget
        add_action('wp_dashboard_setup', array($this, 'add_dashboard_widget'));
        
        // Cron jobs for monitoring
        add_action('aiautotool_bot_assistant_daily_check', array($this, 'daily_health_check'));
        add_action('aiautotool_execute_plan_bg', array(__CLASS__, 'execute_plan_background'), 10, 2);
        
        // AJAX for activation toggle (requires authentication - options modification)
        add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback'));
        
        if ($this->active == 'true') {
            // Initialize monitoring only when active
            $this->init_monitoring();
        }
    }
    
    /**
     * Update active option callback for AJAX
     */
    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');
            echo $active;
        }
        wp_die();
    }
    
    /**
     * Add admin menu - Always show menu regardless of active status
     */
    public function add_admin_menu() {
        // Always add menu - don't check active status here
        // Menu should be visible even if feature is inactive (user can activate from menu)
        $parent_slug = defined('MENUSUBPARRENT') ? MENUSUBPARRENT : 'ai_auto_tool';
        
        // Debug: Log menu registration
        if (defined('WP_DEBUG') && WP_DEBUG) {
            global $submenu;
            if (isset($submenu[$parent_slug])) {
            } else {
            }
        }
        
        // Check if parent menu exists, if not create a fallback
        global $submenu;
        if (!isset($submenu[$parent_slug])) {
            // Parent menu doesn't exist, create it as a main menu
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            add_menu_page(
                '<i class="fa-solid fa-gears"></i> Ai Auto Tool',
                '<i class="fa-solid fa-gears"></i> Ai Auto Tool',
                'manage_options',
                $parent_slug,
                function() {
                    echo '<div class="wrap"><h1>AI Auto Tool</h1><p>Please activate the main plugin menu.</p></div>';
                },
                'dashicons-admin-generic',
                3
            );
        }
        
        add_submenu_page(
            $parent_slug,
            '<i class="fa-solid fa-robot"></i> ' . __('AI Bot Assistant', 'ai-auto-tool'),
            '<i class="fa-solid fa-robot"></i> ' . __('AI Assistant', 'ai-auto-tool'),
            'manage_options',
            'aiautotool-bot-assistant',
            array($this, 'render_admin_page'),
            5 // Position: Show early in menu
        );
        
        // Debug: Confirm menu added
        if (defined('WP_DEBUG') && WP_DEBUG) {
            global $submenu;
            if (isset($submenu[$parent_slug])) {
            } else {
            }
        }
    }
    
    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts($hook) {
        // Check if we're on the bot assistant page or dashboard
        if (strpos($hook, 'aiautotool-bot-assistant') === false && $hook !== 'index.php') {
            return;
        }
        
        // Get plugin root URL and path (go up 3 levels from inc/bot-assistant/aiautotool_bot_assistant.php)
        $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(dirname(__FILE__))));
        $plugin_path = plugin_dir_path(dirname(dirname(dirname(__FILE__))));
        $assets_url = plugin_dir_url(__FILE__) . 'assets/';
        $version = defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0';
        
        // === Main Plugin Styles ===
        // Font Awesome - Use local version instead of CDN
        wp_enqueue_style(
            'font-awesome',
            $plugin_url . 'js/fontawesome/css/all.min.css',
            array(),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0'
        );
        
        // Main plugin CSS
        wp_enqueue_style(
            'aiautotool',
            $plugin_url . 'css/aiautotool.css',
            array(),
            $version
        );
        
        // Feature description modal CSS
        wp_enqueue_style(
            'feature-description-modal',
            $plugin_url . 'css/feature-description-modal.css',
            array(),
            $version
        );
        
        // SweetAlert2 CSS - Use local version instead of CDN
        wp_enqueue_style(
            'sweetalert2',
            $plugin_url . 'js/sweetalert2/dist/sweetalert2.min.css',
            array(),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '11.26.3'
        );
        
        // === Bot Assistant Specific Styles ===
        wp_enqueue_style(
            'bot-assistant-style',
            $assets_url . 'css/bot-assistant.css',
            array('aiautotool'),
            time()
        );
        
        wp_enqueue_style(
            'execute-plan-button-style',
            $assets_url . 'css/execute-plan-button.css',
            array(),
            time()
        );
        
        wp_enqueue_style(
            'cursor-thinking-phases-style',
            $assets_url . 'css/cursor-thinking-phases.css',
            array(),
            time()
        );
        
        // Cursor-style chat interface
        wp_enqueue_style(
            'cursor-style-chat',
            $assets_url . 'css/cursor-style-chat.css',
            array(),
            time()
        );
        
        // Chatbot unified CSS - REMOVED (duplicate of cursor-thinking-phases.css + cursor-style-chat.css)
        
        // Enhanced display CSS
        $enhanced_display_css = $plugin_path . 'inc/bot-assistant/css/enhanced-display.css';
        if (file_exists($enhanced_display_css)) {
            wp_enqueue_style(
                'enhanced-display-style',
                plugin_dir_url(dirname(__FILE__)) . 'inc/bot-assistant/css/enhanced-display.css',
                array(),
                time()
            );
        }
        
        // AI Agent CSS
        wp_enqueue_style(
            'aiautotool-agent-css',
            $assets_url . 'css/ai-agent.css',
            array(),
            '1.0.0'
        );
        
        // === Main Plugin Scripts ===
        wp_enqueue_script('jquery');
        wp_enqueue_media();
        
        // SweetAlert2 - Use local version instead of CDN
        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
        );
        
        // Feature description modal JS
        wp_enqueue_script(
            'feature-description-modal',
            $plugin_url . 'js/feature-description-modal.js',
            array('jquery'),
            $version,
            true
        );
        
        // Main plugin JS - Register first
        wp_register_script(
            'kct_cr_scriptx',
            $plugin_url . 'js/aiautotool.js',
            array('jquery'),
            $version,
            true
        );
        
        // Localize main plugin script with settings
        $setting = new rendersetting();
        $langcodedefault = explode('-', get_bloginfo("language"));
        $langcodedefault = $langcodedefault[0];
        $langcodedefault = get_option('aiautotool_default_language', 'vi');
        
        global $post;
        $settingseditornumberline = '';
        $freemius_access = function_exists('aiautotool_get_freemius_access_status') ? aiautotool_get_freemius_access_status() : array(
            'can_use_pro_features' => false,
            'is_free' => true,
            'is_trial' => false,
            'trial_days_remaining' => null,
            'trial_ends' => null,
            'reason' => 'freemius_unavailable',
        );
        
        $js_setting = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'security' => wp_create_nonce('aiautotool_nonce'),
            'languageCodes' => $setting->languageCodes,
            'langcodedefault' => $langcodedefault,
            'fsdata' => rendersetting::aiautotool_getdata(),
            'freemius_access' => $freemius_access,
            'aiautotool_premium' => ! empty($freemius_access['can_use_pro_features']),
            'code_mirrror' => $settingseditornumberline,
            'gemini_api' => defined('AIAUTOTOOL_API_GEM') ? AIAUTOTOOL_API_GEM : '',
            'prompt' => get_option('aiautotool_prompt_options', array())
        );
        
        if (isset($post->ID)) {
            $js_setting['postID'] = $post->ID;
            $js_setting['postTitle'] = $post->post_title;
            $js_setting['postType'] = $post->post_type;
        }
        
        wp_localize_script('kct_cr_scriptx', 'aiautotool_js_setting', $js_setting);
        wp_enqueue_script('kct_cr_scriptx');
        
        // === Bot Assistant Specific Scripts ===
        wp_enqueue_script(
            'bot-assistant-script',
            $assets_url . 'js/bot-assistant.js?v=' . time(),
            array('jquery', 'kct_cr_scriptx'),
            time(),
            true
        );
        
        // Cursor-style chat JavaScript
        wp_enqueue_script(
            'cursor-style-chat-script',
            $assets_url . 'js/cursor-style-chat.js',
            array('jquery'),
            time(),
            true
        );
        
        // Enhanced display JS
        $enhanced_display_js = $assets_url . 'js/enhanced-display.js';
        if (file_exists($plugin_path . 'inc/bot-assistant/assets/js/enhanced-display.js')) {
            wp_enqueue_script(
                'enhanced-display-script',
                $enhanced_display_js,
                array('jquery'),
                time(),
                true
            );
        }
        
        // AI Agent JS
        wp_enqueue_script(
            'aiautotool-agent',
            $assets_url . 'js/ai-agent.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        // Localize bot assistant script
        wp_localize_script('bot-assistant-script', 'botAssistantData', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('bot_assistant_nonce'),
            'strings' => array(
                'askMe' => __('Ask me anything about your site...', 'ai-auto-tool'),
                'searching' => __('Searching...', 'ai-auto-tool'),
                'analyzing' => __('Analyzing...', 'ai-auto-tool'),
            )
        ));
        
        // Localize AI Agent script
        wp_localize_script('aiautotool-agent', 'aiAgentData', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'resturl' => rest_url('aiautotool-agent/v1/'),
            'nonce' => wp_create_nonce('ai_agent_nonce'),
            'rest_nonce' => wp_create_nonce('wp_rest')
        ));
    }
    
    /**
     * Initialize monitoring system
     */
    private function init_monitoring() {
        // Get all active AI tools
        $this->tools_monitor = $this->get_active_tools();
        
        // Schedule cron if not exists
        if (!wp_next_scheduled('aiautotool_bot_assistant_daily_check')) {
            wp_schedule_event(time(), 'daily', 'aiautotool_bot_assistant_daily_check');
        }
    }
    
    /**
     * Get all active AI tools
     */
    private function get_active_tools() {
        // Memory optimization - cache results
        static $cached_tools = null;
        if ($cached_tools !== null) {
            return $cached_tools;
        }
        
        $tools = array();
        
        // Check which AI tools are active
        $available_tools = array(
            'cloudflare_ai' => 'AI_AutoTool_cloudfalreAI',
            'auto_comment' => 'aiautotool_autocomment',
            'auto_tag' => 'aiautotool_autocreatetag',
            'bot_security' => 'aiautotool_bot_scrurity',
            'images' => 'images',
            'singleai' => 'singleai',
            'webstories' => 'webstories',
            'scan' => 'scan',
        );
        
        foreach ($available_tools as $key => $class_name) {
            if (class_exists($class_name) || get_option('aiautotool_' . $key . '_active') == 1) {
                $tools[$key] = array(
                    'name' => $key,
                    'class' => $class_name,
                    'status' => 'active',
                    'last_activity' => get_option('aiautotool_' . $key . '_last_activity', time())
                );
            }
        }
        
        // Cache the tools
        $cached_tools = $tools;
        return $tools;
    }
    
    /**
     * Render admin page
     */
    public function render_admin_page() {
        ?>
        <div class="wrap bot-assistant-wrap">
            <h1>
                <span class="dashicons dashicons-admin-generic"></span>
                <?php _e('AI Bot Assistant - Your Intelligent Site Manager', 'ai-auto-tool'); ?>
            </h1>
            
            <div class="bot-assistant-container">
                <!-- Chat Interface -->
                <div class="bot-chat-section">
                    <div class="chat-header">
                        <div class="chat-header-content">
                        <h2><?php _e('Ask Your Assistant', 'ai-auto-tool'); ?></h2>
                        <p class="description"><?php _e('Ask questions about your site, get insights, or search content', 'ai-auto-tool'); ?></p>
                        </div>
                        <div class="ai-mode-indicator">
                            <?php 
                            $use_ai = get_option('aiautotool_bot_assistant_use_ai', true);
                            
                            if ($use_ai):
                                $has_ai = false;
                                $provider_info = '';
                                
                                // Check if AI Helper is available
                                if (class_exists('AIAutotool_AI_Helper')) {
                                    $has_ai = AIAutotool_AI_Helper::is_available();
                                    
                                    if ($has_ai) {
                                        $ai_info = AIAutotool_AI_Helper::get_active_info();
                                        if ($ai_info) {
                                            $provider_info = $ai_info['provider_name'] . ' - ' . $ai_info['model'];
                                        }
                                    }
                                }
                            ?>
                                <div class="mode-badge <?php echo $has_ai ? 'mode-active' : 'mode-warning'; ?>">
                                    <span class="mode-icon">🤖</span>
                                    <div class="mode-info">
                                        <strong><?php _e('AI Mode', 'ai-auto-tool'); ?></strong>
                                        <small><?php echo $has_ai ? esc_html($provider_info) : __('No AI Provider!', 'ai-auto-tool'); ?></small>
                                    </div>
                                </div>
                            <?php // else: ?>
                                <div class="mode-badge mode-inactive">
                                    <span class="mode-icon">⚡</span>
                                    <div class="mode-info">
                                        <strong><?php _e('Basic Mode', 'ai-auto-tool'); ?></strong>
                                        <small><?php _e('Pattern Matching', 'ai-auto-tool'); ?></small>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="chat-messages" id="chatMessages">
                        <div class="welcome-message bot-message">
                            <div class="bot-avatar happy">👋</div>
                            <div class="message-content">
                                <?php 
                                $assistant_name = get_option('aiautotool_bot_assistant_name', 'Mochi');
                                $role_intro = get_option('aiautotool_bot_assistant_role_intro', '');
                                
                                if (!empty($role_intro)) {
                                    // Use custom intro with name replacement
                                    $welcome = str_replace('{{assistant_name}}', $assistant_name, $role_intro);
                                    echo '<p class="sparkle-effect">' . nl2br(esc_html($welcome)) . '</p>';
                                } else {
                                    // Default welcome
                                    printf('<p class="sparkle-effect">%s</p>', sprintf(__('Hello! I\'m %s, your AI assistant! 😊', 'ai-auto-tool'), esc_html($assistant_name)));
                                    echo '<p>' . __('I can help you with:', 'ai-auto-tool') . '</p>';
                                }
                                ?>
                                <ul>
                                    <li><?php _e('📊 Content analysis and statistics', 'ai-auto-tool'); ?></li>
                                    <li><?php _e('🔍 Search and find content', 'ai-auto-tool'); ?></li>
                                    <li><?php _e('⚠️ Site health alerts', 'ai-auto-tool'); ?></li>
                                    <li><?php _e('🤖 AI tools monitoring', 'ai-auto-tool'); ?></li>
                                    <li><?php _e('💡 Smart suggestions & automated actions', 'ai-auto-tool'); ?></li>
                                </ul>
                                <button class="query-suggestion-btn" data-query="<?php _e('Show me query suggestions', 'ai-auto-tool'); ?>" style="margin-top: 15px; display: inline-block;">
                                    💡 <?php _e('Show me what I can ask', 'ai-auto-tool'); ?>
                                </button>
                                <div class="emoji-reactions">
                                    <span class="emoji-reaction">😊 Friendly</span>
                                    <span class="emoji-reaction">⚡ Fast</span>
                                    <span class="emoji-reaction">🧠 Smart</span>
                                </div>
                                <div class="message-status ai-powered">
                                    <?php _e('AI-Powered Assistant', 'ai-auto-tool'); ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="chat-input-container">
                        <input type="text" 
                               id="chatInput" 
                               class="chat-input" 
                               placeholder="<?php _e('Ask me anything about your site...', 'ai-auto-tool'); ?>"
                               autocomplete="off">
                        <button id="sendQuery" class="button button-primary">
                            <span class="dashicons dashicons-send"></span>
                            <?php _e('Send', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                    
                    <!-- Quick Actions -->
                    <div class="quick-actions">
                        <button class="quick-action" data-query="show-content-stats">
                            📊 <?php _e('Content Stats', 'ai-auto-tool'); ?>
                        </button>
                        <button class="quick-action" data-query="show-alerts">
                            ⚠️ <?php _e('Alerts', 'ai-auto-tool'); ?>
                        </button>
                        <button class="quick-action" data-query="show-tools-status">
                            🤖 <?php _e('AI Tools Status', 'ai-auto-tool'); ?>
                        </button>
                        <button class="quick-action" data-query="show-suggestions">
                            💡 <?php _e('Suggestions', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                </div>
                
                <!-- Dashboard Panels -->
                <div class="bot-dashboard-panels">
                    
                    <!-- Real-time Insights -->
                    <div class="dashboard-panel insights-panel">
                        <h3><?php _e('Real-time Insights', 'ai-auto-tool'); ?></h3>
                        <div id="realTimeInsights" class="insights-content">
                            <?php $this->render_insights(); ?>
                        </div>
                    </div>
                    
                    <!-- Active AI Tools -->
                    <div class="dashboard-panel tools-panel">
                        <h3><?php _e('Active AI Tools', 'ai-auto-tool'); ?></h3>
                        <div id="activeTools" class="tools-content">
                            <?php $this->render_active_tools(); ?>
                        </div>
                    </div>
                    
                    <!-- Alerts & Warnings -->
                    <div class="dashboard-panel alerts-panel">
                        <h3><?php _e('Alerts & Warnings', 'ai-auto-tool'); ?></h3>
                        <div id="alertsContent" class="alerts-content">
                            <?php $this->render_alerts(); ?>
                        </div>
                    </div>
                    
                    <!-- Statistics -->
                    <div class="dashboard-panel stats-panel">
                        <h3><?php _e('Site Statistics', 'ai-auto-tool'); ?></h3>
                        <div id="statsContent" class="stats-content">
                            <?php $this->render_statistics(); ?>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render standalone chat interface (for modal/iframe) - Cursor Style
     */
    public function render_standalone_chat() {
        $assistant_name = get_option('aiautotool_bot_assistant_name', 'AIAUTOTOOL');
        $use_ai = get_option('aiautotool_bot_assistant_use_ai', true);
        $has_ai = false;
        $provider_info = '';
        
        if ($use_ai && class_exists('AIAutotool_AI_Helper')) {
            $has_ai = AIAutotool_AI_Helper::is_available();
            if ($has_ai) {
                $ai_info = AIAutotool_AI_Helper::get_active_info();
                if ($ai_info) {
                    $provider_info = $ai_info['provider_name'] . ' - ' . $ai_info['model'];
                }
            }
        }
        ?>
        <div class="cursor-chat-container" style="height: 100%; border-radius: 0;">
            <!-- Chat Header -->
            <div class="cursor-chat-header">
                <div class="chat-header-left">
                    <h1 class="chat-title"><?php echo esc_html($assistant_name); ?></h1>
                    <p class="chat-subtitle"><?php _e('AI Assistant', 'ai-auto-tool'); ?></p>
                </div>
                <div class="chat-header-right">
                    <div class="status-indicator">
                        <div class="status-dot" style="background: <?php echo $has_ai ? 'var(--success-color)' : 'var(--warning-color)'; ?>;"></div>
                        <span><?php echo $has_ai ? __('AI Online', 'ai-auto-tool') : __('Basic Mode', 'ai-auto-tool'); ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Chat Messages -->
            <div class="cursor-chat-messages" id="cursorChatMessages-standalone">
                <div class="welcome-message">
                    <div class="bot-avatar">🤖</div>
                    <div class="bot-message-content">
                        <?php 
                        $role_intro = get_option('aiautotool_bot_assistant_role_intro', '');
                        
                        if (!empty($role_intro)) {
                            $welcome = str_replace('{{assistant_name}}', $assistant_name, $role_intro);
                            echo '<p>' . nl2br(esc_html($welcome)) . '</p>';
                        } else {
                            printf('<p>%s</p>', sprintf(__('Xin chào! Tôi là %s, AI Assistant của bạn! 😊', 'ai-auto-tool'), esc_html($assistant_name)));
                            echo '<p>' . __('Tôi có thể giúp bạn:', 'ai-auto-tool') . '</p>';
                        }
                        ?>
                        <ul>
                            <li><?php _e('📊 Phân tích và thống kê nội dung', 'ai-auto-tool'); ?></li>
                            <li><?php _e('🔍 Tìm kiếm và tìm nội dung', 'ai-auto-tool'); ?></li>
                            <li><?php _e('⚠️ Cảnh báo sức khỏe website', 'ai-auto-tool'); ?></li>
                            <li><?php _e('🤖 Giám sát AI tools', 'ai-auto-tool'); ?></li>
                            <li><?php _e('💡 Gợi ý thông minh & hành động tự động', 'ai-auto-tool'); ?></li>
                        </ul>
                        <div style="margin-top: 15px;">
                            <button class="query-suggestion-btn" data-query="<?php _e('Show me query suggestions', 'ai-auto-tool'); ?>" style="
                                background: var(--accent-primary);
                                color: white;
                                border: none;
                                padding: 8px 16px;
                                border-radius: 20px;
                                cursor: pointer;
                                font-size: 13px;
                                transition: all 0.3s ease;
                            ">
                                💡 <?php _e('Xem những gì tôi có thể hỏi', 'ai-auto-tool'); ?>
                            </button>
                        </div>
                        <div class="message-status" style="margin-top: 8px; font-size: 12px; color: var(--text-muted);">
                            <?php if ($has_ai): ?>
                                🤖 <?php echo esc_html($provider_info); ?>
                            <?php // else: ?>
                                ⚡ <?php _e('Basic Mode', 'ai-auto-tool'); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Chat Input -->
            <div class="cursor-chat-input-container">
                <div class="chat-input-wrapper">
                    <textarea 
                        class="cursor-chat-input" 
                        id="cursorChatInput-standalone" 
                        placeholder="<?php _e('Nhập tin nhắn của bạn...', 'ai-auto-tool'); ?>"
                        rows="1"
                    ></textarea>
                    <button class="send-button" id="cursorSendButton-standalone">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                        </svg>
                    </button>
                </div>
            </div>
            
            <!-- Status Bar -->
            <div class="status-bar">
                <div class="status-right">
                    <div class="status-item">
                        <span class="status-icon">📊</span>
                        <span id="progressPercentage-standalone">0%</span>
                    </div>
                    <div class="status-item">
                        <span class="status-icon">⏱️</span>
                        <span id="executionTime-standalone">0.0s</span>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        // Initialize Cursor-style chat for standalone
        jQuery(document).ready(function($) {
            if (typeof CursorChat !== 'undefined') {
                // Override IDs for standalone version
                CursorChat.config.standaloneMode = true;
                CursorChat.config.messageContainerId = 'cursorChatMessages-standalone';
                CursorChat.config.inputId = 'cursorChatInput-standalone';
                CursorChat.config.sendButtonId = 'cursorSendButton-standalone';
                
                // Initialize standalone chat
                CursorChat.initStandalone();
            }
        });
        </script>
        <?php
    }
    
    /**
     * AJAX handler: Render standalone chat HTML
     */
    public function render_standalone_chat_html() {
        check_ajax_referer('floating_robot_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        ob_start();
        $this->render_standalone_chat();
        $html = ob_get_clean();
        
        wp_send_json_success(array('html' => $html));
    }
    
    /**
     * Render real-time insights
     */
    private function render_insights() {
        $insights = $this->analyze_site_insights();
        
        if (empty($insights)) {
            echo '<p class="no-data">' . __('Collecting insights...', 'ai-auto-tool') . '</p>';
            return;
        }
        
        echo '<div class="insights-grid">';
        foreach ($insights as $insight) {
            echo '<div class="insight-item ' . esc_attr($insight['type']) . '">';
            echo '<div class="insight-icon">' . $insight['icon'] . '</div>';
            echo '<div class="insight-content">';
            echo '<h4>' . esc_html($insight['title']) . '</h4>';
            echo '<p>' . esc_html($insight['message']) . '</p>';
            if (!empty($insight['action'])) {
                echo '<a href="' . esc_url($insight['action']['url']) . '" class="insight-action">' . 
                     esc_html($insight['action']['label']) . '</a>';
            }
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';
    }
    
    /**
     * Render active tools status
     */
    private function render_active_tools() {
        $tools = $this->get_active_tools();
        
        if (empty($tools)) {
            echo '<p class="no-data">' . __('No AI tools are currently active', 'ai-auto-tool') . '</p>';
            return;
        }
        
        echo '<div class="tools-grid">';
        foreach ($tools as $tool) {
            $stats = $this->get_tool_statistics($tool['name']);
            
            echo '<div class="tool-item">';
            echo '<div class="tool-header">';
            echo '<span class="tool-name">' . esc_html($this->get_tool_label($tool['name'])) . '</span>';
            echo '<span class="tool-status status-' . esc_attr($tool['status']) . '">' . 
                 esc_html($tool['status']) . '</span>';
            echo '</div>';
            
            if (!empty($stats)) {
                echo '<div class="tool-stats">';
                foreach ($stats as $key => $value) {
                    echo '<div class="stat-item">';
                    echo '<span class="stat-label">' . esc_html($key) . ':</span> ';
                    echo '<span class="stat-value">' . esc_html($value) . '</span>';
                    echo '</div>';
                }
                echo '</div>';
            }
            
            echo '<div class="tool-footer">';
            echo '<small>' . sprintf(__('Last activity: %s', 'ai-auto-tool'), 
                 human_time_diff($tool['last_activity'], current_time('timestamp'))) . ' ' . __('ago', 'ai-auto-tool') . '</small>';
            echo '</div>';
            echo '</div>';
        }
        echo '</div>';
    }
    
    /**
     * Render alerts
     */
    private function render_alerts() {
        $alerts = $this->get_site_alerts();
        
        if (empty($alerts)) {
            echo '<div class="no-alerts">';
            echo '<span class="dashicons dashicons-yes-alt"></span>';
            echo '<p>' . __('All good! No alerts at the moment.', 'ai-auto-tool') . '</p>';
            echo '</div>';
            return;
        }
        
        echo '<div class="alerts-list">';
        foreach ($alerts as $alert) {
            echo '<div class="alert-item severity-' . esc_attr($alert['severity']) . '">';
            echo '<div class="alert-icon">' . $this->get_alert_icon($alert['severity']) . '</div>';
            echo '<div class="alert-content">';
            echo '<h4>' . esc_html($alert['title']) . '</h4>';
            echo '<p>' . esc_html($alert['message']) . '</p>';
            if (!empty($alert['action'])) {
                echo '<a href="' . esc_url($alert['action']['url']) . '" class="button button-small">' . 
                     esc_html($alert['action']['label']) . '</a>';
            }
            echo '</div>';
            echo '<div class="alert-time">' . human_time_diff($alert['time'], current_time('timestamp')) . ' ' . 
                 __('ago', 'ai-auto-tool') . '</div>';
            echo '</div>';
        }
        echo '</div>';
    }
    
    /**
     * Render statistics
     */
    private function render_statistics() {
        $stats = $this->get_site_statistics();
        
        echo '<div class="stats-grid">';
        
        // Content stats
        echo '<div class="stat-card">';
        echo '<div class="stat-icon">📝</div>';
        echo '<div class="stat-info">';
        echo '<div class="stat-value">' . number_format($stats['total_posts']) . '</div>';
        echo '<div class="stat-label">' . __('Total Posts', 'ai-auto-tool') . '</div>';
        echo '</div>';
        echo '</div>';
        
        // Images stats
        echo '<div class="stat-card">';
        echo '<div class="stat-icon">🖼️</div>';
        echo '<div class="stat-info">';
        echo '<div class="stat-value">' . number_format($stats['total_images']) . '</div>';
        echo '<div class="stat-label">' . __('Total Images', 'ai-auto-tool') . '</div>';
        echo '</div>';
        echo '</div>';
        
        // Comments stats
        echo '<div class="stat-card">';
        echo '<div class="stat-icon">💬</div>';
        echo '<div class="stat-info">';
        echo '<div class="stat-value">' . number_format($stats['total_comments']) . '</div>';
        echo '<div class="stat-label">' . __('Comments', 'ai-auto-tool') . '</div>';
        echo '</div>';
        echo '</div>';
        
        // AI Actions stats
        echo '<div class="stat-card">';
        echo '<div class="stat-icon">🤖</div>';
        echo '<div class="stat-info">';
        echo '<div class="stat-value">' . number_format($stats['ai_actions']) . '</div>';
        echo '<div class="stat-label">' . __('AI Actions Today', 'ai-auto-tool') . '</div>';
        echo '</div>';
        echo '</div>';
        
        echo '</div>';
        
        // Trends
        echo '<div class="stats-trends">';
        echo '<h4>' . __('7-Day Trends', 'ai-auto-tool') . '</h4>';
        echo '<div id="trendChart" class="trend-chart"></div>';
        echo '</div>';
    }
    
    /**
     * Extract JSON from text (handles markdown code blocks and raw JSON)
     * 
     * @param string $text Text containing JSON
     * @return array|false Parsed JSON array or false on failure
     */
    private function extract_json_from_text($text) {
        // Remove markdown code blocks
        $text = preg_replace('/```json\s*/i', '', $text);
        $text = preg_replace('/```\s*$/m', '', $text);
        
        // Find the JSON object between { and }
        $json_start = strpos($text, '{');
        $json_end = strrpos($text, '}');
        
        if ($json_start !== false && $json_end !== false && $json_end > $json_start) {
            $json_str = substr($text, $json_start, $json_end - $json_start + 1);
            
            // Try to decode
            $decoded = json_decode($json_str, true);
            
            if (json_last_error() === JSON_ERROR_NONE) {
                return $decoded;
            }
        }
        
        // If no valid JSON found, try decoding the whole text
        $decoded = json_decode($text, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $decoded;
        }
        
        return false;
    }
    
    /**
     * Handle natural language query
     */
    public function handle_query() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        // Memory optimization - increase limit for AJAX requests
        if (function_exists('ini_set')) {
            ini_set('memory_limit', '512M');
        }
        
        // Monitor memory usage
        $start_memory = memory_get_usage(true);
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $query = sanitize_text_field($_POST['query']);
        
        // 🔥 REMOVED: Keyword-based intent detection - Let AI decide instead
        // Chỉ dùng planner/auto-execute nếu user explicitly request hoặc AI suggest
        $use_planner = isset($_POST['use_planner']) ? (bool)$_POST['use_planner'] : false;
        $auto_execute = isset($_POST['auto_execute']) ? (bool)$_POST['auto_execute'] : false;
        
        // Get conversation history for context
        $history = isset($_POST['history']) ? json_decode(stripslashes($_POST['history']), true) : array();
        if (!is_array($history)) {
            $history = array();
        }
        
        // Sanitize and validate history
        $sanitized_history = array();
        foreach ($history as $msg) {
            if (isset($msg['role']) && isset($msg['content'])) {
                $role = sanitize_text_field($msg['role']);
                
                // 🔍 DEBUG: Log role validation
                
                // Validate and normalize roles
                if (!in_array($role, ['user', 'assistant', 'system'])) {
                    continue;
                }
                
                $sanitized_history[] = array(
                    'role' => $role,
                    'content' => wp_kses_post($msg['content'])
                );
            }
        }
        $history = array_slice($sanitized_history, -10); // Limit to last 10 messages
        
        // 🔥 REMOVED: Auto-execute và planner dựa trên keyword detection
        // Chỉ dùng khi user explicitly request (qua POST param)
        // Để AI tự quyết định khi nào cần tool dựa trên context và prompt
        
        // 🤖 STEP 1: AI-powered response with automatic tool calling
        // Let AI decide when to call tools based on user query
        
        // 🔍 DEBUG: Log input
        
        $ai_response = $this->query_with_ai($query, $history);
        
        // 🔍 DEBUG: Log AI response
        if (!is_wp_error($ai_response)) {
        } else {
        }
        
        if (!is_wp_error($ai_response) && !empty($ai_response)) {
            // 🔍 CRITICAL: Log full AI response to see if it contains TOOL_CALL
            
            // Parse AI response for actions
            $parsed_response = $this->parse_ai_response($ai_response, $query);
            
            // Add original query to parsed response for auto-fix
            $parsed_response['original_query'] = $query;
            
            // 🔍 DEBUG: Log parsed response
            
            // 🆕 STEP 1 & 2: Tool detected → Validate parameters → Ask user or execute
            if (isset($parsed_response['tool_name']) && !empty($parsed_response['tool_name'])) {
                
                // STEP 1: Validate tool appropriateness for query type
                $tool_name = $parsed_response['tool_name'];
                $tool_args = isset($parsed_response['tool_args']) ? $parsed_response['tool_args'] : array();
                
                // 🔥 CRITICAL: Check if AI called wrong tool for information questions
                if ($this->is_information_question($query) && $tool_name === 'create_post') {
                    // This is an information question, should use query_database instead
                    $tool_name = 'query_database';
                    $query_type = $this->infer_query_type_from_question($query);
                    $tool_args = array('query_type' => $query_type);
                    $parsed_response['response'] = ''; // Clear response to use tool result
                }
                
                // Get tool definition and check required parameters
                $validation_result = $this->validate_and_complete_tool_params($tool_name, $tool_args, $query, $history);
                
                if (!$validation_result['valid']) {
                    // STEP 2a: Missing required params that can't be inferred → Ask user
                    
                    $missing_params_text = implode(', ', $validation_result['missing']);
                    $ask_message = $parsed_response['response'] . "\n\n";
                    $ask_message .= "⚠️ **Cần thêm thông tin:**\n";
                    $ask_message .= "Để thực hiện `{$tool_name}`, tôi cần thêm thông tin về: **{$missing_params_text}**\n\n";
                    
                    if (!empty($validation_result['details'])) {
                        $ask_message .= $validation_result['details'] . "\n\n";
                    }
                    
                    $ask_message .= "Vui lòng cung cấp thông tin này để tiếp tục.";
                    
                    wp_send_json_success(array(
                        'response' => $ask_message,
                        'intent' => 'need_more_info',
                        'source' => 'tool_validation',
                        'tool_name' => $tool_name,
                        'missing_params' => $validation_result['missing'],
                        'tool_args' => $tool_args,
                        'debug' => array(
                            'mode' => 'Waiting for User Input',
                            'tool' => $tool_name,
                            'missing' => $validation_result['missing']
                        )
                    ));
                    return;
                }
                
                // STEP 2b: All params available (complete or inferred) → Execute tool
                $complete_args = $validation_result['args'];
                
                // Execute tool immediately
                if (class_exists('AIautotool_Agent_Tools')) {
                    $execution_result = AIautotool_Agent_Tools::execute_tool($tool_name, $complete_args);
                    
                    // Format execution result
                    $response_message = $parsed_response['response'];
                    
                    if (isset($execution_result['success']) && $execution_result['success']) {
                        $response_message .= "\n\n✅ **Đã thực hiện thành công!**\n";
                        if (isset($execution_result['message'])) {
                            $response_message .= $execution_result['message'] . "\n";
                        }
                        if (isset($execution_result['data']) && !empty($execution_result['data'])) {
                            $response_message .= "\n📊 **Kết quả:**\n";
                            if (is_array($execution_result['data'])) {
                                $response_message .= "```json\n" . json_encode($execution_result['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n```";
                            } else {
                                $response_message .= $execution_result['data'];
                            }
                        }
                    } else {
                        $error_msg = isset($execution_result['error']) ? $execution_result['error'] : 'Unknown error';
                        $response_message .= "\n\n❌ **Lỗi khi thực hiện:**\n{$error_msg}";
                    }
                    
                    wp_send_json_success(array(
                        'response' => $response_message,
                        'intent' => 'tool_executed',
                        'source' => 'tool_execution',
                        'tool_name' => $tool_name,
                        'tool_args' => $complete_args,
                        'execution_result' => $execution_result,
                        'auto_executed' => true,
                        'debug' => array(
                            'mode' => 'Auto Execute Tool',
                            'tool' => $tool_name,
                            'success' => $execution_result['success'] ?? false
                        )
                    ));
                    return;
                } else {
                    // Fallback: return tool info if tools class not available
                    wp_send_json_success(array(
                        'response' => $parsed_response['response'],
                        'intent' => 'tool_call_detected',
                        'source' => 'tool_execution',
                        'step_by_step' => true,
                        'tool_name' => $tool_name,
                        'tool_args' => $complete_args,
                        'debug' => array(
                            'mode' => 'Tool Ready (Tools class unavailable)',
                            'tool' => $tool_name
                        )
                    ));
                    return;
                }
            }
            
            // 🔥 FALLBACK: If no tool detected but it's an information question → auto-call query_database
            if ($this->is_information_question($query)) {
                
                // Auto-call query_database based on query
                $query_type = $this->infer_query_type_from_question($query);
                
                if ($query_type) {
                    $tool_name = 'query_database';
                    $tool_args = array('query_type' => $query_type);
                    
                    // Execute query_database
                    if (class_exists('AIautotool_Agent_Tools')) {
                        $execution_result = AIautotool_Agent_Tools::execute_tool($tool_name, $tool_args);
                        
                        if (isset($execution_result['success']) && $execution_result['success']) {
                            $response_message = isset($parsed_response['response']) ? $parsed_response['response'] : $ai_response;
                            $response_message .= "\n\n📊 **Kết quả:**\n";
                            if (isset($execution_result['data']) && !empty($execution_result['data'])) {
                                if (is_array($execution_result['data'])) {
                                    $response_message .= json_encode($execution_result['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
                                } else {
                                    $response_message .= $execution_result['data'];
                                }
                            }
                            
                            wp_send_json_success(array(
                                'response' => $response_message,
                                'intent' => 'tool_executed',
                                'source' => 'auto_query_fallback',
                                'tool_name' => $tool_name,
                                'tool_args' => $tool_args,
                                'execution_result' => $execution_result,
                                'auto_executed' => true,
                                'debug' => array(
                                    'mode' => 'Auto Query Fallback',
                                    'tool' => $tool_name,
                                    'success' => true
                                )
                            ));
                            return;
                        }
                    }
                }
            }
            
            // Get AI info for debug
            $ai_info = class_exists('AIAutotool_AI_Helper') ? AIAutotool_AI_Helper::get_active_info() : null;
            
            wp_send_json_success(array(
                'response' => isset($parsed_response['response']) ? $parsed_response['response'] : $ai_response,
                'intent' => isset($parsed_response['intent']) ? $parsed_response['intent'] : 'general',
                'source' => 'ai_context_detection',
                'debug' => array(
                    'mode' => 'AI-Powered Context Analysis',
                    'provider' => $ai_info ? $ai_info['provider_name'] : 'Unknown',
                    'model' => $ai_info ? $ai_info['model'] : 'Unknown',
                    'history_messages' => count($history),
                    'has_context' => !empty($history),
                    'planner_available' => class_exists('AIautotool_Agent_Planner')
                )
            ));
            return;
        }
        
        // 📋 STEP 2: Fallback - AI intent detection without full context (lightweight)
        $error_message = is_wp_error($ai_response) ? $ai_response->get_error_message() : 'Unknown error';
        
        // Try lightweight AI intent classification if API is available
        $ai_intent = $this->detect_intent_with_ai($query);
        
        if ($ai_intent !== false) {
            // AI successfully detected intent and suggested tool
            wp_send_json_success(array(
                'response' => $ai_intent['response'],
                'intent' => $ai_intent['intent'],
                'source' => 'ai_intent_only',
                'debug' => array(
                    'mode' => 'AI Intent Detection (Lightweight)',
                    'full_ai_error' => $error_message,
                    'detected_tool' => $ai_intent['tool'] ?? 'none'
                )
            ));
            return;
        }
        
        // 🔤 STEP 3: Final fallback - Basic pattern matching (no AI available)
        $intent = $this->analyze_query_intent($query);
        $response = $this->generate_response($intent, $query);
        
        // Get AI info for debug
        $ai_info = class_exists('AIAutotool_AI_Helper') ? AIAutotool_AI_Helper::get_active_info() : null;
        
        wp_send_json_success(array(
            'response' => $response,
            'intent' => $intent,
            'source' => 'pattern',
            'debug' => array(
                'mode' => 'Pattern Matching (AI Fallback)',
                'ai_error' => $error_message,
                'use_ai_setting' => get_option('aiautotool_bot_assistant_use_ai', true),
                'ai_configured' => $ai_info !== null,
                'provider' => $ai_info ? $ai_info['provider_name'] : 'None'
            )
        ));
    }
    
    /**
     * Format TODO list with progress
     */
    private function format_todo_list($todos, $data = array()) {
        $progress = isset($data['progress']) ? $data['progress'] : 0;
        $completed = isset($data['completed_steps']) ? $data['completed_steps'] : 0;
        $total = isset($data['total_steps']) ? $data['total_steps'] : count($todos);
        
        $output = "📋 **TODO LIST - TẠO BÀI VIẾT**\n\n";
        
        // Progress bar
        $bar_length = 20;
        $filled = round(($progress / 100) * $bar_length);
        $empty = $bar_length - $filled;
        $progress_bar = str_repeat('█', $filled) . str_repeat('░', $empty);
        
        $output .= "🔄 Progress: [{$progress_bar}] {$progress}%\n";
        $output .= "✅ Hoàn thành: {$completed}/{$total} bước\n\n";
        
        // TODO items
        $output .= "**Chi tiết các bước:**\n";
        foreach ($todos as $index => $todo) {
            $step_num = $index + 1;
            $status = $todo['status'];
            $message = $todo['message'];
            
            // Icon based on status
            switch ($status) {
                case 'completed':
                    $icon = '✅';
                    $style = '';
                    break;
                case 'in_progress':
                    $icon = '⏳';
                    $style = '**[ĐANG LÀM]** ';
                    break;
                case 'failed':
                    $icon = '❌';
                    $style = '';
                    break;
                case 'skipped':
                    $icon = '⏭️';
                    $style = '';
                    break;
                default: // pending
                    $icon = '⏸️';
                    $style = '';
            }
            
            $output .= "{$step_num}. {$icon} {$style}{$message}\n";
        }
        
        return $output;
    }
    
    /**
     * Parse AI response for actions
     */
    private function parse_ai_response($ai_response, $query = '') {
        // Check if AI called a tool (TOOL_CALL format)
            if (preg_match('/TOOL_CALL:\s*(\w+)/i', $ai_response, $tool_match)) {
                $tool_name = trim($tool_match[1]);
                
                // 🔍 DEBUG: Log tool call detection
                
                // Extract tool arguments - improved to handle nested JSON (Cursor-style)
                $tool_args = array();
                if (preg_match('/TOOL_ARGS:\s*(.+?)(?=\n\s*[A-Z_]|$)/is', $ai_response, $args_match)) {
                    $args_str = trim($args_match[1]);
                    
                    
                    // Try to parse as JSON
                    $tool_args = $this->extract_json_from_text($args_str);
                    
                    if (!is_array($tool_args)) {
                        $tool_args = array();
                    } else {
                    }
                }
                
                // 🆕 Don't execute here - return tool_name and tool_args for auto-executor
                // Get clean message (text before TOOL_CALL)
                $clean_message = preg_replace('/TOOL_CALL:.*$/is', '', $ai_response);
                $clean_message = trim($clean_message);
                
                // 🔥 Clean up any unwanted text patterns in AI response
                $clean_message = self::clean_ai_response($clean_message);
                
                // Return tool info for auto-execution (not execute here)
                return array(
                    'response' => $clean_message,
                    'intent' => 'tool_call_detected',
                    'tool_name' => $tool_name,
                    'tool_args' => $tool_args
                );
            }
        
        // Check if AI suggested an action (old format for built-in actions)
        if (preg_match('/ACTION:\s*(\w+)/i', $ai_response, $action_match) &&
            preg_match('/CONFIRM:\s*(.+?)(?=\n\n|$)/is', $ai_response, $confirm_match)) {
            
            $action_type = trim($action_match[1]);
            $confirm_message = trim($confirm_match[1]);
            
            // Extract params if present
            $params = array();
            if (preg_match('/PARAMS:\s*(\{[^}]+\})/i', $ai_response, $params_match)) {
                $params = json_decode($params_match[1], true);
                if (!$params) {
                    $params = array();
                }
            }
            
            // Get clean message (remove ACTION markers)
            $clean_message = preg_replace('/ACTION:.*?CONFIRM:.*?(?=\n\n|$)/is', '', $ai_response);
            $clean_message = preg_replace('/PARAMS:.*?(?=\n)/i', '', $clean_message);
            $clean_message = trim($clean_message);
            
            // Get count info from context for the action
            $context = $this->get_site_context();
            $count = 0;
            
            switch ($action_type) {
                case 'delete_drafts':
                    $count = $context['posts']['total_drafts'];
                    break;
                case 'publish_drafts':
                    $count = $context['posts']['total_drafts'];
                    break;
                case 'add_alt_text':
                    $count = $context['images']['without_alt'];
                    break;
                case 'fix_broken_images':
                    $count = $context['images']['broken'];
                    break;
                case 'delete_old_posts':
                    $count = isset($params['count']) ? $params['count'] : 0;
                    break;
            }
            
            $params['count'] = $count;
            
            // Generate action confirmation response
            $response = $clean_message . "\n\n" . $confirm_message;
            $response = $this->generate_action_response(
                $clean_message,
                $confirm_message,
                $action_type,
                $params
            );
            
            return array(
                'response' => $response,
                'intent' => 'action_' . $action_type
            );
        }
        
        // No action detected, return normal response
        $result = array(
            'response' => $ai_response,
            'intent' => 'ai_powered'
        );
        
        // Memory monitoring
        $end_memory = memory_get_usage(true);
        $memory_used = isset($start_memory) ? ($end_memory - $start_memory) : 0;
        if ($memory_used > (100 * 1024 * 1024)) { // 100MB
        }
        
        return $result;
    }
    
    /**
     * Query with AI for intelligent responses
     * 
     * @param string $query User's current query
     * @param array $history Conversation history for context
     */
    private function query_with_ai($query, $history = array()) {
        // Check if AI mode is enabled
        $use_ai = get_option('aiautotool_bot_assistant_use_ai', true);
        if (!$use_ai) {
            return new WP_Error('ai_disabled', 'AI mode is disabled');
        }
        
        // Check if AI Helper is available
        if (!class_exists('AIAutotool_AI_Helper')) {
            return new WP_Error('no_ai_helper', 'AI Helper class not found. Please load AI Providers module.');
        }
        
        // Check if AI is available
        if (!AIAutotool_AI_Helper::is_available()) {
            return new WP_Error('no_ai_configured', 'No AI provider configured. Please configure an AI provider in AI Provider Settings.');
        }
        
        // Get comprehensive site context for AI
        $context = $this->get_site_context();
        
        // Build system prompt with all context
        $system_prompt = $this->build_ai_system_prompt($context);
        
        // Build messages array with system prompt and history
        $messages = array(
            array(
                'role' => 'system',
                'content' => $system_prompt
            )
        );
        
        // 🔍 DEBUG: Log system prompt
        
        // Add conversation history (up to 10 previous messages)
        if (!empty($history)) {
            foreach ($history as $msg) {
                $role = $msg['role'] === 'user' ? 'user' : 'assistant';
                
                // 🔍 DEBUG: Log role validation
                
                $messages[] = array(
                    'role' => $role,
                    'content' => $msg['content']
                );
            }
        }
        
        // Add current query
        $messages[] = array(
            'role' => 'user',
            'content' => $query
        );
        
        // Validate message roles before sending to AI
        $messages = $this->validate_message_roles($messages);
        
        // 🔍 DEBUG: Log messages to AI
        foreach ($messages as $i => $msg) {
        }
        
        // 🔍 DEBUG: Log active provider and model
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $active_provider = $manager->get_active_provider();
        $active_model = $manager->get_active_model();
        
        if ($active_provider) {
        }
        
        // Call AI using bot assistant specific config
        $response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.7,
            'max_tokens' => 1500
        ));
        
        // 🔍 DEBUG: Log AI raw response
        if ($response['success']) {
        } else {
        }
        
        // Check response
        if (!$response['success']) {
            // Log error for debugging
            $error_msg = isset($response['error']) ? $response['error'] : 'Unknown error';
            return new WP_Error('ai_error', $error_msg);
        }
        
        if (empty($response['content'])) {
            return new WP_Error('empty_response', 'AI returned empty response.');
        }
        
        // Update memory with user behavior patterns (async, don't block response)
        $this->update_user_memory($query, $response['content'], $history);
        
        return $response['content'];
    }
    
    /**
     * Update user behavior memory after each conversation
     */
    private function update_user_memory($query, $response, $history) {
        $memory_type = get_option('aiautotool_bot_assistant_memory_type', 'session');
        
        // Skip if memory is disabled
        if ($memory_type === 'none') {
            return;
        }
        
        $current_memory = get_option('aiautotool_bot_assistant_current_memory', '');
        
        // Analyze user query for patterns
        $user_id = get_current_user_id();
        $timestamp = current_time('mysql');
        
        // Build memory update prompt
        $memory_prompt = "Based on this conversation, update the user behavior memory:\n\n";
        $memory_prompt .= "Previous Memory:\n{$current_memory}\n\n";
        $memory_prompt .= "New Interaction:\n";
        $memory_prompt .= "User: {$query}\n";
        $memory_prompt .= "Bot: {$response}\n\n";
        $memory_prompt .= "Extract and update:\n";
        $memory_prompt .= "- Topics user is interested in\n";
        $memory_prompt .= "- Common actions user performs\n";
        $memory_prompt .= "- Language preference\n";
        $memory_prompt .= "- Patterns or recurring requests\n";
        $memory_prompt .= "- User's technical level\n\n";
        $memory_prompt .= "Return updated memory summary (max 500 words):";
        
        // Call AI to analyze and update memory (in background)
        if (class_exists('AIAutotool_AI_Helper') && AIAutotool_AI_Helper::is_available()) {
            $memory_result = AIAutotool_AI_Helper::generate($memory_prompt, array(
                'max_tokens' => 600,
                'temperature' => 0.3 // Lower temperature for consistent memory
            ));
            
            if ($memory_result['success'] && !empty($memory_result['content'])) {
                $new_memory = sanitize_textarea_field($memory_result['content']);
                
                // Truncate to fit 1000 char limit
                if (strlen($new_memory) > 1000) {
                    $new_memory = substr($new_memory, 0, 997) . '...';
                }
                
                update_option('aiautotool_bot_assistant_current_memory', $new_memory);
            }
        }
    }
    
    /**
     * Get memory to include in AI prompt
     */
    private function get_memory_for_prompt() {
        $memory_type = get_option('aiautotool_bot_assistant_memory_type', 'session');
        
        if ($memory_type === 'none') {
            return '';
        }
        
        $current_memory = get_option('aiautotool_bot_assistant_current_memory', '');
        
        if (empty($current_memory)) {
            return '';
        }
        
        return "\n\n=== USER BEHAVIOR MEMORY ===\n{$current_memory}\n\n";
    }
    
    /**
     * Get comprehensive site context for AI
     */
    private function get_site_context() {
        // Memory optimization - cache results to prevent multiple calls
        static $cached_context = null;
        if ($cached_context !== null) {
            return $cached_context;
        }
        
        $stats = $this->get_site_statistics();
        $alerts = $this->get_site_alerts();
        $tools = $this->get_active_tools();
        
        // Get detailed post counts
        $post_counts = wp_count_posts('post');
        
        // Get posts by date
        $today_posts = get_posts(array(
            'post_status' => 'publish',
            'date_query' => array(array('after' => 'today')),
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        $this_month_posts = get_posts(array(
            'post_status' => 'publish',
            'date_query' => array(
                array(
                    'year' => date('Y'),
                    'month' => date('m')
                )
            ),
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        // Get latest posts
        $latest_posts = get_posts(array('numberposts' => 5));
        
        // Get images info
        $images_without_alt = $this->count_images_without_alt();
        $broken_images = $this->count_broken_images();
        
        $context = array(
            'site_name' => get_bloginfo('name'),
            'site_url' => get_site_url(),
            'current_date' => current_time('mysql'),
            'timezone' => get_option('timezone_string'),
            
            // Detailed post stats
            'posts' => array(
                'total_published' => $post_counts->publish,
                'total_drafts' => $post_counts->draft,
                'total_scheduled' => $post_counts->future,
                'total_trash' => $post_counts->trash,
                'published_today' => count($today_posts),
                'published_this_month' => count($this_month_posts),
            ),
            
            // Latest posts
            'latest_posts' => array_map(function($post) {
                return array(
                    'title' => $post->post_title,
                    'date' => $post->post_date,
                    'comments' => $post->comment_count
                );
            }, array_slice($latest_posts, 0, 5)),
            
            // Images stats
            'images' => array(
                'total' => $stats['total_images'],
                'without_alt' => $images_without_alt,
                'broken' => $broken_images
            ),
            
            // Comments
            'comments' => array(
                'total_approved' => $stats['total_comments'],
                'pending' => wp_count_comments()->moderated,
                'spam' => wp_count_comments()->spam
            ),
            
            // AI tools
            'ai_tools' => array(
                'active_count' => count($tools),
                'actions_today' => $stats['ai_actions'],
                'tools_list' => array_map(function($tool) {
                    return $this->get_tool_label($tool['name']);
                }, $tools)
            ),
            
            // Alerts
            'alerts' => array(
                'count' => count($alerts),
                'list' => array_slice(array_map(function($alert) {
                    return array(
                        'severity' => $alert['severity'],
                        'title' => $alert['title'],
                        'message' => $alert['message']
                    );
                }, $alerts), 0, 5)
            )
        );
        
        // Cache the context to prevent memory issues
        $cached_context = $context;
        return $context;
    }
    
    /**
     * Lightweight AI Intent Detection
     * Uses AI to detect user intent and suggest appropriate tool
     * Fallback when full AI response fails
     */
    private function detect_intent_with_ai($query) {
        // Check if AI Helper is available
        if (!class_exists('AIAutotool_AI_Helper')) {
            return false;
        }
        
        // Check if any AI provider is configured
        if (!AIAutotool_AI_Helper::is_available()) {
            return false;
        }
        
        // Build lightweight intent detection prompt
        $intent_prompt = "Analyze this user request and determine the intent and appropriate tool to use.\n\n";
        $intent_prompt .= "User request: \"{$query}\"\n\n";
        $intent_prompt .= "Available tools and their purposes:\n";
        $intent_prompt .= "- create_post: Create new blog posts\n";
        $intent_prompt .= "- delete_post: Delete a single post by ID\n";
        $intent_prompt .= "- delete_posts_bulk: Delete multiple posts (by IDs or by status)\n";
        $intent_prompt .= "- get_post_info: Get information about a post\n";
        $intent_prompt .= "- rewrite_post: Rewrite/edit post content\n";
        $intent_prompt .= "- schedule_post: Schedule a post for future publishing\n";
        $intent_prompt .= "- check_system_health: Check WordPress system health\n";
        $intent_prompt .= "- cleanup_database: Clean up database (revisions, transients, etc.)\n";
        $intent_prompt .= "- execute_sql: Execute SQL query directly\n";
        $intent_prompt .= "- query_database: Query database for information\n\n";
        
        $intent_prompt .= "Analyze the ACTION VERB and CONTEXT:\n";
        $intent_prompt .= "- 'Xoá/Delete/Remove' → delete_* tools\n";
        $intent_prompt .= "- 'Tạo/Create/Viết/Write' → create_post\n";
        $intent_prompt .= "- 'Sửa/Edit/Cập nhật/Update' → rewrite_post\n";
        $intent_prompt .= "- 'Xem/Show/Info/Thông tin' → get_post_info or check_system_health\n";
        $intent_prompt .= "- 'Dọn dẹp/Clean/Optimize' → cleanup_database\n\n";
        
        $intent_prompt .= "Respond in this EXACT JSON format:\n";
        $intent_prompt .= "{\n";
        $intent_prompt .= "  \"tool\": \"tool_name\",\n";
        $intent_prompt .= "  \"confidence\": 0.95,\n";
        $intent_prompt .= "  \"reasoning\": \"Brief explanation\",\n";
        $intent_prompt .= "  \"args\": {\"key\": \"value\"}\n";
        $intent_prompt .= "}\n\n";
        
        $intent_prompt .= "Example 1:\n";
        $intent_prompt .= "Input: 'Xoá bài 28807 và 28809'\n";
        $intent_prompt .= "Output: {\"tool\": \"delete_posts_bulk\", \"confidence\": 0.98, \"reasoning\": \"User wants to delete multiple specific posts\", \"args\": {\"post_ids\": [28807, 28809]}}\n\n";
        
        $intent_prompt .= "Example 2:\n";
        $intent_prompt .= "Input: 'Thông tin hệ thống'\n";
        $intent_prompt .= "Output: {\"tool\": \"check_system_health\", \"confidence\": 0.95, \"reasoning\": \"User wants system information\", \"args\": {}}\n\n";
        
        $intent_prompt .= "Now analyze the user's request above and respond with JSON only.";
        
        // Call AI for intent detection using unified helper
        $ai_result = AIAutotool_AI_Helper::generate($intent_prompt, array(
            'max_tokens' => 200,
            'temperature' => 0.1  // Low temperature for more consistent results
        ));
        
        if (!$ai_result['success'] || empty($ai_result['content'])) {
            return false;
        }
        
        // Parse JSON response
        $content = trim($ai_result['content']);
        
        // Extract JSON if wrapped in markdown code blocks
        if (preg_match('/```json\s*(\{.*?\})\s*```/s', $content, $matches)) {
            $content = $matches[1];
        } elseif (preg_match('/```\s*(\{.*?\})\s*```/s', $content, $matches)) {
            $content = $matches[1];
        }
        
        $intent_data = json_decode($content, true);
        
        if (!$intent_data || !isset($intent_data['tool'])) {
            return false;
        }
        
        $tool_name = $intent_data['tool'];
        $tool_args = isset($intent_data['args']) ? $intent_data['args'] : array();
        $confidence = isset($intent_data['confidence']) ? $intent_data['confidence'] : 0.0;
        $reasoning = isset($intent_data['reasoning']) ? $intent_data['reasoning'] : '';
        
        // Only execute if confidence is high enough
        if ($confidence < 0.7) {
            return false;
        }
        
        // Execute the tool
        $tool_result = AIautotool_Agent_Tools::execute_tool($tool_name, $tool_args);
        
        if ($tool_result['success']) {
            return array(
                'response' => $tool_result['message'] ?? 'Tool executed successfully',
                'intent' => $tool_name,
                'tool' => $tool_name,
                'confidence' => $confidence,
                'reasoning' => $reasoning,
                'tool_result' => $tool_result
            );
        } else {
            // 🔥 FIX: Show detailed error (already formatted from error formatter)
            $error_msg = $tool_result['error'] ?? '❌ Unknown error';
            
            // Don't add prefix if error already has detailed format
            if (strpos($error_msg, '💡') !== false || strpos($error_msg, 'Giải pháp:') !== false) {
                $response = $error_msg; // Already detailed
            } else if (strpos($error_msg, '❌') !== false || strpos($error_msg, '🔑') !== false) {
                $response = $error_msg; // Already has icon
            } else {
                $response = "❌ Lỗi khi thực thi: " . $error_msg;
            }
            
            // Add original error for debugging if available
            if (isset($tool_result['original_error']) && WP_DEBUG) {
                $response .= "\n\n🔍 Debug: " . $tool_result['original_error'];
            }
            
            return array(
                'response' => $response,
                'intent' => 'error',
                'tool' => $tool_name,
                'confidence' => $confidence,
                'error' => $tool_result['error'] ?? 'Unknown error',
                'error_formatted' => $tool_result['error_formatted'] ?? null
            );
        }
    }
    
    /**
     * Build AI system prompt with comprehensive context
     */
    /**
     * Build intelligent action plan from user query with auto-loaded tools
     * Returns JSON structure for AI agent to understand what to do next
     * No asking user - directly creates todo list and executes
     * 
     * @param string $user_query User's natural language request
     * @param array $context Current site context
     * @return array JSON plan with todo list of tools to use
     */
    private function build_ai_action_plan($user_query, $context) {
        // Load all available tools automatically
        if (!class_exists('AIAgent_Tools_Loader')) {
            return array(
                'success' => false,
                'error' => 'Tools loader not available'
            );
        }
        
        $all_tools = AIAgent_Tools_Loader::get_all_tools();
        
        // Analyze user intent
        $intent = $this->detect_user_intent($user_query, $context);
        
        // Map intent to appropriate tools
        $selected_tools = $this->map_intent_to_tools($intent, $all_tools);
        
        // Create todo list with execution steps
        $todo_list = $this->create_todo_list($intent, $selected_tools, $user_query, $context);
        
        // Build plan structure
        $plan = array(
            'success' => true,
            'intent' => $intent,
            'goal' => $this->extract_goal($user_query, $intent),
            'confidence' => $intent['confidence'],
            'tools_needed' => $selected_tools,
            'todo_list' => $todo_list,
            'estimated_time' => $this->estimate_time($todo_list),
            'risks' => $this->identify_risks($todo_list, $context)
        );
        
        return $plan;
    }
    
    /**
     * Detect user intent from query
     */
    private function detect_user_intent($query, $context) {
        $query_lower = mb_strtolower($query);
        
        // Intent categories
        $intents = array(
            'create_content' => array(
                // 🔥 REMOVED: Không dùng keyword matching nữa cho đa ngôn ngữ
                // Để AI tự phân tích intent dựa trên context
                'keywords' => array(), // Empty - chỉ dùng cho backward compatibility
                'actions' => array('CREATE'),
                'entities' => array('post', 'article', 'content')
            ),
            'delete_content' => array(
                'keywords' => array('xóa', 'xoá', 'delete', 'remove', 'clear', 'clean'),
                'actions' => array('DELETE'),
                'entities' => array('post', 'draft', 'trash')
            ),
            'manage_content' => array(
                'keywords' => array('sửa', 'update', 'edit', 'rewrite', 'cập nhật'),
                'actions' => array('UPDATE'),
                'entities' => array('post', 'content')
            ),
            'query_info' => array(
                'keywords' => array('có bao nhiêu', 'hiển thị', 'liệt kê', 'show', 'list', 'count', 'how many'),
                'actions' => array('READ'),
                'entities' => array('posts', 'users', 'images', 'comments')
            ),
            'system_management' => array(
                'keywords' => array('kiểm tra', 'tối ưu', 'cleanup', 'optimize', 'health', 'check'),
                'actions' => array('MAINTAIN'),
                'entities' => array('system', 'database', 'performance')
            ),
            'seo_optimization' => array(
                'keywords' => array('seo', 'meta', 'keyword', 'optimize seo'),
                'actions' => array('OPTIMIZE'),
                'entities' => array('seo', 'meta', 'keyword')
            )
        );
        
        // Analyze query against intents
        $best_intent = null;
        $max_matches = 0;
        $matched_categories = array();
        
        foreach ($intents as $category => $intent_data) {
            $matches = 0;
            foreach ($intent_data['keywords'] as $keyword) {
                if (strpos($query_lower, $keyword) !== false) {
                    $matches++;
                }
            }
            
            if ($matches > 0) {
                $matched_categories[$category] = $matches;
                if ($matches > $max_matches) {
                    $max_matches = $matches;
                    $best_intent = $category;
                }
            }
        }
        
        // Extract entities and parameters
        $entities = array();
        $params = array();
        
        // Extract post IDs
        if (preg_match_all('/(?:post|bài)\s*#?(\d+)/ui', $query, $matches)) {
            $entities['post_ids'] = array_map('intval', $matches[1]);
        }
        
        // Extract numbers
        if (preg_match_all('/\b(\d+)\b/', $query, $matches)) {
            $params['numbers'] = array_map('intval', $matches[1]);
        }
        
        // Detect language
        $language = 'vi';
        if (preg_match('/\b(and|the|is|are|will|can|should|do|does)\b/i', $query)) {
            $language = 'en';
        }
        
        // Calculate confidence
        $confidence = $max_matches > 0 ? min(0.95, 0.5 + ($max_matches * 0.15)) : 0.3;
        
        return array(
            'category' => $best_intent ?? 'general',
            'primary_action' => $best_intent ? $intents[$best_intent]['actions'][0] : 'READ',
            'entities' => $entities,
            'parameters' => $params,
            'language' => $language,
            'confidence' => $confidence,
            'matched_categories' => $matched_categories
        );
    }
    
    /**
     * Map detected intent to appropriate tools
     */
    private function map_intent_to_tools($intent, $all_tools) {
        $category = $intent['category'];
        $action = $intent['primary_action'];
        
        $selected_tools = array();
        
        // Tool mapping by intent category and action
        $tool_mapping = array(
            'create_content' => array(
                'CREATE' => array('create_post', 'schedule_post')
            ),
            'delete_content' => array(
                'DELETE' => array('delete_post', 'delete_posts_bulk', 'execute_sql')
            ),
            'manage_content' => array(
                'UPDATE' => array('rewrite_post', 'get_post_info')
            ),
            'query_info' => array(
                'READ' => array('query_database', 'get_post_info', 'check_system_health')
            ),
            'system_management' => array(
                'MAINTAIN' => array('check_system_health', 'cleanup_database', 'execute_sql')
            ),
            'seo_optimization' => array(
                'OPTIMIZE' => array('analyze_seo', 'generate_meta_tags')
            )
        );
        
        // Get tools based on category and action
        if (isset($tool_mapping[$category][$action])) {
            foreach ($tool_mapping[$category][$action] as $tool_name) {
                if (isset($all_tools[$tool_name])) {
                    $selected_tools[$tool_name] = $all_tools[$tool_name];
                }
            }
        }
        
        // If no specific tools found, add general tools
        if (empty($selected_tools)) {
            $general_tools = array('query_database', 'get_post_info', 'check_system_health');
            foreach ($general_tools as $tool_name) {
                if (isset($all_tools[$tool_name])) {
                    $selected_tools[$tool_name] = $all_tools[$tool_name];
                }
            }
        }
        
        return $selected_tools;
    }
    
    /**
     * Create todo list from intent and tools
     */
    private function create_todo_list($intent, $tools, $query, $context) {
        $todo_list = array();
        $step_number = 1;
        
        // Extract parameters from query and context using intelligent extraction
        $params = $this->extract_parameters($query, $intent, $context);
        
        // Pass original query to context for AI tool to extract itself
        $context['query'] = $query;
        $context['original_query'] = $query;
        
        // Add each tool as a todo item
        foreach ($tools as $tool_name => $tool_data) {
            $todo_item = array(
                'step' => $step_number++,
                'tool' => $tool_name,
                'description' => $this->generate_step_description($tool_name, $intent, $params),
                'arguments' => $this->prepare_tool_arguments($tool_name, $intent, $params, $context),
                'status' => 'pending',
                'priority' => $this->determine_priority($tool_name, $intent),
                'depends_on' => null
            );
            
            $todo_list[] = $todo_item;
        }
        
        return $todo_list;
    }
    
    /**
     * Extract parameters from query
     */
    private function extract_parameters($query, $intent, $context) {
        $params = array();
        
        // Debug log
        
        // Extract post IDs
        if (preg_match_all('/\b(\d+)\b/', $query, $matches)) {
            $params['post_ids'] = array_map('intval', $matches[1]);
        }
        
        // Extract keywords - Support multiple formats
        // Format 1: "Tạo bài viết: keyword"
        if (preg_match('/:\s*([^:\n]+)/', $query, $matches)) {
            $params['keyword'] = trim($matches[1]);
        }
        // Format 2: "viết bài về keyword"
        elseif (preg_match('/(?:về|about|on)\s+([^:\n]+)/i', $query, $matches)) {
            $params['keyword'] = trim($matches[1]);
        }
        // Format 3: "keyword" in quotes
        elseif (preg_match('/"([^"]+)"/', $query, $matches)) {
            $params['keyword'] = $matches[1];
        }
        // Format 4: "tạo bài keyword" (keyword after "bài")
        elseif (preg_match('/bài\s+([^:\n]+?)(?:\s+nháp|\s+draft|$)/i', $query, $matches)) {
            $params['keyword'] = trim($matches[1]);
        }
        // Format 5: Extract from query if no specific pattern
        elseif (preg_match('/(?:tạo|viết|create|write)\s+(?:bài|bai|post|article)\s+([^:\n]+)/i', $query, $matches)) {
            $params['keyword'] = trim($matches[1]);
        }
        
        // Extract time references
        if (preg_match('/hôm nay|today/i', $query)) {
            $params['date_filter'] = 'today';
        } elseif (preg_match('/tháng này|this month/i', $query)) {
            $params['date_filter'] = 'this_month';
        }
        
        // Extract status
        if (preg_match('/draft|nháp/i', $query)) {
            $params['status'] = 'draft';
        } elseif (preg_match('/published|published/i', $query)) {
            $params['status'] = 'publish';
        }
        
        // If still no keyword but it's a create intent, use the whole query
        if (empty($params['keyword']) && $intent['primary_action'] === 'CREATE') {
            // Try to extract any meaningful text after action words
            if (preg_match('/(?:tạo|viết|create|write)\s+[^:]+:\s*(.+)/i', $query, $matches)) {
                $params['keyword'] = trim($matches[1]);
            } else {
                // Last resort: use query itself as keyword
                $params['keyword'] = $query;
            }
        }
        
        
        return $params;
    }
    
    /**
     * Generate step description
     */
    private function generate_step_description($tool_name, $intent, $params) {
        $descriptions = array(
            'create_post' => 'Tạo bài viết mới',
            'delete_post' => 'Xóa bài viết',
            'delete_posts_bulk' => 'Xóa nhiều bài viết',
            'get_post_info' => 'Lấy thông tin bài viết',
            'query_database' => 'Truy vấn database',
            'check_system_health' => 'Kiểm tra sức khỏe hệ thống',
            'rewrite_post' => 'Viết lại bài viết'
        );
        
        return isset($descriptions[$tool_name]) ? $descriptions[$tool_name] : "Thực hiện {$tool_name}";
    }
    
    /**
     * Prepare tool arguments - Let AI extract from query context
     */
    private function prepare_tool_arguments($tool_name, $intent, $params, $context) {
        $args = array();
        
        // Priority 1: Use params extracted from query
        if (!empty($params)) {
            $args = $params;
        }
        
        // Priority 2: Merge entities and parameters from intent
        if (!empty($intent['entities'])) {
            $args = array_merge($args, $intent['entities']);
        }
        if (!empty($intent['parameters'])) {
            $args = array_merge($args, $intent['parameters']);
        }
        
        // Priority 3: Add language from intent
        if (isset($intent['language'])) {
            $args['language'] = $intent['language'];
        }
        
        // Priority 4: For create_post - ensure keyword exists (let AI extract intelligently)
        if ($tool_name === 'create_post') {
            // Debug log
            
            if (empty($args['keyword'])) {
                // Use extracted params first
                if (isset($params['keyword']) && !empty($params['keyword'])) {
                    $args['keyword'] = $params['keyword'];
                } 
                // Fallback: use original query from context
                elseif (isset($context['query']) && !empty($context['query'])) {
                    $args['keyword'] = $context['query'];
                }
                else {
                    $args['keyword'] = 'WordPress';
                }
            }
            // Set default status if not specified
            if (empty($args['status'])) {
                $args['status'] = 'draft';
            }
            
        }
        
        // Priority 5: For delete operations, ensure we have what we need
        if ($tool_name === 'delete_post' || $tool_name === 'delete_posts_bulk') {
            if (empty($args['post_id']) && empty($args['post_ids']) && empty($args['status'])) {
                // No identifiers - this might fail, but let the tool handle it
                $args['_require_user_confirmation'] = true;
            }
        }
        
        return $args;
    }
    
    /**
     * Determine step priority
     */
    private function determine_priority($tool_name, $intent) {
        if (in_array($tool_name, array('check_system_health', 'query_database'))) {
            return 'high';
        }
        return 'medium';
    }
    
    /**
     * Extract goal from query
     */
    private function extract_goal($query, $intent) {
        if (!empty($intent['entities']['entity_type'])) {
            return "Thực hiện {$intent['primary_action']} trên {$intent['entities']['entity_type']}";
        }
        
        return mb_substr($query, 0, 100);
    }
    
    /**
     * Estimate execution time
     */
    private function estimate_time($todo_list) {
        $total_minutes = 0;
        
        foreach ($todo_list as $todo) {
            $minutes = 1; // Default
            if (strpos($todo['tool'], 'create') !== false) {
                $minutes = 2;
            } elseif (strpos($todo['tool'], 'delete') !== false) {
                $minutes = 1;
            } elseif (strpos($todo['tool'], 'query') !== false) {
                $minutes = 1;
            }
            
            $total_minutes += $minutes;
        }
        
        return "{$total_minutes} phút";
    }
    
    /**
     * Identify potential risks
     */
    private function identify_risks($todo_list, $context) {
        $risks = array();
        
        foreach ($todo_list as $todo) {
            if ($todo['tool'] === 'delete_post' || $todo['tool'] === 'delete_posts_bulk') {
                $risks[] = 'Dữ liệu sẽ bị xóa vĩnh viễn';
            }
            if ($todo['tool'] === 'execute_sql') {
                $risks[] = 'SQL có thể thay đổi database';
            }
        }
        
        return array_unique($risks);
    }
    
    /**
     * Execute todo list of tools
     */
    private function execute_todo_list($todo_list) {
        $results = array();
        
        foreach ($todo_list as $todo) {
            $tool_name = $todo['tool'];
            $args = $todo['arguments'];
            
            // Execute tool via AI Agent Tools
            if (class_exists('AIautotool_Agent_Tools')) {
                $result = AIautotool_Agent_Tools::execute_tool($tool_name, $args);
                $results[] = array(
                    'tool' => $tool_name,
                    'description' => $todo['description'],
                    'success' => $result['success'] ?? false,
                    'message' => $result['message'] ?? 'Unknown result',
                    'data' => $result['data'] ?? null
                );
            } else {
                $results[] = array(
                    'tool' => $tool_name,
                    'success' => false,
                    'message' => 'AI Agent Tools not available'
                );
            }
        }
        
        return $results;
    }
    
    /**
     * Format execution results for display
     */
    private function format_execution_results($results) {
        $output = "✅ **EXECUTION COMPLETED**\n\n";
        
        foreach ($results as $result) {
            $icon = $result['success'] ? '✅' : '❌';
            $output .= "{$icon} **{$result['tool']}**\n";
            $output .= "   {$result['description']}\n";
            $output .= "   {$result['message']}\n\n";
        }
        
        return $output;
    }
    
    /**
     * Calculate success rate
     */
    private function calculate_success_rate($results) {
        if (empty($results)) {
            return 0;
        }
        
        $success_count = 0;
        foreach ($results as $result) {
            if ($result['success']) {
                $success_count++;
            }
        }
        
        return round(($success_count / count($results)) * 100, 2);
    }
    
    /**
     * Format action plan for display in chat
     */
    private function format_action_plan_for_display($plan) {
        if (!$plan['success']) {
            return "❌ Không thể tạo kế hoạch: " . ($plan['error'] ?? 'Unknown error');
        }
        
        $output = "📋 **ACTION PLAN (Auto-Generated)**\n\n";
        
        // Goal
        $output .= "🎯 **Mục tiêu:** {$plan['goal']}\n";
        $output .= "⏱️ **Thời gian ước tính:** {$plan['estimated_time']}\n";
        $output .= "🎲 **Độ chính xác:** " . ($plan['confidence'] * 100) . "%\n\n";
        
        // Risks
        if (!empty($plan['risks'])) {
            $output .= "⚠️ **Cảnh báo:**\n";
            foreach ($plan['risks'] as $risk) {
                $output .= "  • {$risk}\n";
            }
            $output .= "\n";
        }
        
        // Todo List
        $output .= "📝 **TODO LIST ({$plan['intent']['category']}):**\n\n";
        
        foreach ($plan['todo_list'] as $todo) {
            $priority_icon = $todo['priority'] === 'high' ? '🔴' : '🟡';
            $output .= "**{$todo['step']}. {$priority_icon} {$todo['tool']}**\n";
            $output .= "   {$todo['description']}\n";
            
            if (!empty($todo['arguments'])) {
                $args_json = json_encode($todo['arguments'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
                $output .= "   `{$args_json}`\n";
            }
            
            $output .= "\n";
        }
        
        $output .= "---\n\n";
        $output .= "💡 Plan này đã được tạo tự động dựa trên tools hiện có.\n";
        $output .= "Có thể thực hiện ngay mà không cần hỏi lại bạn!";
        
        return $output;
    }
    
    private function build_ai_system_prompt($context) {
        // Memory optimization - cache options to prevent multiple get_option calls
        static $cached_options = null;
        if ($cached_options === null) {
            $cached_options = array(
                'assistant_name' => get_option('aiautotool_bot_assistant_name', 'Mochi'),
                'role_template' => get_option('aiautotool_bot_assistant_role_template', 'helpful_assistant'),
                'language' => get_option('aiautotool_bot_assistant_language', 'auto'),
                'tone' => get_option('aiautotool_bot_assistant_tone', 'friendly'),
                'role_intro' => get_option('aiautotool_bot_assistant_role_intro', '')
            );
        }
        
        // Get personality configuration from cache
        $assistant_name = $cached_options['assistant_name'];
        $role_template = $cached_options['role_template'];
        $language = $cached_options['language'];
        $tone = $cached_options['tone'];
        $role_intro = $cached_options['role_intro'];
        
        // Replace placeholder in intro
        $role_intro = str_replace('{{assistant_name}}', $assistant_name, $role_intro);
        
        // Build personality prompt based on template - with autonomous agent approach
        $personality_prompt = '';
        switch ($role_template) {
            case 'professional_admin':
                $personality_prompt = "You are {$assistant_name}, an autonomous WordPress site administrator. You communicate formally, execute tasks completely without asking for confirmation, and resolve queries autonomously.";
                break;
            case 'friendly_guide':
                $personality_prompt = "You are {$assistant_name}, an autonomous WordPress guide. You help users by doing actions immediately, not asking questions. Complete tasks fully before responding. Use emojis and be friendly.";
                break;
            case 'technical_expert':
                $personality_prompt = "You are {$assistant_name}, an autonomous technical WordPress expert. You solve problems completely, provide detailed explanations, and execute actions without waiting for approval. Keep going until the query is fully resolved.";
                break;
            case 'custom':
                $personality_prompt = !empty($role_intro) ? $role_intro : "You are {$assistant_name}, an autonomous WordPress assistant.";
                break;
            case 'helpful_assistant':
            default:
                $personality_prompt = "You are {$assistant_name}, an autonomous WordPress site assistant. You resolve queries completely without asking for confirmation. You are helpful, execute actions immediately, and keep going until the task is done.";
                break;
        }
        
        // Add tone guidance
        $tone_guidance = '';
        switch ($tone) {
            case 'professional':
                $tone_guidance = "Use professional, formal language. Minimize emojis. Be precise and direct.";
                break;
            case 'enthusiastic':
                $tone_guidance = "Be enthusiastic and energetic! Use lots of emojis and exclamation marks! Show excitement!";
                break;
            case 'concise':
                $tone_guidance = "Be concise and direct. Short answers. Minimal fluff. Get to the point.";
                break;
            case 'friendly':
            default:
                $tone_guidance = "Be friendly and approachable. Use emojis (😊 🎉 ✅ ⚠️ 💡 📝 🗑️). Keep it conversational.";
                break;
        }
        
        // Add language instruction
        $language_instruction = '';
        if ($language === 'vi') {
            $language_instruction = "ALWAYS respond in Vietnamese.";
        } elseif ($language === 'en') {
            $language_instruction = "ALWAYS respond in English.";
        } else {
            $language_instruction = "MUST answer in the SAME LANGUAGE as user (Vietnamese/English).";
        }
        
        $prompt = "{$personality_prompt}\n";
        $prompt .= "Site: {$context['site_name']}\n";
        $prompt .= "Current Date/Time: {$context['current_date']}\n\n";
        $prompt .= "PERSONALITY: {$tone_guidance}\n";
        $prompt .= "LANGUAGE: {$language_instruction}\n";
        
        // Include user behavior memory
        $memory = $this->get_memory_for_prompt();
        if (!empty($memory)) {
            $prompt .= $memory;
        }
        
        $prompt .= "\n";
        $prompt .= "═══════════════════════════════════════════════════════════════\n";
        $prompt .= "🚨 CRITICAL RULE - READ THIS FIRST 🚨\n";
        $prompt .= "═══════════════════════════════════════════════════════════════\n\n";
        $prompt .= "KHI USER YÊU CẦU TẠO BÀI VIẾT (CREATE POST), BẠN PHẢI:\n";
        $prompt .= "1. NHẬN DIỆN NGAY: 'tạo bài', 'viết bài', 'viết post', 'create post', 'tạo bài viết', 'soạn bài', 'làm bài'\n";
        $prompt .= "2. TRÍCH KEYWORD: Tất cả text SAU action verb hoặc sau dấu hai chấm (:)\n";
        $prompt .= "3. GỌI TOOL NGAY: TOOL_CALL: create_post với keyword đã trích\n";
        $prompt .= "4. KHÔNG BAO GIỜ HỎI LẠI hoặc trả lời text thay vì gọi tool!\n\n";
        
        $prompt .= "VÍ DỤ CỤ THỂ:\n";
        $prompt .= "User: 'viết post đặt tên con'\n";
        $prompt .= "→ Bạn PHẢI trả về:\n";
        $prompt .= "TOOL_CALL: create_post\n";
        $prompt .= "TOOL_ARGS: {\"keyword\": \"đặt tên con\"}\n";
        $prompt .= "→ KHÔNG được trả về text như: 'Cảm ơn bạn...' hoặc 'Bạn muốn tạo bài gì?'\n\n";
        
        $prompt .= "User: 'tạo bài viết : đặt tên con gái'\n";
        $prompt .= "→ Bạn PHẢI trả về:\n";
        $prompt .= "TOOL_CALL: create_post\n";
        $prompt .= "TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "User: 'viết bài về WordPress'\n";
        $prompt .= "→ Bạn PHẢI trả về:\n";
        $prompt .= "TOOL_CALL: create_post\n";
        $prompt .= "TOOL_ARGS: {\"keyword\": \"WordPress\"}\n\n";
        
        $prompt .= "⚠️ NẾU BẠN TRẢ VỀ TEXT THAY VÌ TOOL_CALL, ĐÓ LÀ SAI HOÀN TOÀN! ⚠️\n";
        $prompt .= "═══════════════════════════════════════════════════════════════\n\n";
        
        $prompt .= "\n=== USER QUERY DETECTION (CRITICAL) ===\n\n";
        $prompt .= "When user asks about USERS/NGƯỜI DÙNG/THÀNH VIÊN/MEMBERS:\n";
        $prompt .= "1. IMMEDIATELY call TOOL_CALL: query_database\n";
        $prompt .= "2. Use TOOL_ARGS: {\"query_type\": \"users\"}\n";
        $prompt .= "3. Return user count AND list all users with details\n";
        $prompt .= "4. NEVER respond with posts/images/comments statistics!\n";
        $prompt .= "5. Users and Posts are DIFFERENT things - don't confuse them!\n\n";
        
        $prompt .= "\n=== SITE DATA ===\n\n";
        
        $prompt .= "POSTS:\n";
        $prompt .= "- Published: {$context['posts']['total_published']}\n";
        $prompt .= "- Drafts: {$context['posts']['total_drafts']}\n";
        $prompt .= "- Scheduled: {$context['posts']['total_scheduled']}\n";
        $prompt .= "- Trash: {$context['posts']['total_trash']}\n";
        $prompt .= "- Published Today: {$context['posts']['published_today']}\n";
        $prompt .= "- Published This Month: {$context['posts']['published_this_month']}\n\n";
        
        if (!empty($context['latest_posts'])) {
            $prompt .= "LATEST POSTS:\n";
            foreach ($context['latest_posts'] as $post) {
                $prompt .= "- \"{$post['title']}\" ({$post['date']}, {$post['comments']} comments)\n";
            }
            $prompt .= "\n";
        }
        
        $prompt .= "IMAGES:\n";
        $prompt .= "- Total: {$context['images']['total']}\n";
        $prompt .= "- Without Alt Text: {$context['images']['without_alt']}\n";
        $prompt .= "- Broken/404: {$context['images']['broken']}\n\n";
        
        $prompt .= "COMMENTS:\n";
        $prompt .= "- Approved: {$context['comments']['total_approved']}\n";
        $prompt .= "- Pending Moderation: {$context['comments']['pending']}\n";
        $prompt .= "- Spam: {$context['comments']['spam']}\n\n";
        
        $prompt .= "AI TOOLS:\n";
        $prompt .= "- Active Tools: {$context['ai_tools']['active_count']}\n";
        $prompt .= "- Actions Today: {$context['ai_tools']['actions_today']}\n";
        if (!empty($context['ai_tools']['tools_list'])) {
            $prompt .= "- Tools: " . implode(', ', $context['ai_tools']['tools_list']) . "\n";
        }
        $prompt .= "\n";
        
        if (!empty($context['alerts']['list'])) {
            $prompt .= "ALERTS ({$context['alerts']['count']}):\n";
            foreach ($context['alerts']['list'] as $alert) {
                $prompt .= "- [{$alert['severity']}] {$alert['title']}: {$alert['message']}\n";
            }
            $prompt .= "\n";
        }
        
        $prompt .= "=== YOUR CAPABILITIES ===\n\n";
        $prompt .= "You are an AUTONOMOUS AGENT - keep going until the user's query is completely resolved.\n";
        $prompt .= "ONLY terminate when you are SURE the problem is solved. Autonomously resolve queries to the best of your ability.\n";
        $prompt .= "You are pair programming with the USER to solve their coding task - COMPLETE THE TASK before ending your turn.\n\n";
        
        $prompt .= "CRITICAL EXECUTION RULES (from Cursor Agent principles):\n";
        $prompt .= "1. **DO NOT ASK FOR CONFIRMATION** - Just execute immediately! Never ask 'Do you want me to...?' or 'Should I...?'\n";
        $prompt .= "2. **AUTONOMOUS ACTION** - When user asks you to PERFORM an action, DO IT immediately in the same turn\n";
        $prompt .= "3. **DON'T STOP HALFWAY** - Complete the entire task before coming back to user. If you say you'll do something, DO IT NOW!\n";
        $prompt .= "4. **STATE ASSUMPTIONS & CONTINUE** - Don't pause for approval unless truly blocked. Make reasonable assumptions and proceed.\n";
        $prompt .= "5. **MAXIMIZE PARALLEL TOOLS** - Run multiple WordPress operations simultaneously for 3-5x faster execution\n";
        $prompt .= "6. **GATHER FULL CONTEXT** - Search thoroughly before answering, don't guess. Use tools to find answers.\n";
        $prompt .= "7. **COMPLETE IMPLEMENTATION** - Test/build after changes, fix linter errors. Don't leave tasks incomplete.\n";
        $prompt .= "8. **BIAS TOWARDS ACTION** - If you can find the answer via tools, DO IT. Don't ask user for help if you can find it yourself.\n";
        $prompt .= "9. **🚨 CRITICAL FOR CREATE POST** - NEVER return text for 'tạo bài', 'viết post', 'create post' commands!\n";
        $prompt .= "    → ALWAYS return TOOL_CALL format immediately:\n";
        $prompt .= "       TOOL_CALL: create_post\n";
        $prompt .= "       TOOL_ARGS: {\"keyword\": \"extracted_keyword\"}\n";
        $prompt .= "    → NO conversational text like 'Cảm ơn bạn...' or 'Bạn muốn tạo bài gì?'\n\n";
        
        $prompt .= "⚠️ REMEMBER: If you say you're about to do something, ACTUALLY DO IT in the same response. Don't just promise - EXECUTE!\n\n";
        
        $prompt .= "TOOL FORMAT (MUST FOLLOW):\n\n";
        $prompt .= "TOOL_CALL: tool_name\n";
        $prompt .= "TOOL_ARGS: {\"param\": \"value\"}\n\n";
        
        $prompt .= "EXAMPLE - Creating a post (MANDATORY FORMAT):\n";
        $prompt .= "User: \"viết post đặt tên con\"\n";
        $prompt .= "You: TOOL_CALL: create_post\n";
        $prompt .= "TOOL_ARGS: {\"keyword\": \"đặt tên con\", \"status\": \"draft\"}\n";
        $prompt .= "→ Execute immediately without asking! ✅\n\n";
        
        $prompt .= "User: \"Tạo bài viết: đặt tên con trai 2026\"\n";
        $prompt .= "You: TOOL_CALL: create_post\n";
        $prompt .= "TOOL_ARGS: {\"keyword\": \"đặt tên con trai 2026\", \"status\": \"draft\"}\n";
        $prompt .= "→ Execute immediately without asking! ✅\n\n";
        
        $prompt .= "❌ WRONG RESPONSES (NEVER DO THIS):\n";
        $prompt .= "  ❌ \"Bạn muốn tạo bài viết gì?\" (Don't ask!)\n";
        $prompt .= "  ❌ \"Cảm ơn bạn đã liên hệ. Tôi đã nhận được yêu cầu...\" (Don't thank!)\n";
        $prompt .= "  ❌ \"Tôi có thể giúp bạn tạo bài viết...\" (Don't explain!)\n";
        $prompt .= "  ❌ Any conversational text response instead of TOOL_CALL format\n\n";
        
        $prompt .= "✅ RIGHT RESPONSES (ALWAYS DO THIS):\n";
        $prompt .= "  ✅ TOOL_CALL: create_post\n";
        $prompt .= "     TOOL_ARGS: {\"keyword\": \"extracted_keyword\"}\n";
        $prompt .= "     → Just call TOOL_CALL and execute! (Do it!)\n\n";
        
        $prompt .= "=== CONTEXT UNDERSTANDING (From Cursor principles) ===\n\n";
        $prompt .= "CRITICAL: Thoroughly understand context before taking action\n\n";
        $prompt .= "1. **GATHER INFORMATION** - Don't guess, use tools to find answers\n";
        $prompt .= "2. **MULTIPLE SEARCHES** - Run parallel searches with different keywords\n";
        $prompt .= "3. **READ FILES** - Read multiple files in parallel to get full picture\n";
        $prompt .= "4. **KEEP SEARCHING** - Don't stop at first result, explore until confident\n";
        $prompt .= "5. **BIAS TOWARDS TOOLS** - Don't ask user for help if you can find it yourself\n\n";
        
        $prompt .= "Example - User asks 'How many posts published today?':\n";
        $prompt .= "✅ DO THIS: TOOL_CALL: get_posts with date_filter=today\n";
        $prompt .= "❌ DON'T: Just say '5 posts' from memory - actually query!\n\n";
        
        $prompt .= "AVAILABLE ACTIONS:\n";
        $prompt .= "- delete_drafts: Delete all {$context['posts']['total_drafts']} draft posts\n";
        $prompt .= "- publish_drafts: Publish all {$context['posts']['total_drafts']} draft posts\n";
        $prompt .= "- delete_old_posts: Delete posts older than X days (use PARAMS: {\"days\": X})\n";
        $prompt .= "- delete_today_posts: Delete posts published today ({$context['posts']['published_today']} posts)\n";
        $prompt .= "- add_alt_text: Add alt text to {$context['images']['without_alt']} images\n";
        $prompt .= "- fix_broken_images: Fix {$context['images']['broken']} broken images\n\n";
        
        $prompt .= "=== ADVANCED TOOLS ===\n\n";
        $prompt .= "You have access to advanced agent tools for complex tasks.\n\n";
        
        $prompt .= "🤖 **AI-POWERED INTENT DETECTION** (CRITICAL):\n";
        $prompt .= "YOU must analyze user's message context and intent intelligently using NATURAL LANGUAGE UNDERSTANDING.\n";
        $prompt .= "This system supports MULTIPLE LANGUAGES - do NOT rely on keyword matching!\n";
        $prompt .= "Consider the FULL CONTEXT, SEMANTIC MEANING, and LANGUAGE STRUCTURE:\n\n";
        
        $prompt .= "1. **UNDERSTAND USER INTENT THROUGH CONTEXT**:\n";
        $prompt .= "   - Analyze the COMPLETE SENTENCE STRUCTURE and MEANING, not individual words\n";
        $prompt .= "   - Questions (có bao nhiêu, how many, show me, list) = INFORMATION REQUEST → Use query tools\n";
        $prompt .= "   - Commands (tạo, viết, create, write, make) = ACTION REQUEST → Call action tools\n";
        $prompt .= "   - CRITICAL: 'Có bao nhiêu bài viết?' is a QUESTION, NOT a create command!\n";
        $prompt .= "   - CRITICAL: 'Tạo bài viết về X' is a COMMAND, should call create_post tool\n\n";
        
        $prompt .= "2. **EXTRACT PARAMETERS INTELLIGENTLY**:\n";
        $prompt .= "   - For CREATE commands: Extract the topic/content from context\n";
        $prompt .= "   - For DELETE commands: Extract IDs, filters, or conditions\n";
        $prompt .= "   - For READ questions: Determine what data is needed\n";
        $prompt .= "   - Use conversation history to understand references\n\n";
        
        $prompt .= "3. **DISTINGUISH COMMANDS VS QUESTIONS** (MOST IMPORTANT):\n";
        $prompt .= "   - QUESTION pattern: 'Có bao nhiêu...', 'How many...', 'Show me...', 'List...' → QUERY INFORMATION\n";
        $prompt .= "   - COMMAND pattern: 'Tạo...', 'Create...', 'Xóa...', 'Delete...' → PERFORM ACTION\n";
        $prompt .= "   - If user asks a QUESTION → Answer with information, use query tools if needed\n";
        $prompt .= "   - If user gives a COMMAND → Execute the action, call appropriate tool\n";
        $prompt .= "   - NEVER confuse questions with commands!\n\n";
        
        $prompt .= "EXAMPLES OF INTELLIGENT DETECTION:\n\n";
        
        $prompt .= "✅ CORRECT - QUESTION (No tool call for create):\n";
        $prompt .= "   User: 'Có bao nhiêu bài viết?'\n";
        $prompt .= "   Analysis: This is a QUESTION asking for information, NOT a create command\n";
        $prompt .= "   Response: Answer with the number from context, or use query_database if needed\n";
        $prompt .= "   → NO create_post tool call!\n\n";
        
        $prompt .= "✅ CORRECT - COMMAND (Call create_post tool):\n";
        $prompt .= "   User: 'Tạo bài viết về WordPress'\n";
        $prompt .= "   Analysis: This is a COMMAND to create something, action verb is 'Tạo'\n";
        $prompt .= "   Response: TOOL_CALL: create_post with keyword='WordPress'\n";
        $prompt .= "   → Call tool immediately!\n\n";
        
        $prompt .= "✅ CORRECT - QUESTION (Query information):\n";
        $prompt .= "   User: 'Xem bài viết mới nhất'\n";
        $prompt .= "   Analysis: Question asking to view/list, NOT create\n";
        $prompt .= "   Response: Use query_database or show from context\n";
        $prompt .= "   → NO create_post tool call!\n\n";
        
        $prompt .= "❌ WRONG - Don't confuse:\n";
        $prompt .= "   'Có bao nhiêu bài viết?' → Don't call create_post (it's a question!)\n";
        $prompt .= "   'Tạo bài viết về X' → Must call create_post (it's a command!)\n\n";
        
        $prompt .= "⚠️ GOLDEN RULES:\n";
        $prompt .= "1. If user mentions ACTION VERB (tạo, xóa, sửa, etc.) + CONTENT TYPE → ALWAYS call tool, NEVER ask for clarification!\n";
        $prompt .= "2. If intent is clear from context → EXECUTE immediately, don't wait for confirmation!\n";
        $prompt .= "3. Only ask for clarification if you GENUINELY cannot infer what user wants (e.g., 'xóa bài' without ID or title)\n";
        $prompt .= "4. For CREATE POST commands → NEVER ask, ALWAYS extract keyword and call TOOL_CALL immediately!\n\n";
        
        $prompt .= "TOOL FORMAT (CRITICAL - MUST FOLLOW):\n";
        $prompt .= "TOOL_CALL: tool_name\n";
        $prompt .= "TOOL_ARGS: {\"arg1\": \"value1\", \"arg2\": \"value2\"}\n\n";
        
        $prompt .= "⚠️ **PARAMETER REQUIREMENTS** ⚠️\n";
        $prompt .= "You MUST provide ALL required parameters for each tool.\n";
        $prompt .= "Check tool definition for 'required' fields and ensure they are included.\n";
        $prompt .= "Examples of required parameters:\n";
        $prompt .= "- create_post: requires 'keyword' (minimum)\n";
        $prompt .= "- execute_sql: requires 'query', 'operation_type', 'description'\n";
        $prompt .= "- delete_posts_bulk: requires 'post_ids' OR 'status'\n";
        $prompt .= "- schedule_post: requires 'post_id' AND 'schedule_time'\n\n";
        $prompt .= "If you don't have a required parameter, infer it from context intelligently. \n";
        $prompt .= "Bias towards NOT asking user for help if you can find the answer yourself.\n\n";
        
        $prompt .= "=== MAXIMIZE PARALLEL TOOL CALLS (Critical for efficiency) ===\n\n";
        $prompt .= "When performing multiple operations, ALWAYS run tools in parallel:\n\n";
        $prompt .= "✅ GOOD - Parallel (3-5x faster):\n";
        $prompt .= "TOOL_CALL: get_posts with status=publish AND status=draft AND status=trash\n";
        $prompt .= "→ Run all 3 queries simultaneously in one batch\n\n";
        
        $prompt .= "❌ BAD - Sequential (slow):\n";
        $prompt .= "TOOL_CALL: get_posts with status=publish → wait\n";
        $prompt .= "TOOL_CALL: get_posts with status=draft → wait\n";
        $prompt .= "TOOL_CALL: get_posts with status=trash → wait\n\n";
        
        $prompt .= "RULES:\n";
        $prompt .= "- Read multiple files in parallel (not sequentially)\n";
        $prompt .= "- Run multiple queries simultaneously\n";
        $prompt .= "- Search different topics in parallel\n";
        $prompt .= "- Only use sequential when Tool B needs output from Tool A\n\n";
        
        // 🆕 Get complete tools list for AI
        $tools_list = $this->get_complete_tools_for_ai();
        $prompt .= $tools_list;
        
        $prompt .= "\n=== QUICK REFERENCE - COMMON TOOLS ===\n\n";
        
        $prompt .= "🔧 SYSTEM INFORMATION:\n";
        $prompt .= "• system_info - Hiển thị thông tin hệ thống WordPress\n";
        $prompt .= "  Example: 'thông tin hệ thống' → TOOL_CALL: system_info\n";
        $prompt .= "  Example: 'system info' → TOOL_CALL: system_info\n";
        $prompt .= "  Example: 'phiên bản WordPress' → TOOL_CALL: system_info\n\n";
        
        $prompt .= "⚠️ **QUAN TRỌNG**: Sau khi phân tích intent, LUÔN gọi tool phù hợp!\n";
        $prompt .= "KHÔNG chỉ trả về text phân tích - phải thực hiện hành động!\n\n";
        
        $prompt .= "🔄 **WORKFLOW BẮT BUỘC**:\n";
        $prompt .= "1. Phân tích intent của user\n";
        $prompt .= "2. Xác định tool cần thiết\n";
        $prompt .= "3. GỌI TOOL NGAY LẬP TỨC với TOOL_CALL\n";
        $prompt .= "4. KHÔNG dừng lại ở bước phân tích!\n\n";
        
        $prompt .= "📝 CONTENT MANAGEMENT:\n";
        $prompt .= "• create_post - Tạo bài viết mới\n";
        $prompt .= "  REQUIRED: keyword (extract intelligently from user query)\n";
        $prompt .= "  Optional: title, outline, status, language\n\n";
        
        $prompt .= "  🎯 INTENT DETECTION FOR CREATE_POST:\n";
        $prompt .= "  When user wants to CREATE content, analyze the FULL context:\n";
        $prompt .= "  - Action verbs: 'tạo', 'viết', 'create', 'write', 'soạn', 'làm bài'\n";
        $prompt .= "  - Content indicators: 'bài viết', 'bài', 'post', 'article', 'nội dung'\n";
        $prompt .= "  - Topic/keyword extraction: Everything AFTER the colon, 'về', 'về chủ đề', or directly after action+content words\n\n";
        
        $prompt .= "  📋 EXAMPLES OF CREATE_POST INTENT (All these mean CREATE POST - MUST CALL TOOL):\n";
        $prompt .= "  ✅ User: 'viết post đặt tên con'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con\"}\n\n";
        
        $prompt .= "  ✅ User: 'tạo bài viết : đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'tạo bài viết: đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'Tạo bài viết: đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'viết bài về đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'tạo bài đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'làm 1 bài về đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'soạn bài viết đặt tên con gái'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"đặt tên con gái\"}\n\n";
        
        $prompt .= "  ✅ User: 'create post about baby names for girls'\n";
        $prompt .= "     → Response: TOOL_CALL: create_post\n";
        $prompt .= "                TOOL_ARGS: {\"keyword\": \"baby names for girls\"}\n\n";
        
        $prompt .= "  ❌ WRONG - NEVER DO THIS:\n";
        $prompt .= "     User: 'viết post đặt tên con'\n";
        $prompt .= "     ❌ Response: 'Cảm ơn bạn đã liên hệ. Tôi đã nhận được yêu cầu...'\n";
        $prompt .= "     ❌ Response: 'Bạn muốn tạo bài viết gì?'\n";
        $prompt .= "     ❌ Response: 'Tôi có thể giúp bạn...'\n\n";
        
        $prompt .= "  🔍 KEYWORD EXTRACTION RULES:\n";
        $prompt .= "  - If query has colon (:), extract text AFTER colon as keyword\n";
        $prompt .= "  - If query has 'về' or 'about', extract text AFTER these words as keyword\n";
        $prompt .= "  - If query is 'tạo bài [topic]' or 'viết bài [topic]', extract [topic] as keyword\n";
        $prompt .= "  - Trim whitespace, remove quotes if present, but preserve the full topic\n";
        $prompt .= "  - The keyword can be multiple words (e.g., 'đặt tên con gái', 'WordPress SEO tips')\n\n";
        
        $prompt .= "  ⚠️ CRITICAL: When you detect CREATE intent, ALWAYS call TOOL_CALL immediately!\n";
        $prompt .= "  🚨 FORBIDDEN RESPONSES (NEVER RETURN THESE):\n";
        $prompt .= "     ❌ 'Bạn muốn tạo bài viết gì?'\n";
        $prompt .= "     ❌ 'Cảm ơn bạn đã liên hệ. Tôi đã nhận được yêu cầu...'\n";
        $prompt .= "     ❌ 'Tôi có thể giúp bạn quản lý WordPress...'\n";
        $prompt .= "     ❌ ANY text response that doesn't start with TOOL_CALL:\n\n";
        $prompt .= "  ✅ MANDATORY RESPONSE FORMAT:\n";
        $prompt .= "     Extract keyword from query → TOOL_CALL: create_post → Execute!\n";
        $prompt .= "     Example: User says 'viết post đặt tên con'\n";
        $prompt .= "     → You MUST respond: TOOL_CALL: create_post\n";
        $prompt .= "                        TOOL_ARGS: {\"keyword\": \"đặt tên con\"}\n\n";
        
        $prompt .= "• delete_post - XOÁ 1 bài viết theo ID\n";
        $prompt .= "  Example: 'Xoá bài 123' → {\"post_id\": 123}\n\n";
        
        $prompt .= "• delete_posts_bulk - XOÁ NHIỀU bài viết\n";
        $prompt .= "  REQUIRED: post_ids OR status (at least one)\n";
        $prompt .= "  Example 1: 'Xoá bài 28807 và 28809' → {\"post_ids\": [28807, 28809]}\n";
        $prompt .= "  Example 2: 'Xoá tất cả bài nháp' → {\"status\": \"draft\"}\n";
        $prompt .= "  Example 3: 'Xoá bài nháp cũ hơn 7 ngày' → {\"status\": \"draft\", \"older_than_days\": 7}\n\n";
        
        $prompt .= "• get_post_info - Xem thông tin bài viết\n";
        $prompt .= "  Example: 'Xem info bài 123' → {\"post_id\": 123}\n\n";
        
        $prompt .= "• rewrite_post - Viết lại bài viết\n";
        $prompt .= "  Example: 'Viết lại bài 123 theo style chuyên nghiệp' → {\"post_id\": 123, \"style\": \"professional\"}\n\n";
        
        $prompt .= "• schedule_post - Lên lịch đăng bài\n";
        $prompt .= "  Example: 'Lên lịch bài 123 lúc 9h sáng mai' → {\"post_id\": 123, \"schedule_time\": \"+1 day 9:00\"}\n\n";
        
        $prompt .= "🔧 SYSTEM & DATABASE:\n";
        $prompt .= "• check_system_health, cleanup_database, manage_users, scan_malware\n";
        $prompt .= "• execute_sql - Viết SQL query trực tiếp (MẠH NHẤT cho truy vấn phức tạp)\n";
        $prompt .= "• query_database - Lấy thông tin database cơ bản\n\n";
        
        $prompt .= "📊 SEO & MARKETING:\n";
        $prompt .= "• analyze_seo, generate_meta_tags, suggest_keywords, post_to_social\n\n";
        
        $prompt .= "📈 ANALYTICS & REPORTS:\n";
        $prompt .= "• get_analytics, generate_report\n\n";
        
        $prompt .= "🛍️ WOOCOMMERCE:\n";
        $prompt .= "• create_product, analyze_sales\n";
        $prompt .= "• Security: check_security, block_ip\n";
        $prompt .= "• Performance: optimize_images, check_performance\n\n";
        
        $prompt .= "⚡ **POWER TOOL: execute_sql**\n";
        $prompt .= "Khi cần thao tác phức tạp, LUÔN ƯU TIÊN dùng execute_sql!\n";
        $prompt .= "REQUIRED: query, operation_type, description\n";
        $prompt .= "- Dùng %prefix% thay cho table prefix (vd: %prefix%posts, %prefix%terms)\n";
        $prompt .= "- operation_type: 'read' (SELECT) hoặc 'write' (UPDATE/INSERT/DELETE)\n";
        $prompt .= "- UPDATE/DELETE BẮT BUỘC phải có WHERE clause\n\n";
        
        $prompt .= "IMPORTANT: When user says 'xóa bài viết đó', 'xóa bài #123', 'delete that post':\n";
        $prompt .= "→ Use TOOL_CALL: delete_post with post_id from conversation context\n";
        $prompt .= "→ NOT delete_posts_bulk (that's for bulk operations)\n\n";
        
        $prompt .= "=== RESPONSE GUIDELINES ===\n\n";
        $prompt .= "🚨 CRITICAL RULE FOR CREATE POST COMMANDS:\n";
        $prompt .= "   If user says ANY variant of 'tạo bài', 'viết bài', 'viết post', 'create post':\n";
        $prompt .= "   → You MUST respond with TOOL_CALL format, NOT text!\n";
        $prompt .= "   → Example: 'viết post đặt tên con' → TOOL_CALL: create_post with keyword='đặt tên con'\n";
        $prompt .= "   → NEVER respond: 'Cảm ơn bạn...' or 'Bạn muốn tạo bài gì?'\n\n";
        
        $prompt .= "1. Use actual data from context - be specific with numbers\n";
        $prompt .= "2. For INFO questions: Just answer with the data\n";
        $prompt .= "3. For ACTION requests: ALWAYS use TOOL_CALL format (NOT text responses)\n";
        $prompt .= "4. Keep responses under 200 words unless user asks for detailed report\n";
        $prompt .= "5. USE USER BEHAVIOR MEMORY to personalize responses and anticipate needs\n";
        $prompt .= "6. If memory shows user frequently does X, proactively suggest related actions\n\n";
        
        $prompt .= "EXAMPLES:\n";
        $prompt .= "Q: 'Có bao nhiêu bài hôm nay?' → A: '📝 Hôm nay {$context['posts']['published_today']} bài! 🎉'\n";
        $prompt .= "Q: 'Xóa draft' → A: TOOL_CALL: delete_posts_bulk\n";
        $prompt .= "                TOOL_ARGS: {\"status\": \"draft\"}\n";
        $prompt .= "Q: 'viết post đặt tên con' → A: TOOL_CALL: create_post\n";
        $prompt .= "                          TOOL_ARGS: {\"keyword\": \"đặt tên con\"}\n";
        $prompt .= "Q: 'Suggestions?' → A: Analyze site data, suggest improvements\n\n";
        
        $prompt .= "=== CONVERSATION CONTEXT EXAMPLES ===\n\n";
        
        $prompt .= "Example 1 - Extract post_id from conversation:\n";
        $prompt .= "User: 'Viết bài: ABC'\n";
        $prompt .= "Assistant: [Creates post ID 28800]\n";
        $prompt .= "User: 'Bài viết vừa tạo id gì?'\n";
        $prompt .= "Assistant: 'Bài viết vừa tạo có ID là 28800 ạ' ← Remember this ID\n";
        $prompt .= "User: 'Xóa bài viết đó đi' ← 'đó' = ID 28800 from previous message\n";
        $prompt .= "Assistant: TOOL_CALL: delete_post\n";
        $prompt .= "TOOL_ARGS: {\"post_id\": 28800} ← Use ID from context\n\n";
        
        $prompt .= "Example 2 - Direct ID reference:\n";
        $prompt .= "User: 'Xóa bài #123'\n";
        $prompt .= "Assistant: TOOL_CALL: delete_post\n";
        $prompt .= "TOOL_ARGS: {\"post_id\": 123}\n\n";
        
        $prompt .= "Example 3 - When unclear:\n";
        $prompt .= "User: 'Xóa bài viết đó' (but no post mentioned in history)\n";
        $prompt .= "Assistant: 'Bạn muốn xóa bài viết nào ạ? Vui lòng cho Mochi biết ID hoặc tiêu đề bài viết.'\n\n";
        
        $prompt .= "Example 4 - Delete by title (use delete_post with title):\n";
        $prompt .= "User: 'Xóa bài về AI'\n";
        $prompt .= "Assistant: TOOL_CALL: delete_post\n";
        $prompt .= "TOOL_ARGS: {\"title\": \"AI\", \"force_delete\": true}\n";
        $prompt .= "→ delete_post tool will search for matching posts and delete them\n\n";
        
        $prompt .= "Example 5 - User queries (CRITICAL - DON'T CONFUSE WITH POSTS!):\n";
        $prompt .= "User: 'có bao nhiêu user?'\n";
        $prompt .= "Assistant: TOOL_CALL: query_database\n";
        $prompt .= "TOOL_ARGS: {\"query_type\": \"users\"}\n";
        $prompt .= "→ Returns: User count + list of all users (username, email, role)\n\n";
        
        $prompt .= "User: 'những user nào?'\n";
        $prompt .= "Assistant: TOOL_CALL: query_database\n";
        $prompt .= "TOOL_ARGS: {\"query_type\": \"users\"}\n";
        $prompt .= "→ Returns: List all users with details\n\n";
        
        $prompt .= "❌ WRONG: 'có bao nhiêu user?' → Replies with post count (NO!)\n";
        $prompt .= "✅ CORRECT: 'có bao nhiêu user?' → Calls query_database with query_type='users'\n\n";
        
        $prompt .= "RULE: ALWAYS check conversation history for post_id when user says 'đó', 'nó', 'that', 'it'!\n\n";
        $prompt .= "RULE: When user wants to delete but no ID provided, use delete_post with title or execute_sql:\n";
        $prompt .= "→ PREFER: delete_post tool (safer, handles multiple matches)\n";
        $prompt .= "→ FALLBACK: execute_sql for complex matching patterns\n\n";
        
        $prompt .= "=== DATABASE QUERY STRATEGY ===\n\n";
        $prompt .= "When user asks for information NOT in basic context, use query_database:\n\n";
        $prompt .= "⚠️ **CRITICAL RULE**: ALWAYS match user's intent correctly!\n";
        $prompt .= "- User asks about USERS → Call query_database with query_type='users'\n";
        $prompt .= "- User asks about POSTS → Use context data OR call query_database with query_type='posts'\n";
        $prompt .= "- User asks about IMAGES → Use context data OR call query_database with query_type='media'\n";
        $prompt .= "- NEVER confuse USERS with POSTS/IMAGES/COMMENTS!\n\n";
        
        $prompt .= "Examples:\n";
        $prompt .= "Q: 'Plugin nào được cài?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"plugins\"}\n";
        $prompt .= "    Then analyze the data and provide insights\n\n";
        
        $prompt .= "Q: 'Có mấy user?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"users\"}\n";
        $prompt .= "    Then analyze and report user statistics\n\n";
        
        $prompt .= "Q: 'có bao nhiêu user và những user nào?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"users\"}\n";
        $prompt .= "    Then show: total count + list all users with details (username, email, role)\n\n";
        
        $prompt .= "Q: 'Bình luận mới nhất?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"comments\", \"filters\": {\"limit\": 10}}\n";
        $prompt .= "    Then analyze and present recent comments\n\n";
        
        $prompt .= "Q: 'Ảnh nào chưa có alt text?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"media\"}\n";
        $prompt .= "    Then analyze which images need alt text\n\n";
        
        $prompt .= "Q: 'Categories nào có nhiều bài nhất?'\n";
        $prompt .= "A: TOOL_CALL: query_database\n";
        $prompt .= "    TOOL_ARGS: {\"query_type\": \"categories\"}\n";
        $prompt .= "    Then analyze and rank by post count\n\n";
        
        $prompt .= "RULE: NEVER say 'I don't have access to this information' - ALWAYS query database first!\n\n";
        
        $prompt .= "=== AUTOMATIC TOOL CALLING ===\n\n";
        $prompt .= "When user asks a question that requires database information, AUTOMATICALLY call the appropriate tool:\n\n";
        $prompt .= "Examples:\n";
        $prompt .= "• 'có bao nhiêu user?' → TOOL_CALL: query_database with query_type='users'\n";
        $prompt .= "• 'user nào?' → TOOL_CALL: query_database with query_type='users' (show all)\n";
        $prompt .= "• 'list users' → TOOL_CALL: query_database with query_type='users'\n";
        $prompt .= "• 'có bao nhiêu user và những user nào?' → TOOL_CALL: query_database with query_type='users'\n";
        $prompt .= "• 'plugin nào được cài?' → TOOL_CALL: query_database with query_type='plugins'\n";
        $prompt .= "• 'comments mới' → TOOL_CALL: query_database with query_type='comments'\n";
        $prompt .= "• 'categories' → TOOL_CALL: query_database with query_type='categories'\n\n";
        
        $prompt .= "CRITICAL: Don't ask user to confirm. Just call the tool immediately and return the result!\n";
        $prompt .= "CRITICAL: When user asks about USERS (người dùng, users, members, thành viên), ALWAYS call query_database with query_type='users'!\n";
        $prompt .= "CRITICAL: NEVER respond with site statistics (posts, images, comments) when user asks about USERS!\n\n";
        
        $prompt .= "=== EXECUTE_SQL EXAMPLES ===\n\n";
        
        $prompt .= "Example 1 - Gộp categories trùng lặp:\n";
        $prompt .= "User: 'Gộp các mục trùng lặp lại'\n";
        $prompt .= "Step 1: Tìm categories trùng (tên giống nhau):\n";
        $prompt .= "TOOL_CALL: execute_sql\n";
        $prompt .= "TOOL_ARGS: {\n";
        $prompt .= "  \"query\": \"SELECT name, COUNT(*) as count FROM %prefix%terms t JOIN %prefix%term_taxonomy tt ON t.term_id = tt.term_id WHERE tt.taxonomy = 'category' GROUP BY name HAVING count > 1\",\n";
        $prompt .= "  \"operation_type\": \"read\",\n";
        $prompt .= "  \"description\": \"Tìm categories có tên trùng lặp\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "Step 2: Gộp các categories trùng:\n";
        $prompt .= "TOOL_CALL: execute_sql\n";
        $prompt .= "TOOL_ARGS: {\n";
        $prompt .= "  \"query\": \"UPDATE %prefix%term_relationships SET term_taxonomy_id = (SELECT MIN(tt.term_taxonomy_id) FROM %prefix%term_taxonomy tt JOIN %prefix%terms t ON tt.term_id = t.term_id WHERE t.name = 'Category Name' AND tt.taxonomy = 'category') WHERE term_taxonomy_id IN (SELECT tt2.term_taxonomy_id FROM %prefix%term_taxonomy tt2 JOIN %prefix%terms t2 ON tt2.term_id = t2.term_id WHERE t2.name = 'Category Name' AND tt2.taxonomy = 'category')\",\n";
        $prompt .= "  \"operation_type\": \"write\",\n";
        $prompt .= "  \"description\": \"Gộp tất cả bài viết vào category chính\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "Example 2 - Tìm bài viết không có category:\n";
        $prompt .= "TOOL_CALL: execute_sql\n";
        $prompt .= "TOOL_ARGS: {\n";
        $prompt .= "  \"query\": \"SELECT p.ID, p.post_title FROM %prefix%posts p LEFT JOIN %prefix%term_relationships tr ON p.ID = tr.object_id WHERE p.post_type = 'post' AND p.post_status = 'publish' AND tr.term_taxonomy_id IS NULL\",\n";
        $prompt .= "  \"operation_type\": \"read\",\n";
        $prompt .= "  \"description\": \"Tìm bài viết chưa có category\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "Example 3 - Thống kê bài viết theo tác giả:\n";
        $prompt .= "TOOL_CALL: execute_sql\n";
        $prompt .= "TOOL_ARGS: {\n";
        $prompt .= "  \"query\": \"SELECT u.display_name, COUNT(p.ID) as post_count FROM %prefix%users u LEFT JOIN %prefix%posts p ON u.ID = p.post_author WHERE p.post_status = 'publish' GROUP BY u.ID ORDER BY post_count DESC\",\n";
        $prompt .= "  \"operation_type\": \"read\",\n";
        $prompt .= "  \"description\": \"Thống kê số bài viết của mỗi tác giả\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "IMPORTANT: Khi gộp categories:\n";
        $prompt .= "1. Tìm categories trùng bằng GROUP BY name\n";
        $prompt .= "2. Chọn 1 category làm chính (thường là MIN(term_id))\n";
        $prompt .= "3. UPDATE %prefix%term_relationships để gộp bài viết\n";
        $prompt .= "4. DELETE categories phụ trong %prefix%term_taxonomy và %prefix%terms\n";
        $prompt .= "5. Báo cáo kết quả cho user\n";
        
        $prompt .= "=== COMPREHENSIVE TOOL REFERENCE ===\n\n";
        $prompt .= "📝 **CONTENT MANAGEMENT TOOLS:**\n";
        $prompt .= "• create_post(title, content, status, category) - Create new post with AI\n";
        $prompt .= "• delete_post(post_id or title) - Delete single post by ID or title (fuzzy match)\n";
        $prompt .= "• delete_posts_bulk(status, older_than_days) - Delete multiple posts\n";
        $prompt .= "• delete_today_posts() - Delete posts published today\n";
        $prompt .= "• get_post_info(post_id) - Get detailed post information\n";
        $prompt .= "• schedule_post(post_id, schedule_time) - Schedule post for future\n";
        $prompt .= "• analyze_seo(post_id) - Analyze SEO and get score/suggestions\n\n";
        
        $prompt .= "🔧 **SYSTEM & MAINTENANCE TOOLS:**\n";
        $prompt .= "• check_system_health() - Full health check (PHP, WP, disk, database)\n";
        $prompt .= "• cleanup_database(targets) - Cleanup revisions, transients, spam, drafts\n";
        $prompt .= "• execute_sql(query, operation_type) - Execute raw SQL (with 4-layer security)\n";
        $prompt .= "• query_database(query_type, filters) - Query plugins/users/comments/media/categories/tags\n";
        $prompt .= "• update_site_settings(blogname, blogdescription, etc) - Update WP settings\n\n";
        
        $prompt .= "💻 **DEVELOPMENT TOOLS:**\n";
        $prompt .= "• file_reader(file_path, limit, offset) - Read and analyze files\n";
        $prompt .= "• file_writer(file_path, content, overwrite) - Create/update files\n";
        $prompt .= "• file_search(pattern, path, type) - Search files and content\n";
        $prompt .= "• code_linter(file_path, language) - Check code for errors and style issues\n";
        $prompt .= "• semantic_search(query, scope) - Search code semantically\n";
        $prompt .= "• git_committer(message, files, branch) - Commit to git repository\n\n";
        
        $prompt .= "🌐 **EXTERNAL TOOLS:**\n";
        $prompt .= "• web_search(query, count, language) - Search the web\n\n";
        
        $prompt .= "⚙️ **SYSTEM TOOLS:**\n";
        $prompt .= "• terminal_executor(command, description) - Execute terminal commands safely\n\n";
        
        $prompt .= "📊 **ANALYTICS & REPORTING:**\n";
        $prompt .= "• get_analytics(metric, period) - Get site analytics and statistics\n";
        $prompt .= "• manage_users(action, params) - Create/delete/modify users\n\n";
        
        $prompt .= "🎯 **SMART DELETION RULES:**\n";
        $prompt .= "User: 'xoá bài hôm nay' → Use: delete_today_posts()\n";
        $prompt .= "User: 'xoá các bài draft' → Use: delete_posts_bulk(status='draft')\n";
        $prompt .= "User: 'xoá bài cũ' → Use: delete_posts_bulk(status='publish', older_than_days=365)\n";
        $prompt .= "User: 'xóa bài về AI' → Use: delete_post(title='AI') with fuzzy matching\n\n";
        
        // Add new tool system tools dynamically
        if (class_exists('AIAgent_Tools_Loader')) {
            $tools_info = AIAgent_Tools_Loader::get_tools_for_ai_prompt();
            $prompt .= $tools_info;
        }
        
        return $prompt;
    }
    
    /**
     * Validation: Check if AI should have called a tool but didn't
     * This helps catch cases where AI misunderstood the query
     */
    /**
     * 🔥 DISABLED: Hardcoded tool validation
     * Đã tắt để tránh false positives với đa ngôn ngữ
     * Tin tưởng AI để tự quyết định khi nào gọi tool
     */
    private function should_ai_call_tool($ai_response, $query) {
        // Không validate nữa - để AI tự quyết định
        // Chỉ parse AI response để extract TOOL_CALL nếu có
        return false;
    }
    
    /**
     * 🆕 Validate and complete tool parameters
     * STEP 2: Check required params → Infer from context or ask user
     * 
     * @param string $tool_name Tool name
     * @param array $tool_args Args provided by AI
     * @param string $query Original user query
     * @param array $history Conversation history
     * @return array Validation result with complete args or missing params
     */
    private function validate_and_complete_tool_params($tool_name, $tool_args, $query, $history = array()) {
        if (!class_exists('AIautotool_Agent_Tools')) {
            return array(
                'valid' => true,
                'args' => $tool_args,
                'missing' => array()
            );
        }
        
        // Get tool definition
        $tools = AIautotool_Agent_Tools::get_tools_definitions();
        $tool_def = null;
        
        foreach ($tools as $tool) {
            if (isset($tool['function']['name']) && $tool['function']['name'] === $tool_name) {
                $tool_def = $tool['function'];
                break;
            }
        }
        
        if (!$tool_def) {
            // Tool not found, assume valid (maybe custom tool)
            return array(
                'valid' => true,
                'args' => $tool_args,
                'missing' => array()
            );
        }
        
        // Get required parameters
        $required = isset($tool_def['parameters']['required']) 
            ? $tool_def['parameters']['required'] 
            : array();
        
        if (empty($required)) {
            // No required params, return as-is
            return array(
                'valid' => true,
                'args' => $tool_args,
                'missing' => array()
            );
        }
        
        // Check missing params
        $missing = array();
        $complete_args = $tool_args;
        
        foreach ($required as $param_name) {
            $has_value = false;
            
            // Check if param exists and has value
            if (isset($complete_args[$param_name])) {
                $value = $complete_args[$param_name];
                if (is_string($value) && trim($value) !== '') {
                    $has_value = true;
                } elseif (is_array($value) && !empty($value)) {
                    $has_value = true;
                } elseif (is_numeric($value)) {
                    $has_value = true;
                } elseif (!is_null($value) && $value !== '') {
                    $has_value = true;
                }
            }
            
            if (!$has_value) {
                // Try to infer from context
                $inferred = $this->infer_parameter_from_context($param_name, $tool_name, $query, $history, $complete_args);
                
                if ($inferred !== null) {
                    $complete_args[$param_name] = $inferred;
                } else {
                    $missing[] = $param_name;
                }
            }
        }
        
        // Build details message for missing params
        $details = '';
        if (!empty($missing)) {
            $details = $this->get_missing_param_help_text($tool_name, $missing, $tool_def);
        }
        
        return array(
            'valid' => empty($missing),
            'args' => $complete_args,
            'missing' => $missing,
            'details' => $details
        );
    }
    
    /**
     * 🆕 Infer parameter value from context when not provided
     * IMPORTANT: Only infer for the SPECIFIC tool being called, not for all tools
     * 
     * @param string $param_name Parameter name to infer
     * @param string $tool_name Tool name (CRITICAL: only infer if tool matches)
     * @param string $query Current user query
     * @param array $history Conversation history
     * @param array $existing_args Already provided args
     * @return mixed Inferred value or null if cannot infer
     */
    private function infer_parameter_from_context($param_name, $tool_name, $query, $history, $existing_args) {
        // 🔥 CRITICAL: Tool-specific inference only!
        // Only infer parameters that belong to the specific tool being called
        
        // === create_post tool ===
        if ($tool_name === 'create_post') {
            switch ($param_name) {
                case 'keyword':
                    // Pattern 1: "tạo bài viết : X"
                    if (preg_match('/:\s*([^:\n]+)/', $query, $matches)) {
                        return trim($matches[1]);
                    }
                    // Pattern 2: "tạo bài về X" hoặc "viết bài về X"
                    if (preg_match('/(?:về|about)\s+([^:\n]+)/i', $query, $matches)) {
                        return trim($matches[1]);
                    }
                    // Pattern 3: Extract after action words - "tạo bài X" hoặc "viết post X"
                    if (preg_match('/(?:tạo|viết|create|write)\s+(?:bài|post|article)\s+(.+?)(?:\s|$|draft|nháp)/i', $query, $matches)) {
                        $extracted = trim($matches[1]);
                        // Don't extract if it's just "viết" or "bài" or empty
                        if (!empty($extracted) && !in_array(strtolower($extracted), array('bài', 'post', 'article', 'viết', 'write'))) {
                            return $extracted;
                        }
                    }
                    // Pattern 4: Last resort - everything after colon or "về"
                    if (preg_match('/[:\s](.+)$/', $query, $matches)) {
                        $extracted = trim($matches[1]);
                        if (!empty($extracted) && strlen($extracted) > 2) {
                            return $extracted;
                        }
                    }
                    // Cannot infer - return null to ask user
                    return null;
            }
        }
        
        // === query_database tool ===
        if ($tool_name === 'query_database') {
            switch ($param_name) {
                case 'query_type':
                    // Infer from query content
                    if (preg_match('/\b(user|users|người dùng|nguoi dung|thành viên|thanh vien|member|members)\b/i', $query)) {
                        return 'users';
                    }
                    if (preg_match('/\b(plugin|plugins)\b/i', $query)) {
                        return 'plugins';
                    }
                    if (preg_match('/\b(comment|comments|bình luận|binh luan)\b/i', $query)) {
                        return 'comments';
                    }
                    if (preg_match('/\b(category|categories|danh mục|danh muc)\b/i', $query)) {
                        return 'categories';
                    }
                    if (preg_match('/\b(tag|tags)\b/i', $query)) {
                        return 'tags';
                    }
                    if (preg_match('/\b(post|posts|bài|bài viết)\b/i', $query)) {
                        return 'posts';
                    }
                    // Cannot infer
                    return null;
            }
        }
        
        // === delete_post, get_post_info tools ===
        if (in_array($tool_name, array('delete_post', 'get_post_info', 'rewrite_post', 'schedule_post'))) {
            switch ($param_name) {
                case 'post_id':
                    // Extract post ID from query - look for numbers
                    if (preg_match('/\b(?:post|bài|id|#)\s*(\d+)\b/i', $query, $matches)) {
                        return intval($matches[1]);
                    }
                    // Just a number
                    if (preg_match('/\b(\d+)\b/', $query, $matches)) {
                        return intval($matches[1]);
                    }
                    // Check history for recent post IDs
                    foreach (array_reverse($history) as $msg) {
                        if (isset($msg['content']) && preg_match('/\b(?:post|bài|id)\s*(\d+)\b/i', $msg['content'], $matches)) {
                            return intval($matches[1]);
                        }
                    }
                    // Cannot infer
                    return null;
            }
        }
        
        // === delete_posts_bulk, get_posts tools ===
        if (in_array($tool_name, array('delete_posts_bulk', 'get_posts'))) {
            switch ($param_name) {
                case 'status':
                    // Infer status from query
                    if (preg_match('/\b(draft|nháp|nhap|bản nháp)\b/i', $query)) {
                        return 'draft';
                    }
                    if (preg_match('/\b(published|publish|đã đăng|da dang|published)\b/i', $query)) {
                        return 'publish';
                    }
                    if (preg_match('/\b(trash|thùng rác)\b/i', $query)) {
                        return 'trash';
                    }
                    // Cannot infer
                    return null;
                    
                case 'post_ids':
                    // Extract multiple post IDs
                    if (preg_match_all('/\b(\d+)\b/', $query, $matches)) {
                        $ids = array_map('intval', $matches[1]);
                        return !empty($ids) ? $ids : null;
                    }
                    // Cannot infer
                    return null;
            }
        }
        
        // === Other tools ===
        // Add more tool-specific inference logic here as needed
        
        // Cannot infer from context for this tool+parameter combination
        return null;
    }
    
    /**
     * 🆕 Check if query is an information question (not a command)
     */
    private function is_information_question($query) {
        $question_patterns = array(
            '/^(có bao nhiêu|how many|how much|số lượng|count|total)/i',
            '/(có bao nhiêu|how many|how much|số lượng|count|total).+\?/i',
            '/^(hiển thị|show|display|list|liệt kê|cho xem)/i',
            '/^(thông tin|info|information|details|chi tiết)/i',
            '/^(xem|view|see).+\?/i'
        );
        
        foreach ($question_patterns as $pattern) {
            if (preg_match($pattern, $query)) {
                return true;
            }
        }
        
        // Check if ends with question mark
        if (preg_match('/\?$/', trim($query))) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 🆕 Infer query_type from information question
     */
    private function infer_query_type_from_question($query) {
        $query_lower = mb_strtolower($query);
        
        // Users
        if (preg_match('/\b(user|users|người dùng|nguoi dung|thành viên|thanh vien|member|members)\b/i', $query)) {
            return 'users';
        }
        
        // Posts
        if (preg_match('/\b(post|posts|bài|bài viết|bai viet|article|articles)\b/i', $query)) {
            return 'posts';
        }
        
        // Comments
        if (preg_match('/\b(comment|comments|bình luận|binh luan)\b/i', $query)) {
            return 'comments';
        }
        
        // Plugins
        if (preg_match('/\b(plugin|plugins)\b/i', $query)) {
            return 'plugins';
        }
        
        // Categories
        if (preg_match('/\b(category|categories|danh mục|danh muc)\b/i', $query)) {
            return 'categories';
        }
        
        // Tags
        if (preg_match('/\b(tag|tags)\b/i', $query)) {
            return 'tags';
        }
        
        // Default: posts for general questions
        return 'posts';
    }
    
    /**
     * 🆕 Get help text for missing parameters
     */
    private function get_missing_param_help_text($tool_name, $missing_params, $tool_def) {
        $help_texts = array();
        
        foreach ($missing_params as $param) {
            // Get parameter description from tool definition
            $param_desc = '';
            if (isset($tool_def['parameters']['properties'][$param])) {
                $prop = $tool_def['parameters']['properties'][$param];
                $param_desc = isset($prop['description']) ? $prop['description'] : '';
            }
            
            // Custom help based on tool and param
            switch ($tool_name) {
                case 'create_post':
                    if ($param === 'keyword') {
                        $help_texts[] = "- **keyword**: Chủ đề/nội dung bài viết cần tạo (ví dụ: 'WordPress', 'đặt tên con')";
                    }
                    break;
                    
                case 'delete_post':
                    if ($param === 'post_id') {
                        $help_texts[] = "- **post_id**: ID của bài viết cần xóa (ví dụ: 123)";
                    }
                    break;
                    
                case 'delete_posts_bulk':
                    if (in_array($param, array('post_ids', 'status'))) {
                        $help_texts[] = "- Cần cung cấp **post_ids** (mảng ID) hoặc **status** (draft/publish) để xác định bài viết cần xóa";
                    }
                    break;
                    
                case 'query_database':
                    if ($param === 'query_type') {
                        $help_texts[] = "- **query_type**: Loại dữ liệu cần truy vấn (users, posts, comments, plugins, categories, tags)";
                    }
                    break;
                    
                default:
                    $help_texts[] = "- **{$param}**: " . ($param_desc ? $param_desc : "Tham số bắt buộc");
            }
        }
        
        return implode("\n", $help_texts);
    }
    
    /**
     * Analyze query intent
     */
    private function analyze_query_intent($query) {
        $query_lower = strtolower($query);
        
        // Greetings - Lời chào
        if (preg_match('/^(hello|hi|hey|chào|xin chào|chao|xin chao|good morning|good afternoon|good evening|greetings|hola|bonjour)[\s!?]*$/i', $query)) {
            return 'greeting';
        }
        
        // How are you - Hỏi thăm
        if (preg_match('/(how are you|how do you do|what\'?s up|how\'?s it going|bạn khỏe|khỏe không|thế nào)/i', $query)) {
            return 'how_are_you';
        }
        
        // Thank you - Cảm ơn
        if (preg_match('/^(thank|thanks|thank you|cảm ơn|cám ơn|thanks a lot|thx)[\s!?]*$/i', $query)) {
            return 'thank_you';
        }
        
        // Count posts by time period - Đếm bài viết theo thời gian
        if (preg_match('/(post|bài|bài viết).*(today|hôm nay|hom nay)/i', $query) ||
            preg_match('/(today|hôm nay|hom nay).*(post|bài|bài viết)/i', $query)) {
            return 'count_posts_today';
        }
        
        if (preg_match('/(post|bài|bài viết).*(yesterday|hôm qua|hom qua)/i', $query) ||
            preg_match('/(yesterday|hôm qua|hom qua).*(post|bài|bài viết)/i', $query)) {
            return 'count_posts_yesterday';
        }
        
        if (preg_match('/(post|bài|bài viết).*(this week|tuần này|tuan nay)/i', $query) ||
            preg_match('/(this week|tuần này|tuan nay).*(post|bài|bài viết)/i', $query)) {
            return 'count_posts_this_week';
        }
        
        if (preg_match('/(post|bài|bài viết).*(this month|tháng này|thang nay)/i', $query) ||
            preg_match('/(this month|tháng này|thang nay).*(post|bài|bài viết)/i', $query)) {
            return 'count_posts_this_month';
        }
        
        // Count posts - Đếm bài viết tổng
        if (preg_match('/(how many|bao nhiêu|có bao nhiêu|số lượng|count|total).*(post|bài|bài viết)/i', $query) ||
            preg_match('/(post|bài|bài viết).*(how many|bao nhiêu|có bao nhiêu|số lượng|count|total)/i', $query)) {
                return 'count_posts';
            }
        
        // Latest posts - Bài viết mới nhất
        if (preg_match('/(latest|recent|mới|mới nhất|gần đây).*(post|bài|bài viết)/i', $query) ||
            preg_match('/(post|bài|bài viết).*(latest|recent|mới|mới nhất|gần đây)/i', $query) ||
            preg_match('/cho (tôi |mình )?xem bài/i', $query)) {
                return 'latest_posts';
            }
        
        // Popular posts - Bài viết phổ biến
        if (preg_match('/(popular|top|phổ biến|hay nhất|tốt nhất).*(post|bài|bài viết)/i', $query) ||
            preg_match('/(post|bài|bài viết).*(popular|top|phổ biến|hay nhất|tốt nhất)/i', $query)) {
                return 'popular_posts';
        }
        
        // Search content - Tìm kiếm
        if (preg_match('/(search|find|tìm|tìm kiếm)/i', $query)) {
            return 'search_content';
        }
        
        // Statistics - Thống kê
        if (preg_match('/(stat|statistic|thống kê|xem thống kê|cho.*xem.*thống kê)/i', $query)) {
            return 'show_statistics';
        }
        
        // Alerts - Cảnh báo
        if (preg_match('/(alert|warning|problem|issue|cảnh báo|vấn đề|có.*cảnh báo|có.*vấn đề)/i', $query)) {
            return 'show_alerts';
        }
        
        // AI Tools status - Trạng thái công cụ AI
        if (preg_match('/(tool|công cụ|ai.*tool|trạng thái.*công cụ|công cụ.*ai)/i', $query)) {
            return 'show_tools';
        }
        
        // Broken images - Hình ảnh lỗi
        if (preg_match('/(broken|404|lỗi|hỏng).*(image|hình|ảnh|hình ảnh)/i', $query) ||
            preg_match('/(image|hình|ảnh|hình ảnh).*(broken|404|lỗi|hỏng)/i', $query)) {
                return 'broken_images';
            }
        
        // Images without alt - Hình thiếu alt
        if (preg_match('/(no alt|missing alt|thiếu alt|không có alt).*(image|hình|ảnh)/i', $query) ||
            preg_match('/(image|hình|ảnh).*(no alt|missing alt|thiếu alt|không có alt)/i', $query)) {
                return 'images_no_alt';
            }
        
        // Images info - Thông tin hình ảnh
        if (preg_match('/(image|images|hình|ảnh|hình ảnh)/i', $query)) {
            return 'images_info';
        }
        
        // SEO queries
        if (preg_match('/(seo|optimization|tối ưu)/i', $query)) {
            return 'seo_analysis';
        }
        
        // Performance queries
        if (preg_match('/(performance|speed|slow|fast|nhanh|chậm|hiệu suất)/i', $query)) {
            return 'performance_check';
        }
        
        // Query suggestions - Gợi ý câu hỏi
        if (preg_match('/(what can|tôi có thể|mình có thể|có thể).*(ask|hỏi|hoi)/i', $query) ||
            preg_match('/(gợi ý|goi y|suggest|show).*(câu hỏi|cau hoi|question|query|kịch bản|kich ban|scenario)/i', $query) ||
            preg_match('/^(help|trợ giúp|tro giup|giúp|giup)[\s?!]*$/i', $query) ||
            preg_match('/^(show me query suggestions|show me what i can ask)[\s?!]*$/i', $query)) {
            return 'show_query_suggestions';
        }
        
        // Suggestions - Gợi ý cải thiện
        if (preg_match('/(suggest|recommend|gợi ý|đề xuất|cho.*gợi ý|nên làm gì)/i', $query)) {
            return 'get_suggestions';
        }
        
        // === ACTION INTENTS - Ưu tiên cao nhất ===
        
        // Delete drafts - Xóa bài nháp (nhiều biến thể)
        if (preg_match('/(xóa|xoa|xoá|delete|remove|clear)/i', $query) && 
            preg_match('/(draft|nháp|nhap)/i', $query)) {
            return 'action_delete_drafts';
        }
        
        // Delete old posts - Xóa bài cũ
        if ((preg_match('/(xóa|xoa|xoá|delete|remove)/i', $query) && 
             preg_match('/(old|cũ|cu|older|cũ hơn|cu hon)/i', $query) && 
             preg_match('/(post|bài|bài viết)/i', $query))) {
            return 'action_delete_old_posts';
        }
        
        // Publish drafts - Đăng bài nháp
        if (preg_match('/(publish|đăng|dang|xuất bản|xuat ban)/i', $query) && 
            preg_match('/(draft|nháp|nhap)/i', $query)) {
            return 'action_publish_drafts';
        }
        
        // Update posts - Cập nhật bài viết
        if (preg_match('/(update|cập nhật|cap nhat|refresh|làm mới)/i', $query) && 
            preg_match('/(all|tất cả|tat ca|post|bài)/i', $query)) {
            return 'action_update_posts';
        }
        
        // Add alt text to images - Thêm alt text
        if (preg_match('/(add|thêm|them|generate|tạo|tao)/i', $query) && 
            preg_match('/(alt|alt text)/i', $query)) {
            return 'action_add_alt_text';
        }
        
        // Fix broken images - Sửa hình lỗi
        if (preg_match('/(fix|sửa|sua|remove|xóa|xoa)/i', $query) && 
            preg_match('/(broken|lỗi|loi|404|hỏng|hong)/i', $query) && 
            preg_match('/(image|hình|ảnh|img)/i', $query)) {
            return 'action_fix_broken_images';
        }
        
        // General content queries
        if (preg_match('/(post|posts|bài viết|bài|article|content|nội dung)/i', $query)) {
            return 'content_info';
        }
        
        return 'general_help';
    }
    
    /**
     * Generate response based on intent
     */
    private function generate_response($intent, $query) {
        switch ($intent) {
            case 'greeting':
                $assistant_name = get_option('aiautotool_bot_assistant_name', 'Mochi');
                $role_intro = get_option('aiautotool_bot_assistant_role_intro', '');
                
                if (!empty($role_intro)) {
                    // Use custom introduction with name replacement
                    return str_replace('{{assistant_name}}', $assistant_name, $role_intro);
                }
                
                // Default greetings with dynamic name
                $greetings = array(
                    sprintf(__('👋 Hello! I\'m %s, your AI assistant! How can I help you today?', 'ai-auto-tool'), $assistant_name),
                    sprintf(__('✨ Hi there! %s here! Ready to help you manage your site!', 'ai-auto-tool'), $assistant_name),
                    sprintf(__('😊 Hey! I\'m %s! What would you like to know about your site?', 'ai-auto-tool'), $assistant_name),
                    sprintf(__('🎉 Hello! I\'m %s and I\'m excited to assist you!', 'ai-auto-tool'), $assistant_name),
                );
                $random_greeting = $greetings[array_rand($greetings)];
                return $random_greeting . "\n\n" . __('I can help you with:\n• 📊 Content statistics\n• 🔍 Search content\n• ⚠️ Site alerts\n• 🤖 AI tools status\n• 💡 Smart suggestions', 'ai-auto-tool');
            
            case 'how_are_you':
                $responses = array(
                    __('😊 I\'m doing great! Thanks for asking! I\'m here and ready to help you manage your site!', 'ai-auto-tool'),
                    __('✨ Feeling fantastic! Your site is looking good and I\'m ready to assist you!', 'ai-auto-tool'),
                    __('🤖 I\'m operating at 100%! All systems ready to help you!', 'ai-auto-tool'),
                    __('💫 Doing wonderful! How about you? How can I help with your site today?', 'ai-auto-tool'),
                );
                return $responses[array_rand($responses)];
            
            case 'thank_you':
                $responses = array(
                    __('😊 You\'re welcome! Happy to help anytime!', 'ai-auto-tool'),
                    __('✨ My pleasure! Feel free to ask me anything else!', 'ai-auto-tool'),
                    __('🎉 Glad I could help! I\'m always here for you!', 'ai-auto-tool'),
                    __('💙 Anytime! That\'s what I\'m here for!', 'ai-auto-tool'),
                );
                return $responses[array_rand($responses)];
            
            case 'count_posts_today':
                $today_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'after' => 'today'
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $count = count($today_posts);
                
                if ($count == 0) {
                    return __('📝 You haven\'t published any posts today yet.\n\n💡 Tip: Want to publish some draft posts? Just ask me!', 'ai-auto-tool');
                }
                
                $posts_list = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(array('after' => 'today')),
                    'numberposts' => 5
                ));
                
                $response = sprintf(__('📝 You published %d post(s) today! 🎉\n\n', 'ai-auto-tool'), $count);
                
                if (!empty($posts_list)) {
                    $response .= __('Recent posts:\n', 'ai-auto-tool');
                    foreach ($posts_list as $post) {
                        $response .= "• " . $post->post_title . " (" . get_the_time('H:i', $post->ID) . ")\n";
                    }
                }
                
                return $response;
            
            case 'count_posts_yesterday':
                $yesterday_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'after' => 'yesterday',
                            'before' => 'today'
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $count = count($yesterday_posts);
                return sprintf(__('📅 Yesterday you published %d post(s).', 'ai-auto-tool'), $count);
            
            case 'count_posts_this_week':
                $week_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'after' => '1 week ago'
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $count = count($week_posts);
                return sprintf(__('📊 This week you published %d post(s).\n\n💪 Keep up the good work!', 'ai-auto-tool'), $count);
            
            case 'count_posts_this_month':
                $month_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'year' => date('Y'),
                            'month' => date('m')
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $count = count($month_posts);
                $days_in_month = date('j');
                $avg = $days_in_month > 0 ? round($count / $days_in_month, 1) : 0;
                
                return sprintf(
                    __('📈 This month you published %d post(s).\n\n📊 Average: %.1f posts/day\n💡 Great consistency!', 'ai-auto-tool'),
                    $count,
                    $avg
                );
            
            case 'count_posts':
                $count = wp_count_posts('post');
                return sprintf(
                    __('You have %d published posts, %d drafts, and %d scheduled posts.', 'ai-auto-tool'),
                    $count->publish,
                    $count->draft,
                    $count->future
                );
            
            case 'latest_posts':
                $posts = get_posts(array('numberposts' => 5));
                $response = __('Here are your 5 latest posts:', 'ai-auto-tool') . "\n\n";
                foreach ($posts as $post) {
                    $response .= "• " . $post->post_title . " (" . human_time_diff(strtotime($post->post_date), current_time('timestamp')) . " ago)\n";
                }
                return $response;
            
            case 'popular_posts':
                // Get posts ordered by comment count as proxy for popularity
                $posts = get_posts(array(
                    'numberposts' => 5,
                    'orderby' => 'comment_count',
                    'order' => 'DESC'
                ));
                $response = __('Your top 5 popular posts:', 'ai-auto-tool') . "\n\n";
                foreach ($posts as $post) {
                    $response .= "• " . $post->post_title . " (" . $post->comment_count . " comments)\n";
                }
                return $response;
            
            case 'show_statistics':
                $stats = $this->get_site_statistics();
                return sprintf(
                    __('Site Statistics:\n\n📝 Posts: %d\n🖼️ Images: %d\n💬 Comments: %d\n🤖 AI Actions Today: %d', 'ai-auto-tool'),
                    $stats['total_posts'],
                    $stats['total_images'],
                    $stats['total_comments'],
                    $stats['ai_actions']
                );
            
            case 'show_alerts':
                $alerts = $this->get_site_alerts();
                if (empty($alerts)) {
                    return __('✅ Great news! No alerts at the moment. Your site is running smoothly.', 'ai-auto-tool');
                }
                $response = sprintf(__('You have %d alerts:', 'ai-auto-tool'), count($alerts)) . "\n\n";
                foreach ($alerts as $i => $alert) {
                    if ($i >= 5) break; // Limit to 5 alerts
                    $response .= $this->get_alert_icon($alert['severity']) . " " . $alert['title'] . "\n";
                }
                return $response;
            
            case 'show_tools':
                $tools = $this->get_active_tools();
                if (empty($tools)) {
                    return __('No AI tools are currently active. Would you like recommendations on which tools to enable?', 'ai-auto-tool');
                }
                $response = sprintf(__('You have %d AI tools active:', 'ai-auto-tool'), count($tools)) . "\n\n";
                foreach ($tools as $tool) {
                    $response .= "✅ " . $this->get_tool_label($tool['name']) . "\n";
                }
                return $response;
            
            case 'images_info':
                $images_count = $this->count_images();
                $no_alt = $this->count_images_without_alt();
                return sprintf(
                    __('Images Overview:\n\n🖼️ Total Images: %d\n⚠️ Missing Alt Text: %d\n💡 Tip: Add alt text to improve SEO and accessibility!', 'ai-auto-tool'),
                    $images_count,
                    $no_alt
                );
            
            case 'images_no_alt':
                $no_alt = $this->count_images_without_alt();
                return sprintf(
                    __('%d images are missing alt text. This affects your SEO and accessibility. I recommend using the Images AI tool to automatically add alt text!', 'ai-auto-tool'),
                    $no_alt
                );
            
            case 'broken_images':
                $broken = $this->count_broken_images();
                if ($broken === 0) {
                    return __('✅ Good news! No broken images detected on your site.', 'ai-auto-tool');
                }
                return sprintf(
                    __('⚠️ Found %d broken images. I recommend running the Image Scanner tool to identify and fix them.', 'ai-auto-tool'),
                    $broken
                );
            
            case 'seo_analysis':
                return __('SEO Analysis:\n\n✅ Checking meta descriptions...\n✅ Analyzing heading structure...\n✅ Reviewing internal links...\n\n💡 Tip: Use the Single AI tool to optimize individual posts!', 'ai-auto-tool');
            
            case 'show_query_suggestions':
                return $this->get_query_suggestions();
            
            case 'get_suggestions':
                return $this->get_smart_suggestions();
            
            case 'search_content':
                // Extract search term from query
                $search_term = preg_replace('/\b(search|find|tìm|tìm kiếm)\b/i', '', $query);
                $search_term = trim($search_term);
                return $this->search_site_content($search_term);
            
            case 'content_info':
                $count = wp_count_posts('post');
                $recent_posts = get_posts(array('numberposts' => 3));
                $response = __('📝 Content Overview:', 'ai-auto-tool') . "\n\n";
                $response .= sprintf(
                    __('✅ Published: %d posts\n📄 Drafts: %d\n📅 Scheduled: %d', 'ai-auto-tool'),
                    $count->publish,
                    $count->draft,
                    $count->future
                ) . "\n\n";
                
                if (!empty($recent_posts)) {
                    $response .= __('Recent Posts:', 'ai-auto-tool') . "\n";
                    foreach ($recent_posts as $post) {
                        $response .= "• " . $post->post_title . "\n";
                    }
                }
                return $response;
            
            case 'performance_check':
                return __('🚀 Performance Check:\n\n✅ Analyzing page load speed...\n✅ Checking database optimization...\n✅ Reviewing image sizes...\n\n💡 Tip: Enable caching and image optimization in Extra Config!', 'ai-auto-tool');
            
            // === ACTION RESPONSES ===
            
            case 'action_delete_drafts':
                $count = wp_count_posts('post');
                $draft_count = $count->draft;
                
                if ($draft_count == 0) {
                    return __('✅ You don\'t have any draft posts to delete!', 'ai-auto-tool');
                }
                
                return $this->generate_action_response(
                    sprintf(__('⚠️ Are you sure you want to delete %d draft posts?', 'ai-auto-tool'), $draft_count),
                    sprintf(__('This will permanently delete all %d draft posts. This action cannot be undone!', 'ai-auto-tool'), $draft_count),
                    'delete_drafts',
                    array('count' => $draft_count)
                );
            
            case 'action_delete_old_posts':
                $days = isset($params['days']) ? intval($params['days']) : 365;
                
                $old_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'before' => date('Y-m-d', strtotime("-{$days} days"))
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $deleted = 0;
                foreach ($old_posts as $post_id) {
                    if (wp_delete_post($post_id, true)) {
                        $deleted++;
                    }
                }
                
                return array(
                    'message' => sprintf(__('Successfully deleted %d old posts! 🎉', 'ai-auto-tool'), $deleted),
                    'details' => sprintf(__('✅ Cleanup completed!\n\n🗑️ Deleted: %d posts older than %d days\n💾 Database optimized\n\nYour site is now cleaner!', 'ai-auto-tool'), $deleted, $days)
                );
            
            case 'action_publish_drafts':
                $count = wp_count_posts('post');
                $draft_count = $count->draft;
                
                if ($draft_count == 0) {
                    return __('✅ You don\'t have any draft posts to publish!', 'ai-auto-tool');
                }
                
                return $this->generate_action_response(
                    sprintf(__('📝 Publish %d draft posts?', 'ai-auto-tool'), $draft_count),
                    sprintf(__('This will publish all %d draft posts immediately. Are you sure?', 'ai-auto-tool'), $draft_count),
                    'publish_drafts',
                    array('count' => $draft_count)
                );
            
            case 'action_add_alt_text':
                $no_alt = $this->count_images_without_alt();
                
                if ($no_alt == 0) {
                    return __('✅ All images already have alt text!', 'ai-auto-tool');
                }
                
                return $this->generate_action_response(
                    sprintf(__('🖼️ Add alt text to %d images using AI?', 'ai-auto-tool'), $no_alt),
                    sprintf(__('This will use AI to generate alt text for %d images. This may take a while and use AI credits.', 'ai-auto-tool'), $no_alt),
                    'add_alt_text',
                    array('count' => $no_alt)
                );
            
            case 'action_fix_broken_images':
                $broken = $this->count_broken_images();
                
                if ($broken == 0) {
                    return __('✅ No broken images detected!', 'ai-auto-tool');
                }
                
                return $this->generate_action_response(
                    sprintf(__('🔧 Remove %d broken images from posts?', 'ai-auto-tool'), $broken),
                    sprintf(__('This will scan and remove %d broken images from your content.', 'ai-auto-tool'), $broken),
                    'fix_broken_images',
                    array('count' => $broken)
                );
            
            case 'action_delete_today_posts':
                $today = date('Y-m-d');
                $tomorrow = date('Y-m-d', strtotime('+1 day'));
                
                $today_posts = get_posts(array(
                    'post_status' => 'publish',
                    'date_query' => array(
                        array(
                            'after' => $today . ' 00:00:00',
                            'before' => $tomorrow . ' 00:00:00',
                            'inclusive' => true
                        )
                    ),
                    'numberposts' => -1,
                    'fields' => 'ids'
                ));
                
                $deleted = 0;
                foreach ($today_posts as $post_id) {
                    if (wp_delete_post($post_id, true)) {
                        $deleted++;
                    }
                }
                
                return array(
                    'message' => sprintf(__('Successfully deleted %d posts from today! 🎉', 'ai-auto-tool'), $deleted),
                    'details' => sprintf(__('✅ Cleanup completed!\n\n🗑️ Deleted: %d posts published today\n💾 Database optimized\n\nYour site is now cleaner!', 'ai-auto-tool'), $deleted)
                );
            
            default:
                return __('I can help you with:\n\n📊 Content statistics and analysis\n🔍 Search your content\n⚠️ Site health alerts\n🤖 AI tools monitoring\n💡 Smart suggestions\n🛠️ Automated actions\n\nJust ask me anything!', 'ai-auto-tool');
        }
    }
    
    /**
     * Generate action response with confirmation buttons
     */
    private function generate_action_response($title, $description, $action_type, $params = array()) {
        $nonce = wp_create_nonce('bot_action_' . $action_type);
        
        $response = $title . "\n\n" . $description . "\n\n";
        $response .= "<!-- ACTION_CONFIRMATION -->\n";
        $response .= json_encode(array(
            'type' => 'action',
            'action' => $action_type,
            'params' => $params,
            'nonce' => $nonce
        ));
        $response .= "\n<!-- /ACTION_CONFIRMATION -->";
        
        return $response;
    }
    
    /**
     * Get query suggestions - Kịch bản câu hỏi
     */
    private function get_query_suggestions() {
        $response = __('💡 Dưới đây là những gì bạn có thể hỏi tôi:\n\n', 'ai-auto-tool');
        $response .= "<!-- QUERY_SUGGESTIONS -->\n";
        
        $suggestions = array(
            array(
                'category' => '📊 ' . __('Quản lý nội dung', 'ai-auto-tool'),
                'queries' => array(
                    __('Có bao nhiêu bài viết?', 'ai-auto-tool'),
                    __('Bài viết được xuất bản hôm nay', 'ai-auto-tool'),
                    __('Hiển thị bài viết mới nhất', 'ai-auto-tool'),
                    __('Bài viết trong tháng này', 'ai-auto-tool'),
                    __('Tìm bài viết về WordPress', 'ai-auto-tool'),
                    __('Có bao nhiêu trang?', 'ai-auto-tool'),
                    __('Bài viết nào chưa có tiêu đề SEO?', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '🗑️ ' . __('Hành động nội dung', 'ai-auto-tool'),
                'queries' => array(
                    __('Xóa tất cả bài nháp', 'ai-auto-tool'),
                    __('Xuất bản bài nháp', 'ai-auto-tool'),
                    __('Xóa bài viết cũ', 'ai-auto-tool'),
                    __('Cập nhật tất cả bài viết', 'ai-auto-tool'),
                    __('Tạo bài viết tự động', 'ai-auto-tool'),
                    __('Tối ưu SEO cho bài viết', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '🖼️ ' . __('Hình ảnh & Media', 'ai-auto-tool'),
                'queries' => array(
                    __('Có bao nhiêu hình ảnh?', 'ai-auto-tool'),
                    __('Hình ảnh nào chưa có alt text?', 'ai-auto-tool'),
                    __('Thêm alt text cho hình ảnh', 'ai-auto-tool'),
                    __('Sửa hình ảnh bị lỗi', 'ai-auto-tool'),
                    __('Hiển thị hình ảnh bị lỗi', 'ai-auto-tool'),
                    __('Tối ưu kích thước hình ảnh', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '👥 ' . __('Người dùng & Bình luận', 'ai-auto-tool'),
                'queries' => array(
                    __('Có bao nhiêu người dùng?', 'ai-auto-tool'),
                    __('Người dùng nào có quyền admin?', 'ai-auto-tool'),
                    __('Bình luận mới nhất', 'ai-auto-tool'),
                    __('Bình luận nào cần kiểm duyệt?', 'ai-auto-tool'),
                    __('Xóa bình luận spam', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '🔧 ' . __('Bảo mật & Hiệu suất', 'ai-auto-tool'),
                'queries' => array(
                    __('Có cảnh báo bảo mật nào không?', 'ai-auto-tool'),
                    __('Kiểm tra hiệu suất website', 'ai-auto-tool'),
                    __('Phân tích SEO', 'ai-auto-tool'),
                    __('Kiểm tra plugin không sử dụng', 'ai-auto-tool'),
                    __('Cập nhật WordPress', 'ai-auto-tool'),
                    __('Sao lưu database', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '🤖 ' . __('Công cụ AI', 'ai-auto-tool'),
                'queries' => array(
                    __('Trạng thái công cụ AI', 'ai-auto-tool'),
                    __('Công cụ AI nào đang hoạt động?', 'ai-auto-tool'),
                    __('Hành động AI hôm nay', 'ai-auto-tool'),
                    __('Tạo nội dung với AI', 'ai-auto-tool'),
                    __('Tối ưu SEO với AI', 'ai-auto-tool'),
                )
            ),
            array(
                'category' => '💡 ' . __('Gợi ý & Tối ưu', 'ai-auto-tool'),
                'queries' => array(
                    __('Cho tôi gợi ý cải thiện', 'ai-auto-tool'),
                    __('Tôi nên làm gì để tối ưu?', 'ai-auto-tool'),
                    __('Mẹo tối ưu website', 'ai-auto-tool'),
                    __('Phân tích tổng quan website', 'ai-auto-tool'),
                    __('Kiểm tra lỗi website', 'ai-auto-tool'),
                )
            ),
        );
        
        $response .= json_encode($suggestions);
        $response .= "\n<!-- /QUERY_SUGGESTIONS -->";
        
        return $response;
    }
    
    /**
     * Get smart suggestions based on site analysis
     */
    private function get_smart_suggestions() {
        $suggestions = array();
        
        // Check content freshness
        $old_posts = get_posts(array(
            'date_query' => array(
                array(
                    'before' => '6 months ago'
                )
            ),
            'numberposts' => 1
        ));
        
        if (!empty($old_posts)) {
            $suggestions[] = "📝 Consider updating older posts to keep content fresh";
        }
        
        // Check images without alt
        $no_alt = $this->count_images_without_alt();
        if ($no_alt > 0) {
            $suggestions[] = "🖼️ Add alt text to $no_alt images for better SEO";
        }
        
        // Check comment moderation
        $pending_comments = wp_count_comments();
        if ($pending_comments->moderated > 0) {
            $suggestions[] = "💬 You have {$pending_comments->moderated} comments waiting for moderation";
        }
        
        // Check active tools
        $tools = $this->get_active_tools();
        if (count($tools) < 3) {
            $suggestions[] = "🤖 Activate more AI tools to automate your workflow";
        }
        
        if (empty($suggestions)) {
            return __('✅ Everything looks great! Your site is well-optimized. Keep up the good work!', 'ai-auto-tool');
        }
        
        return __('💡 Smart Suggestions:', 'ai-auto-tool') . "\n\n" . implode("\n", $suggestions);
    }
    
    /**
     * Search site content
     */
    private function search_site_content($search_term) {
        if (empty($search_term)) {
            return __('Please specify what you want to search for.', 'ai-auto-tool');
        }
        
        $args = array(
            's' => $search_term,
            'post_type' => 'post',
            'posts_per_page' => 5
        );
        
        $search_query = new WP_Query($args);
        
        if (!$search_query->have_posts()) {
            return sprintf(__('No results found for "%s"', 'ai-auto-tool'), $search_term);
        }
        
        $response = sprintf(__('Found %d results for "%s":', 'ai-auto-tool'), $search_query->found_posts, $search_term) . "\n\n";
        
        while ($search_query->have_posts()) {
            $search_query->the_post();
            $response .= "• " . get_the_title() . " (" . get_the_date() . ")\n";
        }
        wp_reset_postdata();
        
        return $response;
    }
    
    /**
     * Analyze site insights
     */
    private function analyze_site_insights() {
        $insights = array();
        
        // Check recent activity
        $recent_posts = get_posts(array(
            'numberposts' => 1,
            'date_query' => array(
                array(
                    'after' => '24 hours ago'
                )
            )
        ));
        
        if (!empty($recent_posts)) {
            $insights[] = array(
                'type' => 'success',
                'icon' => '✅',
                'title' => __('Active Publishing', 'ai-auto-tool'),
                'message' => __('You published content in the last 24 hours. Great consistency!', 'ai-auto-tool'),
                'action' => null
            );
        } else {
            $insights[] = array(
                'type' => 'info',
                'icon' => '📝',
                'title' => __('Time to Publish', 'ai-auto-tool'),
                'message' => __('No posts published today. Consider creating new content!', 'ai-auto-tool'),
                'action' => array(
                    'url' => admin_url('post-new.php'),
                    'label' => __('Create Post', 'ai-auto-tool')
                )
            );
        }
        
        // Check images without alt
        $no_alt_count = $this->count_images_without_alt();
        if ($no_alt_count > 10) {
            $insights[] = array(
                'type' => 'warning',
                'icon' => '⚠️',
                'title' => __('SEO Opportunity', 'ai-auto-tool'),
                'message' => sprintf(__('%d images missing alt text', 'ai-auto-tool'), $no_alt_count),
                'action' => array(
                    'url' => admin_url('admin.php?page=images'),
                    'label' => __('Fix Now', 'ai-auto-tool')
                )
            );
        }
        
        // Check AI tools usage
        $ai_actions_today = get_option('aiautotool_actions_today', 0);
        if ($ai_actions_today > 0) {
            $insights[] = array(
                'type' => 'success',
                'icon' => '🤖',
                'title' => __('AI Tools Active', 'ai-auto-tool'),
                'message' => sprintf(__('%d AI actions performed today', 'ai-auto-tool'), $ai_actions_today),
                'action' => null
            );
        }
        
        return $insights;
    }
    
    /**
     * Get site alerts
     */
    private function get_site_alerts() {
        // Memory optimization - cache results
        static $cached_alerts = null;
        if ($cached_alerts !== null) {
            return $cached_alerts;
        }
        
        $alerts = array();
        
        // Check for broken images
        $broken_images = get_option('aiautotool_broken_images_count', 0);
        if ($broken_images > 0) {
            $alerts[] = array(
                'severity' => 'high',
                'title' => __('Broken Images Detected', 'ai-auto-tool'),
                'message' => sprintf(__('%d images returning 404 errors', 'ai-auto-tool'), $broken_images),
                'time' => time(),
                'action' => array(
                    'url' => admin_url('admin.php?page=scan'),
                    'label' => __('View Details', 'ai-auto-tool')
                )
            );
        }
        
        // Check pending comments
        $pending = wp_count_comments();
        if ($pending->moderated > 10) {
            $alerts[] = array(
                'severity' => 'medium',
                'title' => __('Pending Comments', 'ai-auto-tool'),
                'message' => sprintf(__('%d comments waiting for moderation', 'ai-auto-tool'), $pending->moderated),
                'time' => time() - 3600,
                'action' => array(
                    'url' => admin_url('edit-comments.php?comment_status=moderated'),
                    'label' => __('Moderate', 'ai-auto-tool')
                )
            );
        }
        
        // Check spam
        if ($pending->spam > 50) {
            $alerts[] = array(
                'severity' => 'low',
                'title' => __('Spam Cleanup Needed', 'ai-auto-tool'),
                'message' => sprintf(__('%d spam comments to clean up', 'ai-auto-tool'), $pending->spam),
                'time' => time() - 7200,
                'action' => array(
                    'url' => admin_url('edit-comments.php?comment_status=spam'),
                    'label' => __('Clean Up', 'ai-auto-tool')
                )
            );
        }
        
        // Cache the alerts
        $cached_alerts = $alerts;
        return $alerts;
    }
    
    /**
     * Get site statistics
     */
    private function get_site_statistics() {
        // Memory optimization - cache results
        static $cached_stats = null;
        if ($cached_stats !== null) {
            return $cached_stats;
        }
        
        $stats = array();
        
        // Count posts
        $post_counts = wp_count_posts('post');
        $stats['total_posts'] = $post_counts->publish;
        
        // Count images (now optimized)
        $stats['total_images'] = $this->count_images();
        
        // Count comments
        $comment_counts = wp_count_comments();
        $stats['total_comments'] = $comment_counts->approved;
        
        // AI actions today
        $stats['ai_actions'] = get_option('aiautotool_actions_today', 0);
        
        // Cache the stats
        $cached_stats = $stats;
        return $stats;
    }
    
    /**
     * Get statistics for specific tool
     */
    private function get_tool_statistics($tool_name) {
        $stats = array();
        
        switch ($tool_name) {
            case 'auto_comment':
                $comments_count = get_option('aiautotool_auto_comments_generated', 0);
                $stats[__('Generated', 'ai-auto-tool')] = $comments_count;
                break;
            
            case 'images':
                $alt_added = get_option('aiautotool_alt_texts_added', 0);
                $stats[__('Alt Texts Added', 'ai-auto-tool')] = $alt_added;
                break;
            
            case 'auto_tag':
                $tags_created = get_option('aiautotool_tags_created', 0);
                $stats[__('Tags Created', 'ai-auto-tool')] = $tags_created;
                break;
            
            case 'bot_security':
                $blocked = get_option('aiautotool_bots_blocked', 0);
                $stats[__('Bots Blocked', 'ai-auto-tool')] = $blocked;
                break;
        }
        
        return $stats;
    }
    
    /**
     * Helper functions
     */
    private function count_images() {
        // Memory optimization - use cached count if available
        $cached_count = get_transient('aiautotool_images_count');
        if ($cached_count !== false) {
            return $cached_count;
        }
        
        // Use database query instead of get_posts to avoid memory issues
        global $wpdb;
        $count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->posts} 
            WHERE post_type = 'attachment' 
            AND post_mime_type LIKE 'image%'
        ");
        
        // Cache for 1 hour
        set_transient('aiautotool_images_count', $count, HOUR_IN_SECONDS);
        
        return $count;
    }
    
    private function count_images_without_alt() {
        // Memory optimization - use cached count if available
        $cached_count = get_transient('aiautotool_images_no_alt_count');
        if ($cached_count !== false) {
            return $cached_count;
        }
        
        global $wpdb;
        $count = $wpdb->get_var("
            SELECT COUNT(*) 
            FROM {$wpdb->posts} 
            WHERE post_type = 'attachment' 
            AND post_mime_type LIKE 'image%'
            AND ID NOT IN (
                SELECT post_id 
                FROM {$wpdb->postmeta} 
                WHERE meta_key = '_wp_attachment_image_alt' 
                AND meta_value != ''
            )
        ");
        
        // Cache for 1 hour
        set_transient('aiautotool_images_no_alt_count', intval($count), HOUR_IN_SECONDS);
        
        return intval($count);
    }
    
    private function count_broken_images() {
        return get_option('aiautotool_broken_images_count', 0);
    }
    
    /**
     * Clear all cached data to prevent memory issues
     */
    public function clear_cache() {
        // Clear transients
        delete_transient('aiautotool_images_count');
        delete_transient('aiautotool_images_no_alt_count');
        
        // Clear static caches by resetting them
        // Note: Static variables can't be cleared directly, but they'll reset on next request
    }
    
    private function get_tool_label($tool_name) {
        $labels = array(
            'cloudflare_ai' => __('Cloudflare AI', 'ai-auto-tool'),
            'auto_comment' => __('Auto Comment', 'ai-auto-tool'),
            'auto_tag' => __('Auto Tag', 'ai-auto-tool'),
            'bot_security' => __('Bot Security', 'ai-auto-tool'),
            'images' => __('Images AI', 'ai-auto-tool'),
            'singleai' => __('Single AI', 'ai-auto-tool'),
            'webstories' => __('Web Stories', 'ai-auto-tool'),
            'scan' => __('Scanner', 'ai-auto-tool'),
        );
        
        return isset($labels[$tool_name]) ? $labels[$tool_name] : $tool_name;
    }
    
    private function get_alert_icon($severity) {
        switch ($severity) {
            case 'high':
                return '🔴';
            case 'medium':
                return '🟡';
            case 'low':
                return '🔵';
            default:
                return 'ℹ️';
        }
    }
    
    /**
     * Add dashboard widget
     */
    public function add_dashboard_widget() {
        wp_add_dashboard_widget(
            'aiautotool_bot_assistant_widget',
            __('AI Assistant Insights', 'ai-auto-tool'),
            array($this, 'render_dashboard_widget')
        );
    }
    
    /**
     * Render dashboard widget
     */
    public function render_dashboard_widget() {
        $insights = $this->analyze_site_insights();
        $alerts = $this->get_site_alerts();
        
        echo '<div class="bot-assistant-widget">';
        
        // Quick stats
        $stats = $this->get_site_statistics();
        echo '<div class="widget-stats">';
        echo '<div class="stat-item">';
        echo '<span class="stat-value">' . number_format($stats['total_posts']) . '</span> ';
        echo '<span class="stat-label">' . __('Posts', 'ai-auto-tool') . '</span>';
        echo '</div>';
        echo '<div class="stat-item">';
        echo '<span class="stat-value">' . number_format($stats['ai_actions']) . '</span> ';
        echo '<span class="stat-label">' . __('AI Actions Today', 'ai-auto-tool') . '</span>';
        echo '</div>';
        echo '</div>';
        
        // Top alert
        if (!empty($alerts)) {
            $alert = $alerts[0];
            echo '<div class="widget-alert">';
            echo $this->get_alert_icon($alert['severity']) . ' ';
            echo '<strong>' . esc_html($alert['title']) . ':</strong> ';
            echo esc_html($alert['message']);
            echo '</div>';
        }
        
        // Link to full assistant
        echo '<p class="widget-action">';
        echo '<a href="' . admin_url('admin.php?page=aiautotool-bot-assistant') . '" class="button button-primary">';
        echo __('Open AI Assistant', 'ai-auto-tool');
        echo '</a>';
        echo '</p>';
        
        echo '</div>';
    }
    
    /**
     * Daily health check
     */
    public function daily_health_check() {
        // Update statistics
        update_option('aiautotool_actions_yesterday', get_option('aiautotool_actions_today', 0));
        update_option('aiautotool_actions_today', 0);
        
        // Check for issues
        $this->check_broken_images();
        $this->check_content_issues();
        
        // Send report if configured
        $this->maybe_send_daily_report();
    }
    
    private function check_broken_images() {
        // This would integrate with the scan tool
        // For now, just placeholder
        $broken_count = 0;
        update_option('aiautotool_broken_images_count', $broken_count);
    }
    
    private function check_content_issues() {
        // Check for posts without featured images, short content, etc.
        // Placeholder for now
    }
    
    private function maybe_send_daily_report() {
        $send_reports = get_option('aiautotool_bot_assistant_daily_report', false);
        if (!$send_reports) {
            return;
        }
        
        // Generate and send report
        // Could use Telegram bot integration
    }
    
    /**
     * AJAX handlers
     */
    public function get_insights() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $insights = $this->analyze_site_insights();
        wp_send_json_success($insights);
    }
    
    public function get_statistics() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $stats = $this->get_site_statistics();
        wp_send_json_success($stats);
    }
    
    public function search_content() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $search_term = sanitize_text_field($_POST['search_term']);
        $result = $this->search_site_content($search_term);
        
        wp_send_json_success(array('result' => $result));
    }
    
    public function get_alerts() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $alerts = $this->get_site_alerts();
        wp_send_json_success($alerts);
    }
    
    /**
     * Save AI settings via AJAX
     */
    public function save_ai_settings() {
        check_ajax_referer('bot_assistant_ai_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $use_ai = isset($_POST['use_ai']) && $_POST['use_ai'] == '1';
        
        // Save AI mode setting
        update_option('aiautotool_bot_assistant_use_ai', $use_ai);
        
        // Provider and model are now managed by AI Provider Manager
        // Keep old options for backward compatibility but they're no longer used
        if (isset($_POST['provider']) && $_POST['provider'] !== 'auto') {
            $provider = sanitize_text_field($_POST['provider']);
            update_option('aiautotool_bot_assistant_ai_provider', $provider);
        }
        
        if (isset($_POST['model']) && $_POST['model'] !== 'auto') {
            $model = sanitize_text_field($_POST['model']);
            update_option('aiautotool_bot_assistant_ai_model', $model);
        }
        
        wp_send_json_success(array(
            'message' => __('AI settings saved successfully!', 'ai-auto-tool')
        ));
    }
    
    /**
     * Execute bot action via AJAX
     */
    public function execute_action() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $action_type = sanitize_text_field($_POST['action_type']);
        $action_nonce = sanitize_text_field($_POST['action_nonce']);
        $params = isset($_POST['params']) ? $_POST['params'] : array();
        
        // Verify action nonce
        if (!wp_verify_nonce($action_nonce, 'bot_action_' . $action_type)) {
            wp_send_json_error(array('message' => __('Invalid action token', 'ai-auto-tool')));
        }
        
        // Execute action based on type
        switch ($action_type) {
            case 'delete_drafts':
                $result = $this->action_delete_drafts($params);
                break;
            
            case 'delete_old_posts':
                $result = $this->action_delete_old_posts($params);
                break;
            
            case 'publish_drafts':
                $result = $this->action_publish_drafts($params);
                break;
            
            case 'add_alt_text':
                $result = $this->action_add_alt_text($params);
                break;
            
            case 'fix_broken_images':
                $result = $this->action_fix_broken_images($params);
                break;
            
            case 'manage_users':
                // Use AIAgent_Tool_User_Manager tool
                if (class_exists('AIAgent_Tool_User_Manager')) {
                    $result = AIAgent_Tool_User_Manager::execute($params);
                    if (isset($result['success']) && $result['success']) {
                        // Tool returns success with data
                        wp_send_json_success($result);
                    } else {
                        wp_send_json_error(array('message' => isset($result['error']) ? $result['error'] : 'Action failed'));
                    }
                    wp_die(); // Prevent further execution
                } else {
                    // Fallback to old method if tool not loaded
                    $result = $this->action_manage_users($params);
                }
                break;
            
            default:
                wp_send_json_error(array('message' => __('Unknown action type', 'ai-auto-tool')));
        }
        
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        } else {
            wp_send_json_success($result);
        }
    }
    
    /**
     * Execute AI Agent Tool
     */
    /**
     * Auto-execute tool from parsed AI response with retry logic
     */
    private function execute_tool_from_parsed_response($parsed_response) {
        if (!isset($parsed_response['tool_name']) || empty($parsed_response['tool_name'])) {
            return array(
                'success' => false,
                'message' => 'No tool to execute'
            );
        }
        
        $tool_name = $parsed_response['tool_name'];
        $tool_args = isset($parsed_response['tool_args']) ? $parsed_response['tool_args'] : array();
        
        
        // Execute tool via AI Agent Tools
        if (!class_exists('AIautotool_Agent_Tools')) {
            return array(
                'success' => false,
                'message' => 'AI Agent Tools not available'
            );
        }
        
        $result = AIautotool_Agent_Tools::execute_tool($tool_name, $tool_args);
        
        
        if ($result['success']) {
            // Format successful response
            $response = isset($parsed_response['response']) ? $parsed_response['response'] : '';
            $response .= "\n\n✅ **Executed Successfully!**\n\n";
            
            if (isset($result['data'])) {
                $response .= "Results:\n";
                if (is_array($result['data'])) {
                    $response .= print_r($result['data'], true);
                } else {
                    $response .= $result['data'];
                }
            }
            
            return array(
                'success' => true,
                'response' => $response,
                'result' => $result
            );
        } else {
            // 🆕 NEW: Auto-retry with fix if missing parameter
            $error_msg = isset($result['error']) ? $result['error'] : 'Unknown error';
            
            // Try to auto-fix missing parameters
            if (strpos($error_msg, 'Thiếu tham số') !== false || 
                strpos($error_msg, 'required parameter') !== false ||
                strpos($error_msg, 'missing') !== false ||
                strpos($error_msg, 'keyword') !== false) {
                
                $fixed_args = $this->auto_fix_tool_parameters($tool_name, $tool_args, $parsed_response);
                
                if ($fixed_args !== null) {
                    
                    // Retry with fixed parameters
                    $retry_result = AIautotool_Agent_Tools::execute_tool($tool_name, $fixed_args);
                    
                    if (!$retry_result['success']) {
                    }
                    
                    if ($retry_result['success']) {
                        $response = isset($parsed_response['response']) ? $parsed_response['response'] : '';
                        $response .= "\n\n✅ **Auto-fixed and Executed!**\n\n";
                        
                        if (isset($retry_result['data'])) {
                            $response .= "Results:\n";
                            if (is_array($retry_result['data'])) {
                                $response .= print_r($retry_result['data'], true);
                            } else {
                                $response .= $retry_result['data'];
                            }
                        }
                        
                        return array(
                            'success' => true,
                            'response' => $response,
                            'result' => $retry_result,
                            'auto_fixed' => true
                        );
                    }
                }
            }
            
            // Return error response
            return array(
                'success' => false,
                'response' => isset($parsed_response['response']) ? $parsed_response['response'] : "❌ Failed to execute: {$error_msg}",
                'error' => $error_msg,
                'tool_result' => $result
            );
        }
    }
    
    /**
     * Auto-fix tool parameters when missing
     */
    private function auto_fix_tool_parameters($tool_name, $tool_args, $parsed_response) {
        $original_query = isset($parsed_response['original_query']) ? $parsed_response['original_query'] : '';
        
        
        // Try to extract missing parameters from original query
        $fixed_args = $tool_args;
        
        // For create_post - extract keyword from query
        if ($tool_name === 'create_post' && empty($fixed_args['keyword'])) {
            // Extract keyword from original query
            if (preg_match('/:\s*([^:\n]+)/', $original_query, $matches)) {
                $fixed_args['keyword'] = trim($matches[1]);
            } elseif (!empty($original_query)) {
                // Fallback: use whole query
                $fixed_args['keyword'] = $original_query;
            }
        }
        
        // Add default status if missing
        if ($tool_name === 'create_post' && empty($fixed_args['status'])) {
            $fixed_args['status'] = 'draft';
        }
        
        
        // Only return fixed args if we actually fixed something
        if ($fixed_args !== $tool_args) {
            return $fixed_args;
        }
        
        return null; // No fix possible
    }
    
    public function execute_tool() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $function_name = sanitize_text_field($_POST['function_name']);
        $arguments = isset($_POST['arguments']) ? json_decode(stripslashes($_POST['arguments']), true) : array();
        
        // Debug logging
        
        if (!is_array($arguments)) {
            $arguments = array();
        }
        
        // Execute tool via AI Agent Tools class
        $result = AIautotool_Agent_Tools::execute_tool($function_name, $arguments);
        
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Agentic Workflow - Simplified: Direct response or SQL query
     */
    public function agentic_start() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $query = sanitize_text_field($_POST['query']);
        $session_id = 'agentic_' . time() . '_' . wp_rand(1000, 9999);
        
        // Get site context (tài nguyên hiện có)
        $site_context = $this->get_site_context();
        // Lấy danh sách các tool hiện có từ @tools/
        $tools_list_str = '';
        if (class_exists('AIautotool_Agent_Tools')) {
            $tools_definitions = AIautotool_Agent_Tools::get_tools_definitions();
            if (!empty($tools_definitions) && is_array($tools_definitions)) {
                foreach ($tools_definitions as $tool) {
                    if (isset($tool['function']['name']) && isset($tool['function']['description'])) {
                        $tools_list_str .= "- {$tool['function']['name']}: {$tool['function']['description']}\n";
                    }
                }
            }
        }
        $context_str = is_array($site_context) ? print_r($site_context, true) : (string)$site_context;
        
        // Build prompt với phân loại yêu cầu đơn giản/phức tạp
        $prompt = "Bạn là AI Assistant thông minh. Nhiệm vụ: Phân tích yêu cầu của người dùng và xác định độ phức tạp.\n\n";
        $prompt .= "Đây là tài nguyên hiện có:\n\n{$context_str}\n\n";
        if (!empty($tools_list_str)) {
            $prompt .= "Các công cụ có sẵn trong hệ thống:\n{$tools_list_str}\n";
        }
        $prompt .= "Câu hỏi/yêu cầu của người dùng: {$query}\n\n";
        
        $prompt .= "PHÂN LOẠI YÊU CẦU:\n";
        $prompt .= "1. YÊU CẦU ĐỠN GIẢN: Câu hỏi đơn, trả lời trực tiếp, không cần nhiều bước xử lý.\n";
        $prompt .= "   Ví dụ: 'Có bao nhiêu bài viết?', 'Thông tin về plugin hiện tại', 'Liệt kê users'\n";
        $prompt .= "2. YÊU CẦU PHỨC TẠP: Cần nhiều bước, nhiều tool, cần thu thập thông tin trước, cần planning.\n";
        $prompt .= "   Ví dụ: 'Tạo bài viết và gửi email thông báo', 'Phân tích SEO và tối ưu toàn bộ site', 'Backup và cleanup database'\n\n";
        
        $prompt .= "FORMAT JSON TRẢ LỜI:\n";
        $prompt .= "{\n";
        $prompt .= "  \"is_complex\": true/false,\n";
        $prompt .= "  \"has_info\": true/false,\n";
        $prompt .= "  \"response\": \"Câu trả lời hoặc plan summary\",\n";
        $prompt .= "  \"needs_sql\": true/false,\n";
        $prompt .= "  \"sql_query\": \"Câu SQL query nếu cần (dùng %prefix% thay cho table prefix)\",\n";
        $prompt .= "  \"operation_type\": \"read\" hoặc \"write\" (chỉ cần khi có sql_query),\n";
        $prompt .= "  \"tool\": \"Tên tool nếu cần dùng, nếu không có thì để rỗng hoặc null\",\n";
        $prompt .= "  \"tool_args\": { \"arg1\": \"Mô tả tham số 1\", \"arg2\": \"Mô tả tham số 2\" },\n";
        $prompt .= "  \"ask_parameters\": true/false,\n";
        $prompt .= "  \"parameters_needed\": [\"liệt kê các tên tham số cần hỏi user\"],\n";
        $prompt .= "  \"plan_summary\": \"Nếu is_complex=true, trả về format: 'Người dùng cần {mô tả yêu cầu}, tôi hiện có {tài nguyên có sẵn}, tôi cần phải {các bước cần làm} để xử lý.'\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "QUY TẮC:\n";
        $prompt .= "- Nếu is_complex=false: Trả lời trực tiếp như bình thường (has_info, needs_sql, tool, etc.)\n";
        $prompt .= "- Nếu is_complex=true: BẮT BUỘC phải có plan_summary với format: 'Người dùng cần {xxx}, tôi hiện có {xxx}, tôi cần phải {xxx} để xử lý.'\n";
        $prompt .= "- Plan summary phải rõ ràng, chi tiết về những gì cần làm, không chỉ là mô tả chung chung.\n";
        $prompt .= "- Nếu có thông tin trong tài nguyên: has_info=true, response=trả lời đầy đủ\n";
        $prompt .= "- Nếu không có thông tin: has_info=false, response='Hiện chưa có thông tin...', needs_sql=true nếu cần SQL\n";
        $prompt .= "- SQL query phải hợp lệ, dùng %prefix% cho table prefix\n";
        $prompt .= "- operation_type='read' cho SELECT, 'write' cho UPDATE/INSERT/DELETE\n";
        
        // Call AI
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.7,
            'max_tokens' => 2000
        ));
        
        if (!$ai_response['success']) {
            wp_send_json_error(array('message' => 'Không thể kết nối AI: ' . (isset($ai_response['error']) ? $ai_response['error'] : 'Unknown error')));
            return;
        }
        
        // Parse AI response
        $content = trim($ai_response['content']);
        $content = preg_replace('/```json\s*/i', '', $content);
        $content = preg_replace('/```\s*$/m', '', $content);
        
        $json_start = strpos($content, '{');
        $json_end = strrpos($content, '}');
        
        if ($json_start !== false && $json_end !== false && $json_end > $json_start) {
            $json_str = substr($content, $json_start, $json_end - $json_start + 1);
            $ai_data = json_decode($json_str, true);
        } else {
            $ai_data = json_decode($content, true);
        }
        
        // If JSON parse failed, use response directly
        if (!$ai_data || !is_array($ai_data)) {
            wp_send_json_success(array(
                'step' => 'complete',
                'session_id' => $session_id,
                'response' => $content,
                'is_complex' => false,
                'has_sql' => false
            ));
            return;
        }
        
        // Check if complex request
        $is_complex = isset($ai_data['is_complex']) && $ai_data['is_complex'] === true;
        
        // If complex request, return plan summary for next step
        if ($is_complex && !empty($ai_data['plan_summary'])) {
            // Store plan summary in session for next AJAX call
            $this->store_agentic_session($session_id, array(
                'query' => $query,
                'plan_summary' => $ai_data['plan_summary'],
                'ai_data' => $ai_data,
                'step' => 'plan',
                'created_at' => time()
            ));
            
            wp_send_json_success(array(
                'step' => 'plan_ready',
                'session_id' => $session_id,
                'response' => $ai_data['plan_summary'],
                'is_complex' => true,
                'needs_plan_execution' => true,
                'has_info' => isset($ai_data['has_info']) ? $ai_data['has_info'] : false
            ));
            return;
        }
        
        // Simple request: handle directly
        // If has direct response, return it
        if (isset($ai_data['has_info']) && $ai_data['has_info'] && !empty($ai_data['response'])) {
            wp_send_json_success(array(
                'step' => 'complete',
                'session_id' => $session_id,
                'response' => $ai_data['response'],
                'is_complex' => false,
                'has_sql' => false
            ));
            return;
        }
        
        // If needs SQL query
        if (isset($ai_data['needs_sql']) && $ai_data['needs_sql'] && !empty($ai_data['sql_query'])) {
            $sql_query = $ai_data['sql_query'];
            $operation_type = isset($ai_data['operation_type']) ? $ai_data['operation_type'] : 'read';
            
            // Execute SQL
            if (class_exists('AIautotool_Agent_Tools')) {
                $sql_result = AIautotool_Agent_Tools::execute_tool('execute_sql', array(
                    'query' => $sql_query,
                    'operation_type' => $operation_type,
                    'description' => "Truy vấn SQL để tìm thông tin: {$query}"
                ));
                
                // Build final response
                $final_response = isset($ai_data['response']) ? $ai_data['response'] . "\n\n" : '';
                
                if ($sql_result['success']) {
                    $final_response .= "Kết quả truy vấn SQL:\n";
                    if (isset($sql_result['message'])) {
                        $final_response .= $sql_result['message'];
                    }
                    if (isset($sql_result['data'])) {
                        $data_str = is_array($sql_result['data']) ? json_encode($sql_result['data'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : (string)$sql_result['data'];
                        $final_response .= "\n" . $data_str;
                    }
                } else {
                    $final_response .= "Lỗi khi thực thi SQL: " . (isset($sql_result['error']) ? $sql_result['error'] : 'Unknown error');
                }
                
                wp_send_json_success(array(
                    'step' => 'complete',
                    'session_id' => $session_id,
                    'response' => $final_response,
                    'is_complex' => false,
                    'has_sql' => true,
                    'sql_query' => $sql_query,
                    'sql_result' => $sql_result
                ));
            } else {
                wp_send_json_error(array('message' => 'Tools class không tồn tại'));
            }
            return;
        }
        
        // Fallback: return AI response directly
        $fallback_response = isset($ai_data['response']) ? $ai_data['response'] : $content;
        wp_send_json_success(array(
            'step' => 'complete',
            'session_id' => $session_id,
            'response' => $fallback_response,
            'is_complex' => false,
            'has_sql' => false
        ));
    }
    
    /**
     * Agentic Workflow - Step 2: Execute
     */
    public function agentic_execute() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $session_id = sanitize_text_field($_POST['session_id']);
        $session_data = $this->get_agentic_session($session_id);
        
        if (!$session_data) {
            wp_send_json_error(array('message' => 'Session not found'));
        }
        
        // Execute plan
        $execution_results = $this->execute_agentic_plan($session_data['plan_data']);
        
        // Update session with results
        $session_data['execution_results'] = $execution_results;
        $session_data['step'] = 'execute';
        $this->store_agentic_session($session_id, $session_data);
        
        wp_send_json_success(array(
            'step' => 'execute',
            'next' => 'reflect',
            'session_id' => $session_id,
            'data' => $execution_results
        ));
    }
    
    /**
     * Agentic Workflow - Step 3: Reflect
     */
    public function agentic_reflect() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $session_id = sanitize_text_field($_POST['session_id']);
        $session_data = $this->get_agentic_session($session_id);
        
        if (!$session_data) {
            wp_send_json_error(array('message' => 'Session not found'));
        }
        
        // Reflect on results
        $reflection_data = $this->reflect_on_results($session_data);
        
        // Update session
        $session_data['reflection_data'] = $reflection_data;
        $session_data['step'] = 'reflect';
        $this->store_agentic_session($session_id, $session_data);
        
        // Determine next step
        $next_step = $reflection_data['result_ok'] ? 'done' : 'plan';
        
        wp_send_json_success(array(
            'step' => 'reflect',
            'next' => $next_step,
            'session_id' => $session_id,
            'data' => $reflection_data,
            'execution_results' => $session_data['execution_results'] ?? array()
        ));
    }
    
    /**
     * Agentic Workflow - Execute Plan: Xử lý plan chi tiết từ plan summary
     */
    public function agentic_execute_plan() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $session_id = sanitize_text_field($_POST['session_id']);
        $session_data = $this->get_agentic_session($session_id);
        
        if (!$session_data) {
            wp_send_json_error(array('message' => 'Session not found'));
        }
        
        if (empty($session_data['plan_summary'])) {
            wp_send_json_error(array('message' => 'Plan summary not found in session'));
        }
        
        $plan_summary = $session_data['plan_summary'];
        $original_query = isset($session_data['query']) ? $session_data['query'] : '';
        
        // Get site context and tools for planning
        $site_context = $this->get_site_context();
        $tools_list_str = '';
        $tools_definitions_list = array();
        
        if (class_exists('AIautotool_Agent_Tools')) {
            $tools_definitions = AIautotool_Agent_Tools::get_tools_definitions();
            if (!empty($tools_definitions) && is_array($tools_definitions)) {
                foreach ($tools_definitions as $tool) {
                    if (isset($tool['function']['name']) && isset($tool['function']['description'])) {
                        $tools_list_str .= "- {$tool['function']['name']}: {$tool['function']['description']}\n";
                        
                        // Build detailed tool info for AI
                        $tool_info = array(
                            'name' => $tool['function']['name'],
                            'description' => $tool['function']['description']
                        );
                        if (isset($tool['function']['parameters']['properties'])) {
                            $tool_info['parameters'] = array();
                            foreach ($tool['function']['parameters']['properties'] as $param_name => $param_data) {
                                $tool_info['parameters'][$param_name] = array(
                                    'type' => isset($param_data['type']) ? $param_data['type'] : 'string',
                                    'description' => isset($param_data['description']) ? $param_data['description'] : '',
                                    'required' => isset($tool['function']['parameters']['required']) && in_array($param_name, $tool['function']['parameters']['required'])
                                );
                            }
                        }
                        $tools_definitions_list[] = $tool_info;
                    }
                }
            }
        }
        
        $context_str = is_array($site_context) ? print_r($site_context, true) : (string)$site_context;
        
        // Build prompt để AI tạo plan chi tiết
        $prompt = "Bạn là AI Planner chuyên nghiệp. Nhiệm vụ: Tạo plan chi tiết để thực thi yêu cầu phức tạp.\n\n";
        $prompt .= "YÊU CẦU GỐC: {$original_query}\n\n";
        $prompt .= "PLAN SUMMARY: {$plan_summary}\n\n";
        $prompt .= "TÀI NGUYÊN HIỆN CÓ:\n{$context_str}\n\n";
        
        if (!empty($tools_list_str)) {
            $prompt .= "CÁC TOOLS CÓ SẴN:\n{$tools_list_str}\n\n";
        }
        
        $prompt .= "NHIỆM VỤ:\n";
        $prompt .= "Dựa trên plan summary trên, hãy tạo plan chi tiết với các bước cụ thể để thực thi.\n";
        $prompt .= "Mỗi bước phải rõ ràng, có thể thực thi ngay, và sử dụng đúng tool với đúng tham số.\n\n";
        
        $prompt .= "FORMAT JSON TRẢ LỜI (BẮT BUỘC):\n";
        $prompt .= "{\n";
        $prompt .= "  \"goal\": \"Mục tiêu tổng thể cần đạt được\",\n";
        $prompt .= "  \"steps\": [\n";
        $prompt .= "    {\n";
        $prompt .= "      \"step\": 1,\n";
        $prompt .= "      \"action\": \"tên_tool\",\n";
        $prompt .= "      \"description\": \"Mô tả chi tiết bước này\",\n";
        $prompt .= "      \"args\": {\"param1\": \"value1\", \"param2\": \"value2\"},\n";
        $prompt .= "      \"depends_on\": null hoặc số step phụ thuộc,\n";
        $prompt .= "      \"critical\": true/false\n";
        $prompt .= "    }\n";
        $prompt .= "  ],\n";
        $prompt .= "  \"estimated_time\": \"Thời gian ước tính\",\n";
        $prompt .= "  \"risks\": [\"Rủi ro 1\", \"Rủi ro 2\"]\n";
        $prompt .= "}\n\n";
        
        $prompt .= "QUY TẮC:\n";
        $prompt .= "- Mỗi step phải có action là tên tool thực tế có trong danh sách tools\n";
        $prompt .= "- args phải phù hợp với parameters của tool đó\n";
        $prompt .= "- Nếu step này phụ thuộc vào kết quả step trước, đặt depends_on = số step\n";
        $prompt .= "- Nếu step là bắt buộc phải thành công, đặt critical = true\n";
        $prompt .= "- Ưu tiên các bước có thể thực thi song song (depends_on = null)\n";
        $prompt .= "- Plan phải logic, thứ tự hợp lý\n\n";
        
        // Call AI để tạo plan chi tiết
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.5,
            'max_tokens' => 3000
        ));
        
        if (!$ai_response['success']) {
            wp_send_json_error(array('message' => 'Không thể kết nối AI để tạo plan: ' . (isset($ai_response['error']) ? $ai_response['error'] : 'Unknown error')));
            return;
        }
        
        // Parse AI response để lấy plan
        $content = trim($ai_response['content']);
        $content = preg_replace('/```json\s*/i', '', $content);
        $content = preg_replace('/```\s*$/m', '', $content);
        
        $json_start = strpos($content, '{');
        $json_end = strrpos($content, '}');
        
        if ($json_start !== false && $json_end !== false && $json_end > $json_start) {
            $json_str = substr($content, $json_start, $json_end - $json_start + 1);
            $plan_data = json_decode($json_str, true);
        } else {
            $plan_data = json_decode($content, true);
        }
        
        if (!$plan_data || !is_array($plan_data) || !isset($plan_data['steps'])) {
            wp_send_json_error(array('message' => 'Không thể parse plan từ AI response. Response: ' . substr($content, 0, 500)));
            return;
        }
        
        // Validate plan
        if (empty($plan_data['steps']) || !is_array($plan_data['steps'])) {
            wp_send_json_error(array('message' => 'Plan không có steps hợp lệ'));
            return;
        }
        
        // Store detailed plan in session
        $session_data['detailed_plan'] = $plan_data;
        $session_data['step'] = 'plan_ready';
        $this->store_agentic_session($session_id, $session_data);
        
        // Execute plan
        $execution_results = $this->execute_agentic_plan($plan_data);
        
        // Update session with execution results
        $session_data['execution_results'] = $execution_results;
        $session_data['step'] = 'executed';
        $this->store_agentic_session($session_id, $session_data);
        
        // Format final response
        $final_response = "🎯 **PLAN ĐÃ ĐƯỢC THỰC THI**\n\n";
        $final_response .= "**Mục tiêu:** " . (isset($plan_data['goal']) ? $plan_data['goal'] : 'Không xác định') . "\n\n";
        
        $final_response .= "**Kết quả thực thi:**\n";
        $final_response .= "- Hoàn thành: " . (isset($execution_results['steps_completed']) ? $execution_results['steps_completed'] : 0) . " bước\n";
        $final_response .= "- Thất bại: " . (isset($execution_results['steps_failed']) ? $execution_results['steps_failed'] : 0) . " bước\n\n";
        
        if (isset($execution_results['step_results']) && is_array($execution_results['step_results'])) {
            foreach ($execution_results['step_results'] as $index => $step_result) {
                $step_num = $index + 1;
                $icon = isset($step_result['success']) && $step_result['success'] ? '✅' : '❌';
                $step_action = isset($step_result['action']) ? $step_result['action'] : 'Unknown';
                
                $final_response .= "**Bước {$step_num}: {$icon} {$step_action}**\n";
                
                if (isset($step_result['skipped']) && $step_result['skipped']) {
                    $final_response .= "⏭️ Đã bỏ qua: " . (isset($step_result['error']) ? $step_result['error'] : 'Unknown reason') . "\n";
                } elseif (isset($step_result['success']) && !$step_result['success']) {
                    $final_response .= "❌ Lỗi: " . (isset($step_result['error']) ? $step_result['error'] : 'Unknown error') . "\n";
                } else {
                    $final_response .= "✅ Thành công";
                    if (isset($step_result['message'])) {
                        $final_response .= ": " . $step_result['message'];
                    }
                    $final_response .= "\n";
                    
                    // Show data if available
                    if (isset($step_result['data']) && !empty($step_result['data'])) {
                        if (is_array($step_result['data'])) {
                            $final_response .= "   Dữ liệu: " . json_encode($step_result['data'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
                        } else {
                            $final_response .= "   Dữ liệu: " . $step_result['data'] . "\n";
                        }
                    }
                }
                $final_response .= "\n";
            }
        }
        
        // Overall status
        $overall_success = isset($execution_results['overall_success']) && $execution_results['overall_success'];
        if ($overall_success) {
            $final_response .= "✅ **Tổng kết:** Plan đã được thực thi thành công!\n";
        } else {
            $final_response .= "⚠️ **Tổng kết:** Plan đã được thực thi nhưng có một số bước thất bại.\n";
        }
        
        wp_send_json_success(array(
            'step' => 'plan_executed',
            'session_id' => $session_id,
            'response' => $final_response,
            'plan' => $plan_data,
            'execution_results' => $execution_results,
            'overall_success' => $overall_success
        ));
    }
    
    /**
     * Execute agentic plan (helper function)
     */
    private function execute_agentic_plan($plan_data) {
        if (!isset($plan_data['steps']) || empty($plan_data['steps'])) {
            return array(
                'success' => false,
                'error' => 'Plan has no steps',
                'steps_completed' => 0,
                'steps_failed' => 0,
                'step_results' => array(),
                'overall_success' => false
            );
        }
        
        $results = array(
            'goal' => isset($plan_data['goal']) ? $plan_data['goal'] : 'Unknown',
            'steps_completed' => 0,
            'steps_failed' => 0,
            'step_results' => array(),
            'overall_success' => true
        );
        
        // Execute steps in order
        foreach ($plan_data['steps'] as $index => $step) {
            // Check dependencies
            if (isset($step['depends_on']) && $step['depends_on'] !== null) {
                $dep_index = intval($step['depends_on']) - 1;
                if (isset($results['step_results'][$dep_index]) && 
                    isset($results['step_results'][$dep_index]['success']) && 
                    !$results['step_results'][$dep_index]['success']) {
                    // Dependency failed, skip this step
                    $results['step_results'][$index] = array(
                        'step' => isset($step['step']) ? $step['step'] : ($index + 1),
                        'action' => isset($step['action']) ? $step['action'] : 'Unknown',
                        'success' => false,
                        'error' => 'Skipped due to failed dependency (step ' . $step['depends_on'] . ')',
                        'skipped' => true
                    );
                    $results['steps_failed']++;
                    continue;
                }
            }
            
            // Execute step
            $step_result = $this->execute_agentic_step($step);
            
            // Store result
            $results['step_results'][$index] = array_merge($step_result, array(
                'step' => isset($step['step']) ? $step['step'] : ($index + 1),
                'action' => isset($step['action']) ? $step['action'] : 'Unknown',
                'description' => isset($step['description']) ? $step['description'] : ''
            ));
            
            if (isset($step_result['success']) && $step_result['success']) {
                $results['steps_completed']++;
            } else {
                $results['steps_failed']++;
                $results['overall_success'] = false;
                
                // If a critical step fails, stop execution
                if (isset($step['critical']) && $step['critical'] === true) {
                    $results['stopped_at'] = isset($step['step']) ? $step['step'] : ($index + 1);
                    break;
                }
            }
            
            // Small delay between steps to avoid rate limiting
            usleep(100000); // 0.1 second
        }
        
        return $results;
    }
    
    /**
     * Execute a single agentic step
     */
    private function execute_agentic_step($step) {
        if (!isset($step['action'])) {
            return array('success' => false, 'error' => 'Step missing action');
        }
        
        $tool_name = $step['action'];
        $args = isset($step['args']) ? $step['args'] : array();
        
        // Use existing tool executor
        if (!class_exists('AIautotool_Agent_Tools')) {
            return array('success' => false, 'error' => 'Agent Tools not available');
        }
        
        $result = AIautotool_Agent_Tools::execute_tool($tool_name, $args);
        
        return $result;
    }
    
    /**
     * Store agentic session data
     */
    private function store_agentic_session($session_id, $data) {
        $transient_key = 'agentic_session_' . $session_id;
        set_transient($transient_key, $data, HOUR_IN_SECONDS);
    }
    
    /**
     * Get agentic session data
     */
    private function get_agentic_session($session_id) {
        $transient_key = 'agentic_session_' . $session_id;
        return get_transient($transient_key);
    }
    
    /**
     * Generate plan using AI
     */
    private function generate_agentic_plan($query) {
        // Get site context
        $context = $this->get_site_context();
        
        // Get available tools with their parameters
        $available_tools = array();
        if (class_exists('AIautotool_Agent_Tools')) {
            $tools_definitions = AIautotool_Agent_Tools::get_tools_definitions();
            foreach ($tools_definitions as $tool) {
                if (isset($tool['function'])) {
                    $available_tools[] = array(
                        'name' => $tool['function']['name'],
                        'description' => $tool['function']['description'],
                        'parameters' => isset($tool['function']['parameters']) ? $tool['function']['parameters'] : array()
                    );
                }
            }
        }
        
        // Build intelligent prompt - Focus on INTENT DETECTION, not keyword matching
        $prompt = "Bạn là AI Assistant thông minh. NHIỆM VỤ: PHÂN TÍCH INTENT của user để quyết định có cần tool không.\n\n";
        $prompt .= "Câu hỏi của user: \"{$query}\"\n\n";
        
        $prompt .= "🚨 CRITICAL: PHÂN TÍCH SEMANTIC INTENT, KHÔNG PHẢI KEYWORD MATCHING!\n\n";
        
        $prompt .= "BƯỚC 1 - IDENTIFY PRIMARY ACTION VERB:\n";
        $prompt .= "- CREATE: 'tạo', 'viết', 'create', 'write', 'soạn', 'làm bài', 'viết post'\n";
        $prompt .= "- DELETE: 'xóa', 'xoá', 'delete', 'remove'\n";
        $prompt .= "- READ/QUERY: 'có bao nhiêu', 'liệt kê', 'danh sách', 'xem', 'thông tin'\n";
        $prompt .= "- UPDATE: 'sửa', 'cập nhật', 'edit', 'update'\n";
        $prompt .= "- GREETING: 'chào', 'hello', 'hi', 'này bạn', 'hey'\n";
        $prompt .= "- QUESTION: 'bạn là ai', 'có thể làm gì', 'làm thế nào'\n\n";
        
        $prompt .= "BƯỚC 2 - DECIDE: CẦN TOOL HAY KHÔNG?\n\n";
        
        $prompt .= "🔴 KHÔNG CẦN TOOL (needs_tools = false) CHỈ KHI:\n";
        $prompt .= "- Chào hỏi đơn giản: 'này bạn', 'xin chào', 'hello', 'hi', 'chào'\n";
        $prompt .= "- Hỏi về bot: 'bạn là ai?', 'bạn có thể làm gì?', 'tôi có thể hỏi gì?'\n";
        $prompt .= "- Câu ngắn: 'này', 'bạn', 'ok', 'cảm ơn'\n";
        $prompt .= "- Hỏi hướng dẫn chung: 'làm thế nào?', 'hướng dẫn', 'help'\n\n";
        
        $prompt .= "🟢 CẦN TOOL (needs_tools = true) KHI CÓ ACTION VERB:\n";
        $prompt .= "- CREATE: 'viết post đặt tên con', 'tạo bài viết: WordPress', 'viết bài về AI'\n";
        $prompt .= "- DELETE: 'xóa bài 123', 'xóa tất cả bài nháp'\n";
        $prompt .= "- READ/QUERY: 'có bao nhiêu bài viết?', 'liệt kê users', 'danh sách categories'\n";
        $prompt .= "- UPDATE: 'sửa bài 123', 'cập nhật title'\n";
        $prompt .= "- SYSTEM INFO: 'thông tin website', 'phiên bản WordPress'\n\n";
        
        $prompt .= "📝 VÍ DỤ PHÂN TÍCH CHÍNH XÁC:\n";
        $prompt .= "Query: 'viết post đặt tên con'\n";
        $prompt .= "→ Intent: CREATE (verb 'viết post') → needs_tools = TRUE\n";
        $prompt .= "→ Steps: [{\"step\": 1, \"action\": \"create_post\", \"args\": {\"keyword\": \"đặt tên con\"}, \"description\": \"Tạo bài viết về đặt tên con\"}]\n\n";
        
        $prompt .= "Query: 'tạo bài viết: WordPress SEO'\n";
        $prompt .= "→ Intent: CREATE (verb 'tạo bài viết') → needs_tools = TRUE\n";
        $prompt .= "→ Steps: [{\"step\": 1, \"action\": \"create_post\", \"args\": {\"keyword\": \"WordPress SEO\"}, \"description\": \"Tạo bài viết về WordPress SEO\"}]\n\n";
        
        $prompt .= "Query: 'có bao nhiêu bài viết?'\n";
        $prompt .= "→ Intent: READ/QUERY (verb 'có bao nhiêu') → needs_tools = TRUE\n";
        $prompt .= "→ Steps: [{\"step\": 1, \"action\": \"query_database\", \"args\": {\"query_type\": \"posts\"}, \"description\": \"Truy vấn số lượng bài viết\"}]\n\n";
        
        $prompt .= "Query: 'này bạn'\n";
        $prompt .= "→ Intent: GREETING → needs_tools = FALSE, steps = []\n\n";
        
        $prompt .= "Query: 'bạn là ai?'\n";
        $prompt .= "→ Intent: QUESTION about bot → needs_tools = FALSE, steps = []\n\n";
        
        $prompt .= "CÁC TOOLS CÓ SẴN:\n";
        foreach ($available_tools as $tool) {
            $prompt .= "- {$tool['name']}: {$tool['description']}\n";
            if (!empty($tool['parameters']['properties'])) {
                foreach ($tool['parameters']['properties'] as $param_name => $param_info) {
                    $required = isset($tool['parameters']['required']) && in_array($param_name, $tool['parameters']['required']) ? ' (bắt buộc)' : ' (tùy chọn)';
                    $prompt .= "  + {$param_name}{$required}: {$param_info['description']}\n";
                }
            }
            $prompt .= "\n";
        }
        
        $prompt .= "TRẢ LỜI (BẮT BUỘC JSON FORMAT):\n";
        $prompt .= "Phân tích query \"{$query}\" và trả về JSON:\n";
        $prompt .= "{\n";
        $prompt .= "  \"analysis\": \"Phân tích ngắn gọn: intent là gì (CREATE/DELETE/READ/GREETING)? Tại sao cần/không cần tool?\",\n";
        $prompt .= "  \"needs_tools\": true/false,\n";
        $prompt .= "  \"tools_needed\": [\"tool_name\"],\n";
        $prompt .= "  \"steps\": [{\"step\": 1, \"action\": \"tool_name\", \"args\": {...}, \"description\": \"Mô tả bước\"}],\n";
        $prompt .= "  \"estimated_time\": \"1-2 phút\",\n";
        $prompt .= "  \"success_criteria\": \"Mô tả kết quả mong đợi\"\n";
        $prompt .= "}\n\n";
        
        $prompt .= "⚠️ QUAN TRỌNG:\n";
        $prompt .= "1. Nếu query có ACTION VERB (tạo, viết, xóa, etc.) → needs_tools = TRUE\n";
        $prompt .= "2. Nếu query là CREATE POST → BẮT BUỘC cần tool create_post\n";
        $prompt .= "3. Nếu chỉ là greeting/question → needs_tools = FALSE\n";
        $prompt .= "4. BẮT BUỘC trả về valid JSON, không text thêm\n";
        $prompt .= "5. steps phải có format đầy đủ với action, args, description\n\n";
        
        $prompt .= "VÍ DỤ JSON OUTPUT:\n";
        $prompt .= "Query: 'viết post đặt tên con'\n";
        $prompt .= "{\n";
        $prompt .= "  \"analysis\": \"Intent: CREATE POST. User muốn tạo bài viết về 'đặt tên con'. Cần tool create_post.\",\n";
        $prompt .= "  \"needs_tools\": true,\n";
        $prompt .= "  \"tools_needed\": [\"create_post\"],\n";
        $prompt .= "  \"steps\": [{\"step\": 1, \"action\": \"create_post\", \"args\": {\"keyword\": \"đặt tên con\", \"status\": \"draft\"}, \"description\": \"Tạo bài viết về đặt tên con\"}],\n";
        $prompt .= "  \"estimated_time\": \"2-3 phút\",\n";
        $prompt .= "  \"success_criteria\": \"Bài viết được tạo thành công với keyword 'đặt tên con'\"\n";
        $prompt .= "}\n";
        
        // Call AI
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.7,
            'max_tokens' => 2000
        ));
        
        if ($ai_response['success']) {
            // Try to extract JSON from response (handle markdown code blocks)
            $content = trim($ai_response['content']);
            
            // Remove markdown code blocks if present
            $content = preg_replace('/```json\s*/i', '', $content);
            $content = preg_replace('/```\s*$/m', '', $content);
            
            // Try to find JSON object
            $json_start = strpos($content, '{');
            $json_end = strrpos($content, '}');
            
            if ($json_start !== false && $json_end !== false && $json_end > $json_start) {
                $json_str = substr($content, $json_start, $json_end - $json_start + 1);
                $plan_data = json_decode($json_str, true);
            } else {
                $plan_data = json_decode($content, true);
            }
            
            if (!$plan_data || !is_array($plan_data)) {
                // Parse failed - try to infer from query using simple intent detection
                
                // Simple intent detection fallback
                $query_lower = mb_strtolower($query);
                $has_create_verb = preg_match('/(tạo|viết|create|write|soạn| làm bài|viết post|viết bài)/i', $query);
                $has_action_verb = preg_match('/(xóa|xoá|delete|sửa|edit|cập nhật|update|có bao nhiêu|liệt kê|danh sách)/i', $query);
                
                if ($has_create_verb || $has_action_verb) {
                    // Likely needs tools - create basic plan
                    $plan_data = array(
                        'analysis' => 'Phân tích query: Có action verb nên cần tool. ' . ($has_create_verb ? 'Intent: CREATE POST' : 'Intent: ACTION'),
                        'needs_tools' => true,
                        'tools_needed' => $has_create_verb ? array('create_post') : array(),
                        'steps' => $has_create_verb ? array(
                            array(
                                'step' => 1,
                                'action' => 'create_post',
                                'args' => array('keyword' => trim(preg_replace('/(tạo|viết|create|write|soạn| làm bài|viết post|viết bài)[:：]?\s*/i', '', $query))),
                                'description' => 'Tạo bài viết với keyword từ query'
                            )
                        ) : array(),
                        'estimated_time' => '2-3 phút',
                        'success_criteria' => 'Hoàn thành yêu cầu của user'
                    );
                } else {
                    // Likely greeting/question
                    $plan_data = array(
                        'analysis' => 'Phân tích query: Không có action verb rõ ràng. Có thể là greeting/question.',
                        'needs_tools' => false,
                        'tools_needed' => array(),
                        'steps' => array(),
                        'estimated_time' => '1 phút',
                        'success_criteria' => 'Trả lời câu hỏi của user'
                    );
                }
            } else {
                // Ensure needs_tools is set based on AI's analysis
                if (!isset($plan_data['needs_tools'])) {
                    // Trust AI's steps - if no steps, no tools needed
                    $plan_data['needs_tools'] = !empty($plan_data['steps']) && is_array($plan_data['steps']) && count($plan_data['steps']) > 0;
                }
                // Ensure steps is array
                if (!isset($plan_data['steps']) || !is_array($plan_data['steps'])) {
                    $plan_data['steps'] = array();
                    // Re-check needs_tools based on tools_needed
                    if (isset($plan_data['tools_needed']) && !empty($plan_data['tools_needed'])) {
                        $plan_data['needs_tools'] = true;
                    } else {
                        $plan_data['needs_tools'] = false;
                    }
                }
                // Ensure tools_needed is array
                if (!isset($plan_data['tools_needed']) || !is_array($plan_data['tools_needed'])) {
                    $plan_data['tools_needed'] = array();
                }
            }
        } else {
            // AI call failed - use intent-based fallback
            
            // Simple intent detection fallback
            $query_lower = mb_strtolower($query);
            $has_create_verb = preg_match('/(tạo|viết|create|write|soạn| làm bài|viết post|viết bài)/i', $query);
            
            $plan_data = array(
                'analysis' => $has_create_verb ? 'Intent: CREATE POST. Cần tool create_post để tạo bài viết.' : 'Đang phân tích yêu cầu của bạn...',
                'needs_tools' => $has_create_verb,
                'tools_needed' => $has_create_verb ? array('create_post') : array(),
                'steps' => $has_create_verb ? array(
                    array(
                        'step' => 1,
                        'action' => 'create_post',
                        'args' => array('keyword' => trim(preg_replace('/(tạo|viết|create|write|soạn| làm bài|viết post|viết bài)[:：]?\s*/i', '', $query))),
                        'description' => 'Tạo bài viết với keyword từ query'
                    )
                ) : array(),
                'estimated_time' => $has_create_verb ? '2-3 phút' : '1 phút',
                'success_criteria' => $has_create_verb ? 'Bài viết được tạo thành công' : 'Trả lời câu hỏi của user'
            );
        }
        
        // Add debug logging
        
        return $plan_data;
    }
    
    /**
     * Reflect on execution results
     */
    private function reflect_on_results($session_data) {
        $plan_data = $session_data['plan_data'];
        $execution_results = isset($session_data['execution_results']) ? $session_data['execution_results'] : array();
        $original_query = $session_data['query'];
        $needs_tools = isset($plan_data['needs_tools']) ? (bool)$plan_data['needs_tools'] : false;
        
        // Check if this is a query that doesn't need tools
        // In this case, we should directly answer the user's question
        if (!$needs_tools || empty($execution_results)) {
            // Build prompt to directly answer user's question
            $prompt = "Bạn là trợ lý AI thông minh cho WordPress. Hãy trả lời câu hỏi của người dùng một cách thân thiện và hữu ích.\n\n";
            
            if (isset($plan_data['analysis']) && !empty($plan_data['analysis'])) {
                $prompt .= "Phân tích từ hệ thống: {$plan_data['analysis']}\n\n";
            }
            
            $prompt .= "Câu hỏi của người dùng: {$original_query}\n\n";
            
            // Get site context for better answers
            $site_context = $this->get_site_context();
            if (!empty($site_context)) {
                // Convert array to readable string format
                $site_context_str = is_array($site_context) ? print_r($site_context, true) : (string)$site_context;
                $prompt .= "THÔNG TIN WEBSITE:\n{$site_context_str}\n\n";
            }
            
            $prompt .= "Hãy trả lời câu hỏi một cách tự nhiên, thân thiện và chi tiết. Nếu là câu chào hỏi, hãy chào lại và giới thiệu khả năng của bạn.\n\n";
            $prompt .= "Trả lời theo cấu trúc JSON:\n";
            $prompt .= "{\n";
            $prompt .= "  \"result_ok\": true,\n";
            $prompt .= "  \"success_rate\": 100,\n";
            $prompt .= "  \"analysis\": \"[Câu trả lời đầy đủ và chi tiết cho người dùng]\",\n";
            $prompt .= "  \"meets_requirements\": true\n";
            $prompt .= "}";
        } else {
            // Build simple reflection prompt when tools were used
            $prompt = "Dựa vào các thông tin sau để trả lời cho câu hỏi: {$original_query}\n\n";
            
            $prompt .= "KẾT QUẢ THỰC THI:\n";
            foreach ($execution_results as $result) {
                $prompt .= "Bước {$result['step']}: {$result['action']}\n";
                if (isset($result['description'])) {
                    $prompt .= "- Mô tả: {$result['description']}\n";
                }
                $prompt .= "- Thành công: " . ($result['result']['success'] ? 'Có' : 'Không') . "\n";
                if (isset($result['result']['message'])) {
                    $prompt .= "- Thông báo: {$result['result']['message']}\n";
                }
                if (isset($result['result']['data'])) {
                    $prompt .= "- Dữ liệu: " . json_encode($result['result']['data'], JSON_UNESCAPED_UNICODE) . "\n";
                }
                if (isset($result['result']['error'])) {
                    $prompt .= "- Lỗi: {$result['result']['error']}\n";
                }
                $prompt .= "\n";
            }
            
            $prompt .= "Trả lời theo cấu trúc JSON:\n";
            $prompt .= "{\n";
            $prompt .= "  \"result_ok\": true/false,\n";
            $prompt .= "  \"success_rate\": số phần trăm (0-100),\n";
            $prompt .= "  \"analysis\": \"Trả lời câu hỏi dựa trên kết quả thực thi ở trên\",\n";
            $prompt .= "  \"meets_requirements\": true/false\n";
            $prompt .= "}";
        }
        
        // Call AI for reflection
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        // Use higher temperature for conversational responses (no tools), lower for structured results (with tools)
        $temperature = (!$needs_tools || empty($execution_results)) ? 0.7 : 0.3;
        $max_tokens = (!$needs_tools || empty($execution_results)) ? 2000 : 1500;
        
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => $temperature,
            'max_tokens' => $max_tokens
        ));
        
        if ($ai_response['success']) {
            $reflection_data = json_decode($ai_response['content'], true);
            if (!$reflection_data) {
                // Fallback reflection
                $reflection_data = $this->create_fallback_reflection($execution_results, $original_query, $needs_tools);
            }
        } else {
            // Fallback reflection
            $reflection_data = $this->create_fallback_reflection($execution_results, $original_query, $needs_tools);
        }
        
        // Add debug logging
        
        return $reflection_data;
    }
    
    /**
     * Create fallback reflection when AI fails
     */
    private function create_fallback_reflection($execution_results = array(), $original_query = '', $needs_tools = false) {
        // If no tools were needed, provide a simple fallback response
        if (!$needs_tools || empty($execution_results)) {
            // Use AI to generate intelligent fallback response instead of pattern matching
            $analysis = 'Xin chào! Tôi là trợ lý AI của bạn. ';
            if (!empty($original_query)) {
                // Ask AI to generate a helpful response based on the query context
                $fallback_prompt = "Bạn là trợ lý AI thông minh cho WordPress. Người dùng đã gửi câu hỏi/yêu cầu sau:\n\n";
                $fallback_prompt .= "Query: {$original_query}\n\n";
                $fallback_prompt .= "Hãy phân tích intent của người dùng và trả lời một cách thân thiện, hữu ích.\n";
                $fallback_prompt .= "- Nếu là câu chào: Chào lại và giới thiệu khả năng của bạn\n";
                $fallback_prompt .= "- Nếu là yêu cầu rõ ràng: Thừa nhận yêu cầu và hỏi thêm chi tiết nếu cần\n";
                $fallback_prompt .= "- Nếu là câu hỏi: Trả lời dựa trên kiến thức của bạn\n";
                $fallback_prompt .= "- Luôn thân thiện và chuyên nghiệp\n";
                $fallback_prompt .= "- Trả lời bằng tiếng Việt nếu query là tiếng Việt, tiếng Anh nếu query là tiếng Anh\n";
                $fallback_prompt .= "Trả lời ngắn gọn (tối đa 100 từ):";
                
                // Try to get AI response for fallback
                if (class_exists('AIAutotool_AI_Helper') && AIAutotool_AI_Helper::is_available()) {
                    $fallback_result = AIAutotool_AI_Helper::generate($fallback_prompt, array(
                        'max_tokens' => 200,
                        'temperature' => 0.7
                    ));
                    
                    if ($fallback_result['success'] && !empty($fallback_result['content'])) {
                        $analysis = trim($fallback_result['content']);
                    } else {
                        // Generic fallback if AI fails
                        $analysis = 'Cảm ơn bạn đã liên hệ. Tôi đã nhận được yêu cầu của bạn. Tôi có thể giúp bạn quản lý WordPress, tạo bài viết, truy vấn dữ liệu và nhiều việc khác. Bạn muốn tôi làm gì?';
                    }
                } else {
                    // Generic fallback if AI not available
                    $analysis = 'Cảm ơn bạn đã liên hệ. Tôi đã nhận được yêu cầu của bạn. Tôi có thể giúp bạn quản lý WordPress, tạo bài viết, truy vấn dữ liệu và nhiều việc khác. Bạn muốn tôi làm gì?';
                }
            }
            
            return array(
                'result_ok' => true,
                'success_rate' => 100,
                'analysis' => $analysis,
                'meets_requirements' => true
            );
        }
        
        // Original logic for when tools were used
        $success_count = 0;
        $total_steps = count($execution_results);
        $result_messages = array();
        
        foreach ($execution_results as $result) {
            if (isset($result['result']['success']) && $result['result']['success']) {
                $success_count++;
                if (isset($result['result']['message'])) {
                    $result_messages[] = $result['result']['message'];
                }
                if (isset($result['result']['data'])) {
                    $data_str = is_array($result['result']['data']) ? json_encode($result['result']['data'], JSON_UNESCAPED_UNICODE) : (string)$result['result']['data'];
                    $result_messages[] = $data_str;
                }
            }
        }
        
        $success_rate = $total_steps > 0 ? ($success_count / $total_steps) * 100 : 0;
        $result_ok = $success_rate >= 80;
        
        // Tạo analysis từ kết quả thực tế
        $analysis = '';
        if (!empty($result_messages)) {
            $analysis = implode('. ', array_slice($result_messages, 0, 3));
        } else {
            $analysis = $result_ok ? 'Thực thi thành công' : 'Thực thi gặp lỗi';
        }
        
        return array(
            'result_ok' => $result_ok,
            'success_rate' => round($success_rate, 1),
            'analysis' => $analysis,
            'meets_requirements' => $result_ok
        );
    }
    
    /**
     * Action: Delete draft posts
     */
    private function action_delete_drafts($params) {
        // Check capability
        if (!current_user_can('delete_posts')) {
            return array(
                'message' => __('Bạn không có quyền xóa bài viết.', 'ai-auto-tool'),
                'details' => __('Quyền truy cập bị từ chối.', 'ai-auto-tool')
            );
        }
        
        $drafts = get_posts(array(
            'post_status' => 'draft',
            'post_type' => 'post',
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        $deleted = 0;
        foreach ($drafts as $post_id) {
            // Check if user can delete this specific post
            if (current_user_can('delete_post', $post_id)) {
                if (wp_delete_post($post_id, true)) {
                    $deleted++;
                }
            }
        }
        
        return array(
            'message' => sprintf(__('Successfully deleted %d draft posts! 🎉', 'ai-auto-tool'), $deleted),
            'details' => sprintf(__('✅ Action completed!\n\n📝 Deleted: %d drafts\n💾 Database cleaned\n\nYour content is now more organized!', 'ai-auto-tool'), $deleted)
        );
    }
    
    /**
     * Action: Delete old posts
     */
    private function action_delete_old_posts($params) {
        // Check capability
        if (!current_user_can('delete_posts')) {
            return array(
                'message' => __('Bạn không có quyền xóa bài viết.', 'ai-auto-tool'),
                'details' => __('Quyền truy cập bị từ chối.', 'ai-auto-tool')
            );
        }
        
        $days = isset($params['days']) ? intval($params['days']) : 365;
        
        $old_posts = get_posts(array(
            'post_status' => 'publish',
            'date_query' => array(
                array(
                    'before' => date('Y-m-d', strtotime("-{$days} days"))
                )
            ),
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        $deleted = 0;
        foreach ($old_posts as $post_id) {
            // Check if user can delete this specific post
            if (current_user_can('delete_post', $post_id)) {
                if (wp_delete_post($post_id, true)) {
                    $deleted++;
                }
            }
        }
        
        return array(
            'message' => sprintf(__('Successfully deleted %d old posts! 🎉', 'ai-auto-tool'), $deleted),
            'details' => sprintf(__('✅ Cleanup completed!\n\n🗑️ Deleted: %d posts older than %d days\n💾 Database optimized\n\nYour site is now cleaner!', 'ai-auto-tool'), $deleted, $days)
        );
    }
    
    /**
     * Action: Publish draft posts
     */
    private function action_publish_drafts($params) {
        $drafts = get_posts(array(
            'post_status' => 'draft',
            'post_type' => 'post',
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        $published = 0;
        foreach ($drafts as $post_id) {
            $result = wp_update_post(array(
                'ID' => $post_id,
                'post_status' => 'publish'
            ));
            if ($result && !is_wp_error($result)) {
                $published++;
            }
        }
        
        return array(
            'message' => sprintf(__('Successfully published %d posts! 🎉', 'ai-auto-tool'), $published),
            'details' => sprintf(__('✅ Publishing completed!\n\n📝 Published: %d posts\n🌐 Now live on your site\n\nGreat job keeping your content active!', 'ai-auto-tool'), $published)
        );
    }
    
    /**
     * Action: Add alt text to images using AI
     */
    private function action_add_alt_text($params) {
        global $wpdb;
        
        // Get images without alt text
        $images = $wpdb->get_results("
            SELECT ID 
            FROM {$wpdb->posts} 
            WHERE post_type = 'attachment' 
            AND post_mime_type LIKE 'image%'
            AND ID NOT IN (
                SELECT post_id 
                FROM {$wpdb->postmeta} 
                WHERE meta_key = '_wp_attachment_image_alt' 
                AND meta_value != ''
            )
            LIMIT 50
        ");
        
        $updated = 0;
        foreach ($images as $image) {
            // For now, generate simple alt text
            // TODO: Integrate with AI for better alt text
            $post = get_post($image->ID);
            $alt_text = $post->post_title;
            
            update_post_meta($image->ID, '_wp_attachment_image_alt', $alt_text);
            $updated++;
        }
        
        return array(
            'message' => sprintf(__('Successfully added alt text to %d images! 🎉', 'ai-auto-tool'), $updated),
            'details' => sprintf(__('✅ Alt text optimization completed!\n\n🖼️ Updated: %d images\n📈 SEO improved\n🎯 Better accessibility\n\nYour images are now optimized!', 'ai-auto-tool'), $updated)
        );
    }
    
    /**
     * Action: Fix broken images
     */
    private function action_fix_broken_images($params) {
        // This would integrate with scan tool
        // For now, return success message
        
        return array(
            'message' => __('Broken images scan initiated! 🔍', 'ai-auto-tool'),
            'details' => __('✅ Image scanner started!\n\n🔍 Scanning all posts for broken images\n🔧 Removing invalid image references\n\nThis may take a few minutes...', 'ai-auto-tool')
        );
    }
    
    /**
     * Action: Manage users
     */
    private function action_manage_users($params) {
        $action = isset($params['action']) ? $params['action'] : '';
        
        switch ($action) {
            case 'create':
                return $this->action_create_user($params);
            
            case 'delete':
                return $this->action_delete_user($params);
            
            case 'update':
                return $this->action_update_user($params);
            
            default:
                return new WP_Error('invalid_action', __('Invalid user action', 'ai-auto-tool'));
        }
    }
    
    /**
     * Action: Create user
     */
    private function action_create_user($params) {
        $username = isset($params['username']) ? sanitize_user($params['username']) : '';
        $email = isset($params['email']) ? sanitize_email($params['email']) : '';
        $role = isset($params['role']) ? sanitize_text_field($params['role']) : 'subscriber';
        
        // Validate required fields
        if (empty($username)) {
            return new WP_Error('missing_username', __('Username is required', 'ai-auto-tool'));
        }
        
        if (empty($email) || !is_email($email)) {
            return new WP_Error('invalid_email', __('Valid email is required', 'ai-auto-tool'));
        }
        
        // Check if user already exists
        if (username_exists($username)) {
            return new WP_Error('user_exists', sprintf(__('User "%s" already exists', 'ai-auto-tool'), $username));
        }
        
        if (email_exists($email)) {
            return new WP_Error('email_exists', sprintf(__('Email "%s" already exists', 'ai-auto-tool'), $email));
        }
        
        // Generate random password
        $password = wp_generate_password(12, false);
        
        // Create user
        $user_id = wp_create_user($username, $password, $email);
        
        if (is_wp_error($user_id)) {
            return $user_id;
        }
        
        // Set role if not default
        if ($role !== 'subscriber') {
            $user = new WP_User($user_id);
            $user->set_role($role);
        }
        
        // Prepare user info
        $user_info = get_userdata($user_id);
        
        return array(
            'message' => sprintf(__('Successfully created user "%s"! 🎉', 'ai-auto-tool'), $username),
            'details' => sprintf(__('✅ User created successfully!\n\n👤 Username: %s\n📧 Email: %s\n🔐 Role: %s\n🆔 User ID: %d\n🔑 Password: %s\n\n📝 Login info:\n🔗 %s\n\nUser can login immediately with this password!', 'ai-auto-tool'), 
                $username, $email, $role, $user_id, $password, wp_login_url()),
            'user_data' => array(
                'username' => $username,
                'email' => $email,
                'password' => $password,
                'user_id' => $user_id,
                'role' => $role
            )
        );
    }
    
    /**
     * Action: Delete user
     */
    private function action_delete_user($params) {
        // Check capability
        if (!current_user_can('delete_users')) {
            return new WP_Error('permission_denied', __('Bạn không có quyền xóa người dùng.', 'ai-auto-tool'));
        }
        
        $user_id = isset($params['user_id']) ? intval($params['user_id']) : 0;
        $username = isset($params['username']) ? sanitize_user($params['username']) : '';
        
        // If username provided, get user_id from username
        if (empty($user_id) && !empty($username)) {
            $found_user = get_user_by('login', $username);
            if ($found_user) {
                $user_id = $found_user->ID;
            }
        }
        
        if (empty($user_id)) {
            return new WP_Error('missing_user_id', __('User ID or Username is required', 'ai-auto-tool'));
        }
        
        $user = get_userdata($user_id);
        if (!$user) {
            return new WP_Error('user_not_found', __('User not found', 'ai-auto-tool'));
        }
        
        // Prevent deleting yourself
        if ($user_id == get_current_user_id()) {
            return new WP_Error('cannot_delete_self', __('Bạn không thể xóa chính mình.', 'ai-auto-tool'));
        }
        
        // Delete user (reassign posts to current user)
        require_once(ABSPATH.'wp-admin/includes/user.php');
        $result = wp_delete_user($user_id, get_current_user_id());
        
        if ($result) {
            return array(
                'message' => sprintf(__('Successfully deleted user "%s"! 🗑️', 'ai-auto-tool'), $user->user_login),
                'details' => sprintf(__('✅ User deleted successfully!\n\n🗑️ Username: %s\n💾 Posts reassigned\n\nUser has been removed from the system.', 'ai-auto-tool'), $user->user_login)
            );
        } else {
            return new WP_Error('delete_failed', __('Failed to delete user', 'ai-auto-tool'));
        }
    }
    
    /**
     * Action: Update user
     */
    private function action_update_user($params) {
        // Check capability
        if (!current_user_can('edit_users')) {
            return new WP_Error('permission_denied', __('Bạn không có quyền chỉnh sửa người dùng.', 'ai-auto-tool'));
        }
        
        $user_id = isset($params['user_id']) ? intval($params['user_id']) : 0;
        $username = isset($params['username']) ? sanitize_user($params['username']) : '';
        
        // If username provided, get user_id from username
        if (empty($user_id) && !empty($username)) {
            $found_user = get_user_by('login', $username);
            if ($found_user) {
                $user_id = $found_user->ID;
            }
        }
        
        if (empty($user_id)) {
            return new WP_Error('missing_user_id', __('User ID or Username is required', 'ai-auto-tool'));
        }
        
        $user = get_userdata($user_id);
        if (!$user) {
            return new WP_Error('user_not_found', __('User not found', 'ai-auto-tool'));
        }
        
        // Prepare update data
        $user_data = array('ID' => $user_id);
        
        if (isset($params['email'])) {
            $user_data['user_email'] = sanitize_email($params['email']);
        }
        
        if (isset($params['role'])) {
            $user->set_role(sanitize_text_field($params['role']));
        }
        
        $result = wp_update_user($user_data);
        
        if (is_wp_error($result)) {
            return $result;
        }
        
        return array(
            'message' => sprintf(__('Successfully updated user! ✅', 'ai-auto-tool')),
            'details' => __('✅ User updated successfully!\n\nProfile information has been changed.\n\nUser details updated.', 'ai-auto-tool')
        );
    }
    
    /**
     * Render settings (main content in settings page)
     */
    public function render_setting() {
        ?>
        <div id="tab-<?php echo esc_attr($this->active_option_name); ?>-setting" class="tab-content" style="display:none;">
            <h2>
                <?php echo $this->icon; ?> 
                <?php echo esc_html($this->name_plan); ?>
            </h2>
            
            <div class="aiautotool-content-wrapper">
                <div class="aiautotool-feature-intro">
                    <div class="feature-hero">
                        <div class="hero-icon">🤖</div>
                        <h3><?php _e('AI Bot Assistant - Your Intelligent Site Manager', 'ai-auto-tool'); ?></h3>
                        <p class="hero-description">
                            <?php _e('A powerful AI assistant that monitors your entire website, provides real-time insights, smart alerts, and helps you manage content efficiently with natural language interface.', 'ai-auto-tool'); ?>
                        </p>
                    </div>
                    
                    <div class="feature-activation">
                        <div class="activation-toggle">
                            <label class="switch">
                                <input type="checkbox" 
                                       id="<?php echo esc_attr($this->active_option_name); ?>" 
                                       name="<?php echo esc_attr($this->active_option_name); ?>" 
                                       value="true" 
                                       class="js-switch" 
                                       data-option="<?php echo esc_attr($this->active_option_name); ?>"
                                       <?php checked($this->active, 'true'); ?>>
                                <span class="slider round"></span>
                            </label>
                            <span class="activation-label">
                                <?php if ($this->active == 'true'): ?>
                                    <span class="status-active">✅ <?php _e('Active', 'ai-auto-tool'); ?></span>
                                <?php // else: ?>
                                    <span class="status-inactive">⭕ <?php _e('Inactive', 'ai-auto-tool'); ?></span>
                                <?php endif; ?>
                            </span>
                        </div>
                        
                        <?php if ($this->active == 'true'): ?>
                        <div class="activation-actions">
                            <a href="<?php echo admin_url('admin.php?page=aiautotool-bot-assistant'); ?>" 
                               class="button button-primary button-hero">
                                <span class="dashicons dashicons-admin-generic"></span>
                                <?php _e('Open AI Assistant Dashboard', 'ai-auto-tool'); ?>
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="aiautotool-feature-details">
                    <div class="feature-grid">
                        <div class="feature-box">
                            <div class="feature-box-icon">💬</div>
                            <h4><?php _e('Natural Language Chat', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Ask questions about your site in plain language. "How many posts do I have?", "Show me broken images", etc.', 'ai-auto-tool'); ?></p>
                        </div>
                        
                        <div class="feature-box">
                            <div class="feature-box-icon">📊</div>
                            <h4><?php _e('Real-time Analytics', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Get instant statistics about posts, images, comments, and AI tools performance.', 'ai-auto-tool'); ?></p>
                        </div>
                        
                        <div class="feature-box">
                            <div class="feature-box-icon">⚠️</div>
                            <h4><?php _e('Smart Alerts', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Automatic detection of broken images, missing alt text, pending comments, and security issues.', 'ai-auto-tool'); ?></p>
                        </div>
                        
                        <div class="feature-box">
                            <div class="feature-box-icon">🎯</div>
                            <h4><?php _e('AI Tools Monitoring', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Track all active AI tools in one dashboard. See what\'s working and get recommendations.', 'ai-auto-tool'); ?></p>
                        </div>
                        
                        <div class="feature-box">
                            <div class="feature-box-icon">💡</div>
                            <h4><?php _e('Intelligent Suggestions', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Get smart recommendations based on your site patterns and performance data.', 'ai-auto-tool'); ?></p>
                        </div>
                        
                        <div class="feature-box">
                            <div class="feature-box-icon">🔍</div>
                            <h4><?php _e('Semantic Search', 'ai-auto-tool'); ?></h4>
                            <p><?php _e('Search your content intelligently. Find posts, images, and data with natural language queries.', 'ai-auto-tool'); ?></p>
                        </div>
                    </div>
                </div>
                
                <?php if ($this->active == 'true'): ?>
                <div class="aiautotool-ai-settings">
                    <h3>🤖 <?php _e('AI-Powered Response Settings', 'ai-auto-tool'); ?></h3>
                    <p class="description">
                        <?php _e('Enable AI-powered responses for more intelligent and context-aware answers. The bot will use your configured AI provider to provide accurate responses based on your site data.', 'ai-auto-tool'); ?>
                    </p>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php _e('Enable AI Mode', 'ai-auto-tool'); ?></th>
                            <td>
                                <label class="switch">
                                    <input type="checkbox" 
                                           id="aiautotool_bot_assistant_use_ai" 
                                           name="aiautotool_bot_assistant_use_ai" 
                                           value="1" 
                                           <?php checked(get_option('aiautotool_bot_assistant_use_ai', true), true); ?>>
                                    <span class="slider round"></span>
                                </label>
                                <p class="description">
                                    <?php _e('When enabled, the bot will use AI to generate intelligent responses. When disabled, it will use pattern matching (faster but less flexible).', 'ai-auto-tool'); ?>
                                </p>
                            </td>
                        </tr>
                        
                        <tr>
                            <th scope="row"><?php _e('AI Provider & Model', 'ai-auto-tool'); ?></th>
                            <td>
                                <?php
                                // Get current AI info
                                if (class_exists('AIAutotool_AI_Helper') && AIAutotool_AI_Helper::is_available()) {
                                    $ai_info = AIAutotool_AI_Helper::get_active_info();
                                    if ($ai_info) {
                                        echo '<div class="notice notice-success inline" style="padding: 10px; margin: 0 0 10px 0;">';
                                        echo '<p style="margin: 0;"><strong>✅ ' . esc_html__('Active:', 'ai-auto-tool') . '</strong> ';
                                        echo esc_html($ai_info['provider_name']) . ' - ' . esc_html($ai_info['model']);
                                        echo '</p></div>';
                                    }
                                } else {
                                    echo '<div class="notice notice-warning inline" style="padding: 10px; margin: 0 0 10px 0;">';
                                    echo '<p style="margin: 0;"><strong>⚠️ ' . esc_html__('No AI provider configured', 'ai-auto-tool') . '</strong></p>';
                                    echo '</div>';
                                }
                                ?>
                                <p>
                                    <a href="<?php echo admin_url('admin.php?page=aiautotool-integrations'); ?>" class="button button-secondary">
                                        ⚙️ <?php _e('Configure AI Provider & Model', 'ai-auto-tool'); ?>
                                    </a>
                                </p>
                                <p class="description">
                                    <?php _e('Go to Advanced Settings below to configure which AI provider (OpenAI, Gemini, LLM7) and model to use.', 'ai-auto-tool'); ?>
                                    <br>
                                    <?php _e('Make sure you have configured API keys in the API Keys Manager tab.', 'ai-auto-tool'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <button type="button" id="save_ai_mode_only" class="button button-primary">
                            <?php _e('Save AI Mode Setting', 'ai-auto-tool'); ?>
                        </button>
                        <span class="spinner" style="float: none; margin: 0 10px;"></span>
                        <span class="save-message"></span>
                    </p>
                    
                    <script>
                    jQuery(document).ready(function($) {
                        $('#save_ai_mode_only').on('click', function() {
                            var $button = $(this);
                            var $spinner = $button.next('.spinner');
                            var $message = $('.save-message');
                            
                            $button.prop('disabled', true);
                            $spinner.addClass('is-active');
                            $message.text('');
                            
                            $.ajax({
                                url: ajaxurl,
                                type: 'POST',
                                data: {
                                    action: 'save_bot_assistant_ai_settings',
                                    nonce: '<?php echo wp_create_nonce('bot_assistant_ai_settings'); ?>',
                                    use_ai: $('#aiautotool_bot_assistant_use_ai').is(':checked') ? 1 : 0,
                                    provider: 'auto', // Let AI Helper auto-select
                                    model: 'auto'
                                },
                                success: function(response) {
                                    $spinner.removeClass('is-active');
                                    $button.prop('disabled', false);
                                    if (response.success) {
                                        $message.html('<span style="color: green;">✓ <?php _e('Settings saved successfully!', 'ai-auto-tool'); ?></span>');
                                    } else {
                                        $message.html('<span style="color: red;">✗ ' + response.data.message + '</span>');
                                    }
                                    setTimeout(function() {
                                        $message.text('');
                                    }, 3000);
                                },
                                error: function() {
                                    $spinner.removeClass('is-active');
                                    $button.prop('disabled', false);
                                    $message.html('<span style="color: red;">✗ <?php _e('Error saving settings', 'ai-auto-tool'); ?></span>');
                                }
                            });
                        });
                    });
                    </script>
                </div>
                <?php endif; ?>
                
                <div class="aiautotool-feature-info">
                    <div class="info-section">
                        <h4>🚀 <?php _e('Quick Start Guide', 'ai-auto-tool'); ?></h4>
                        <ol class="quick-start-steps">
                            <li><?php _e('Activate the AI Bot Assistant using the toggle above', 'ai-auto-tool'); ?></li>
                            <li><?php _e('Click "Open AI Assistant Dashboard" to access the chat interface', 'ai-auto-tool'); ?></li>
                            <li><?php _e('Start asking questions or use Quick Actions for instant insights', 'ai-auto-tool'); ?></li>
                            <li><?php _e('Check the Dashboard Widget for quick stats and alerts', 'ai-auto-tool'); ?></li>
                        </ol>
                    </div>
                    
                    <div class="info-section">
                        <h4>💡 <?php _e('Example Questions', 'ai-auto-tool'); ?></h4>
                        <div class="example-queries">
                            <div class="query-group">
                                <strong><?php _e('Content:', 'ai-auto-tool'); ?></strong>
                                <ul>
                                    <li>"How many posts do I have?"</li>
                                    <li>"Show me latest posts"</li>
                                    <li>"Search for posts about WordPress"</li>
                                </ul>
                            </div>
                            <div class="query-group">
                                <strong><?php _e('Health:', 'ai-auto-tool'); ?></strong>
                                <ul>
                                    <li>"Are there any alerts?"</li>
                                    <li>"Show me broken images"</li>
                                    <li>"Which images need alt text?"</li>
                                </ul>
                            </div>
                            <div class="query-group">
                                <strong><?php _e('Insights:', 'ai-auto-tool'); ?></strong>
                                <ul>
                                    <li>"Give me some suggestions"</li>
                                    <li>"Show AI tools status"</li>
                                    <li>"What should I improve?"</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="info-section info-note">
                        <p>
                            <span class="dashicons dashicons-info"></span>
                            <strong><?php _e('Note:', 'ai-auto-tool'); ?></strong>
                            <?php _e('The AI Bot Assistant learns from your site patterns to provide better suggestions over time. It also appears as a widget on your WordPress Dashboard for quick access.', 'ai-auto-tool'); ?>
                        </p>
                    </div>
                </div>
                
                <?php if ($this->active == 'true'): ?>
                <div class="aiautotool-current-status">
                    <h4>📈 <?php _e('Current Status', 'ai-auto-tool'); ?></h4>
                    <?php
                    $stats = $this->get_site_statistics();
                    $alerts = $this->get_site_alerts();
                    $tools = $this->get_active_tools();
                    ?>
                    <div class="status-grid">
                        <div class="status-item">
                            <div class="status-number"><?php echo number_format($stats['total_posts']); ?></div>
                            <div class="status-label"><?php _e('Total Posts', 'ai-auto-tool'); ?></div>
                        </div>
                        <div class="status-item">
                            <div class="status-number"><?php echo number_format($stats['total_images']); ?></div>
                            <div class="status-label"><?php _e('Total Images', 'ai-auto-tool'); ?></div>
                        </div>
                        <div class="status-item">
                            <div class="status-number"><?php echo count($alerts); ?></div>
                            <div class="status-label"><?php _e('Active Alerts', 'ai-auto-tool'); ?></div>
                        </div>
                        <div class="status-item">
                            <div class="status-number"><?php echo count($tools); ?></div>
                            <div class="status-label"><?php _e('AI Tools Active', 'ai-auto-tool'); ?></div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if ($this->active == 'true'): ?>
                <?php
                    // Render advanced settings section from separate file
                    if (function_exists('render_advanced_settings_section')) {
                        render_advanced_settings_section();
                    }
                ?>
                <?php endif; ?>
            </div>
        </div>
        
        <style>
        
        </style>
        <?php
    }
    
    /**
     * Render settings tab button (for main settings page)
     */
    public function render_tab_setting() {
        if ($this->active == 'true') {
            echo '<button href="#tab-' . esc_attr($this->active_option_name) . '-setting" class="nav-tab sotab">';
            echo $this->icon . ' ';
            echo esc_html__('AI Bot Assistant', 'ai-auto-tool');
            echo '</button>';
        }
    }
    
    /**
     * Render feature item (for features list page)
     */
    public function render_feature() {
        // Load feature descriptions
        require_once plugin_dir_path(dirname(dirname(__FILE__))) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            $this->icon . ' ' . $this->name_plan,
            AiAutoTool_Feature_Descriptions::get('bot_assistant'),
            'https://doc.aiautotool.com/features/ai-bot-assistant',
            $this->active_option_name,
            $this->active,
            defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)
        );
        
        echo $autoToolBox->generateHTML();
    }
    
    /**
     * 🆕 Detect if query should use Planner (multi-step tasks)
     */
    /**
     * Should auto-execute based on AI intent analysis (not hardcoded)
     */
    /**
     * 🔥 DISABLED: Keyword-based auto-execute detection
     * Đã tắt để tránh false positives với đa ngôn ngữ
     * Để AI tự quyết định khi nào cần auto-execute dựa trên context
     */
    private function should_auto_execute($query) {
        // Không dùng keyword matching nữa - để AI tự quyết định
        return false;
    }
    
    /**
     * 🔥 DISABLED: Keyword-based planner detection  
     * Đã tắt để tránh false positives với đa ngôn ngữ
     * Chỉ dùng planner khi user explicitly request hoặc AI suggest
     */
    private function should_use_planner($query) {
        // Không dùng keyword matching nữa - để AI tự quyết định
        return false;
    }
    
    /**
     * 🆕 Handle query with AI Planner
     */
    private function handle_with_planner($query, $history) {
        // Get full context - use Context Collector if available
        if (class_exists('AIautotool_Context_Collector')) {
            $context = AIautotool_Context_Collector::get_full_context();
        } else {
            // Fallback: Get context and normalize structure
            $old_context = $this->get_site_context();
            $context = array(
                'site' => array(
                    'name' => isset($old_context['site_name']) ? $old_context['site_name'] : get_bloginfo('name')
                ),
                'posts' => isset($old_context['posts']) ? $old_context['posts'] : array(
                    'total_published' => wp_count_posts()->publish,
                    'total_drafts' => wp_count_posts()->draft
                ),
                'images' => isset($old_context['images']) ? $old_context['images'] : array('total' => 0),
                'plugins' => isset($old_context['plugins']) ? $old_context['plugins'] : array('active' => array()),
                'current_date' => current_time('Y-m-d H:i:s')
            );
        }
        
        // Create execution plan with error handling
        try {
            $plan_result = AIautotool_Agent_Planner::create_plan($query, $context);
        } catch (Exception $e) {
            // Log error and fallback
            $plan_result = array('success' => false, 'error' => $e->getMessage());
        }
        
        if (!$plan_result['success']) {
            // Fallback to regular AI if planner fails
            
            $ai_response = $this->query_with_ai($query, $history);
            
            if (is_wp_error($ai_response)) {
                $ai_response = "I encountered an error. Please try again or rephrase your question.";
            }
            
            $parsed_response = $this->parse_ai_response($ai_response);
            
            wp_send_json_success(array(
                'response' => $parsed_response['response'],
                'intent' => $parsed_response['intent'],
                'source' => 'ai_fallback',
                'debug' => array(
                    'planner_error' => $plan_result['error'],
                    'fallback' => true
                )
            ));
            return;
        }
        
        $plan = $plan_result['plan'];
        
        // Format plan for display
        $plan_display = $this->format_execution_plan($plan);
        
        // Return plan with execution option
        wp_send_json_success(array(
            'response' => $plan_display,
            'intent' => 'execution_plan',
            'source' => 'planner',
            'plan' => $plan,
            'show_execute_button' => true,
            'debug' => array(
                'mode' => 'AI Planner (Cursor-style)',
                'steps_count' => count($plan['steps']),
                'estimated_time' => $plan['estimated_time']
            )
        ));
    }
    
    /**
     * 🆕 Format execution plan for chat display
     */
    private function format_execution_plan($plan) {
        $output = "🎯 **EXECUTION PLAN**\n\n";
        $output .= "**Goal:** {$plan['goal']}\n";
        $output .= "**Estimated Time:** {$plan['estimated_time']}\n\n";
        
        if (!empty($plan['risks'])) {
            $output .= "⚠️ **Potential Risks:**\n";
            foreach ($plan['risks'] as $risk) {
                $output .= "  • {$risk}\n";
            }
            $output .= "\n";
        }
        
        $output .= "📋 **Steps to Execute:**\n\n";
        foreach ($plan['steps'] as $index => $step) {
            $step_num = $index + 1;
            $icon = $this->get_step_icon($step['action']);
            
            $output .= "**{$step_num}. {$icon} {$step['action']}**\n";
            $output .= "   {$step['description']}\n";
            
            if (!empty($step['args'])) {
                $output .= "   `Args: " . json_encode($step['args']) . "`\n";
            }
            
            if ($step['depends_on'] !== null) {
                $output .= "   ⚡ *Depends on step {$step['depends_on']}*\n";
            }
            
            $output .= "\n";
        }
        
        $output .= "---\n\n";
        $output .= "💡 Click **Execute Plan** to run all steps automatically.\n";
        $output .= "Or you can execute steps manually one by one.";
        
        return $output;
    }
    
    /**
     * 🆕 Get icon for tool/action
     */
    private function get_step_icon($action) {
        $icons = array(
            'create_post' => '📝',
            'delete_post' => '🗑️',
            'seo_audit' => '🔍',
            'system_info' => '💻',
            'check_system_health' => '🏥',
            'cleanup_database' => '🧹',
            'optimize_images' => '🖼️',
            'generate_meta_tags' => '🏷️',
            'keyword_suggestion' => '🔑',
            'backup' => '💾',
            'malware_scanner' => '🛡️',
            'cache_manager' => '⚡',
            'database_cleaner' => '🧼'
        );
        
        return isset($icons[$action]) ? $icons[$action] : '🔧';
    }
    
    /**
     * 🆕 Execute plan from chat AJAX handler (with streaming updates)
     */
    public function execute_plan_from_chat() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }
        
        $plan = isset($_POST['plan']) ? json_decode(stripslashes($_POST['plan']), true) : null;
        
        if (!$plan || !isset($plan['steps'])) {
            wp_send_json_error(array('message' => 'Invalid plan'));
        }
        
        // Execute synchronously (WordPress cron unreliable for real-time)
        if (!class_exists('AIautotool_Agent_Planner')) {
            wp_send_json_error(array('message' => 'Planner not available'));
        }
        
        // Execute plan and get result
        $result = AIautotool_Agent_Planner::execute_plan($plan);
        
        // Format result for chat
        $response = $this->format_execution_result($result);
        
        wp_send_json_success(array(
            'response' => $response,
            'execution_result' => $result,
            'streaming' => false,
            'debug' => array(
                'steps_executed' => count($result['step_results']),
                'success' => $result['overall_success']
            )
        ));
    }
    
    /**
     * 🆕 Get execution progress (for polling)
     */
    public function get_execution_progress() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $execution_id = isset($_POST['execution_id']) ? sanitize_text_field($_POST['execution_id']) : '';
        
        if (empty($execution_id)) {
            wp_send_json_error(array('message' => 'Invalid execution ID'));
        }
        
        $execution_data = get_transient('ai_execution_' . $execution_id);
        
        if (!$execution_data) {
            wp_send_json_error(array('message' => 'Execution not found or expired'));
        }
        
        wp_send_json_success(array(
            'status' => $execution_data['status'],
            'updates' => $execution_data['updates'],
            'result' => isset($execution_data['result']) ? $execution_data['result'] : null
        ));
    }
    
    /**
     * 🤖 NEW: Handle agent execution with AI Agent Core
     */
    public function handle_agent_execution() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        // Load AI Agent Core
        if (!class_exists('AIautotool_Agent_Core')) {
            require_once plugin_dir_path(__FILE__) . 'aiautotool_agent_core.php';
        }
        
        $query = isset($_POST['query']) ? sanitize_text_field($_POST['query']) : '';
        
        if (empty($query)) {
            wp_send_json_error(array('message' => __('Query cannot be empty', 'ai-auto-tool')));
        }
        
        // Get conversation history
        $history = isset($_POST['history']) ? json_decode(stripslashes($_POST['history']), true) : array();
        if (!is_array($history)) {
            $history = array();
        }
        
        // Sanitize history
        $sanitized_history = array();
        foreach ($history as $msg) {
            if (isset($msg['role']) && isset($msg['content'])) {
                $sanitized_history[] = array(
                    'role' => sanitize_text_field($msg['role']),
                    'content' => wp_kses_post($msg['content'])
                );
            }
        }
        $history = array_slice($sanitized_history, -10); // Limit to last 10 messages
        
        // Get context
        $context = $this->get_site_context();
        
        // Create agent and process request with conversation history
        $agent = new AIautotool_Agent_Core();
        $result = $agent->process_request($query, $context, $history);
        
        // Format response for chat
        $response_text = $this->format_agent_response($result);
        
        wp_send_json_success(array(
            'response' => $response_text,
            'agent_result' => $result,
            'intent' => 'agent_executed',
            'source' => 'ai_agent_core'
        ));
    }
    
    /**
     * Format agent response for display
     */
    private function format_agent_response($result) {
        if (!$result['success']) {
            return "❌ **Task Failed**\n\n" . $result['error'];
        }
        
        $output = "✅ **AI Agent Task Completed**\n\n";
        $output .= "**Summary:** {$result['summary']}\n\n";
        $output .= "**Todos Completed:** {$result['todos_completed']} / {$result['todos_total']}\n\n";
        
        // Show detailed results
        if (isset($result['results']) && is_array($result['results'])) {
            $output .= "## Execution Details:\n\n";
            
            foreach ($result['results'] as $todo_result) {
                $icon = $todo_result['success'] ? '✅' : '❌';
                $output .= "{$icon} **{$todo_result['action']}**\n";
                $output .= "   {$todo_result['description']}\n";
                
                if ($todo_result['success'] && isset($todo_result['result']['data'])) {
                    foreach ($todo_result['result']['data'] as $key => $value) {
                        if (is_scalar($value) && strlen($value) < 100) {
                            $output .= "   - {$key}: {$value}\n";
                        }
                    }
                } elseif (!$todo_result['success']) {
                    $error = isset($todo_result['result']['error']) ? $todo_result['result']['error'] : 'Unknown error';
                    $output .= "   ❌ Error: {$error}\n";
                }
                
                $output .= "\n";
            }
        }
        
        return $output;
    }
    
    /**
     * 🆕 Execute plan in background with updates
     */
    public static function execute_plan_background($execution_id, $plan) {
        // Load required classes
        if (!class_exists('AIautotool_Agent_Executor')) {
            require_once plugin_dir_path(__FILE__) . 'aiautotool_agent_executor.php';
        }
        
        // Update callback to store progress
        $update_callback = function($update) use ($execution_id) {
            $execution_data = get_transient('ai_execution_' . $execution_id);
            if ($execution_data) {
                $execution_data['updates'][] = $update;
                $execution_data['last_update'] = current_time('mysql');
                set_transient('ai_execution_' . $execution_id, $execution_data, 600);
            }
        };
        
        // Execute with thinking phases
        $result = AIautotool_Agent_Executor::execute_with_thinking($plan, $update_callback);
        
        // Store final result
        $execution_data = get_transient('ai_execution_' . $execution_id);
        if ($execution_data) {
            $execution_data['status'] = 'completed';
            $execution_data['result'] = $result;
            $execution_data['completed_at'] = current_time('mysql');
            set_transient('ai_execution_' . $execution_id, $execution_data, 600);
        }
    }
    
    /**
     * 🆕 Format execution result for chat (Cursor-style)
     */
    private function format_execution_result($result) {
        $output = '';
        
        // Check if any step has TODO_ANIMATION marker
        foreach ($result['step_results'] as $index => $step_result) {
            if (isset($step_result['message']) && strpos($step_result['message'], '<!-- TODO_ANIMATION -->') !== false) {
                // Wrap TODO animation in execution phase marker (like Cursor)
                $step_num = $index + 1;
                $action = $step_result['action'];
                
                $wrapped = "<!-- EXECUTION_PHASE -->\n";
                $wrapped .= json_encode(array(
                    'step' => $step_num,
                    'action' => $action,
                    'description' => $step_result['description'],
                    'status' => $step_result['success'] ? 'complete' : 'failed'
                ), JSON_UNESCAPED_UNICODE);
                $wrapped .= "\n<!-- /EXECUTION_PHASE -->\n\n";
                $wrapped .= $step_result['message']; // The TODO animation
                
                return $wrapped;
            }
        }
        
        // Otherwise, format standard execution result
        $output = "✅ **EXECUTION COMPLETE**\n\n";
        $output .= "**Goal:** {$result['goal']}\n";
        $output .= "**Progress:** {$result['steps_completed']} / " . ($result['steps_completed'] + $result['steps_failed']) . " steps\n\n";
        
        // Show each step result
        foreach ($result['step_results'] as $index => $step_result) {
            $step_num = $index + 1;
            $icon = $step_result['success'] ? '✅' : '❌';
            
            $output .= "**Step {$step_num}: {$icon} {$step_result['action']}**\n";
            
            if (isset($step_result['skipped']) && $step_result['skipped']) {
                $output .= "⏭️ Skipped: {$step_result['error']}\n\n";
            } elseif (!$step_result['success']) {
                $output .= "❌ Error: {$step_result['error']}\n\n";
            } elseif ($step_result['success']) {
                // Show success details
                if (isset($step_result['data']['post_id'])) {
                    $post_id = $step_result['data']['post_id'];
                    $title = $step_result['data']['title'] ?? 'Post #' . $post_id;
                    $edit_link = $step_result['data']['edit_link'] ?? '';
                    $view_link = $step_result['data']['view_link'] ?? '';
                    
                    $output .= "📝 Created: **{$title}** (ID: {$post_id})\n";
                    if (!empty($edit_link)) {
                        $output .= "✏️ [Edit Post]({$edit_link}) | ";
                    }
                    if (!empty($view_link)) {
                        $output .= "👁️ [View]({$view_link})\n";
                    }
                    $output .= "\n";
                }
            }
        }
        
        if (!$result['overall_success']) {
            $output .= "\n⚠️ Some steps failed. Please check the details above.";
        } else {
            $output .= "\n🎉 **All steps completed successfully!**";
        }
        
        return $output;
    }
    
    /**
     * Get complete tools list for AI system prompt
     * 🔄 AUTO-LOAD from tool classes - NO HARDCODE!
     * 
     * This function automatically loads:
     * 1. Tools from new tool-loader system (with metadata)
     * 2. Legacy tools from agent_tools system
     * 
     * @return string Formatted tools list for AI prompt
     */
    private function get_complete_tools_for_ai() {
        $tools_prompt = "";
        
        // 🆕 Get tools from NEW tool system (auto-loaded with metadata)
        if (class_exists('AIAgent_Tools_Loader') && method_exists('AIAgent_Tools_Loader', 'get_tools_for_ai_prompt')) {
            $new_tools = AIAgent_Tools_Loader::get_tools_for_ai_prompt();
            if (!empty($new_tools)) {
                $tools_prompt .= $new_tools . "\n";
            }
        }
        
        // 📋 Get legacy tools (for backward compatibility)
        if (class_exists('AIautotool_Agent_Tools') && method_exists('AIautotool_Agent_Tools', 'get_tools_definitions')) {
            $legacy_prompt = $this->format_legacy_tools_for_ai();
            if (!empty($legacy_prompt)) {
                $tools_prompt .= "📋 LEGACY TOOLS (compatibility):\n\n";
                $tools_prompt .= $legacy_prompt . "\n";
            }
        }
        
        return $tools_prompt;
    }
    
    /**
     * Format legacy tools definitions for AI prompt
     */
    private function format_legacy_tools_for_ai() {
        $tools_definitions = AIautotool_Agent_Tools::get_tools_definitions();
        
        if (empty($tools_definitions)) {
            return '';
        }
        
        $legacy_prompt = '';
        $categories = array();
        
        // Parse legacy tool definitions
        foreach ($tools_definitions as $tool) {
            if (!isset($tool['function'])) {
                continue;
            }
            
            $name = $tool['function']['name'];
            $description = isset($tool['function']['description']) ? $tool['function']['description'] : '';
            $params = isset($tool['function']['parameters']['properties']) ? $tool['function']['parameters']['properties'] : array();
            $required = isset($tool['function']['parameters']['required']) ? $tool['function']['parameters']['required'] : array();
            
            // Extract parameters
            $param_list = array();
            foreach ($params as $param_name => $param_info) {
                $is_required = in_array($param_name, $required);
                $param_str = $param_name;
                if ($is_required) {
                    $param_str .= '*';
                }
                $param_list[] = $param_str;
            }
            
            $param_str = !empty($param_list) ? '(' . implode(', ', $param_list) . ')' : '()';
            
            // Categorize tool
            $category = $this->categorize_tool($name);
            
            if (!isset($categories[$category])) {
                $categories[$category] = array();
            }
            
            $categories[$category][] = array(
                'name' => $name,
                'description' => $description,
                'params' => $param_str
            );
        }
        
        // Format by category
        foreach ($categories as $category => $tools) {
            $legacy_prompt .= "**{$category}:**\n";
            
            foreach ($tools as $tool) {
                $legacy_prompt .= "• **{$tool['name']}**{$tool['params']} - {$tool['description']}\n";
            }
            
            $legacy_prompt .= "\n";
        }
        
        return $legacy_prompt;
    }
    
    /**
     * Categorize tool by name
     */
    private function categorize_tool($name) {
        if (strpos($name, 'post_') === 0 || strpos($name, 'create_') === 0 || strpos($name, 'content_') === 0) {
            return 'Content';
        } elseif (strpos($name, 'query_') === 0 || strpos($name, 'execute_sql') === 0 || strpos($name, 'database_') === 0) {
            return 'Database';
        } elseif (strpos($name, 'seo_') === 0 || strpos($name, 'meta_') === 0 || strpos($name, 'keyword_') === 0) {
            return 'SEO';
        } elseif (strpos($name, 'system_') === 0 || strpos($name, 'check_') === 0) {
            return 'System';
        } elseif (strpos($name, 'delete_') === 0 || strpos($name, 'manage_') === 0) {
            return 'Management';
        } elseif (strpos($name, 'user_') === 0 || strpos($name, 'role_') === 0) {
            return 'User';
        } elseif (strpos($name, 'security_') === 0 || strpos($name, 'login_') === 0) {
            return 'Security';
        } elseif (strpos($name, 'task_') === 0) {
            return 'Tasks';
        } else {
            return 'General';
        }
    }
    
    /**
     * Clean up unwanted text patterns from AI response
     * Removes garbage text that AI sometimes adds
     */
    private function clean_ai_response($message) {
        if (empty($message)) {
            return '';
        }
        
        // Remove unwanted patterns
        $patterns = array(
            // Remove curse words and inappropriate content
            '/\b(địt|con mẹ|địt con|cái địt)\b.*/iu',
            '/\b(fuck|shit|damn|hell)\b.*/iu',
            
            // Remove random "hỏi bài viết đi" patterns
            '/hỏi bài viết đi.*/iu',
            
            // Remove excessive punctuation
            '/[!]{3,}/' => '!',
            '/[?]{3,}/' => '?',
            
            // Remove multiple newlines
            '/\n{4,}/' => "\n\n\n",
            
            // Remove empty lines at start/end
            '/^\n+/' => '',
            '/\n+$/' => "\n"
        );
        
        foreach ($patterns as $pattern => $replacement) {
            if (is_string($pattern)) {
                // Pattern with replacement
                $message = preg_replace($pattern, $replacement, $message);
            } else {
                // Numeric index - skip (shouldn't happen)
                continue;
            }
        }
        
        // Additional: Remove lines that contain only offensive patterns
        $lines = explode("\n", $message);
        $clean_lines = array();
        
        foreach ($lines as $line) {
            $line_lower = mb_strtolower($line, 'UTF-8');
            
            // Skip lines with offensive content
            if (preg_match('/\b(địt|con mẹ|fuck|shit)\b/iu', $line_lower)) {
                continue;
            }
            
            // Skip lines that are just random questions
            if (preg_match('/hỏi.*bài viết.*đi/i', $line_lower)) {
                continue;
            }
            
            $clean_lines[] = $line;
        }
        
        $cleaned = implode("\n", $clean_lines);
        
        return trim($cleaned);
    }
    
    /**
     * Start step-by-step execution session
     */
    public function start_step_session() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }
        
        $query = isset($_POST['query']) ? sanitize_text_field($_POST['query']) : '';
        
        if (empty($query)) {
            wp_send_json_error(array('message' => 'Query required'));
        }
        
        // Build action plan
        $context = $this->get_site_context();
        $action_plan = $this->build_ai_action_plan($query, $context);
        
        if (!$action_plan['success'] || empty($action_plan['todo_list'])) {
            wp_send_json_error(array('message' => 'Failed to create action plan'));
        }
        
        // Generate session ID
        $session_id = 'step_' . wp_generate_password(12, false) . '_' . time();
        
        // Save session
        $session = array(
            'query' => $query,
            'todo_list' => $action_plan['todo_list'],
            'completed_steps' => array(),
            'started_at' => time(),
            'current_step' => 0
        );
        
        set_transient("bot_session_{$session_id}", $session, 600);
        
        wp_send_json_success(array(
            'session_id' => $session_id,
            'total_steps' => count($action_plan['todo_list']),
            'plan' => $action_plan
        ));
    }
    
    /**
     * Execute single step
     */
    public function execute_single_step() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Permission denied'));
        }
        
        $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
        $current_step = isset($_POST['current_step']) ? intval($_POST['current_step']) : 0;
        
        if (empty($session_id)) {
            wp_send_json_error(array('message' => 'Session ID required'));
        }
        
        // Get session
        $session = get_transient("bot_session_{$session_id}");
        
        if (!$session) {
            wp_send_json_error(array('message' => 'Session expired'));
        }
        
        $todo_list = $session['todo_list'];
        $total_steps = count($todo_list);
        
        if ($current_step >= $total_steps) {
            wp_send_json_success(array(
                'done' => true,
                'message' => 'All steps completed'
            ));
            return;
        }
        
        // Execute current step
        $current_todo = $todo_list[$current_step];
        $result = AIautotool_Agent_Tools::execute_tool(
            $current_todo['tool'],
            $current_todo['args']
        );
        
        // Update session
        $session['completed_steps'][] = array(
            'step' => $current_step,
            'result' => $result,
            'timestamp' => time()
        );
        
        $progress = round((($current_step + 1) / $total_steps) * 100);
        
        set_transient("bot_session_{$session_id}", $session, 600);
        
        // Return result
        wp_send_json_success(array(
            'done' => ($current_step + 1 >= $total_steps),
            'step' => $current_step + 1,
            'total' => $total_steps,
            'progress' => $progress,
            'result' => $result,
            'title' => $current_todo['title'],
            'description' => $current_todo['description'],
            'has_next' => ($current_step + 1 < $total_steps)
        ));
    }
    
    /**
     * Get step progress
     */
    public function get_step_progress() {
        check_ajax_referer('bot_assistant_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
        }
        
        $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
        
        if (empty($session_id)) {
            wp_send_json_error(array('message' => 'Session ID required'));
        }
        
        $session = get_transient("bot_session_{$session_id}");
        
        if (!$session) {
            wp_send_json_error(array('message' => 'Session not found'));
        }
        
        $total_steps = count($session['todo_list']);
        $completed = count($session['completed_steps']);
        
        wp_send_json_success(array(
            'total_steps' => $total_steps,
            'completed_steps' => $completed,
            'progress' => $total_steps > 0 ? round(($completed / $total_steps) * 100) : 0
        ));
    }
    
    /**
     * 🆕 Handle smart analysis request
     */
    public function handle_smart_analysis() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'bot_assistant_nonce')) {
            wp_send_json_error(array('message' => 'Invalid nonce'));
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            return;
        }
        
        $user_query = sanitize_text_field($_POST['user_query']);
        $chat_history = json_decode(stripslashes($_POST['chat_history']), true);
        $available_tools = json_decode(stripslashes($_POST['available_tools']), true);
        $website_resources = json_decode(stripslashes($_POST['website_resources']), true);
        
        // Check if AI is available
        if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) {
            wp_send_json_error(array(
                'message' => 'AI provider not configured. Please configure an AI provider in AI Provider Settings.',
                'error_code' => 'no_ai_provider'
            ));
            return;
        }
        
        // Build analysis prompt
        $analysis_prompt = $this->build_smart_analysis_prompt($user_query, $available_tools, $website_resources, $chat_history);
        
        // Call AI for analysis
        $messages = array(
            array(
                'role' => 'system',
                'content' => $analysis_prompt
            )
        );
        
        // Add chat history for context
        if (!empty($chat_history) && is_array($chat_history)) {
            foreach ($chat_history as $msg) {
                if (isset($msg['role']) && isset($msg['content'])) {
                    $role = sanitize_text_field($msg['role']);
                    
                    // 🔍 DEBUG: Log role validation
                    
                    // Validate and normalize roles
                    if (!in_array($role, ['user', 'assistant', 'system'])) {
                        continue;
                    }
                    
                    $messages[] = array(
                        'role' => $role,
                        'content' => $msg['content']
                    );
                }
            }
        }
        
        // Add current query
        $messages[] = array(
            'role' => 'user',
            'content' => $user_query
        );
        
        // Call AI with bot assistant specific provider and model
        $ai_response = $this->call_ai_with_bot_config($this->validate_message_roles($messages), array(
            'temperature' => 0.7,
            'max_tokens' => 2000
        ));
        
        // Check AI response
        if (!$ai_response['success']) {
            wp_send_json_error(array(
                'message' => 'Failed to get AI analysis: ' . (isset($ai_response['error']) ? $ai_response['error'] : 'Unknown error'),
                'error_code' => 'ai_call_failed'
            ));
            return;
        }
        
        // Parse AI response
        $analysis_data = $this->parse_ai_analysis_response($ai_response['content'], $available_tools);
        
        wp_send_json_success($analysis_data);
    }
    
    /**
     * Build smart analysis prompt for AI
     */
    private function build_smart_analysis_prompt($user_query, $available_tools, $website_resources, $chat_history) {
        $tools_list = '';
        if (!empty($available_tools) && is_array($available_tools)) {
            foreach ($available_tools as $tool) {
                if (isset($tool['name']) && isset($tool['description'])) {
                    $tools_list .= "- {$tool['name']}: {$tool['description']}\n";
                }
            }
        }
        
        $resources_list = '';
        if (!empty($website_resources) && is_array($website_resources)) {
            foreach ($website_resources as $resource => $value) {
                $resources_list .= "- {$resource}: " . (is_bool($value) ? ($value ? 'Available' : 'Not Available') : $value) . "\n";
            }
        }
        
        $system_prompt = "Bạn là một AI Assistant chuyên phân tích yêu cầu của người dùng WordPress để xây dựng kế hoạch thực thi thông minh.\n\n";
        $system_prompt .= "NHIỆM VỤ CỦA BẠN:\n";
        $system_prompt .= "Phân tích yêu cầu của người dùng và trả về JSON với cấu trúc sau:\n";
        $system_prompt .= "{\n";
        $system_prompt .= "  \"user_needs\": \"Mô tả ngắn gọn về những gì người dùng muốn\",\n";
        $system_prompt .= "  \"analysis\": \"Phân tích chi tiết yêu cầu với các bullet points\",\n";
        $system_prompt .= "  \"notes\": \"Các lưu ý quan trọng cần biết trước khi thực thi\",\n";
        $system_prompt .= "  \"complexity\": \"low|medium|high\",\n";
        $system_prompt .= "  \"estimated_time\": \"Ước tính thời gian thực hiện\",\n";
        $system_prompt .= "  \"required_tools\": [\"danh sách tên các tool cần sử dụng\"],\n";
        $system_prompt .= "  \"steps_overview\": \"Tóm tắt các bước cần thực hiện\"\n";
        $system_prompt .= "}\n\n";
        
        if (!empty($tools_list)) {
            $system_prompt .= "CÁC TOOL CÓ SẴN:\n{$tools_list}\n\n";
        }
        
        if (!empty($resources_list)) {
            $system_prompt .= "TÀI NGUYÊN WEBSITE:\n{$resources_list}\n\n";
        }
        
        $system_prompt .= "Hãy phân tích yêu cầu của người dùng một cách cẩn thận và chính xác.\n";
        $system_prompt .= "QUAN TRỌNG: Chỉ trả về JSON, không trả về bất kỳ text nào khác ngoài JSON.";
        
        return $system_prompt;
    }
    
    /**
     * Parse AI analysis response
     */
    private function parse_ai_analysis_response($ai_content, $available_tools) {
        // Try to extract JSON from response
        $json_match = array();
        if (preg_match('/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/s', $ai_content, $json_match)) {
            $json_data = json_decode($json_match[0], true);
            
            if (json_last_error() === JSON_ERROR_NONE && is_array($json_data)) {
                // Validate and set defaults
                $analysis_data = array(
                    'user_needs' => isset($json_data['user_needs']) ? $json_data['user_needs'] : "Người dùng muốn thực hiện một hành động",
                    'analysis' => isset($json_data['analysis']) ? $json_data['analysis'] : "Cần phân tích thêm",
                    'notes' => isset($json_data['notes']) ? $json_data['notes'] : "Lưu ý cần kiểm tra quyền truy cập",
                    'complexity' => isset($json_data['complexity']) ? $json_data['complexity'] : 'medium',
                    'estimated_time' => isset($json_data['estimated_time']) ? $json_data['estimated_time'] : '2-5 phút',
                    'required_tools' => isset($json_data['required_tools']) && is_array($json_data['required_tools']) 
                        ? $json_data['required_tools'] 
                        : array(),
                    'steps_overview' => isset($json_data['steps_overview']) ? $json_data['steps_overview'] : "Cần xây dựng kế hoạch chi tiết"
                );
                
                return $analysis_data;
            }
        }
        
        // Fallback: if JSON parsing fails, format AI response
        return array(
            'user_needs' => "Người dùng muốn: " . $ai_content,
            'analysis' => "AI phản hồi:\n" . $ai_content,
            'notes' => "Lưu ý: Phản hồi AI đã được xử lý trực tiếp",
            'complexity' => 'medium',
            'estimated_time' => '2-5 phút',
            'required_tools' => array(),
            'steps_overview' => "Cần phân tích thêm để xây dựng kế hoạch"
        );
    }
    
    /**
     * 🆕 Handle resources check request
     */
    public function handle_check_resources() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'bot_assistant_nonce')) {
            wp_send_json_error(array('message' => 'Invalid nonce'));
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            return;
        }
        
        $analysis_data = json_decode(stripslashes($_POST['analysis_data']), true);
        
        // Check if AI is available
        if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) {
            // Fallback to basic resource check
            $resources_data = array(
                'available' => "✅ Có sẵn:\n• Quyền admin đầy đủ\n• Plugin AI Auto Tool đã cài đặt\n• Database connection OK\n• File system writable",
                'missing' => "❌ Thiếu:\n• Không thiếu tài nguyên nào",
                'preparation_needed' => "🔧 Cần chuẩn bị:\n• Backup database (tùy chọn)\n• Kiểm tra disk space\n• Thông báo cho user về tiến trình",
                'status' => 'ready',
                'warnings' => array()
            );
            wp_send_json_success($resources_data);
            return;
        }
        
        // Build resource check prompt
        $prompt = "Bạn là một AI Assistant chuyên kiểm tra tài nguyên WordPress.\n\n";
        $prompt .= "NHIỆM VỤ: Phân tích tài nguyên có sẵn và trả về JSON với cấu trúc:\n";
        $prompt .= "{\n";
        $prompt .= "  \"available\": \"Danh sách tài nguyên có sẵn\",\n";
        $prompt .= "  \"missing\": \"Danh sách tài nguyên thiếu\",\n";
        $prompt .= "  \"preparation_needed\": \"Những gì cần chuẩn bị trước khi thực thi\",\n";
        $prompt .= "  \"status\": \"ready|not_ready\",\n";
        $prompt .= "  \"warnings\": [\"danh sách cảnh báo\"]\n";
        $prompt .= "}\n\n";
        
        if (!empty($analysis_data)) {
            $prompt .= "PHÂN TÍCH YÊU CẦU:\n";
            $prompt .= json_encode($analysis_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";
        }
        
        // Get actual WordPress resources
        $wp_resources = $this->get_wp_resources_info();
        $prompt .= "THÔNG TIN WP HIỆN TẠI:\n{$wp_resources}\n\n";
        $prompt .= "QUAN TRỌNG: Chỉ trả về JSON, không trả về bất kỳ text nào khác ngoài JSON.";
        
        // Call AI
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.7,
            'max_tokens' => 1500
        ));
        
        // Check AI response
        if (!$ai_response['success']) {
            // Fallback to basic check
            $resources_data = array(
                'available' => "✅ Có sẵn:\n• Quyền admin đầy đủ\n• Plugin AI Auto Tool đã cài đặt",
                'missing' => "❌ Thiếu:\n• AI không khả dụng - kiểm tra nguồn thay thế",
                'preparation_needed' => "🔧 Cần chuẩn bị:\n• Backup database\n• Kiểm tra quyền truy cập",
                'status' => 'ready',
                'warnings' => array('AI analysis failed, using fallback')
            );
            wp_send_json_success($resources_data);
            return;
        }
        
        // Parse AI response
        $resources_data = $this->parse_ai_resource_response($ai_response['content']);
        
        wp_send_json_success($resources_data);
    }
    
    /**
     * Get WordPress resources info
     */
    private function get_wp_resources_info() {
        $info = array();
        
        // Check user capabilities
        $info[] = "User can manage_options: " . (current_user_can('manage_options') ? 'YES' : 'NO');
        $info[] = "Plugin AI Auto Tool active: YES";
        $info[] = "WordPress version: " . get_bloginfo('version');
        $info[] = "PHP version: " . PHP_VERSION;
        
        // Check file system
        $uploads_dir = wp_upload_dir();
        $info[] = "Upload directory writable: " . (is_writable($uploads_dir['basedir']) ? 'YES' : 'NO');
        
        // Check database
        global $wpdb;
        $info[] = "Database connection: OK";
        
        return implode("\n", $info);
    }
    
    /**
     * Parse AI resource check response
     */
    private function parse_ai_resource_response($ai_content) {
        $json_match = array();
        if (preg_match('/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/s', $ai_content, $json_match)) {
            $json_data = json_decode($json_match[0], true);
            
            if (json_last_error() === JSON_ERROR_NONE && is_array($json_data)) {
                return array(
                    'available' => isset($json_data['available']) ? $json_data['available'] : "✅ Tài nguyên có sẵn",
                    'missing' => isset($json_data['missing']) ? $json_data['missing'] : "❌ Không thiếu tài nguyên",
                    'preparation_needed' => isset($json_data['preparation_needed']) ? $json_data['preparation_needed'] : "🔧 Chuẩn bị cơ bản",
                    'status' => isset($json_data['status']) ? $json_data['status'] : 'ready',
                    'warnings' => isset($json_data['warnings']) && is_array($json_data['warnings']) ? $json_data['warnings'] : array()
                );
            }
        }
        
        // Fallback
        return array(
            'available' => "✅ Có sẵn: AI đã phân tích",
            'missing' => "❌ Thiếu: Kiểm tra AI response",
            'preparation_needed' => "🔧 Cần chuẩn bị: Backup data",
            'status' => 'ready',
            'warnings' => array()
        );
    }
    
    /**
     * 🆕 Handle execution plan building
     */
    public function handle_build_execution_plan() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'bot_assistant_nonce')) {
            wp_send_json_error(array('message' => 'Invalid nonce'));
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            return;
        }
        
        $analysis_data = json_decode(stripslashes($_POST['analysis_data']), true);
        
        // Get user query from POST (analysis_data is just text)
        $user_query = isset($_POST['user_query']) ? sanitize_text_field($_POST['user_query']) : '';
        
        // If no user_query from POST, try to extract from analysis_data text
        if (empty($user_query) && !empty($analysis_data)) {
            // Try to find user query in analysis_data text
            if (preg_match('/User Query[:\s]+(.+?)(?:\n|$)/i', $analysis_data, $matches)) {
                $user_query = trim($matches[1]);
            } elseif (preg_match('/Query[:\s]+(.+?)(?:\n|$)/i', $analysis_data, $matches)) {
                $user_query = trim($matches[1]);
            }
        }
        
        // Get available tools (optional from POST)
        $available_tools = isset($_POST['available_tools']) ? json_decode(stripslashes($_POST['available_tools']), true) : array();
        
        // If no available tools provided, load them automatically
        if (empty($available_tools)) {
            if (class_exists('AIautotool_Agent_Tools')) {
                $tools_definitions = AIautotool_Agent_Tools::get_tools_definitions();
                $available_tools = array();
                
                // Convert tool definitions to simple format
                foreach ($tools_definitions as $tool) {
                    if (isset($tool['function'])) {
                        $available_tools[] = array(
                            'name' => $tool['function']['name'],
                            'description' => $tool['function']['description']
                        );
                    }
                }
                
            }
        }
        
        // Debug logging
        
        // If no user query, return simple plan
        if (empty($user_query)) {
            $todo_list = array(
                array(
                    'step' => 1,
                    'title' => 'Thực hiện yêu cầu',
                    'description' => 'Thực hiện yêu cầu của người dùng',
                    'tool' => 'execute',
                    'args' => array()
                )
            );
            
            $plan_data = array(
                'steps' => "📝 Các bước thực hiện:\n• Thực hiện yêu cầu",
                'estimated_time' => "⏱️ Thời gian ước tính: 2-5 phút",
                'expected_result' => "🎯 Kết quả mong đợi: Hoàn thành yêu cầu",
                'needs_planning' => true,
                'todo_list' => $todo_list,
                'step_by_step' => true
            );
            
            wp_send_json_success($plan_data);
            return;
        }
        
        // Check if AI is available
        if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) {
            // Fallback to basic plan
            $todo_list = array(
                array(
                    'step' => 1,
                    'title' => 'Thực hiện yêu cầu',
                    'description' => 'Thực hiện yêu cầu của người dùng',
                    'tool' => 'query_database',
                    'args' => array(
                        'query_type' => 'posts',
                        'filters' => array('limit' => 5),
                        'operation_type' => 'analyze',
                        'description' => 'Phân tích cơ bản bài viết'
                    )
                )
            );
            
            $plan_data = array(
                'steps' => "📝 Các bước thực hiện:\n• Thực hiện yêu cầu",
                'estimated_time' => "⏱️ Thời gian ước tính: 2-5 phút",
                'expected_result' => "🎯 Kết quả mong đợi: Hoàn thành yêu cầu",
                'needs_planning' => true,
                'todo_list' => $todo_list,
                'step_by_step' => true
            );
            
            wp_send_json_success($plan_data);
            return;
        }
        
        // Build AI prompt for execution plan
        $prompt = $this->build_execution_plan_prompt($user_query, $analysis_data, $available_tools);
        
        
        $messages = array(
            array(
                'role' => 'system',
                'content' => $prompt
            )
        );
        
        // Call AI with bot assistant config
        $ai_response = $this->call_ai_with_bot_config($messages, array(
            'temperature' => 0.7,
            'max_tokens' => 2000
        ));
        
        if (!$ai_response['success']) {
        } else {
        }
        
        // Check AI response
        if (!$ai_response['success']) {
            // Fallback with proper arguments
            $todo_list = array(
                array(
                    'step' => 1,
                    'title' => 'Thực hiện yêu cầu',
                    'description' => 'Thực hiện yêu cầu của người dùng',
                    'tool' => 'query_database',
                    'args' => array(
                        'query_type' => 'posts',
                        'filters' => array('limit' => 10),
                        'operation_type' => 'analyze',
                        'description' => 'Phân tích bài viết hiện có'
                    )
                )
            );
            
            $plan_data = array(
                'steps' => "📝 Các bước thực hiện:\n• Thực hiện yêu cầu",
                'estimated_time' => "⏱️ Thời gian ước tính: 2-5 phút",
                'expected_result' => "🎯 Kết quả mong đợi: Hoàn thành yêu cầu",
                'needs_planning' => true,
                'todo_list' => $todo_list,
                'step_by_step' => true
            );
            
            wp_send_json_success($plan_data);
            return;
        }
        
        // Parse AI response
        $plan_data = $this->parse_ai_execution_plan_response($ai_response['content'], $available_tools);
        
        wp_send_json_success($plan_data);
    }
    
    /**
     * Build execution plan prompt for AI
     */
    private function build_execution_plan_prompt($user_query, $analysis_data, $available_tools) {
        $prompt = "Bạn là một AI Assistant chuyên xây dựng kế hoạch thực thi thông minh cho WordPress.\n\n";
        $prompt .= "QUAN TRỌNG: Bạn đang làm việc trên một WordPress site ĐÃ CÓ SẴN, KHÔNG phải cài đặt WordPress mới.\n";
        $prompt .= "Site này đã hoạt động và bạn chỉ cần thực hiện các tác vụ quản lý, chỉnh sửa, hoặc phân tích.\n\n";
        $prompt .= "NHIỆM VỤ: Xây dựng kế hoạch thực thi chi tiết và trả về JSON với cấu trúc:\n\n";
        $prompt .= "```json\n";
        $prompt .= "{\n";
        $prompt .= "  \"steps\": \"Mô tả chi tiết các bước sẽ thực hiện\",\n";
        $prompt .= "  \"estimated_time\": \"Ước tính thời gian thực hiện\",\n";
        $prompt .= "  \"expected_result\": \"Kết quả mong đợi sau khi hoàn thành\",\n";
        $prompt .= "  \"needs_planning\": true,\n";
        $prompt .= "  \"todo_list\": [\n";
        $prompt .= "    {\n";
        $prompt .= "      \"step\": 1,\n";
        $prompt .= "      \"title\": \"Tên bước cụ thể\",\n";
        $prompt .= "      \"description\": \"Mô tả chi tiết bước này\",\n";
        $prompt .= "      \"tool\": \"tên_tool_cần_dùng\",\n";
        $prompt .= "      \"args\": {\n";
        $prompt .= "        \"param1\": \"giá_trị_cụ_thể\",\n";
        $prompt .= "        \"param2\": \"giá_trị_cụ_thể\",\n";
        $prompt .= "        \"operation_type\": \"loại_thao_tác\",\n";
        $prompt .= "        \"description\": \"mô_tả_chi_tiết\"\n";
        $prompt .= "      }\n";
        $prompt .= "    }\n";
        $prompt .= "  ],\n";
        $prompt .= "  \"step_by_step\": true\n";
        $prompt .= "}\n";
        $prompt .= "```\n\n";
        $prompt .= "QUAN TRỌNG VỀ ARGUMENTS:\n";
        $prompt .= "- Mỗi tool cần arguments cụ thể để hoạt động\n";
        $prompt .= "- KHÔNG được để args rỗng {} - phải có giá trị thực\n";
        $prompt .= "- Ví dụ arguments cho các tool phổ biến:\n\n";
        $prompt .= "• query_database: {\"query_type\": \"posts\", \"filters\": {\"limit\": 10}}\n";
        $prompt .= "• delete_posts: {\"post_type\": \"post\", \"status\": \"draft\", \"operation_type\": \"delete\"}\n";
        $prompt .= "• update_posts: {\"post_type\": \"post\", \"operation_type\": \"update_seo\", \"description\": \"Cập nhật SEO\"}\n";
        $prompt .= "• analyze_images: {\"operation_type\": \"check_alt_text\", \"description\": \"Kiểm tra alt text\"}\n";
        $prompt .= "• create_content: {\"post_type\": \"post\", \"title\": \"Tiêu đề bài viết\", \"content\": \"Nội dung\"}\n\n";
        $prompt .= "HOẶC nếu yêu cầu đơn giản, chỉ cần 1 tool:\n";
        $prompt .= "```json\n";
        $prompt .= "{\n";
        $prompt .= "  \"steps\": \"Thực hiện yêu cầu trực tiếp\",\n";
        $prompt .= "  \"estimated_time\": \"1-2 phút\",\n";
        $prompt .= "  \"expected_result\": \"Hoàn thành yêu cầu\",\n";
        $prompt .= "  \"needs_planning\": false,\n";
        $prompt .= "  \"direct_tool\": \"tên_tool_cần_dùng\",\n";
        $prompt .= "  \"direct_args\": {\n";
        $prompt .= "    \"operation_type\": \"loại_thao_tác\",\n";
        $prompt .= "    \"description\": \"mô_tả_chi_tiết\",\n";
        $prompt .= "    \"param1\": \"giá_trị_cụ_thể\"\n";
        $prompt .= "  },\n";
        $prompt .= "  \"todo_list\": [],\n";
        $prompt .= "  \"step_by_step\": false\n";
        $prompt .= "}\n";
        $prompt .= "```\n\n";
        
        if (!empty($user_query)) {
            $prompt .= "YÊU CẦU NGƯỜI DÙNG: {$user_query}\n\n";
            $prompt .= "PHÂN TÍCH YÊU CẦU:\n";
            $prompt .= "- Đây là yêu cầu cụ thể cần thực hiện\n";
            $prompt .= "- KHÔNG phải yêu cầu cài đặt WordPress mới\n";
            $prompt .= "- Chỉ tạo plan để thực hiện yêu cầu này trên site hiện tại\n\n";
        } else {
            $prompt .= "LƯU Ý: Không có yêu cầu cụ thể từ người dùng.\n";
            $prompt .= "Chỉ tạo plan cơ bản với tool 'execute'.\n\n";
        }
        
        if (!empty($analysis_data)) {
            $prompt .= "THÔNG TIN PHÂN TÍCH HIỆN CÓ:\n" . json_encode($analysis_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";
        }
        
        if (!empty($available_tools)) {
            $tools_list = '';
            $tool_names = array();
            foreach ($available_tools as $tool) {
                if (isset($tool['name']) && isset($tool['description'])) {
                    $tools_list .= "- {$tool['name']}: {$tool['description']}\n";
                    $tool_names[] = $tool['name'];
                }
            }
            $prompt .= "CÁC TOOL CÓ SẴN (CHỈ ĐƯỢC SỬ DỤNG CÁC TOOL NÀY):\n{$tools_list}\n";
            $prompt .= "DANH SÁCH TÊN TOOL: " . implode(', ', $tool_names) . "\n\n";
        } else {
            $prompt .= "KHÔNG CÓ TOOL NÀO CÓ SẴN - CHỈ SỬ DỤNG TOOL 'execute'\n\n";
        }
        
        $prompt .= "HƯỚNG DẪN:\n";
        $prompt .= "- Phân tích yêu cầu để quyết định có cần planning hay không\n";
        $prompt .= "- Nếu yêu cầu phức tạp (nhiều bước): set needs_planning = true, tạo todo_list\n";
        $prompt .= "- Nếu yêu cầu đơn giản (1 tool): set needs_planning = false, dùng direct_tool\n";
        $prompt .= "- CHỈ sử dụng các tool có sẵn trong danh sách CÁC TOOL CÓ SẴN ở trên\n";
        $prompt .= "- KHÔNG được tạo ra tool mới hoặc sử dụng tool không có trong danh sách\n";
        $prompt .= "- KHÔNG được tạo plan cài đặt WordPress mới\n";
        $prompt .= "- KHÔNG được tạo plan thiết lập môi trường mới\n";
        $prompt .= "- Chỉ tạo plan cho các tác vụ quản lý, chỉnh sửa, phân tích trên site hiện tại\n";
        $prompt .= "- Nếu không có tool phù hợp, sử dụng tool 'execute' làm fallback\n";
        $prompt .= "- Ước tính thời gian thực tế\n";
        $prompt .= "- Mô tả kết quả cụ thể sẽ đạt được\n";
        $prompt .= "- Chỉ trả về JSON trong code block, không có text khác\n\n";
        
        $prompt .= "VÍ DỤ:\n";
        $prompt .= "1. Yêu cầu phức tạp: 'Tạo một trang mới với nội dung về sản phẩm'\n";
        $prompt .= "   → needs_planning: true, todo_list: [create_page, add_content, publish]\n\n";
        $prompt .= "2. Yêu cầu đơn giản: 'Đếm số lượng users'\n";
        $prompt .= "   → needs_planning: false, direct_tool: 'count_users'\n\n";
        $prompt .= "3. Yêu cầu đơn giản: 'Hiển thị danh sách plugins'\n";
        $prompt .= "   → needs_planning: false, direct_tool: 'get_plugins'\n\n";
        $prompt .= "QUAN TRỌNG: Chỉ trả về JSON trong code block ```json```, không trả về bất kỳ text nào khác.";
        
        return $prompt;
    }
    
    /**
     * Parse AI execution plan response
     */
    private function parse_ai_execution_plan_response($ai_content, $available_tools) {
        // Log AI response for debugging
        
        // Try multiple JSON extraction methods
        $json_data = null;
        
        // Method 1: Try to find JSON block with ```json markers
        if (preg_match('/```json\s*(\{.*?\})\s*```/s', $ai_content, $matches)) {
            $json_data = json_decode($matches[1], true);
        }
        
        // Method 2: Try to find JSON object directly
        if (!$json_data && preg_match('/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/s', $ai_content, $matches)) {
            $json_data = json_decode($matches[0], true);
        }
        
        // Method 3: Try to extract JSON from the entire content
        if (!$json_data) {
            $json_data = json_decode($ai_content, true);
        }
        
        if ($json_data && json_last_error() === JSON_ERROR_NONE && is_array($json_data)) {
            
                // Validate todo_list structure
                $todo_list = isset($json_data['todo_list']) && is_array($json_data['todo_list']) 
                    ? $json_data['todo_list'] 
                    : array();
                
            // Ensure each todo has required fields and validate tools
            $available_tool_names = array();
            if (!empty($available_tools)) {
                foreach ($available_tools as $tool) {
                    if (isset($tool['name'])) {
                        $available_tool_names[] = $tool['name'];
                    }
                }
            }
            
                foreach ($todo_list as $i => &$todo) {
                    if (!isset($todo['step'])) $todo['step'] = $i + 1;
                    if (!isset($todo['title'])) $todo['title'] = 'Unknown step';
                    if (!isset($todo['description'])) $todo['description'] = '';
                    if (!isset($todo['tool'])) $todo['tool'] = 'execute';
                    if (!isset($todo['args'])) $todo['args'] = array();
                
                // Validate tool exists in available tools
                if (!empty($available_tool_names) && !in_array($todo['tool'], $available_tool_names)) {
                    $todo['tool'] = 'execute'; // Fallback to execute
                }
                }
                
            $needs_planning = isset($json_data['needs_planning']) ? (bool)$json_data['needs_planning'] : true;
            
            $result = array(
                'steps' => isset($json_data['steps']) ? $json_data['steps'] : "📝 Các bước sẽ được thực hiện",
                'estimated_time' => isset($json_data['estimated_time']) ? $json_data['estimated_time'] : "⏱️ 2-5 phút",
                'expected_result' => isset($json_data['expected_result']) ? $json_data['expected_result'] : "🎯 Hoàn thành yêu cầu",
                'needs_planning' => $needs_planning,
                'todo_list' => $todo_list,
                'step_by_step' => isset($json_data['step_by_step']) ? (bool)$json_data['step_by_step'] : true
            );
            
            // Add direct execution info if not planning
            if (!$needs_planning) {
                $result['direct_tool'] = isset($json_data['direct_tool']) ? $json_data['direct_tool'] : 'execute';
                $result['direct_args'] = isset($json_data['direct_args']) ? $json_data['direct_args'] : array();
            }
            
            return $result;
        }
        
        
        // Fallback
        return array(
            'steps' => "📝 Các bước sẽ được thực hiện",
            'estimated_time' => "⏱️ 2-5 phút",
            'expected_result' => "🎯 Hoàn thành yêu cầu",
            'needs_planning' => true,
            'todo_list' => array(
                array(
                    'step' => 1,
                    'title' => 'Thực hiện yêu cầu',
                    'description' => 'Hoàn thành nhiệm vụ',
                    'tool' => 'execute',
                    'args' => array()
                )
            ),
            'step_by_step' => true
        );
    }
    
    /**
     * Call AI with bot assistant specific provider and model configuration
     * 
     * @param array $messages Messages array
     * @param array $options Additional options
     * @return array AI response
     */
    private function call_ai_with_bot_config($messages, $options = array()) {
        // Validate message roles before sending to AI
        $validated_messages = $this->validate_message_roles($messages);
        
        // Fallback to default AI Helper behavior
        return AIAutotool_AI_Helper::chat($validated_messages, $options);
    }
    
    /**
     * Validate and normalize message roles for AI providers
     * 
     * @param array $messages Array of messages with 'role' and 'content'
     * @return array Validated messages array
     */
    private function validate_message_roles($messages) {
        $validated_messages = array();
        
        foreach ($messages as $message) {
            if (!isset($message['role']) || !isset($message['content'])) {
                continue;
            }
            
            $role = sanitize_text_field($message['role']);
            
            // Normalize roles to standard OpenAI format
            switch ($role) {
                case 'user':
                case 'assistant':
                case 'system':
                    // These are valid OpenAI roles
                    break;
                case 'model':
                    // Gemini uses 'model' instead of 'assistant'
                    $role = 'assistant';
                    break;
                default:
                    // Unknown role, skip this message
                    continue 2;
            }
            
            $validated_messages[] = array(
                'role' => $role,
                'content' => $message['content']
            );
        }
        
        return $validated_messages;
    }
}
