<?php 
/**
 * AI Auto Tool - Auto Comment Feature
 * 
 * This class handles automatic comment generation using AI for WordPress posts.
 * 
 * Features:
 * - Automatic comment generation based on post content
 * - Support for multiple post types (post, product, custom post types)
 * - Configurable comment generation interval
 * - AI-powered comment generation with various tones
 * - Support for WooCommerce product reviews
 * - Quota management and usage tracking
 * - Cron-based scheduling
 * 
 * @package AI_Auto_Tool
 * @subpackage Auto_Comment
 * @version 2.0
 */

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

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

    /**
     * Feature Configuration
     */
    public $active = false;
    public $active_option_name = 'AIautotool_autocomment_active';
    public $usage_option_name = 'Commentauto_AI_usage';
    public $settings_option_name = 'aiautotool_setting_autocomment';
    public $generated_posts_option = 'autocomment_generated_posts';
    
    /**
     * Display & UI
     */
    public $icon = '<i class="fa-regular fa-comments"></i>';
    public $name_plan;
    
    /**
     * Quota Management
     */
    public $limit = AIAUTOTOOL_FREE;
    private $plan_limit_aiautotool;
    public $config = array();
    
    /**
     * Helper Objects
     */
    private $client = null;
    public $notices = [];
    public $notice;

    /**
     * Constructor - Initialize the Auto Comment feature
     */
    public function __construct() {
        $this->name_plan = __('Auto Comments By AI', 'ai-auto-tool');
        $this->plan_limit_aiautotool = 'plan_limit_aiautotool_' . $this->active_option_name;
        
        $this->notice = new aiautotool_Warning_Notice();
        $this->active = get_option($this->active_option_name, false);
        
        // Initialize feature if active
        if ($this->active == 'true') {
            $this->init();
        }
        
        // Register AJAX handlers
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, 
                   array($this, 'update_active_option_callback'));
        
        // Register manual comment generation AJAX handler
        add_action('wp_ajax_aiautotool_manual_generate_comments', 
                   array($this, 'manual_generate_comments_callback'));
    }

    /**
     * ========================================
     * QUOTA & LIMIT MANAGEMENT
     * ========================================
     */

    /**
     * Check if plugin data exists
     * 
     * @return bool
     */
    private function aiautotool_has_plugin_data() {
        return get_option($this->plan_limit_aiautotool) !== false;
    }

    /**
     * Initialize plugin quota data
     */
    private function aiautotool_initialize_plugin_data() {
        $current_date = date('Y-m-d');
        $expiration = date('Y-m-d', strtotime('+1 month', strtotime($current_date)));
        
        update_option($this->plan_limit_aiautotool, array(
            'start_date' => $current_date,
            'expiration' => $expiration
        ));
    }

    /**
     * Check if usage limit is exceeded
     * 
     * @return bool
     */
    public function aiautotool_checklimit($config) {
        return $this->check_quota();
    }

    /**
     * Check post limit and reset if new month
     * 
     * @return bool
     */
    public function aiautotool_check_post_limit() {
        if (!$this->aiautotool_checklimit($this->config)) {
            $this->show_upgrade_notice();
            return false;
        }
        
        $stored_data = get_option($this->plan_limit_aiautotool, array());
        $current_date = date('Y-m-d');
        
        // Reset quota if new month
        if (isset($stored_data['start_date']) && $this->is_new_month($current_date, $stored_data['start_date'])) {
            $expiration = date('Y-m-d', strtotime('+1 month', strtotime($current_date)));
            update_option($this->plan_limit_aiautotool, array(
                'start_date' => $current_date,
                'expiration' => $expiration
            ));
            update_option($this->usage_option_name, 0, null, 'no');
        }
        
        return true;
    }

    /**
     * Check if it's a new month
     * 
     * @param string $current_date
     * @param string $start_date
     * @return bool
     */
    private function is_new_month($current_date, $start_date) {
        $current_month = date('m', strtotime($current_date));
        $start_month = date('m', strtotime($start_date));
        return ($current_month != $start_month);
    }

    /**
     * Update usage counter
     * 
     * @return int New usage value
     */
    public function aiautotool__update_usage() {
        $this->aiautotool_check_post_limit();
        
        $current_value = get_option($this->usage_option_name, 0);
        $new_value = $current_value + 1;
        
        // Update only if within limit
        if ($this->config['number_post'] != -1) {
            if ($this->config['number_post'] >= $new_value) {
                update_option($this->usage_option_name, $new_value, 'no');
            }
        } else {
            update_option($this->usage_option_name, $new_value, 'no');
        }
        
        return $new_value;
    }

    /**
     * Show upgrade notice
     */
    private function show_upgrade_notice() {
        $title = sprintf(
            'AI Auto Tool Limit Quota. Please <a class="aiautotool_btn_upgradepro aiautotool_red" href="%s" target="_blank"><i class="fa-solid fa-unlock-keyhole"></i> Upgrade Pro</a>',
            aiautotool_premium()->get_upgrade_url()
        );
        
        $this->notice->add_notice($title, 'notice-error', null, true, 'aiautotool');
    }

    /**
     * ========================================
     * INITIALIZATION & SETUP
     * ========================================
     */

    /**
     * Initialize the feature
     */
    function init() {
        // Initialize plugin data if not exists
        if (!$this->aiautotool_has_plugin_data()) {
            $this->aiautotool_initialize_plugin_data();
        }
        
        $configs = get_option($this->plan_limit_aiautotool, array());
        
        // Setup configuration
        $this->config = array(
            'number_post' => $this->limit,
            'usage' => get_option($this->usage_option_name, 0, 'no'),
            'time_exprice' => isset($configs['expiration']) ? $configs['expiration'] : ''
        );
        
        // Premium checks removed - always set unlimited limits
        $fs = $this->is_premium();
        if ($fs && is_object($fs)) {
            $license = $fs->_get_license();
            $expiration = (is_object($license) && isset($license->expiration)) ? $license->expiration : (isset($configs['expiration']) ? $configs['expiration'] : '');
            $this->config = array(
                'number_post' => -1,
                'usage' => get_option($this->usage_option_name, 0, 'no'),
                'time_exprice' => $expiration
            );
        } else {
            // Even if Freemius not loaded, set unlimited
            $this->config = array(
                'number_post' => -1,
                'usage' => get_option($this->usage_option_name, 0, 'no'),
                'time_exprice' => isset($configs['expiration']) ? $configs['expiration'] : ''
            );
        }

        // Register hooks
        add_action('admin_init', array($this, 'init_settings'));
        add_action('admin_init', array($this, 'aiautotool_check_post_limit'));
        add_action('admin_notices', array($this, 'display_notices'), 10, 1);

        // Add meta box for manual comment generation
        add_action('add_meta_boxes', array($this, 'add_comment_generator_meta_box'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));

        // Setup cron if within limit
        if ($this->aiautotool_checklimit($this->config)) {
            $this->setup_cron_schedule();
        } else {
            $this->show_upgrade_notice();
        }
    }

    /**
     * Setup cron schedule for auto comment generation
     */
    private function setup_cron_schedule() {
        add_filter('cron_schedules', array($this, 'aiautotool_schedule_autocomment_intervals'));
        
        if (!wp_next_scheduled('schedule_create_autocomment_event_new')) {
            wp_schedule_event(time(), 'aiautotool_schedule_autocomment_intervals', 
                            'schedule_create_autocomment_event_new');
        }
        
        add_action('schedule_create_autocomment_event_new', array($this, 'schedule_create_autocomments'));
    }

    /**
     * Define custom cron intervals
     * 
     * @param array $schedules
     * @return array
     */
    public function aiautotool_schedule_autocomment_intervals($schedules) {
        $setting = get_option($this->settings_option_name);
        $current_interval = 5; // Default 5 minutes
        
        if (!empty($setting) && isset($setting['time_comment'])) {
            $current_interval = intval($setting['time_comment']);
        }
        
        $schedules['aiautotool_schedule_autocomment_intervals'] = array(
            'interval' => $current_interval * 60,
            'display' => 'Schedule create auto Comment'
        );
        
        return $schedules;
    }

    /**
     * ========================================
     * COMMENT GENERATION - AUTO MODE
     * ========================================
     */

    /**
     * Main function: Auto generate comments for posts (Cron Job)
     */
    public function schedule_create_autocomments() {
        // Ensure textdomain is loaded (important for cron jobs)
        // Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
        if (!is_textdomain_loaded('ai-auto-tool') || !is_textdomain_loaded('aiautotool-cron-widget')) {
            if (did_action('init')) {
                if (function_exists('aiautotool_load_textdomain')) {
                    aiautotool_load_textdomain();
                }
            }
        }
        
        $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance();
        
        // Update status - starting
        $cron_widget->update_cron_status(array(
            'is_running' => true,
            'current_task' => __('Searching for posts to comment...', 'aiautotool-cron-widget'),
            'current_post_title' => '',
            'progress' => 10,
            'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
        ));
        
        // Check quota
        if (!$this->aiautotool_checklimit($this->config)) {
            $this->show_upgrade_notice();
            $cron_widget->update_cron_status(array(
                'is_running' => false,
                'current_task' => __('Usage limit exceeded', 'aiautotool-cron-widget'),
                'current_post_title' => '',
                'progress' => 100,
                'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
            ));
            return false;
        }
        
        // Get post to process
        $post = $this->get_next_post_for_comment();
        
        if (!$post) {
            $this->notice->add_notice(
                __('No Post find', 'ai-auto-tool'),
                'notice-info',
                null,
                true,
                $this->name_plan
            );
            
            $cron_widget->update_cron_status(array(
                'is_running' => false,
                'current_task' => __('No posts found to comment', 'aiautotool-cron-widget'),
                'current_post_title' => '',
                'progress' => 100,
                'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
            ));
            return;
        }
        
        // Generate comments for the post
        $result = $this->generate_comments_for_post($post, $cron_widget);
        
        if ($result) {
            $this->aiautotool__update_usage();
        }
    }

    /**
     * Get next post for comment generation
     * 
     * @return object|null WP_Post object or null
     */
    private function get_next_post_for_comment() {
        $generated_posts = get_option($this->generated_posts_option, array());
        $setting = get_option($this->settings_option_name);
        
        // Get post types from settings
        $post_types = array('post');
        if (isset($setting['post_type']) && !empty($setting['post_type'])) {
            $post_types = array_map('sanitize_key', $setting['post_type']);
        }
        
        // Allow filtering post types
        $post_types = apply_filters('aiautotool_comment_post_types', $post_types);
        
        // Build WP_Query args
        $args = array(
            'post_type' => $post_types,
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'orderby' => 'date',
            'order' => 'DESC',
            'post__not_in' => !empty($generated_posts) ? $generated_posts : array(),
            'ignore_sticky_posts' => true,
        );
        
        // Allow filtering query args
        $args = apply_filters('aiautotool_comment_query_args', $args);
        
        $query = new WP_Query($args);
        
        if ($query->have_posts()) {
            $post = $query->posts[0];
            wp_reset_postdata();
            return $post;
        }
        
        wp_reset_postdata();
        return null;
    }

    /**
     * Generate comments for a specific post
     * 
     * @param object $post WP_Post object
     * @param object $cron_widget Cron status widget instance
     * @return bool Success status
     */
    private function generate_comments_for_post($post, $cron_widget = null) {
        $post_id = $post->ID;
        $post_title = $post->post_title;
        $post_content = $post->post_content;
        
        if ($cron_widget) {
            $cron_widget->update_cron_status(array(
                'is_running' => true,
                'current_task' => __('Found post to comment', 'aiautotool-cron-widget'),
                'current_post_title' => get_the_title($post_id),
                'progress' => 30,
                'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
            ));
        }
        
        // Get AI-generated comments
        $comments_data = $this->get_ai_comments($post_title, $post_content, $post_id, $cron_widget);
        
        if (!$comments_data || count($comments_data) == 0) {
            if ($cron_widget) {
                $cron_widget->update_cron_status(array(
                    'is_running' => false,
                    'current_task' => __('Error: Unable to create comments', 'aiautotool-cron-widget'),
                    'current_post_title' => get_the_title($post_id),
                    'progress' => 100,
                    'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
                ));
            }
            return false;
        }
        
        // Insert comments
        $success = $this->insert_comments($post, $comments_data, $cron_widget);
        
        if ($success) {
            // Mark post as processed
            $generated_posts = get_option($this->generated_posts_option, array());
            $generated_posts[] = $post_id;
            update_option($this->generated_posts_option, $generated_posts);
            
            if ($cron_widget) {
                $cron_widget->update_cron_status(array(
                    'is_running' => false,
                    'current_task' => __('Comment creation completed', 'aiautotool-cron-widget'),
                    'current_post_title' => $post_title,
                    'progress' => 100,
                    'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
                ));
            }
        }
        
        return $success;
    }

    /**
     * Get AI-generated comments for a post
     * 
     * @param string $post_title
     * @param string $post_content
     * @param int $post_id
     * @param object $cron_widget
     * @return array|false Array of comment data or false on failure
     */
    private function get_ai_comments($post_title, $post_content, $post_id, $cron_widget = null) {
        if ($cron_widget) {
            $cron_widget->update_cron_status(array(
                'is_running' => true,
                'current_task' => __('Calling AI for comments...', 'aiautotool-cron-widget'),
                'current_post_title' => get_the_title($post_id),
                'progress' => 50,
                'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
            ));
        }
        
        $post = get_post($post_id);
        $bardGenContent = new BardGenContent();
        
        // Build AI prompt with post context
        $num_comments = rand(8, 15);
        
        // Allow filtering number of comments
        $num_comments = apply_filters('aiautotool_comment_count', $num_comments, $post);
        
        $prompt = $this->build_comment_prompt($post_title, $num_comments, $post);
        
        // Get language - check multiple sources
        $lang = get_post_meta($post_id, 'lang', true);
        
        // Try to detect language from site locale if not set
        if (empty($lang)) {
            $site_locale = get_locale();
            $lang_map = array(
                'vi' => 'Vietnamese',
                'en' => 'English',
                'es' => 'Spanish',
                'fr' => 'French',
                'de' => 'German',
                'ja' => 'Japanese',
                'ko' => 'Korean',
                'zh' => 'Chinese',
            );
            
            $lang_code = substr($site_locale, 0, 2);
            $lang = isset($lang_map[$lang_code]) ? $lang_map[$lang_code] : 'the SAME LANGUAGE as the original text (text between "======")';
        }
        
        // Allow filtering language
        $lang = apply_filters('aiautotool_comment_language', $lang, $post);
        
        // Call AI API
        $json_response = $bardGenContent->bardcontentmore($prompt, $lang);
        
        // Parse and validate response
        $comments_data = $this->aiautotool_fixjsonreturn($json_response);
        
        // Allow filtering generated comments before insert
        $comments_data = apply_filters('aiautotool_generated_comments', $comments_data, $post);
        
        return $comments_data;
    }

    /**
     * Build prompt for AI comment generation
     * 
     * @param string $post_title
     * @param int $num_comments
     * @param object $post Optional post object for context
     * @return string
     */
    private function build_comment_prompt($post_title, $num_comments, $post = null) {
        // Detect post type for customized prompts
        $post_type = $post ? $post->post_type : 'post';
        $comment_type_text = 'comments';
        
        // Customize based on post type
        switch ($post_type) {
            case 'product':
                $comment_type_text = 'product reviews';
                break;
            case 'page':
                $comment_type_text = 'feedback comments';
                break;
            default:
                $comment_type_text = 'comments';
                break;
        }
        
        $prompt = "The most important: the response must be in the SAME LANGUAGE as the original text (text between \"======\").

Create $num_comments $comment_type_text from readers of the {$post_type}.

Requirements:
- Each comment must have a different tone: positive, negative, informative, argumentative, ironic, sarcastic, or comical
- Commenters must have a \"$post_title\" intellectual level
- Most comments should have several syntactic errors (to make them look natural)
- Include neutral nicknames (unrelated to the topic) of one to two words separated by spaces
- Comments should be realistic and varied in length
- Some comments should be short (1-2 sentences), others longer (3-5 sentences)";
        
        // Add specific instructions for products
        if ($post_type === 'product') {
            $prompt .= "\n- For products: include ratings perspective (quality, value, satisfaction)";
            $prompt .= "\n- Some comments should mention usage experience";
        }
        
        $prompt .= "\n\nThe {$post_type}'s title is: \"$post_title\"

The answer must be in JSON format ONLY, with this exact structure:
{ \"nickname\": \"commenter name\", \"comment\": \"comment text\", \"tone\": \"tone type\" }

Return an array of comment objects.";
        
        // Allow filtering the prompt
        $prompt = apply_filters('aiautotool_comment_prompt', $prompt, $post_title, $num_comments, $post);
        
        return $prompt;
    }

    /**
     * Insert comments into database
     * 
     * @param object $post WP_Post object
     * @param array $comments_data Array of comment data
     * @param object $cron_widget Cron status widget instance
     * @return bool Success status
     */
    private function insert_comments($post, $comments_data, $cron_widget = null) {
        if ($cron_widget) {
            $cron_widget->update_cron_status(array(
                'is_running' => true,
                'current_task' => __('Processing and saving comments...', 'aiautotool-cron-widget'),
                'current_post_title' => $post->post_title,
                'progress' => 80,
                'cron_type' => __('Auto Comment', 'aiautotool-cron-widget')
            ));
        }
        
        $success = false;
        $post_id = $post->ID;
        $post_type = $post->post_type;
        
        // Get timezone
        $timezone = get_option('timezone_string');
        if (!empty($timezone)) {
            date_default_timezone_set($timezone);
        }
        
        // Calculate timestamp range
        $post_publish_timestamp = strtotime($post->post_date);
        $current_timestamp = time();
        
        $comments_inserted = 0;
        
        foreach ($comments_data as $comment_data) {
            $comment_data = (object) $comment_data;
            
            // Validate comment data
            if (!isset($comment_data->nickname) || !isset($comment_data->comment)) {
                continue;
            }
            
            $comment_author = sanitize_text_field($comment_data->nickname);
            $comment_content = sanitize_textarea_field($comment_data->comment);
            
            // Generate random comment timestamp
            $comment_timestamp = mt_rand($post_publish_timestamp, $current_timestamp);
            
            // Prepare base comment data
            $commentdata = array(
                'comment_author' => $comment_author,
                'comment_content' => $comment_content,
                'comment_date' => date('Y-m-d H:i:s', $comment_timestamp),
                'comment_date_gmt' => gmdate('Y-m-d H:i:s', $comment_timestamp),
                'comment_post_ID' => $post_id,
                'comment_parent' => 0,
                'comment_approved' => 1,
                'comment_author_email' => '',
                'comment_author_url' => '',
                'comment_author_IP' => '',
                'comment_agent' => 'AI Auto Tool',
            );
            
            // Customize comment type based on post type
            $comment_type = $this->get_comment_type_for_post_type($post_type);
            if ($comment_type) {
                $commentdata['comment_type'] = $comment_type;
            }
            
            // Allow filtering comment data before insert
            $commentdata = apply_filters('aiautotool_before_insert_comment', $commentdata, $post, $comment_data);
            
            // Insert comment
            $comment_id = wp_insert_comment($commentdata);
            
            if ($comment_id) {
                $success = true;
                $comments_inserted++;
                
                // Add meta to identify AI-generated comments
                add_comment_meta($comment_id, '_aiautotool_generated', true);
                add_comment_meta($comment_id, '_aiautotool_generated_date', current_time('mysql'));
                add_comment_meta($comment_id, '_aiautotool_post_type', $post_type);
                
                // Store tone if available
                if (isset($comment_data->tone)) {
                    add_comment_meta($comment_id, '_aiautotool_comment_tone', $comment_data->tone);
                }
                
                // Fire action after comment inserted
                do_action('aiautotool_after_insert_comment', $comment_id, $post, $comment_data);
            }
        }
        
        if ($success && $comments_inserted > 0) {
            // Show notice with count
            $message = sprintf(
                'Generated %1$d AI comments for %2$s: <a href="%3$s">%4$s</a>',
                $comments_inserted,
                $post_type,
                get_permalink($post_id),
                $post->post_title
            );
            
            $this->notice->add_notice($message, 'notice-info', null, true, $this->name_plan);
            
            // Fire action after all comments inserted
            do_action('aiautotool_after_generate_comments', $post_id, $comments_inserted, $post);
        }
        
        return $success;
    }
    
    /**
     * Get comment type for specific post type
     * 
     * @param string $post_type
     * @return string|null Comment type or null
     */
    private function get_comment_type_for_post_type($post_type) {
        $comment_types = array(
            'product' => 'review',  // WooCommerce
            'download' => 'review', // Easy Digital Downloads
        );
        
        // Allow filtering comment types
        $comment_types = apply_filters('aiautotool_comment_types', $comment_types);
        
        return isset($comment_types[$post_type]) ? $comment_types[$post_type] : null;
    }

    /**
     * ========================================
     * META BOX & MANUAL GENERATION UI
     * ========================================
     */

    /**
     * Add meta box for comment generation in post editor
     */
    public function add_comment_generator_meta_box() {
        $setting = get_option($this->settings_option_name);
        $post_types = array('post');
        
        if (isset($setting['post_type']) && !empty($setting['post_type'])) {
            $post_types = $setting['post_type'];
        }
        
        foreach ($post_types as $post_type) {
            add_meta_box(
                'aiautotool_comment_generator',
                '<span class="dashicons dashicons-admin-comments"></span> ' . __('AI Comment Generator', 'ai-auto-tool'),
                array($this, 'render_comment_generator_meta_box'),
                $post_type,
                'side',
                'default'
            );
        }
    }

    /**
     * Render meta box content
     * 
     * @param WP_Post $post Current post object
     */
    public function render_comment_generator_meta_box($post) {
        wp_nonce_field('aiautotool_generate_comments', 'aiautotool_comment_nonce');
        
        // Check if post is published
        $is_published = $post->post_status === 'publish';
        $has_content = !empty($post->post_title) && !empty($post->post_content);
        
        // Get existing comments count
        $comments_count = wp_count_comments($post->ID);
        $approved_comments = $comments_count->approved;
        
        // Check if already generated
        $generated_posts = get_option($this->generated_posts_option, array());
        $already_generated = in_array($post->ID, $generated_posts);
        
        ?>
        <div class="aiautotool-comment-generator-box">
            <div class="aiautotool-comment-stats">
                <p>
                    <strong><?php esc_html_e('Current Comments:', 'ai-auto-tool'); ?></strong> 
                    <span class="comment-count"><?php echo esc_html($approved_comments); ?></span>
                </p>
                
                <?php if ($already_generated): ?>
                    <p class="aiautotool-notice-success">
                        <span class="dashicons dashicons-yes-alt"></span>
                        <?php esc_html_e('AI comments already generated for this post', 'ai-auto-tool'); ?>
                    </p>
                <?php endif; ?>
            </div>

            <div class="aiautotool-comment-actions">
                <?php if (!$is_published): ?>
                    <p class="aiautotool-notice-warning">
                        <span class="dashicons dashicons-info"></span>
                        <?php esc_html_e('Post must be published to generate comments', 'ai-auto-tool'); ?>
                    </p>
                <?php elseif (!$has_content): ?>
                    <p class="aiautotool-notice-warning">
                        <span class="dashicons dashicons-info"></span>
                        <?php esc_html_e('Post must have title and content', 'ai-auto-tool'); ?>
                    </p>
                <?php else: ?>
                    <button type="button" 
                            id="aiautotool-generate-comments-btn" 
                            class="button button-primary button-large"
                            data-post-id="<?php echo esc_attr($post->ID); ?>">
                        <span class="dashicons dashicons-admin-comments"></span>
                        <?php esc_html_e('Generate AI Comments', 'ai-auto-tool'); ?>
                    </button>
                    
                    <div class="aiautotool-generation-info" style="display:none; margin-top:10px;">
                        <div class="aiautotool-spinner">
                            <span class="spinner is-active"></span>
                            <span class="status-text"><?php esc_html_e('Generating comments...', 'ai-auto-tool'); ?></span>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <div class="aiautotool-comment-info">
                <h4><?php esc_html_e('How it works:', 'ai-auto-tool'); ?></h4>
                <ul>
                    <li><?php esc_html_e('AI analyzes your post content', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Generates 8-15 realistic comments', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Various tones: positive, negative, informative', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Random timestamps between post date and now', 'ai-auto-tool'); ?></li>
                </ul>
                
                <div class="aiautotool-usage-info">
                    <p>
                        <strong><?php esc_html_e('Usage:', 'ai-auto-tool'); ?></strong> 
                        <?php echo esc_html($this->config['usage']); ?>
                        <?php if ($this->config['number_post'] != -1): ?>
                            / <?php echo esc_html($this->config['number_post']); ?>
                        <?php else: ?>
                            / <?php esc_html_e('Unlimited', 'ai-auto-tool'); ?>
                        <?php endif; ?>
                    </p>
                </div>
            </div>
        </div>
        
        <style>
            .aiautotool-comment-generator-box {
                padding: 10px 0;
            }
            
            .aiautotool-comment-stats {
                margin-bottom: 15px;
                padding: 10px;
                background: #f8f9fa;
                border-radius: 4px;
            }
            
            .aiautotool-comment-stats .comment-count {
                font-size: 18px;
                color: #2271b1;
                font-weight: bold;
            }
            
            .aiautotool-notice-success {
                color: #00a32a;
                margin: 10px 0;
            }
            
            .aiautotool-notice-warning {
                color: #d63638;
                margin: 10px 0;
            }
            
            .aiautotool-notice-success .dashicons,
            .aiautotool-notice-warning .dashicons {
                vertical-align: middle;
                margin-right: 5px;
            }
            
            .aiautotool-comment-actions {
                margin-bottom: 15px;
            }
            
            #aiautotool-generate-comments-btn {
                width: 100%;
                height: auto;
                padding: 12px;
                font-size: 14px;
            }
            
            #aiautotool-generate-comments-btn .dashicons {
                vertical-align: middle;
                margin-right: 5px;
            }
            
            #aiautotool-generate-comments-btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
            
            .aiautotool-generation-info {
                text-align: center;
                padding: 10px;
                background: #f0f0f1;
                border-radius: 4px;
            }
            
            .aiautotool-spinner {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 10px;
            }
            
            .aiautotool-spinner .spinner {
                float: none;
                margin: 0;
            }
            
            .aiautotool-comment-info {
                margin-top: 15px;
                padding-top: 15px;
                border-top: 1px solid #ddd;
            }
            
            .aiautotool-comment-info h4 {
                margin-top: 0;
                margin-bottom: 10px;
                font-size: 13px;
            }
            
            .aiautotool-comment-info ul {
                margin: 0 0 15px 0;
                padding-left: 20px;
                font-size: 12px;
                color: #666;
            }
            
            .aiautotool-comment-info li {
                margin-bottom: 5px;
            }
            
            .aiautotool-usage-info {
                padding: 10px;
                background: #e7f5ff;
                border-radius: 4px;
                font-size: 12px;
            }
            
            .aiautotool-usage-info p {
                margin: 0;
            }
        </style>
        <?php
    }

    /**
     * Enqueue admin scripts and styles
     * 
     * @param string $hook Current admin page hook
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on post edit pages
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }
        
        // Check if current post type is supported
        global $post;
        if (!$post) {
            return;
        }
        
        $setting = get_option($this->settings_option_name);
        $post_types = array('post');
        
        if (isset($setting['post_type']) && !empty($setting['post_type'])) {
            $post_types = $setting['post_type'];
        }
        
        if (!in_array($post->post_type, $post_types)) {
            return;
        }
        
        // Enqueue script
        wp_enqueue_script(
            'aiautotool-comment-generator',
            plugins_url('assets/js/comment-generator.js', __FILE__),
            array('jquery'),
            defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '2.0',
            true
        );
        
        // Localize script
        wp_localize_script('aiautotool-comment-generator', 'aiautotoolCommentGen', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('aiautotool_nonce'),
            'i18n' => array(
                'generating' => __('Generating comments...', 'ai-auto-tool'),
                'success' => __('Comments generated successfully!', 'ai-auto-tool'),
                'error' => __('Failed to generate comments. Please try again.', 'ai-auto-tool'),
                'limitExceeded' => __('Usage limit exceeded. Please upgrade to Pro.', 'ai-auto-tool'),
                'confirm' => __('This will generate 8-15 AI comments for this post. Continue?', 'ai-auto-tool'),
            )
        ));
    }

    /**
     * ========================================
     * COMMENT GENERATION - MANUAL MODE
     * ========================================
     */

    /**
     * AJAX callback for manual comment generation
     */
    public function manual_generate_comments_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            return;
        }
        
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        
        if (!$post_id) {
            wp_send_json_error(array('message' => __('Invalid post ID', 'ai-auto-tool')));
            return;
        }
        
        // Check quota
        if (!$this->aiautotool_checklimit($this->config)) {
            wp_send_json_error(array(
                'message' => __('Usage limit exceeded. Please upgrade to Pro.', 'ai-auto-tool')
            ));
            return;
        }
        
        $post = get_post($post_id);
        
        if (!$post) {
            wp_send_json_error(array('message' => __('Post not found', 'ai-auto-tool')));
            return;
        }
        
        // Generate comments
        $result = $this->generate_comments_for_post($post);
        
        if ($result) {
            $this->aiautotool__update_usage();
            wp_send_json_success(array(
                'message' => __('Comments generated successfully!', 'ai-auto-tool')
            ));
        } else {
            wp_send_json_error(array(
                'message' => __('Failed to generate comments. Please try again.', 'ai-auto-tool')
            ));
        }
    }

    /**
     * ========================================
     * HELPER FUNCTIONS
     * ========================================
     */

    /**
     * Fix and parse JSON response from AI
     * 
     * @param string $result JSON string from AI
     * @return array|null Array of parsed comments or null on failure
     */
    public function aiautotool_fixjsonreturn($result) {
        $pattern = '/\{(?:[^{}]|(?R))*\}/';
        preg_match_all($pattern, $result, $matches);
        $arritem = array();
        
        foreach ($matches[0] as $jsonString) {
            $decodedJson = json_decode($jsonString, true);
            
            if ($decodedJson !== null) {
                // Check if response has 'comments' wrapper
                if (isset($decodedJson['comments']) && is_array($decodedJson['comments'])) {
                    foreach ($decodedJson['comments'] as $item) {
                        $arritem[] = $item;
                    }
                } else {
                    $arritem[] = $decodedJson;
                }
            }
        }
        
        return !empty($arritem) ? $arritem : null;
    }

    /**
     * Clean post content for AI processing
     * 
     * @param string $content
     * @return string
     */
    private function aiautotool_fixcontent_PostContent($content) {
        $cleaned_content = strip_tags($content);
        $cleaned_content = substr($cleaned_content, 0, 1000);
        return $cleaned_content;
    }

    /**
     * ========================================
     * SETTINGS & UI
     * ========================================
     */

    /**
     * Initialize settings
     */
    public function init_settings() {
        register_setting('aiautotool-settings-group', $this->settings_option_name, array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_autocomment_setting'),
        ));
        add_settings_section(
            'aiautotool-section',
            __('AI Auto Tool Settings', 'ai-auto-tool'),
            array($this, 'section_callback'),
            'aiautotool-settings'
        );
    }
    
    /**
     * Sanitize autocomment setting
     * 
     * @param mixed $value Input value
     * @return array Sanitized array
     */
    public function sanitize_autocomment_setting($value) {
        if (!is_array($value)) {
            return array();
        }
        return map_deep($value, 'sanitize_text_field');
    }

    /**
     * Render settings page
     */
    public function render_setting() {
        if ($this->active != "true") {
            return '';
        }
        
        $setting = get_option($this->settings_option_name);
        $current_interval = 5;
        
        if (!empty($setting)) {
            if (isset($setting['time_comment'])) {
                $current_interval = $setting['time_comment'];
            }
        } else {
            $setting = array(
                'time_comment' => 5,
                'post_type' => array('post')
            );
            update_option($this->settings_option_name, $setting, null, 'no');
        }
        ?>

        <div id="tool-autocomment" class="tab-content" style="display:none;">
            <h1>
                <i class="fa-regular fa-comments"></i> 
                <?php esc_html_e('Auto General Comment using AI', 'ai-auto-tool'); ?>
            </h1>
            
            <div class="wrap">
                <h3><?php esc_html_e('Configuration', 'ai-auto-tool'); ?></h3>
                
                <form method="post" action="options.php">
                    <?php settings_fields('aiautotool-settings-group'); ?>

                    <!-- Comment Generation Interval -->
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Comment generation interval', 'ai-auto-tool'); ?>
                    </p>
                    <select id="aiautotool_setting_autocomment[time_comment]" 
                            name="aiautotool_setting_autocomment[time_comment]">
                        <option value="1" <?php selected($current_interval, 1); ?>>
                            <?php esc_html_e('1 minute', 'ai-auto-tool'); ?>
                        </option>
                        <option value="5" <?php selected($current_interval, 5); ?>>
                            <?php esc_html_e('5 minutes', 'ai-auto-tool'); ?>
                        </option>
                        <option value="10" <?php selected($current_interval, 10); ?>>
                            <?php esc_html_e('10 minutes', 'ai-auto-tool'); ?>
                        </option>
                        <option value="15" <?php selected($current_interval, 15); ?>>
                            <?php esc_html_e('15 minutes', 'ai-auto-tool'); ?>
                        </option>
                        <option value="30" <?php selected($current_interval, 30); ?>>
                            <?php esc_html_e('30 minutes', 'ai-auto-tool'); ?>
                        </option>
                        <option value="60" <?php selected($current_interval, 60); ?>>
                            <?php esc_html_e('1 hour', 'ai-auto-tool'); ?>
                        </option>
                        <option value="180" <?php selected($current_interval, 180); ?>>
                            <?php esc_html_e('3 hours', 'ai-auto-tool'); ?>
                        </option>
                        <option value="300" <?php selected($current_interval, 300); ?>>
                            <?php esc_html_e('5 hours', 'ai-auto-tool'); ?>
                        </option>
                        <option value="600" <?php selected($current_interval, 600); ?>>
                            <?php esc_html_e('10 hours', 'ai-auto-tool'); ?>
                        </option>
                        <option value="900" <?php selected($current_interval, 900); ?>>
                            <?php esc_html_e('15 hours', 'ai-auto-tool'); ?>
                        </option>
                        <option value="1440" <?php selected($current_interval, 1440); ?>>
                            <?php esc_html_e('24 hours', 'ai-auto-tool'); ?>
                        </option>
                    </select>

                    <!-- Post Type Selection -->
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Select post types for auto comment generation', 'ai-auto-tool'); ?>
                    </p>

                    <?php
                    $post_types = get_post_types(array('public' => true), 'names');
                    foreach ($post_types as $post_type) {
                        $checked = isset($setting['post_type']) && in_array($post_type, $setting['post_type']);
                        ?>
                        <p>
                            <label class="nut-switch">
                                <input type="checkbox" 
                                       name="aiautotool_setting_autocomment[post_type][]" 
                                       value="<?php echo esc_attr($post_type); ?>" 
                                       <?php checked($checked); ?> />
                                <span class="slider"></span>
                            </label>
                            <label class="ft-label-right">
                                <?php 
                                echo esc_html__('Enable for: ', 'ai-auto-tool') . 
                                     esc_html($post_type); 
                                ?>
                            </label>
                        </p>
                        <?php
                    }
                    ?>

                    <?php submit_button(__('Save Settings', 'ai-auto-tool'), 'ft-submit'); ?>
                </form>

                <!-- Usage Statistics -->
                <div class="aiautotool-usage-stats">
                    <h3><?php esc_html_e('Usage Statistics', 'ai-auto-tool'); ?></h3>
                    <p>
                        <strong><?php esc_html_e('Current Usage:', 'ai-auto-tool'); ?></strong> 
                        <?php echo esc_html($this->config['usage']); ?>
                        <?php if ($this->config['number_post'] != -1): ?>
                            / <?php echo esc_html($this->config['number_post']); ?>
                        <?php else: ?>
                            / <?php esc_html_e('Unlimited', 'ai-auto-tool'); ?>
                        <?php endif; ?>
                    </p>
                    <?php if (!empty($this->config['time_exprice'])): ?>
                        <p>
                            <strong><?php esc_html_e('Expires:', 'ai-auto-tool'); ?></strong> 
                            <?php echo esc_html($this->config['time_exprice']); ?>
                        </p>
                    <?php endif; ?>
                </div>

                <!-- Manual Generation Section -->
                <div class="aiautotool-manual-section">
                    <h3><?php esc_html_e('Manual Comment Generation', 'ai-auto-tool'); ?></h3>
                    <p class="ft-note">
                        <i class="fa-solid fa-info-circle"></i>
                        <?php esc_html_e('Generate comments manually for specific posts from the post edit screen.', 'ai-auto-tool'); ?>
                    </p>
                    <p>
                        <?php esc_html_e('Look for the "Generate AI Comments" button in the post editor sidebar.', 'ai-auto-tool'); ?>
                    </p>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render tab in settings
     */
    public function render_tab_setting() {
        if ($this->active == "true") {
            echo '<button href="#tool-autocomment" class="nav-tab sotab">' .
                 '<i class="fa-regular fa-comments"></i> ' .
                 esc_html__('Auto Comment', 'ai-auto-tool') .
                 '</button>';
        }
    }

    /**
     * Render feature box
     */
    public function render_feature() {
        // Load feature descriptions
        require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            $this->icon . ' ' . $this->name_plan,
            AiAutoTool_Feature_Descriptions::get('auto_comment'),
            "https://doc.aiautotool.com/features/auto-comment",
            $this->active_option_name,
            $this->active,
            plugins_url('../../images/logo.svg', __FILE__)
        );
        
        echo $autoToolBox->generateHTML();
    }

    /**
     * Render usage plan info
     */
    public function render_plan() {
        if ($this->active == 'true') {
            $quota = $this->config['number_post'] == -1 ? 
                     'Unlimited' : 
                     esc_html($this->config['number_post']);

            echo wp_kses(
                '<p>' . $this->icon . ' ' . esc_html($this->name_plan) .
                ': <strong>Usage: ' . esc_html($this->config['usage']) . '</strong></p>',
                [
                    'p' => [],
                    'i' => ['class' => []],
                    'strong' => [],
                ]
            );
        }
    }

    /**
     * Section callback
     */
    public function section_callback() {
        echo '<p>' . esc_html__('Configure auto comment generation settings.', 'ai-auto-tool') . '</p>';
    }

    /**
     * Display admin notices
     */
    public function display_notices() {
        $screen = get_current_screen();
        $stored = get_option('aiautotool_submitindex_notices', []);
        $this->notices = array_merge($stored, $this->notices);
        delete_option('aiautotool_submitindex_notices');
        
        foreach ($this->notices as $notice) {
            if (!empty($notice['show_on']) && is_array($notice['show_on']) && 
                !in_array($screen->id, $notice['show_on'], true)) {
                continue;
            }
            
            $class = 'notice instant-indexing-notice ' . $notice['class'];
            printf(
                '<div class="%1$s"><p>%2$s</p></div>',
                esc_attr($class),
                wp_kses_post($notice['message'])
            );
        }
    }

    /**
     * AJAX callback to update active status
     */
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, null, 'no');
            echo esc_html($active);
        }
        
        wp_die();
    }

    /**
     * Add notice
     * 
     * @param string $message
     * @param string $class
     * @param mixed $show_on
     * @param bool $persist
     * @param string $id
     */
    public function add_notice($message, $class = '', $show_on = null, $persist = false, $id = '') {
        $notice = [
            'message' => $message,
            'class' => $class . ' is-dismissible',
            'show_on' => $show_on,
        ];

        if (!$id) {
            $id = md5(serialize($notice));
        }

        if ($persist) {
            $notices = get_option('aiautotool_submitindex_notices', []);
            $notices[$id] = $notice;
            update_option('aiautotool_submitindex_notices', $notices, null, 'no');
            return;
        }
        
        $this->notices[$id] = $notice;
    }
}
} // End of class_exists check
