<?php
/**
 * Auto Create Categories Feature
 * Tự động tạo danh sách category theo cây thư mục dựa trên chủ đề website
 * 
 * @package AIAutoTool
 * @subpackage AutoCreateCategories
 * @since 1.0.0
 */

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

if (!class_exists('AIAutoTool_AutoCreateCategories')) {
    class AIAutoTool_AutoCreateCategories extends rendersetting {
        
        /**
         * Flag to prevent multiple initialization
         */
        private static $initialized = false;
        
        /**
         * Flag to prevent duplicate hooks registration in init()
         */
        private static $init_hooks_registered = false;
        
        /**
         * Flag to prevent duplicate hooks registration in add_category_meta_box()
         */
        private static $hooks_registered = false;
        
        /**
         * Flag to prevent duplicate rendering
         */
        private static $rendered = false;
        
        public $active = false;
        public $active_option_name = 'AIAutoTool_auto_create_categories_active';
        public $icon = '<i class="fa-solid fa-sitemap"></i>';
        public $name_plan;
        
        public function __construct() {
            // Prevent multiple initialization of hooks and actions
            // Check if this instance's class has already been initialized
            $class_name = get_class($this);
            
            // If already initialized, skip hook registration
            if (self::$initialized) {
                // Still set basic properties for this instance
                $this->name_plan = __('Auto Create Categories', 'ai-auto-tool');
                $this->active_option_name = 'AIAutoTool_auto_create_categories_active';
                $this->active = get_option($this->active_option_name, 'false');
                return;
            }
            
            // Mark as initialized
            self::$initialized = true;
            
            $this->name_plan = __('Auto Create Categories', 'ai-auto-tool');
            $this->active_option_name = 'AIAutoTool_auto_create_categories_active';
            $this->active = get_option($this->active_option_name, 'false');
            
            if ($this->active == 'true') {
                $this->init();
            }
            
            // Register AJAX handler only once
            add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
        }
        
        public function update_active_option_callback() {
            check_ajax_referer('aiautotool_nonce', 'security');
            
            if (!current_user_can('manage_options')) {
                wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
            }
            
            if (isset($_POST['active'])) {
                $active = sanitize_text_field($_POST['active']);
                update_option($this->active_option_name, $active, null, 'no');
                print_r($active);
            }
            
            wp_die();
        }
        
        public function init() {
            // Prevent duplicate hooks registration in init()
            if (self::$init_hooks_registered) {
                return;
            }
            
            self::$init_hooks_registered = true;
            
            // Enqueue scripts and styles on category edit page
            add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
            
            // Add meta box to category edit page
            add_action('admin_init', array($this, 'add_category_meta_box'));
            
            // Register settings
            add_action('admin_init', array($this, 'register_settings'));
            
            // AJAX handlers
            add_action('wp_ajax_aiautotool_generate_category_tree', array($this, 'ajax_generate_category_tree'));
            add_action('wp_ajax_aiautotool_create_categories', array($this, 'ajax_create_categories'));
            
            // AJAX handlers for auto write descriptions
            add_action('wp_ajax_aiautotool_get_categories', array($this, 'ajax_get_categories'));
            add_action('wp_ajax_aiautotool_generate_category_description', array($this, 'ajax_generate_category_description'));
            add_action('wp_ajax_aiautotool_save_category_description', array($this, 'ajax_save_category_description'));
            add_action('wp_ajax_aiautotool_schedule_cron_descriptions', array($this, 'ajax_schedule_cron_descriptions'));
            add_action('wp_ajax_aiautotool_get_cron_descriptions_status', array($this, 'ajax_get_cron_status'));
            add_action('wp_ajax_aiautotool_get_cron_status', array($this, 'ajax_get_cron_status'));
            
            // Cron job for background processing
            add_filter('cron_schedules', array($this, 'add_category_desc_cron_schedule'));
            add_action('aiautotool_auto_write_category_descriptions', array($this, 'cron_write_category_descriptions'));
            
            // Initialize cron if there are pending categories
            $this->maybe_schedule_cron();
        }
        
        /**
         * Maybe schedule cron if there are pending categories
         */
        private function maybe_schedule_cron() {
            $pending = get_option('aiautotool_pending_category_descriptions', array());
            if (!empty($pending) && !wp_next_scheduled('aiautotool_auto_write_category_descriptions')) {
                wp_schedule_event(time(), 'aiautotool_category_desc_interval', 'aiautotool_auto_write_category_descriptions');
            }
        }
        
        /**
         * Register settings
         */
        public function register_settings() {
            register_setting(
                'aiautotool_auto_categories_settings',
                'aiautotool_auto_categories_enabled_taxonomies',
                array(
                    'type' => 'array',
                    'sanitize_callback' => array($this, 'sanitize_taxonomies'),
                    'default' => array('category')
                )
            );
        }
        
        /**
         * Sanitize taxonomies array
         */
        public function sanitize_taxonomies($taxonomies) {
            if (!is_array($taxonomies)) {
                return array('category');
            }
            
            // Validate each taxonomy exists
            $valid_taxonomies = get_taxonomies(array('public' => true));
            $sanitized = array();
            
            foreach ($taxonomies as $taxonomy) {
                $taxonomy = sanitize_text_field($taxonomy);
                if (in_array($taxonomy, $valid_taxonomies)) {
                    $sanitized[] = $taxonomy;
                }
            }
            
            // Always include category if empty
            if (empty($sanitized)) {
                $sanitized = array('category');
            }
            
            return $sanitized;
        }
        
        /**
         * Enqueue scripts and styles
         */
        public function enqueue_assets($hook) {
            // Only load on taxonomy edit page
            if ($hook !== 'edit-tags.php' && $hook !== 'term.php') {
                return;
            }
            
            global $current_screen;
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            
            if (!isset($current_screen->taxonomy) || !in_array($current_screen->taxonomy, $enabled_taxonomies)) {
                return;
            }
            
            // Get plugin URL for Font Awesome
            $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(dirname(__FILE__))));
            
            // Enqueue Font Awesome for icons
            wp_enqueue_style(
                'font-awesome-auto-categories',
                $plugin_url . 'js/fontawesome/css/all.min.css',
                array(),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0'
            );
            
            // Enqueue CSS
            wp_enqueue_style(
                'auto-create-categories-css',
                plugin_dir_url(__FILE__) . 'assets/css/auto-create-categories.css',
                array('font-awesome-auto-categories'),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0'
            );
            
            // Enqueue JS
            wp_enqueue_script(
                'auto-create-categories-js',
                plugin_dir_url(__FILE__) . 'assets/js/auto-create-categories.js',
                array('jquery'),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0',
                true
            );
            
            // Localize script
            wp_localize_script('auto-create-categories-js', 'autoCreateCategories', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('aiautotool_auto_categories_nonce'),
                'ajaxurl_settings' => admin_url('admin-ajax.php'),
                'strings' => array(
                    'generating' => __('Generating category list...', 'ai-auto-tool'),
                    'error' => __('An error occurred. Please try again.', 'ai-auto-tool'),
                    'creating' => __('Creating categories...', 'ai-auto-tool'),
                    'success' => __('Categories created successfully!', 'ai-auto-tool'),
                    'confirm_delete' => __('Are you sure you want to delete this category?', 'ai-auto-tool'),
                    'please_enter_topic' => __('Please enter a topic', 'ai-auto-tool'),
                    'invalid_data' => __('Invalid data', 'ai-auto-tool'),
                    'no_data_to_add' => __('No category data to add', 'ai-auto-tool'),
                    'created_successfully' => __('Created successfully', 'ai-auto-tool'),
                    'categories' => __('categories', 'ai-auto-tool'),
                    'errors' => __('Errors', 'ai-auto-tool'),
                    'error_occurred' => __('An error occurred while creating categories', 'ai-auto-tool'),
                    'analyzing' => __('Analyzing and generating category tree...', 'ai-auto-tool'),
                    'delete' => __('Delete', 'ai-auto-tool'),
                    'category_tree_list' => __('Category Tree List:', 'ai-auto-tool'),
                    'step_enter_topic' => __('Enter Topic', 'ai-auto-tool'),
                    'step_review_edit' => __('Review & Edit', 'ai-auto-tool'),
                    'previous' => __('Previous', 'ai-auto-tool'),
                    'next' => __('Next', 'ai-auto-tool'),
                    // New strings for description feature
                    'auto_write_descriptions' => __('Auto Write Category Descriptions', 'ai-auto-tool'),
                    'select_categories' => __('Select Categories', 'ai-auto-tool'),
                    'generating_descriptions' => __('Generating Descriptions', 'ai-auto-tool'),
                    'select_categories_first' => __('Please select at least one category', 'ai-auto-tool'),
                    'generating_desc_for' => __('Generating description for', 'ai-auto-tool'),
                    'description_generated' => __('Description generated successfully', 'ai-auto-tool'),
                    'description_saved' => __('Description saved successfully', 'ai-auto-tool'),
                    'all_descriptions_completed' => __('All descriptions completed!', 'ai-auto-tool'),
                    'enable_cron' => __('Enable Auto Run (Cron)', 'ai-auto-tool'),
                    'run_now' => __('Run Now', 'ai-auto-tool'),
                    'processing' => __('Processing...', 'ai-auto-tool'),
                    'completed' => __('Completed', 'ai-auto-tool'),
                    'failed' => __('Failed', 'ai-auto-tool'),
                    'view_cron_status' => __('View Cron Status', 'ai-auto-tool'),
                    'pending' => __('Pending', 'ai-auto-tool'),
                    'completed_label' => __('Completed', 'ai-auto-tool'),
                    'next_run' => __('Next Run', 'ai-auto-tool'),
                    'cron_status' => __('Cron Status', 'ai-auto-tool'),
                    'not_scheduled' => __('Not Scheduled', 'ai-auto-tool'),
                    'next_category' => __('Next Category to Process', 'ai-auto-tool'),
                    'position' => __('Position', 'ai-auto-tool'),
                    'pending_categories' => __('Pending Categories', 'ai-auto-tool'),
                    'no' => __('No.', 'ai-auto-tool'),
                    'category_name' => __('Category Name', 'ai-auto-tool'),
                    'taxonomy' => __('Taxonomy', 'ai-auto-tool'),
                    'status' => __('Status', 'ai-auto-tool'),
                    'waiting' => __('Waiting', 'ai-auto-tool'),
                    'no_pending' => __('No pending categories. All descriptions have been generated!', 'ai-auto-tool'),
                    'recently_completed' => __('Recently Completed', 'ai-auto-tool'),
                    'showing_last_20' => __('Showing last 20 completed. Total:', 'ai-auto-tool'),
                )
            ));
        }
        
        /**
         * Add meta box to category edit page
         */
        public function add_category_meta_box() {
            // Prevent duplicate hooks registration
            if (self::$hooks_registered) {
                return;
            }
            
            global $pagenow;
            
            // Only on edit-tags.php
            if ($pagenow === 'edit-tags.php') {
                // Get enabled taxonomies
                $enabled_taxonomies = $this->get_enabled_taxonomies();
                
                // Add hooks for each enabled taxonomy
                foreach ($enabled_taxonomies as $taxonomy) {
                    add_action($taxonomy . '_add_form_fields', array($this, 'render_category_meta_box'));
                    add_action($taxonomy . '_edit_form_fields', array($this, 'render_category_meta_box'));
                }
                
                // Also add to admin_footer for the list page
                add_action('admin_footer', array($this, 'render_category_meta_box'));
                
                // Mark as registered
                self::$hooks_registered = true;
            }
        }
        
        /**
         * Get enabled taxonomies
         */
        private function get_enabled_taxonomies() {
            $enabled = get_option('aiautotool_auto_categories_enabled_taxonomies', array('category'));
            // Ensure it's an array
            if (!is_array($enabled)) {
                $enabled = array('category');
            }
            return $enabled;
        }
        
        /**
         * Render meta box HTML
         */
        public function render_category_meta_box() {
            // Prevent duplicate rendering - only render once per page load
            if (self::$rendered) {
                return;
            }
            
            global $current_screen, $pagenow;
            
            // Check if current taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            
            // Determine current taxonomy
            $current_taxonomy = '';
            if (isset($current_screen->taxonomy)) {
                $current_taxonomy = $current_screen->taxonomy;
            } elseif ($pagenow === 'edit-tags.php' && isset($_GET['taxonomy'])) {
                $current_taxonomy = sanitize_text_field($_GET['taxonomy']);
            }
            
            // Only render if taxonomy is enabled
            if (empty($current_taxonomy) || !in_array($current_taxonomy, $enabled_taxonomies)) {
                return;
            }
            
            // Mark as rendered to prevent duplicate
            self::$rendered = true;
            ?>
            <!-- Hidden container - will be moved to left column by JavaScript -->
            <div id="auto-create-categories-meta-box" style="display: none;">
                <!-- Cron Status Widget -->
                <div id="cron-descriptions-status-widget" class="cron-descriptions-status-widget" style="display: none;">
                    <div class="cron-status-header">
                        <h3>
                            <i class="fa-solid fa-clock"></i> 
                            <?php esc_html_e('Auto Write Descriptions - Cron Status', 'ai-auto-tool'); ?>
                        </h3>
                        <button type="button" class="button button-small" id="refresh-cron-status" style="margin-left: auto;">
                            <i class="fa-solid fa-sync-alt"></i> <?php esc_html_e('Refresh', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                    <div id="cron-status-content">
                        <div class="loading-indicator">
                            <div class="spinner is-active"></div>
                            <p><?php esc_html_e('Loading status...', 'ai-auto-tool'); ?></p>
                        </div>
                    </div>
                </div>
                
                <!-- Trigger Buttons -->
                <div class="auto-create-categories-trigger">
                    <button type="button" id="open-auto-categories-modal" class="button button-primary button-large">
                        <i class="fa-solid fa-sitemap"></i> 
                        <?php esc_html_e('Auto Create Category Tree', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="open-auto-descriptions-modal" class="button button-secondary button-large" style="margin-left: 10px;">
                        <i class="fa-solid fa-file-lines"></i> 
                        <?php esc_html_e('Auto Write Category Descriptions', 'ai-auto-tool'); ?>
                    </button>
                    <button type="button" id="open-cron-status-modal" class="button button-secondary button-large" style="margin-left: 10px;">
                        <i class="fa-solid fa-clock"></i> 
                        <?php esc_html_e('View Cron Status', 'ai-auto-tool'); ?>
                    </button>
                </div>
                
                <!-- Modal Overlay -->
                <div id="auto-create-categories-overlay" class="auto-create-categories-overlay" style="display: none;">
                    <div class="auto-create-categories-modal">
                        <div class="auto-create-categories-modal-header">
                            <h2>
                                <i class="fa-solid fa-sitemap"></i> 
                                <?php esc_html_e('Auto Create Category Tree', 'ai-auto-tool'); ?>
                            </h2>
                            <button type="button" class="auto-create-categories-close" id="close-auto-categories-modal">
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                        
                        <div class="auto-create-categories-modal-body">
                            <div class="auto-create-categories-container">
                                <div class="aiautotool-card">
                                    <div class="aiautotool-card-header">
                                        <p>
                                            <?php esc_html_e('Enter your website topic or category. AI will automatically analyze and generate a category tree structure optimized for SEO.', 'ai-auto-tool'); ?>
                                        </p>
                                    </div>
                                    
                                    <!-- Step Header -->
                                    <div class="step-header">
                                        <div class="step-item active" data-step="1">
                                            <div class="step-number">1</div>
                                            <div class="step-label"><?php esc_html_e('Enter Topic', 'ai-auto-tool'); ?></div>
                                        </div>
                                        <div class="step-connector"></div>
                                        <div class="step-item" data-step="2">
                                            <div class="step-number">2</div>
                                            <div class="step-label"><?php esc_html_e('Review & Edit', 'ai-auto-tool'); ?></div>
                                        </div>
                                    </div>
                                    
                                    <div class="aiautotool-card-body">
                                        <!-- Step 1: Input Topic -->
                                        <div class="step-content" id="step-1">
                                            <div class="form-group">
                                                <label for="category-topic">
                                                    <strong><?php esc_html_e('Website Topic/Category:', 'ai-auto-tool'); ?></strong>
                                                </label>
                                                <input 
                                                    type="text" 
                                                    id="category-topic" 
                                                    class="regular-text" 
                                                    placeholder="<?php esc_attr_e('Example: car reviews, technology, travel...', 'ai-auto-tool'); ?>"
                                                    style="width: 100%; padding: 10px; margin-top: 10px;"
                                                />
                                            </div>
                                            
                                            <div class="form-group" style="margin-top: 20px;">
                                                <label for="category-language">
                                                    <strong><?php esc_html_e('Output Language:', 'ai-auto-tool'); ?></strong>
                                                </label>
                                                <select 
                                                    id="category-language" 
                                                    class="regular-text" 
                                                    style="width: 100%; padding: 10px; margin-top: 10px; height: 42px;"
                                                >
                                                    <?php
                                                    // Use languageCodes from parent class (rendersetting)
                                                    $language_codes = $this->languageCodes;
                                                    $default_lang = get_locale();
                                                    $default_lang_code = substr($default_lang, 0, 2); // Get first 2 chars (e.g., 'en' from 'en_US')
                                                    
                                                    // If default language is not in the list, default to 'en'
                                                    if (!isset($language_codes[$default_lang_code])) {
                                                        $default_lang_code = 'en';
                                                    }
                                                    
                                                    foreach ($language_codes as $code => $name) {
                                                        $selected = ($code === $default_lang_code) ? 'selected' : '';
                                                        echo '<option value="' . esc_attr($code) . '" ' . $selected . '>' . esc_html($name) . '</option>';
                                                    }
                                                    ?>
                                                </select>
                                                <p style="margin-top: 5px; font-size: 12px; color: #646970;">
                                                    <?php esc_html_e('Select the language for the generated category names.', 'ai-auto-tool'); ?>
                                                </p>
                                            </div>
                                            
                                            <div id="loading-indicator" class="loading-indicator" style="display: none;">
                                                <div class="spinner is-active"></div>
                                                <p><?php esc_html_e('Analyzing and generating category tree...', 'ai-auto-tool'); ?></p>
                                            </div>
                                            
                                            <div id="error-message" class="error-message" style="display: none;"></div>
                                            
                                            <!-- Step Navigation -->
                                            <div class="step-navigation">
                                                <div></div>
                                                <button type="button" id="generate-category-tree" class="button button-primary button-large">
                                                    <i class="fa-solid fa-magic"></i> 
                                                    <?php esc_html_e('Generate Category Tree', 'ai-auto-tool'); ?>
                                                    <i class="fa-solid fa-arrow-right" style="margin-left: 8px;"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <!-- Step 2: Review and Edit Tree -->
                                        <div class="step-content" id="step-2" style="display: none;">
                                            <div class="category-tree-container">
                                                <h3><?php esc_html_e('Category Tree List:', 'ai-auto-tool'); ?></h3>
                                                <div id="category-tree-preview"></div>
                                            </div>
                                            
                                            <div id="add-progress" class="add-progress" style="display: none;">
                                                <div class="progress-bar">
                                                    <div class="progress-fill" id="progress-fill">0%</div>
                                                </div>
                                                <p class="progress-text" id="progress-text"></p>
                                            </div>
                                            
                                            <div id="success-message" class="success-message" style="display: none;"></div>
                                            
                                            <!-- Step Navigation -->
                                            <div class="step-navigation">
                                                <button type="button" id="prev-to-step-1" class="button">
                                                    <i class="fa-solid fa-arrow-left" style="margin-right: 8px;"></i>
                                                    <?php esc_html_e('Previous', 'ai-auto-tool'); ?>
                                                </button>
                                                <button type="button" id="add-categories" class="button button-primary button-large">
                                                    <i class="fa-solid fa-plus"></i> 
                                                    <?php esc_html_e('Add Categories to WordPress', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Auto Write Descriptions Modal -->
                <div id="auto-write-descriptions-overlay" class="auto-create-categories-overlay" style="display: none;">
                    <div class="auto-create-categories-modal">
                        <div class="auto-create-categories-modal-header">
                            <h2>
                                <i class="fa-solid fa-file-lines"></i> 
                                <?php esc_html_e('Auto Write Category Descriptions', 'ai-auto-tool'); ?>
                            </h2>
                            <button type="button" class="auto-create-categories-close" id="close-auto-descriptions-modal">
                                <i class="fa-solid fa-times"></i>
                            </button>
                                        </div>
                        
                        <div class="auto-create-categories-modal-body">
                            <div class="auto-create-categories-container">
                                <div class="aiautotool-card">
                                    <div class="aiautotool-card-header">
                                        <p>
                                            <?php esc_html_e('Select categories to automatically generate SEO-optimized descriptions using AI.', 'ai-auto-tool'); ?>
                                        </p>
                                    </div>
                                    
                                    <!-- Step Header -->
                                    <div class="step-header">
                                        <div class="step-item active" data-step="1">
                                            <div class="step-number">1</div>
                                            <div class="step-label"><?php esc_html_e('Select Categories', 'ai-auto-tool'); ?></div>
                                </div>
                                        <div class="step-connector"></div>
                                        <div class="step-item" data-step="2">
                                            <div class="step-number">2</div>
                                            <div class="step-label"><?php esc_html_e('Generating Descriptions', 'ai-auto-tool'); ?></div>
                            </div>
                        </div>
                                    
                                    <div class="aiautotool-card-body">
                                        <!-- Step 1: Select Categories -->
                                        <div class="step-content" id="desc-step-1">
                                            <div class="form-group">
                                                <label for="category-selector">
                                                    <strong><?php esc_html_e('Select Categories:', 'ai-auto-tool'); ?></strong>
                                                </label>
                                                <div id="category-selector-container" style="max-height: 400px; overflow-y: auto; border: 1px solid #8c8f94; border-radius: 4px; padding: 15px; margin-top: 10px; background: #fff;">
                                                    <div class="loading-indicator" id="categories-loading">
                                                        <div class="spinner is-active"></div>
                                                        <p><?php esc_html_e('Loading categories...', 'ai-auto-tool'); ?></p>
                    </div>
                                                    <div id="categories-list" style="display: none;"></div>
                                                </div>
                                                <p style="margin-top: 10px; font-size: 12px; color: #646970;">
                                                    <?php esc_html_e('Select one or more categories to generate descriptions for.', 'ai-auto-tool'); ?>
                                                </p>
                                            </div>
                                            
                                            <div class="form-group" style="margin-top: 20px;">
                                                <label>
                                                    <input type="checkbox" id="enable-cron-desc" style="margin-right: 8px;">
                                                    <strong><?php esc_html_e('Enable Auto Run (Cron)', 'ai-auto-tool'); ?></strong>
                                                </label>
                                                <p style="margin-top: 5px; font-size: 12px; color: #646970; margin-left: 24px;">
                                                    <?php esc_html_e('Process categories in background using cron job. Descriptions will be generated sequentially.', 'ai-auto-tool'); ?>
                                                </p>
                                            </div>
                                            
                                            <div id="desc-error-message" class="error-message" style="display: none;"></div>
                                            
                                            <!-- Step Navigation -->
                                            <div class="step-navigation">
                                                <div></div>
                                                <button type="button" id="start-generate-descriptions" class="button button-primary button-large">
                                                    <i class="fa-solid fa-magic"></i> 
                                                    <?php esc_html_e('Start Generating', 'ai-auto-tool'); ?>
                                                    <i class="fa-solid fa-arrow-right" style="margin-left: 8px;"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <!-- Step 2: Generating Descriptions -->
                                        <div class="step-content" id="desc-step-2" style="display: none;">
                                            <div class="category-tree-container">
                                                <h3><?php esc_html_e('Processing Categories:', 'ai-auto-tool'); ?></h3>
                                                <div id="descriptions-progress-list"></div>
                                            </div>
                                            
                                            <div id="desc-progress" class="add-progress" style="display: none;">
                                                <div class="progress-bar">
                                                    <div class="progress-fill" id="desc-progress-fill">0%</div>
                                                </div>
                                                <p class="progress-text" id="desc-progress-text"></p>
                                            </div>
                                            
                                            <div id="desc-success-message" class="success-message" style="display: none;"></div>
                                            
                                            <!-- Step Navigation -->
                                            <div class="step-navigation">
                                                <button type="button" id="desc-prev-to-step-1" class="button" style="display: none;">
                                                    <i class="fa-solid fa-arrow-left" style="margin-right: 8px;"></i>
                                                    <?php esc_html_e('Back', 'ai-auto-tool'); ?>
                                                </button>
                                                <div></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Cron Status Modal -->
                <div id="cron-status-overlay" class="auto-create-categories-overlay" style="display: none;">
                    <div class="auto-create-categories-modal" style="max-width: 1000px;">
                        <div class="auto-create-categories-modal-header">
                            <h2>
                                <i class="fa-solid fa-clock"></i> 
                                <?php esc_html_e('Cron Status - Auto Write Descriptions', 'ai-auto-tool'); ?>
                            </h2>
                            <button type="button" class="auto-create-categories-close" id="close-cron-status-modal">
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                        
                        <div class="auto-create-categories-modal-body">
                            <div class="auto-create-categories-container">
                                <div class="aiautotool-card">
                                    <div class="aiautotool-card-header">
                                        <p>
                                            <?php esc_html_e('View the status of background cron jobs that are generating category descriptions.', 'ai-auto-tool'); ?>
                                        </p>
                                    </div>
                                    
                                    <div class="aiautotool-card-body">
                                        <div id="cron-status-modal-content">
                                            <div class="loading-indicator">
                                                <div class="spinner is-active"></div>
                                                <p><?php esc_html_e('Loading cron status...', 'ai-auto-tool'); ?></p>
                                            </div>
                                        </div>
                                        
                                        <div class="step-navigation" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e5e5;">
                                            <button type="button" class="button button-small" id="refresh-cron-status-modal">
                                                <i class="fa-solid fa-sync-alt"></i> 
                                                <?php esc_html_e('Refresh', 'ai-auto-tool'); ?>
                                            </button>
                                            <div></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        
        /**
         * AJAX: Generate category tree using AI
         */
        public function ajax_generate_category_tree() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $topic = isset($_POST['topic']) ? sanitize_text_field($_POST['topic']) : '';
            $language = isset($_POST['language']) ? sanitize_text_field($_POST['language']) : 'en';
            
            if (empty($topic)) {
                wp_send_json_error(array('message' => __('Please enter a topic', 'ai-auto-tool')));
            }
            
            // Validate language - use languageCodes from parent class (rendersetting)
            $supported_languages = $this->languageCodes;
            if (!isset($supported_languages[$language])) {
                $language = 'en'; // Default to English if invalid
            }
            $language_name = isset($supported_languages[$language]) ? $supported_languages[$language] : 'English';
            
            // Check if AI Helper is available
            if (!class_exists('AIAutotool_AI_Helper')) {
                wp_send_json_error(array('message' => __('AI Helper is not available. Please check AI Provider configuration.', 'ai-auto-tool')));
            }
            
            if (!AIAutotool_AI_Helper::is_available()) {
                wp_send_json_error(array('message' => __('AI Provider is not configured. Please configure it in AI Provider Settings.', 'ai-auto-tool')));
            }
            
            // Build prompt for AI with language
            $prompt = $this->build_category_tree_prompt($topic, $language, $language_name);
            
            // Call AI
            $messages = array(
                array(
                    'role' => 'system',
                    'content' => __('You are an SEO and website content architecture expert. Your task is to create a category tree (site structure) optimized for SEO using the topic cluster model. Return ONLY JSON result, no other text.', 'ai-auto-tool')
                ),
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            );
            
            $result = AIAutotool_AI_Helper::chat($messages, array(
                'temperature' => 0.7,
                'max_tokens' => 2000
            ));
            
            if (!$result['success']) {
                $error_message = isset($result['error']) && !empty($result['error']) 
                    ? $result['error'] 
                    : 'Unknown error occurred. Please check your AI provider configuration and try again.';
                
                // Log detailed error for debugging
                
                wp_send_json_error(array(
                    'message' => __('Error calling AI: ', 'ai-auto-tool') . $error_message
                ));
            }
            
            $content = $result['content'];
            
            // Extract JSON from response
            $json_data = $this->extract_json_from_response($content);
            
            if (!$json_data) {
                wp_send_json_error(array('message' => __('Unable to parse AI response. Please try again.', 'ai-auto-tool')));
            }
            
            // Validate structure
            if (!isset($json_data['mainTopic']) || !isset($json_data['categoryTree'])) {
                wp_send_json_error(array('message' => __('Invalid data structure.', 'ai-auto-tool')));
            }
            
            wp_send_json_success($json_data);
        }
        
        /**
         * Build prompt for category tree generation
         */
        private function build_category_tree_prompt($topic, $language_code = 'en', $language_name = 'English') {
            $prompt = sprintf(__("You are an SEO and website content architecture expert.

Your task:
- Input: ** %s **
- Create a **category tree structure** (site structure).
- IMPORTANT: All category names must be in %s language.
- Categories must be clearly hierarchical: 
  - Main Category
  - Level 1 Sub-category
  - Level 2 Sub-category (if needed)
- Content must:
  - Cover the entire topic
  - No duplicates
  - SEO optimized using topic clusters
  - Useful for users and easy to navigate
  - All category names written in %s
- Return the following JSON format (NO OTHER TEXT, JSON ONLY):

{
  \"mainTopic\": \"%s\",
  \"categoryTree\": [
    {
      \"category\": \"Main category name in %s\",
      \"sub\": [
        {
          \"subCategory\": \"Sub category 1 name in %s\",
          \"sub\": [
            \"Level 2 sub category in %s (if any)\"
          ]
        }
      ]
    }
  ]
}

Start! Create a category tree for a website with topic: **%s** in %s language.", 'ai-auto-tool'), 
                $topic, 
                $language_name, 
                $language_name,
                $topic,
                $language_name,
                $language_name,
                $language_name,
                $topic,
                $language_name
            );
            
            return $prompt;
        }
        
        /**
         * Extract JSON from AI response
         */
        private function extract_json_from_response($content) {
            // Try to find JSON in the response
            // Remove markdown code blocks if present
            $content = preg_replace('/```json\s*/', '', $content);
            $content = preg_replace('/```\s*/', '', $content);
            $content = trim($content);
            
            // Try to find JSON object
            $pattern = '/\{[\s\S]*\}/';
            preg_match($pattern, $content, $matches);
            
            if (!empty($matches[0])) {
                $json_string = $matches[0];
                $json_data = json_decode($json_string, true);
                
                if (json_last_error() === JSON_ERROR_NONE) {
                    return $json_data;
                }
            }
            
            // Try direct decode
            $json_data = json_decode($content, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return $json_data;
            }
            
            return false;
        }
        
        /**
         * AJAX: Create categories from tree
         */
        public function ajax_create_categories() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $category_tree = isset($_POST['categoryTree']) ? $_POST['categoryTree'] : array();
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool')));
            }
            
            if (empty($category_tree) || !is_array($category_tree)) {
                wp_send_json_error(array('message' => __('Invalid category tree data', 'ai-auto-tool')));
            }
            
            $created = array();
            $errors = array();
            
            // Process each main category
            foreach ($category_tree as $main_category) {
                if (!isset($main_category['category']) || empty($main_category['category'])) {
                    continue;
                }
                
                $main_cat_name = sanitize_text_field($main_category['category']);
                
                // Create main category
                $main_cat_id = $this->create_category($main_cat_name, 0, $taxonomy);
                
                if (is_wp_error($main_cat_id)) {
                    $errors[] = sprintf(__('Error creating category "%s": %s', 'ai-auto-tool'), $main_cat_name, $main_cat_id->get_error_message());
                    continue;
                }
                
                $created[] = array(
                    'name' => $main_cat_name,
                    'id' => $main_cat_id,
                    'parent' => 0,
                    'level' => 0
                );
                
                // Process sub-categories level 1
                if (isset($main_category['sub']) && is_array($main_category['sub'])) {
                    foreach ($main_category['sub'] as $sub1) {
                        if (!isset($sub1['subCategory']) || empty($sub1['subCategory'])) {
                            continue;
                        }
                        
                        $sub1_name = sanitize_text_field($sub1['subCategory']);
                        $sub1_id = $this->create_category($sub1_name, $main_cat_id, $taxonomy);
                        
                        if (is_wp_error($sub1_id)) {
                            $errors[] = sprintf(__('Error creating sub-category "%s": %s', 'ai-auto-tool'), $sub1_name, $sub1_id->get_error_message());
                            continue;
                        }
                        
                        $created[] = array(
                            'name' => $sub1_name,
                            'id' => $sub1_id,
                            'parent' => $main_cat_id,
                            'level' => 1
                        );
                        
                        // Process sub-categories level 2
                        if (isset($sub1['sub']) && is_array($sub1['sub'])) {
                            foreach ($sub1['sub'] as $sub2_name) {
                                if (empty($sub2_name)) {
                                    continue;
                                }
                                
                                $sub2_name = sanitize_text_field($sub2_name);
                                $sub2_id = $this->create_category($sub2_name, $sub1_id, $taxonomy);
                                
                                if (is_wp_error($sub2_id)) {
                                    $errors[] = sprintf(__('Error creating level 2 sub-category "%s": %s', 'ai-auto-tool'), $sub2_name, $sub2_id->get_error_message());
                                    continue;
                                }
                                
                                $created[] = array(
                                    'name' => $sub2_name,
                                    'id' => $sub2_id,
                                    'parent' => $sub1_id,
                                    'level' => 2
                                );
                            }
                        }
                    }
                }
            }
            
            wp_send_json_success(array(
                'created' => $created,
                'errors' => $errors,
                'total' => count($created)
            ));
        }
        
        /**
         * Create a category
         */
        private function create_category($name, $parent_id = 0, $taxonomy = 'category') {
            // Check if category already exists
            $existing = term_exists($name, $taxonomy, $parent_id);
            
            if ($existing !== null && $existing !== 0) {
                // Category exists, return its ID
                return is_array($existing) ? $existing['term_id'] : $existing;
            }
            
            // Create new category
            $result = wp_insert_term(
                $name,
                $taxonomy,
                array(
                    'parent' => $parent_id
                )
            );
            
            if (is_wp_error($result)) {
                return $result;
            }
            
            return $result['term_id'];
        }
        
        /**
         * Render feature settings
         */
        public function render_setting() {
            if ($this->active != "true") {
                return '';
            }
            
            // Save settings
            if (isset($_POST['aiautotool_auto_categories_save_settings']) && check_admin_referer('aiautotool_auto_categories_settings')) {
                $enabled_taxonomies = isset($_POST['enabled_taxonomies']) ? array_map('sanitize_text_field', $_POST['enabled_taxonomies']) : array();
                update_option('aiautotool_auto_categories_enabled_taxonomies', $enabled_taxonomies, false);
                echo '<div class="updated"><p>' . esc_html__('Settings saved successfully!', 'ai-auto-tool') . '</p></div>';
            }
            
            $enabled_taxonomies = get_option('aiautotool_auto_categories_enabled_taxonomies', array('category'));
            
            // Get all taxonomies
            $taxonomies = get_taxonomies(array('public' => true), 'objects');
            
            ?>
            <div id="tool-auto-create-categories" class="tab-content" style="display:none;">
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px; margin-bottom: 20px; color: white;">
                    <h2 style="margin: 0 0 10px 0; color: white; display: flex; align-items: center; gap: 10px;">
                        <i class="fa-solid fa-sitemap"></i> <?php echo esc_html__('Auto Create Categories Settings', 'ai-auto-tool'); ?>
                    </h2>
                    <p style="margin: 0; opacity: 0.95; font-size: 14px;">
                        <?php echo esc_html__('Select which taxonomies to enable for auto category creation and description generation.', 'ai-auto-tool'); ?>
                    </p>
                </div>
                
                <form method="post" action="">
                    <?php wp_nonce_field('aiautotool_auto_categories_settings'); ?>
                    
                    <div style="background: #f8f9fa; border-left: 4px solid #667eea; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                        <h3 style="margin: 0 0 10px 0; display: flex; align-items: center; gap: 10px;">
                            <i class="fa-solid fa-circle-info"></i> <?php echo esc_html__('Taxonomy Selection', 'ai-auto-tool'); ?>
                        </h3>
                        <p style="margin: 0 0 10px 0; color: #555; font-size: 14px; line-height: 1.6;">
                            <?php echo esc_html__('Enable the auto create categories and auto write descriptions features for the selected taxonomies. Only enabled taxonomies will show the feature buttons on their admin pages.', 'ai-auto-tool'); ?>
                        </p>
                    </div>
                    
                    <div style="background: #fff; border: 1px solid #e0e0e0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                        <h3 style="margin: 0 0 15px 0; display: flex; align-items: center; gap: 10px;">
                            <i class="fa-solid fa-list-check"></i> <?php echo esc_html__('Available Taxonomies', 'ai-auto-tool'); ?>
                        </h3>
                        
                        <div style="max-height: 500px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 15px; background: #fafafa;">
                            <?php if (empty($taxonomies)): ?>
                                <p style="color: #666;"><?php echo esc_html__('No taxonomies found.', 'ai-auto-tool'); ?></p>
                            <?php else: ?>
                                <table class="widefat" style="background: #fff;">
                                    <thead>
                                        <tr>
                                            <th style="width: 50px; text-align: center;">
                                                <input type="checkbox" id="select-all-taxonomies" style="cursor: pointer;">
                                            </th>
                                            <th><?php echo esc_html__('Taxonomy', 'ai-auto-tool'); ?></th>
                                            <th><?php echo esc_html__('Label', 'ai-auto-tool'); ?></th>
                                            <th><?php echo esc_html__('Type', 'ai-auto-tool'); ?></th>
                                            <th><?php echo esc_html__('Status', 'ai-auto-tool'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $index = 0;
                                        foreach ($taxonomies as $taxonomy): 
                                            $is_enabled = in_array($taxonomy->name, $enabled_taxonomies);
                                            $is_builtin = $taxonomy->_builtin;
                                            $index++;
                                        ?>
                                            <tr style="<?php echo $index % 2 === 0 ? 'background: #f9f9f9;' : ''; ?>">
                                                <td style="text-align: center;">
                                                    <input 
                                                        type="checkbox" 
                                                        name="enabled_taxonomies[]" 
                                                        value="<?php echo esc_attr($taxonomy->name); ?>"
                                                        id="taxonomy-<?php echo esc_attr($taxonomy->name); ?>"
                                                        <?php checked($is_enabled); ?>
                                                        style="cursor: pointer;"
                                                    >
                                                </td>
                                                <td>
                                                    <label for="taxonomy-<?php echo esc_attr($taxonomy->name); ?>" style="cursor: pointer; font-weight: 600;">
                                                        <?php echo esc_html($taxonomy->name); ?>
                                                    </label>
                                                </td>
                                                <td>
                                                    <?php echo esc_html($taxonomy->label); ?>
                                                </td>
                                                <td>
                                                    <?php if ($is_builtin): ?>
                                                        <span style="padding: 4px 8px; background: #e3f2fd; color: #1976d2; border-radius: 3px; font-size: 11px; font-weight: 600;">
                                                            <?php echo esc_html__('Built-in', 'ai-auto-tool'); ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span style="padding: 4px 8px; background: #f3e5f5; color: #7b1fa2; border-radius: 3px; font-size: 11px; font-weight: 600;">
                                                            <?php echo esc_html__('Custom', 'ai-auto-tool'); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($is_enabled): ?>
                                                        <span style="padding: 4px 8px; background: #e8f5e9; color: #2e7d32; border-radius: 3px; font-size: 11px; font-weight: 600;">
                                                            <i class="fa-solid fa-check-circle"></i> <?php echo esc_html__('Enabled', 'ai-auto-tool'); ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span style="padding: 4px 8px; background: #ffebee; color: #c62828; border-radius: 3px; font-size: 11px; font-weight: 600;">
                                                            <i class="fa-solid fa-times-circle"></i> <?php echo esc_html__('Disabled', 'ai-auto-tool'); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                        
                        <p style="margin-top: 15px; padding: 12px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px; color: #856404; font-size: 13px;">
                            <i class="fa-solid fa-lightbulb"></i> <strong><?php echo esc_html__('Tip:', 'ai-auto-tool'); ?></strong> 
                            <?php echo esc_html__('Only enable taxonomies where you want to use the auto create categories and auto write descriptions features. Disabled taxonomies will not show the feature buttons.', 'ai-auto-tool'); ?>
                        </p>
                    </div>
                    
                    <p class="submit">
                        <input 
                            type="submit" 
                            name="aiautotool_auto_categories_save_settings" 
                            class="button button-primary button-large" 
                            value="💾 <?php echo esc_attr__('Save Settings', 'ai-auto-tool'); ?>" 
                            style="padding: 12px 24px; font-size: 15px; font-weight: 600;" 
                        />
                    </p>
                </form>
                
                <!-- Cron Status Section -->
                <div style="background: #fff; border: 1px solid #e0e0e0; padding: 20px; border-radius: 8px; margin-top: 30px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3 style="margin: 0; display: flex; align-items: center; gap: 10px;">
                            <i class="fa-solid fa-clock-rotate-left"></i> <?php echo esc_html__('Cron Job Status', 'ai-auto-tool'); ?>
                        </h3>
                        <button type="button" id="refresh-cron-status" class="button" style="padding: 8px 16px;">
                            <i class="fa-solid fa-arrow-rotate-right"></i> <?php echo esc_html__('Refresh', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                    
                    <div id="cron-status-container">
                        <div class="loading-indicator" style="text-align: center; padding: 20px;">
                            <div class="spinner is-active"></div>
                            <p><?php echo esc_html__('Loading status...', 'ai-auto-tool'); ?></p>
                        </div>
                    </div>
                </div>
                
                <script>
                jQuery(document).ready(function($) {
                    // Select all checkbox
                    $('#select-all-taxonomies').on('change', function() {
                        $('input[name="enabled_taxonomies[]"]').prop('checked', $(this).is(':checked'));
                    });
                    
                    // Update select all when individual checkboxes change
                    $('input[name="enabled_taxonomies[]"]').on('change', function() {
                        var total = $('input[name="enabled_taxonomies[]"]').length;
                        var checked = $('input[name="enabled_taxonomies[]"]:checked').length;
                        $('#select-all-taxonomies').prop('checked', total === checked);
                    });
                    
                    // Set initial state of select all
                    var total = $('input[name="enabled_taxonomies[]"]').length;
                    var checked = $('input[name="enabled_taxonomies[]"]:checked').length;
                    $('#select-all-taxonomies').prop('checked', total === checked);
                    
                    // Load cron status on page load
                    loadCronStatus();
                    
                    // Refresh button
                    $('#refresh-cron-status').on('click', function() {
                        loadCronStatus();
                    });
                    
                    // Auto refresh every 30 seconds
                    setInterval(function() {
                        loadCronStatus();
                    }, 30000);
                    
                    function loadCronStatus() {
                        $.ajax({
                            url: '<?php echo admin_url('admin-ajax.php'); ?>',
                            type: 'POST',
                            data: {
                                action: 'aiautotool_get_cron_status',
                                nonce: '<?php echo wp_create_nonce('aiautotool_auto_categories_nonce'); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    displayCronStatus(response.data);
                                } else {
                                    $('#cron-status-container').html('<p style="color: #d63638;">' + (response.data.message || 'Error loading status') + '</p>');
                                }
                            },
                            error: function() {
                                $('#cron-status-container').html('<p style="color: #d63638;">Error loading status</p>');
                            }
                        });
                    }
                    
                    function displayCronStatus(data) {
                        var html = '';
                        
                        if (!data.has_pending && !data.completed.length) {
                            html = '<div style="padding: 20px; text-align: center; color: #646970;">';
                            html += '<i class="fa-solid fa-check-circle" style="font-size: 48px; color: #00a32a; margin-bottom: 10px;"></i>';
                            html += '<p style="font-size: 16px; margin: 0;"><?php echo esc_js(__('No pending categories. All descriptions are completed!', 'ai-auto-tool')); ?></p>';
                            html += '</div>';
                        } else {
                            // Next to process
                            if (data.next_category) {
                                html += '<div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
                                html += '<h4 style="margin: 0 0 10px 0; color: #1976d2; display: flex; align-items: center; gap: 8px;">';
                                html += '<i class="fa-solid fa-arrow-right"></i> <?php echo esc_js(__('Next to Process', 'ai-auto-tool')); ?>';
                                html += '</h4>';
                                html += '<div style="display: flex; align-items: center; gap: 10px;">';
                                html += '<strong>' + escapeHtml(data.next_category.name) + '</strong>';
                                html += '<span style="padding: 4px 8px; background: #fff; border-radius: 3px; font-size: 11px; color: #666;">' + escapeHtml(data.next_category.taxonomy) + '</span>';
                                html += '</div>';
                                html += '</div>';
                            }
                            
                            // Pending list
                            if (data.pending.length > 0) {
                                html += '<div style="margin-bottom: 20px;">';
                                html += '<h4 style="margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 8px;">';
                                html += '<i class="fa-solid fa-clock"></i> <?php echo esc_js(__('Pending Categories', 'ai-auto-tool')); ?> (' + data.pending.length + ')';
                                html += '</h4>';
                                html += '<div style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; background: #fafafa;">';
                                html += '<table class="widefat" style="background: #fff; margin: 0;">';
                                html += '<thead><tr><th style="padding: 10px;"><?php echo esc_js(__('Category', 'ai-auto-tool')); ?></th><th style="padding: 10px;"><?php echo esc_js(__('Taxonomy', 'ai-auto-tool')); ?></th><th style="padding: 10px; width: 100px;"><?php echo esc_js(__('Position', 'ai-auto-tool')); ?></th></tr></thead>';
                                html += '<tbody>';
                                data.pending.forEach(function(cat, index) {
                                    html += '<tr style="' + (index % 2 === 0 ? 'background: #f9f9f9;' : '') + '">';
                                    html += '<td style="padding: 10px;"><strong>' + escapeHtml(cat.name) + '</strong></td>';
                                    html += '<td style="padding: 10px;"><span style="padding: 4px 8px; background: #e3f2fd; border-radius: 3px; font-size: 11px;">' + escapeHtml(cat.taxonomy) + '</span></td>';
                                    html += '<td style="padding: 10px; text-align: center;"><span style="padding: 4px 8px; background: #fff3cd; border-radius: 3px; font-size: 11px; font-weight: 600;">#' + (index + 1) + '</span></td>';
                                    html += '</tr>';
                                });
                                html += '</tbody></table>';
                                html += '</div>';
                                html += '</div>';
                            }
                            
                            // Completed list
                            if (data.completed.length > 0) {
                                html += '<div>';
                                html += '<h4 style="margin: 0 0 15px 0; color: #333; display: flex; align-items: center; gap: 8px;">';
                                html += '<i class="fa-solid fa-check-circle" style="color: #00a32a;"></i> <?php echo esc_js(__('Completed Categories', 'ai-auto-tool')); ?> (' + data.completed.length + ')';
                                html += '</h4>';
                                html += '<div style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; background: #fafafa;">';
                                html += '<table class="widefat" style="background: #fff; margin: 0;">';
                                html += '<thead><tr><th style="padding: 10px;"><?php echo esc_js(__('Category', 'ai-auto-tool')); ?></th><th style="padding: 10px;"><?php echo esc_js(__('Taxonomy', 'ai-auto-tool')); ?></th><th style="padding: 10px; width: 150px;"><?php echo esc_js(__('Completed', 'ai-auto-tool')); ?></th></tr></thead>';
                                html += '<tbody>';
                                data.completed.forEach(function(cat, index) {
                                    html += '<tr style="' + (index % 2 === 0 ? 'background: #f9f9f9;' : '') + '">';
                                    html += '<td style="padding: 10px;"><strong>' + escapeHtml(cat.name) + '</strong></td>';
                                    html += '<td style="padding: 10px;"><span style="padding: 4px 8px; background: #e8f5e9; border-radius: 3px; font-size: 11px;">' + escapeHtml(cat.taxonomy) + '</span></td>';
                                    html += '<td style="padding: 10px;"><span style="padding: 4px 8px; background: #e8f5e9; color: #2e7d32; border-radius: 3px; font-size: 11px; font-weight: 600;"><i class="fa-solid fa-check"></i> ' + escapeHtml(cat.completed_time) + '</span></td>';
                                    html += '</tr>';
                                });
                                html += '</tbody></table>';
                                html += '</div>';
                                html += '</div>';
                            }
                        }
                        
                        // Cron schedule info
                        if (data.cron_scheduled) {
                            html += '<div style="margin-top: 20px; padding: 15px; background: #f0f7ff; border-left: 4px solid #4facfe; border-radius: 4px;">';
                            html += '<p style="margin: 0; color: #1976d2; font-size: 13px;">';
                            html += '<i class="fa-solid fa-info-circle"></i> <strong><?php echo esc_js(__('Cron Status:', 'ai-auto-tool')); ?></strong> ';
                            html += '<?php echo esc_js(__('Active', 'ai-auto-tool')); ?> - <?php echo esc_js(__('Next run:', 'ai-auto-tool')); ?> ' + escapeHtml(data.next_run);
                            html += '</p>';
                            html += '</div>';
                        }
                        
                        $('#cron-status-container').html(html);
                    }
                    
                    function escapeHtml(text) {
                        var map = {
                            '&': '&amp;',
                            '<': '&lt;',
                            '>': '&gt;',
                            '"': '&quot;',
                            "'": '&#039;'
                        };
                        return text ? String(text).replace(/[&<>"']/g, function(m) { return map[m]; }) : '';
                    }
                });
                </script>
                
                <!-- Cron Status Widget Script -->
                <script>
                jQuery(document).ready(function($) {
                    // Load cron status on page load
                    loadCronStatus();
                    
                    // Refresh button
                    $('#refresh-cron-status').on('click', function() {
                        const $btn = $(this);
                        $btn.addClass('loading').prop('disabled', true);
                        loadCronStatus();
                        setTimeout(function() {
                            $btn.removeClass('loading').prop('disabled', false);
                        }, 1000);
                    });
                    
                    // Auto refresh every 30 seconds
                    setInterval(function() {
                        loadCronStatus();
                    }, 30000);
                    
                    function loadCronStatus() {
                        // Check if autoCreateCategories is defined
                        if (typeof autoCreateCategories === 'undefined') {
                            console.warn('autoCreateCategories is not defined. Using fallback values.');
                            // Use fallback values
                            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
                            var nonce = '<?php echo wp_create_nonce('aiautotool_auto_categories_nonce'); ?>';
                        } else {
                            var ajaxurl = autoCreateCategories.ajaxurl;
                            var nonce = autoCreateCategories.nonce;
                        }
                        
                        const taxonomy = getCurrentTaxonomyForStatus();
                        
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'aiautotool_get_cron_descriptions_status',
                                nonce: nonce,
                                taxonomy: taxonomy
                            },
                            success: function(response) {
                                if (response.success) {
                                    displayCronStatus(response.data);
                                } else {
                                    $('#cron-status-content').html('<p class="error-message">' + (response.data && response.data.message ? response.data.message : 'Error loading status') + '</p>');
                                }
                            },
                            error: function() {
                                $('#cron-status-content').html('<p class="error-message">Error loading status</p>');
                            }
                        });
                    }
                    
                    function displayCronStatus(data) {
                        let html = '';
                        
                        if (!data.has_pending && data.completed_count === 0) {
                            // No pending and no completed - hide widget
                            $('#cron-descriptions-status-widget').hide();
                            return;
                        }
                        
                        // Show widget
                        $('#cron-descriptions-status-widget').show();
                        
                        // Overall status
                        html += '<div class="cron-status-summary">';
                        html += '<div class="status-item">';
                        html += '<span class="status-label"><?php echo esc_js(__('Pending:', 'ai-auto-tool')); ?></span>';
                        html += '<span class="status-value pending">' + data.pending_count + '</span>';
                        html += '</div>';
                        html += '<div class="status-item">';
                        html += '<span class="status-label"><?php echo esc_js(__('Completed:', 'ai-auto-tool')); ?></span>';
                        html += '<span class="status-value completed">' + data.completed_count + '</span>';
                        html += '</div>';
                        if (data.cron_active) {
                            html += '<div class="status-item">';
                            html += '<span class="status-label"><?php echo esc_js(__('Next Run:', 'ai-auto-tool')); ?></span>';
                            html += '<span class="status-value">' + escapeHtmlForStatus(data.next_run) + '</span>';
                            html += '</div>';
                        }
                        html += '</div>';
                        
                        // Pending list
                        if (data.pending && data.pending.length > 0) {
                            html += '<div class="cron-status-section">';
                            html += '<h4><i class="fa-solid fa-clock"></i> <?php echo esc_js(__('Pending Categories', 'ai-auto-tool')); ?> <span class="badge">' + data.pending.length + '</span></h4>';
                            html += '<ul class="cron-status-list pending-list">';
                            data.pending.forEach(function(cat) {
                                html += '<li>';
                                html += '<i class="fa-solid fa-hourglass-half"></i> ';
                                html += '<span>' + escapeHtmlForStatus(cat.name) + '</span>';
                                html += '</li>';
                            });
                            html += '</ul>';
                            html += '</div>';
                        }
                        
                        // Completed list
                        if (data.completed && data.completed.length > 0) {
                            html += '<div class="cron-status-section">';
                            html += '<h4><i class="fa-solid fa-check-circle"></i> <?php echo esc_js(__('Completed Categories', 'ai-auto-tool')); ?> <span class="badge">' + data.completed.length + '</span></h4>';
                            html += '<ul class="cron-status-list completed-list">';
                            data.completed.forEach(function(cat) {
                                html += '<li>';
                                html += '<i class="fa-solid fa-check"></i> ';
                                html += '<span>' + escapeHtmlForStatus(cat.name) + '</span>';
                                html += '</li>';
                            });
                            html += '</ul>';
                            html += '</div>';
                        }
                        
                        $('#cron-status-content').html(html);
                    }
                    
                    function getCurrentTaxonomyForStatus() {
                        const urlParams = new URLSearchParams(window.location.search);
                        return urlParams.get('taxonomy') || 'category';
                    }
                    
                    function escapeHtmlForStatus(text) {
                        const map = {
                            '&': '&amp;',
                            '<': '&lt;',
                            '>': '&gt;',
                            '"': '&quot;',
                            "'": '&#039;'
                        };
                        return text ? String(text).replace(/[&<>"']/g, function(m) { return map[m]; }) : '';
                    }
                });
                </script>
            </div>
            <?php
        }
        
        /**
         * Render feature tab
         */
        public function render_tab_setting() {
            if ($this->active == "true") {
                echo '<button href="#tool-auto-create-categories" class="nav-tab sotab">' . 
                     wp_kses($this->icon, array('i' => array('class' => array()))) . ' ' . 
                     esc_html__('Auto Create Categories', 'ai-auto-tool') . '</button>';
            }
        }
        
        /**
         * Render feature description
         */
        public function render_feature() {
            // Load feature descriptions
            require_once plugin_dir_path(dirname(__FILE__)) . '../lib/feature-descriptions.php';
            
            $autoToolBox = new AutoToolBox(
                $this->icon . ' ' . $this->name_plan,
                __('Automatically create a category tree structure based on your website topic. AI will analyze and generate an SEO-optimized category structure.', 'ai-auto-tool'),
                "https://doc.aiautotool.com/features/auto-create-categories",
                $this->active_option_name,
                $this->active,
                plugins_url('../../images/logo.svg', __FILE__)
            );
            
            echo ($autoToolBox->generateHTML());
        }
        
        /**
         * AJAX: Get all categories
         */
        public function ajax_get_categories() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            // Get taxonomy from request, default to category
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool')));
            }
            
            $categories = get_terms(array(
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (is_wp_error($categories)) {
                wp_send_json_error(array('message' => $categories->get_error_message()));
            }
            
            $formatted_categories = array();
            foreach ($categories as $category) {
                $formatted_categories[] = array(
                    'id' => $category->term_id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'parent' => $category->parent,
                    'description' => $category->description,
                    'has_description' => !empty($category->description)
                );
            }
            
            wp_send_json_success($formatted_categories);
        }
        
        /**
         * AJAX: Generate category description
         */
        public function ajax_generate_category_description() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            if (!$category_id) {
                wp_send_json_error(array('message' => __('Invalid category ID', 'ai-auto-tool')));
            }
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool')));
            }
            
            $category = get_term($category_id, $taxonomy);
            if (!$category || is_wp_error($category)) {
                wp_send_json_error(array('message' => __('Category not found', 'ai-auto-tool')));
            }
            
            // Check if AI Helper is available
            if (!class_exists('AIAutotool_AI_Helper')) {
                wp_send_json_error(array('message' => __('AI Helper is not available. Please check AI Provider configuration.', 'ai-auto-tool')));
            }
            
            if (!AIAutotool_AI_Helper::is_available()) {
                wp_send_json_error(array('message' => __('AI Provider is not configured. Please configure it in AI Provider Settings.', 'ai-auto-tool')));
            }
            
            // Build prompt for description generation
            $prompt = $this->build_description_prompt($category);
            
            // Call AI
            $messages = array(
                array(
                    'role' => 'system',
                    'content' => __('You are an SEO expert. Generate a concise, SEO-optimized description for a WordPress category. The description should be informative, keyword-rich, and between 100-200 words. Return ONLY the description text, no other text or formatting.', 'ai-auto-tool')
                ),
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            );
            
            $result = AIAutotool_AI_Helper::chat($messages, array(
                'temperature' => 0.7,
                'max_tokens' => 300
            ));
            
            if (!$result['success']) {
                $error_message = isset($result['error']) && !empty($result['error']) 
                    ? $result['error'] 
                    : 'Unknown error occurred. Please check your AI provider configuration and try again.';
                
                // Log detailed error for debugging
                
                wp_send_json_error(array(
                    'message' => __('Error calling AI: ', 'ai-auto-tool') . $error_message
                ));
            }
            
            $description = trim($result['content']);
            
            // Clean up description (remove markdown code blocks if any)
            $description = preg_replace('/```[\s\S]*?```/', '', $description);
            $description = trim($description);
            
            wp_send_json_success(array(
                'category_id' => $category_id,
                'description' => $description
            ));
        }
        
        /**
         * Build prompt for description generation
         */
        private function build_description_prompt($category) {
            $site_name = get_bloginfo('name');
            $site_description = get_bloginfo('description');
            $parent_info = '';
            
            if ($category->parent > 0) {
                $parent = get_category($category->parent);
                if ($parent) {
                    $parent_info = sprintf(__('Parent category: %s. ', 'ai-auto-tool'), $parent->name);
                }
            }
            
            $prompt = sprintf(
                __('Generate an SEO-optimized description for a WordPress category with the following details:

Website: %s
Site Description: %s
Category Name: %s
Category Slug: %s
%s

Create a professional, SEO-friendly description (100-200 words) that:
- Clearly explains what this category is about
- Includes relevant keywords naturally
- Is informative and useful for visitors
- Encourages engagement
- Is written in a professional tone

Return ONLY the description text, no introduction or explanation.', 'ai-auto-tool'),
                $site_name,
                $site_description,
                $category->name,
                $category->slug,
                $parent_info
            );
            
            return $prompt;
        }
        
        /**
         * AJAX: Save category description
         */
        public function ajax_save_category_description() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
            $description = isset($_POST['description']) ? wp_kses_post($_POST['description']) : '';
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            if (!$category_id) {
                wp_send_json_error(array('message' => __('Invalid category ID', 'ai-auto-tool')));
            }
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool')));
            }
            
            $result = wp_update_term($category_id, $taxonomy, array(
                'description' => $description
            ));
            
            if (is_wp_error($result)) {
                wp_send_json_error(array('message' => $result->get_error_message()));
            }
            
            wp_send_json_success(array(
                'category_id' => $category_id,
                'message' => __('Description saved successfully', 'ai-auto-tool')
            ));
        }
        
        /**
         * AJAX: Schedule cron job for descriptions
         */
        public function ajax_schedule_cron_descriptions() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $category_ids = isset($_POST['category_ids']) ? $_POST['category_ids'] : array();
            
            if (empty($category_ids) || !is_array($category_ids)) {
                wp_send_json_error(array('message' => __('Invalid category IDs', 'ai-auto-tool')));
            }
            
            // Get taxonomy from request, default to category
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                wp_send_json_error(array('message' => __('Taxonomy not enabled', 'ai-auto-tool')));
            }
            
            // Filter out categories that already have descriptions
            $pending_ids = array();
            $pending_data = array(); // Store taxonomy for each category
            foreach ($category_ids as $cat_id) {
                $cat_id = intval($cat_id);
                if ($cat_id > 0) {
                    $category = get_term($cat_id, $taxonomy);
                    if ($category && !is_wp_error($category) && empty($category->description)) {
                        $pending_ids[] = $cat_id;
                        $pending_data[$cat_id] = $taxonomy;
                    }
                }
            }
            
            if (empty($pending_ids)) {
                wp_send_json_success(array('message' => __('All selected categories already have descriptions', 'ai-auto-tool')));
            }
            
            // Save pending categories and their taxonomies
            update_option('aiautotool_pending_category_descriptions', $pending_ids);
            update_option('aiautotool_pending_category_descriptions_data', $pending_data);
            
            // Schedule cron event if not already scheduled
            if (!wp_next_scheduled('aiautotool_auto_write_category_descriptions')) {
                wp_schedule_event(time(), 'aiautotool_category_desc_interval', 'aiautotool_auto_write_category_descriptions');
            }
            
            wp_send_json_success(array(
                'message' => sprintf(__('%d categories queued for background processing', 'ai-auto-tool'), count($pending_ids)),
                'count' => count($pending_ids)
            ));
        }
        
        /**
         * Add custom cron schedule for category descriptions
         */
        public function add_category_desc_cron_schedule($schedules) {
            $schedules['aiautotool_category_desc_interval'] = array(
                'interval' => 300, // 5 minutes
                'display' => __('Every 5 Minutes (Category Descriptions)', 'ai-auto-tool')
            );
            return $schedules;
        }
        
        /**
         * Cron job: Write category descriptions in background
         */
        public function cron_write_category_descriptions() {
            // Ensure textdomain is loaded (important for cron jobs)
            // Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
            if (!is_textdomain_loaded('ai-auto-tool')) {
                if (did_action('init')) {
                    if (function_exists('aiautotool_load_textdomain')) {
                        aiautotool_load_textdomain();
                    }
                }
            }
            
            // Get pending categories from option
            $pending_categories = get_option('aiautotool_pending_category_descriptions', array());
            
            if (empty($pending_categories)) {
                return;
            }
            
            // Process one category at a time
            $category_id = array_shift($pending_categories);
            
            if (!$category_id) {
                update_option('aiautotool_pending_category_descriptions', array());
                return;
            }
            
            // Get taxonomy from pending data or default to category
            $pending_data = get_option('aiautotool_pending_category_descriptions_data', array());
            $taxonomy = isset($pending_data[$category_id]) ? $pending_data[$category_id] : 'category';
            
            // Validate taxonomy is enabled
            $enabled_taxonomies = $this->get_enabled_taxonomies();
            if (!in_array($taxonomy, $enabled_taxonomies)) {
                // Skip if taxonomy not enabled
                update_option('aiautotool_pending_category_descriptions', $pending_categories);
                return;
            }
            
            $category = get_term($category_id, $taxonomy);
            if (!$category || is_wp_error($category)) {
                // Skip invalid category
                update_option('aiautotool_pending_category_descriptions', $pending_categories);
                return;
            }
            
            // Skip if already has description
            if (!empty($category->description)) {
                update_option('aiautotool_pending_category_descriptions', $pending_categories);
                return;
            }
            
            // Check if AI Helper is available
            if (!class_exists('AIAutotool_AI_Helper') || !AIAutotool_AI_Helper::is_available()) {
                // Put back and try later
                array_unshift($pending_categories, $category_id);
                update_option('aiautotool_pending_category_descriptions', $pending_categories);
                return;
            }
            
            // Generate description
            $prompt = $this->build_description_prompt($category);
            
            $messages = array(
                array(
                    'role' => 'system',
                    'content' => __('You are an SEO expert. Generate a concise, SEO-optimized description for a WordPress category. The description should be informative, keyword-rich, and between 100-200 words. Return ONLY the description text, no other text or formatting.', 'ai-auto-tool')
                ),
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            );
            
            $result = AIAutotool_AI_Helper::chat($messages, array(
                'temperature' => 0.7,
                'max_tokens' => 300
            ));
            
            if ($result['success']) {
                $description = trim($result['content']);
                $description = preg_replace('/```[\s\S]*?```/', '', $description);
                $description = trim($description);
                
                // Save description
                wp_update_term($category_id, $taxonomy, array(
                    'description' => $description
                ));
            }
            
            // Update pending list
            update_option('aiautotool_pending_category_descriptions', $pending_categories);
            
            // Update completed list
            if ($result['success']) {
                $completed = get_option('aiautotool_completed_category_descriptions', array());
                $completed[] = array(
                    'category_id' => $category_id,
                    'taxonomy' => $taxonomy,
                    'completed_at' => current_time('mysql')
                );
                update_option('aiautotool_completed_category_descriptions', $completed);
            }
            
            // Save completed category info
            if ($result['success']) {
                $completed_categories = get_option('aiautotool_completed_category_descriptions', array());
                $completed_categories[] = array(
                    'id' => $category_id,
                    'name' => $category->name,
                    'taxonomy' => $taxonomy,
                    'completed_time' => current_time('mysql')
                );
                // Keep only last 50 completed
                if (count($completed_categories) > 50) {
                    $completed_categories = array_slice($completed_categories, -50);
                }
                update_option('aiautotool_completed_category_descriptions', $completed_categories);
            }
        }
        
        /**
         * AJAX: Get cron job status
         */
        public function ajax_get_cron_status() {
            check_ajax_referer('aiautotool_auto_categories_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : 'category';
            
            $pending_ids = get_option('aiautotool_pending_category_descriptions', array());
            $pending_data = get_option('aiautotool_pending_category_descriptions_data', array());
            $completed = get_option('aiautotool_completed_category_descriptions', array());
            
            // Filter by taxonomy
            $pending_categories = array();
            $completed_categories = array();
            $next_category = null;
            
            // Get pending categories for this taxonomy
            foreach ($pending_ids as $index => $cat_id) {
                $cat_taxonomy = isset($pending_data[$cat_id]) ? $pending_data[$cat_id] : 'category';
                if ($cat_taxonomy !== $taxonomy) {
                    continue;
                }
                
                $category = get_term($cat_id, $taxonomy);
                
                if ($category && !is_wp_error($category)) {
                    $cat_info = array(
                        'id' => $cat_id,
                        'name' => $category->name,
                        'slug' => $category->slug,
                        'taxonomy' => $taxonomy,
                        'position' => $index + 1
                    );
                    
                    $pending_categories[] = $cat_info;
                    
                    // First one is next to process
                    if ($next_category === null) {
                        $next_category = $cat_info;
                    }
                }
            }
            
            // Get completed categories for this taxonomy
            foreach ($completed as $item) {
                if (isset($item['taxonomy']) && $item['taxonomy'] === $taxonomy) {
                    $cat_id = isset($item['category_id']) ? $item['category_id'] : (isset($item['id']) ? $item['id'] : 0);
                    if ($cat_id > 0) {
                        $category = get_term($cat_id, $taxonomy);
                        if ($category && !is_wp_error($category)) {
                            $completed_categories[] = array(
                                'id' => $cat_id,
                                'name' => $category->name,
                                'slug' => $category->slug
                            );
                        }
                    }
                }
            }
            
            // Check if cron is scheduled
            $cron_scheduled = wp_next_scheduled('aiautotool_auto_write_category_descriptions');
            $next_run = '';
            if ($cron_scheduled) {
                $next_run = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $cron_scheduled);
            }
            
            wp_send_json_success(array(
                'has_pending' => !empty($pending_categories),
                'pending' => $pending_categories,
                'completed' => $completed_categories,
                'next_category' => $next_category,
                'cron_active' => (bool)$cron_scheduled,
                'cron_scheduled' => (bool)$cron_scheduled,
                'next_run' => $next_run,
                'pending_count' => count($pending_categories),
                'completed_count' => count($completed_categories),
                'total_pending' => count($pending_categories),
                'total_completed' => count($completed_categories)
            ));
        }
    }
}

