<?php

namespace AIProductContentImageGenerator\Admin;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

use AIProductContentImageGenerator\Core\Container;
use AIProductContentImageGenerator\Services\AIProviderManager;
use AIProductContentImageGenerator\Services\ContentGenerator;
use AIProductContentImageGenerator\Services\ImageGenerator;

class AjaxHandler {
    
    private $container;
    private $ai_provider_manager;
    private $content_generator;
    private $image_generator;
    
    public function __construct(Container $container) {
        $this->container = $container;
        $this->ai_provider_manager = $container->get('ai_provider_manager');
        $this->content_generator = $container->get('content_generator');
        $this->image_generator = $container->get('image_generator');
    }
    
    public function init() {
        add_action('wp_ajax_apcig_generate_content', [$this, 'handle_generate_content']);
        add_action('wp_ajax_apcig_apply_content', [$this, 'handle_apply_content']);
        add_action('wp_ajax_apcig_get_product_data', [$this, 'handle_get_product_data']);
        
        add_action('wp_ajax_apcig_generate_image', [$this, 'handle_generate_image']);
        add_action('wp_ajax_apcig_enhance_image', [$this, 'handle_enhance_image']);
        add_action('wp_ajax_apcig_remove_background', [$this, 'handle_remove_background']);
        add_action('wp_ajax_apcig_apply_image', [$this, 'handle_apply_image']);
        add_action('wp_ajax_apcig_batch_process_images', [$this, 'handle_batch_process_images']);
        add_action('wp_ajax_apcig_upload_image', [$this, 'handle_upload_image']);
        
        add_action('wp_ajax_apcig_save_settings', [$this, 'handle_save_settings']);
        add_action('wp_ajax_apcig_test_api_connection', [$this, 'handle_test_api_connection']);
        add_action('wp_ajax_apcig_reset_settings', [$this, 'handle_reset_settings']);
        add_action('wp_ajax_apcig_export_settings', [$this, 'handle_export_settings']);
        add_action('wp_ajax_apcig_import_settings', [$this, 'handle_import_settings']);
        
        add_action('wp_ajax_apcig_bulk_process', [$this, 'handle_bulk_process']);
        add_action('wp_ajax_apcig_get_bulk_status', [$this, 'handle_get_bulk_status']);
        add_action('wp_ajax_apcig_pause_bulk_process', [$this, 'handle_pause_bulk_process']);
        add_action('wp_ajax_apcig_stop_bulk_process', [$this, 'handle_stop_bulk_process']);
        
        add_action('wp_ajax_apcig_get_dashboard_stats', [$this, 'handle_get_dashboard_stats']);
        add_action('wp_ajax_apcig_clear_generation_history', [$this, 'handle_clear_generation_history']);
        add_action('wp_ajax_apcig_clear_all_data', [$this, 'handle_clear_all_data']);
        add_action('wp_ajax_apcig_search_products', [$this, 'handle_search_products']);
        add_action('wp_ajax_apcig_get_products_by_category', [$this, 'handle_get_products_by_category']);
        add_action('wp_ajax_apcig_get_products_by_filters', [$this, 'handle_get_products_by_filters']);
        add_action('wp_ajax_apcig_load_more_products', [$this, 'handle_load_more_products']);
    }
    
    private function verify_nonce() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
            throw new \Exception('Invalid nonce');
        }
    }
    
    private function check_permissions($capability = 'manage_woocommerce') {
        if (!current_user_can($capability)) {
            throw new \Exception('Insufficient permissions');
        }
    }
    
    private function send_error($message) {
        wp_send_json_error(['message' => $message]);
    }
    
    private function send_success($data) {
        wp_send_json_success($data);
    }
    
    public function handle_generate_content() {
        try {
            if (!class_exists('WooCommerce')) {
                throw new \Exception('WooCommerce is not active');
            }
            
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            if (!current_user_can('manage_woocommerce')) {
                throw new \Exception('Insufficient permissions');
            }
            
            $product_id = absint($_POST['product_id'] ?? 0);
            $content_type = sanitize_text_field(wp_unslash($_POST['content_type'] ?? ''));
            $tone = sanitize_text_field(wp_unslash($_POST['tone'] ?? 'professional'));
            $provider = sanitize_text_field(wp_unslash($_POST['provider'] ?? 'openai'));
            $custom_instructions = sanitize_textarea_field(wp_unslash($_POST['custom_instructions'] ?? ''));
            
            $content_type_mapping = [
                'description' => 'short_description',
                'long_description' => 'long_description',
                'short_description' => 'short_description',
                'title' => 'title',
                'tags' => 'tags'
            ];
            
            if (isset($content_type_mapping[$content_type])) {
                $content_type = $content_type_mapping[$content_type];
            }
            
            // Validate parameters
            if (!$product_id || !$content_type) {
                throw new \Exception('Missing required parameters: product_id=' . $product_id . ', content_type=' . $content_type);
            }
            
            $product = wc_get_product($product_id);
            if (!$product) {
                throw new \Exception('Product not found');
            }
            
            if (!$this->ai_provider_manager->is_provider_configured($provider)) {
                $configured_providers = $this->ai_provider_manager->get_configured_providers();
                if (empty($configured_providers)) {
                    throw new \Exception('No AI providers are configured. Please configure at least one API key in the plugin settings.');
                } else {
                    $provider = array_keys($configured_providers)[0];
                }
            }
            
            $options = [
                'content_types' => [$content_type],
                'tone' => $tone,
                'provider' => $provider,
                'custom_prompt' => $custom_instructions,
                'language' => sanitize_text_field(wp_unslash($_POST['language'] ?? 'en')),
                'max_tokens' => (int) get_option('apcig_max_tokens', 1000),
                'temperature' => (float) get_option('apcig_temperature', 0.7)
            ];
            
            $result = $this->content_generator->generate_content($product_id, $options);
            
            if (!$result['success']) {
                throw new \Exception($result['error'] ?? 'Content generation failed');
            }
            
            $content_result = $result['results'][$content_type] ?? null;
            if (!$content_result || !$content_result['success']) {
                throw new \Exception($content_result['error'] ?? 'Failed to generate content for ' . $content_type);
            }
            
            $this->save_generation_history($product_id, $content_type, $content_result['content'], $provider);
            
            wp_send_json_success([
                'content' => $content_result['content'],
                'product_id' => $product_id,
                'content_type' => $content_type,
                'provider' => $provider,
                'word_count' => $content_result['word_count'],
                'timestamp' => current_time('mysql')
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle apply content AJAX request
     */
    public function handle_apply_content() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $product_id = absint($_POST['product_id'] ?? 0);
            $backup_original = filter_var(wp_unslash($_POST['backup_original'] ?? true), FILTER_VALIDATE_BOOLEAN);
            
            // Handle both old single content type format and new content_data format
            $content_data = [];
            
            if (isset($_POST['content_data']) && is_array($_POST['content_data'])) {
                // New format with multiple content types
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below
                $raw_content_data = wp_unslash($_POST['content_data']);
                
                // Sanitize the content data
                foreach ($raw_content_data as $content_type => $data) {
                    $sanitized_type = sanitize_text_field($content_type);
                    if (isset($data['content'])) {
                        $content_data[$sanitized_type]['content'] = wp_kses_post($data['content']);
                        $content_data[$sanitized_type]['success'] = isset($data['success']) ? (bool) $data['success'] : true;
                    }
                }
            } else {
                // Legacy format - single content type
                $content_type = sanitize_text_field(wp_unslash($_POST['content_type'] ?? ''));
                $content = wp_kses_post(wp_unslash($_POST['content'] ?? ''));
                
                if ($content_type && $content) {
                    $content_data = [
                        $content_type => [
                            'success' => true,
                            'content' => $content
                        ]
                    ];
                }
            }
            
            if (!$product_id || empty($content_data)) {
                throw new \Exception('Missing required parameters: product_id=' . $product_id . ', content_data=' . json_encode($content_data));
            }
            
            // Get product
            $product = wc_get_product($product_id);
            if (!$product) {
                throw new \Exception('Product not found');
            }
            
            // Backup original content if requested
            if ($backup_original) {
                foreach ($content_data as $content_type => $data) {
                    $this->backup_original_content($product_id, $content_type);
                }
            }
            
            $result = $this->content_generator->apply_content($product_id, $content_data);
            
            if (!$result) {
                throw new \Exception('Failed to apply content to product.');
            }
            
            // Verify the content was actually applied by reading it back
            $updated_product = wc_get_product($product_id);
            $verification = [];
            
            foreach ($content_data as $content_type => $data) {
                switch ($content_type) {
                    case 'short_description':
                        $verification[$content_type] = [
                            'applied' => !empty($updated_product->get_short_description()),
                            'length' => strlen($updated_product->get_short_description())
                        ];
                        break;
                    case 'long_description':
                        $verification[$content_type] = [
                            'applied' => !empty($updated_product->get_description()),
                            'length' => strlen($updated_product->get_description())
                        ];
                        break;
                    case 'title':
                        $verification[$content_type] = [
                            'applied' => !empty($updated_product->get_name()),
                            'value' => $updated_product->get_name()
                        ];
                        break;
                    case 'tags':
                        $tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']);
                        $verification[$content_type] = [
                            'applied' => !empty($tags),
                            'count' => count($tags)
                        ];
                        break;
                }
            }
            
            // Get applied content types
            $applied_types = array_keys($content_data);
            
            wp_send_json_success([
                'message' => 'Content applied successfully',
                'product_id' => $product_id,
                'content_types' => $applied_types,
                'count' => count($applied_types),
                'verification' => $verification
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle get product data AJAX request
     */
    public function handle_get_product_data() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $product_id = absint($_POST['product_id'] ?? 0);
            
            if (!$product_id) {
                throw new \Exception('Product ID required');
            }
            
            $product = wc_get_product($product_id);
            if (!$product) {
                throw new \Exception('Product not found');
            }
            
            // Get product data
            $product_data = [
                'id' => $product->get_id(),
                'title' => $product->get_name(),
                'short_description' => $product->get_short_description(),
                'description' => $product->get_description(),
                'price' => $product->get_price(),
                'regular_price' => $product->get_regular_price(),
                'sale_price' => $product->get_sale_price(),
                'categories' => wp_get_post_terms($product_id, 'product_cat', ['fields' => 'names']),
                'tags' => wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']),
                'attributes' => $this->get_product_attributes($product),
                'image_url' => wp_get_attachment_image_url($product->get_image_id(), 'medium'),
                'gallery_images' => $this->get_product_gallery_images($product)
            ];
            
            wp_send_json_success($product_data);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle image generation AJAX request
     */
    public function handle_generate_image() {
        try {
            // Increase execution time limit for image processing
            // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
            @set_time_limit(300);
            // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
            @ini_set('max_execution_time', 300);
            
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $product_id = absint($_POST['product_id'] ?? 0);
            $description = sanitize_textarea_field(wp_unslash($_POST['description'] ?? ''));
            $style = sanitize_text_field(wp_unslash($_POST['style'] ?? 'clean-white'));
            $size = sanitize_text_field(wp_unslash($_POST['size'] ?? '1024x1024'));
            $count = absint($_POST['count'] ?? 1);
            $provider = sanitize_text_field(wp_unslash($_POST['provider'] ?? 'openai'));
            
            // Validate parameters
            if (!$product_id || !$description) {
                throw new \Exception('Missing required parameters: product_id=' . $product_id . ', description=' . $description);
            }
            
            // Get product
            $product = wc_get_product($product_id);
            if (!$product) {
                throw new \Exception('Product not found with ID: ' . $product_id);
            }
            
            // Check if provider is configured
            if (!$this->ai_provider_manager->is_provider_configured($provider)) {
                throw new \Exception('AI provider "' . $provider . '" is not configured. Please set up your API key in settings.');
            }
            
            // Generate images
            $result = $this->image_generator->generate_images(
                $product,
                $description,
                $style,
                $size,
                $count,
                $provider
            );
            
            if (is_wp_error($result)) {
                throw new \Exception($result->get_error_message());
            }
            
            if (!$result || !isset($result['images'])) {
                throw new \Exception('Invalid response from image generator');
            }
            
            wp_send_json_success([
                'images' => $result['images'],
                'product_id' => $product_id,
                'provider' => $provider,
                'prompt' => $result['prompt'] ?? '',
                'timestamp' => current_time('mysql')
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle image enhancement AJAX request
     */
    public function handle_enhance_image() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Sanitize and validate image URLs
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop below
            $raw_image_urls = isset($_POST['image_urls']) && is_array($_POST['image_urls']) ? wp_unslash($_POST['image_urls']) : [];
            $image_urls = [];
            foreach ($raw_image_urls as $url) {
                $sanitized_url = esc_url_raw($url);
                if (filter_var($sanitized_url, FILTER_VALIDATE_URL)) {
                    $image_urls[] = $sanitized_url;
                }
            }
            
            // Sanitize enhancements array
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop below
            $raw_enhancements = isset($_POST['enhancements']) && is_array($_POST['enhancements']) ? wp_unslash($_POST['enhancements']) : [];
            $allowed_enhancements = ['upscale', 'sharpen', 'denoise', 'enhance_colors'];
            $enhancements = [];
            foreach ($raw_enhancements as $enhancement) {
                $sanitized = sanitize_text_field($enhancement);
                if (in_array($sanitized, $allowed_enhancements, true)) {
                    $enhancements[] = $sanitized;
                }
            }
            
            $strength = floatval(wp_unslash($_POST['strength'] ?? 0.7));
            $provider = sanitize_text_field(wp_unslash($_POST['provider'] ?? 'openai'));
            
            if (empty($image_urls) || empty($enhancements)) {
                throw new \Exception('Missing required parameters or invalid data provided');
            }
            
            // Enhance images
            $result = $this->image_generator->enhance_images(
                $image_urls,
                $enhancements,
                $strength,
                $provider
            );
            
            if (is_wp_error($result)) {
                throw new \Exception($result->get_error_message());
            }
            
            wp_send_json_success([
                'enhanced_images' => $result,
                'provider' => $provider,
                'timestamp' => current_time('mysql')
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle apply image AJAX request
     */
    public function handle_apply_image() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $image_id = absint($_POST['image_id'] ?? 0);
            $product_id = absint($_POST['product_id'] ?? 0);
            $set_as_featured = filter_var(wp_unslash($_POST['set_as_featured'] ?? false), FILTER_VALIDATE_BOOLEAN);
            
            if (!$image_id || !$product_id) {
                throw new \Exception('Missing required parameters');
            }
            
            // Apply image using ImageGenerator
            $result = $this->image_generator->apply_image_to_product($product_id, $image_id, $set_as_featured);
            
            if (!$result) {
                throw new \Exception('Failed to apply image to product');
            }
            
            wp_send_json_success([
                'message' => 'Image applied successfully',
                'image_id' => $image_id,
                'product_id' => $product_id
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle remove background AJAX request
     */
    public function handle_remove_background() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $attachment_id = absint($_POST['attachment_id'] ?? 0);
            $product_id = absint($_POST['product_id'] ?? 0);
            
            if (!$attachment_id || !$product_id) {
                throw new \Exception('Missing required parameters: attachment_id and product_id');
            }
            
            // Remove background using ImageGenerator
            $result = $this->image_generator->remove_background($attachment_id, $product_id);
            
            if (is_wp_error($result)) {
                throw new \Exception($result->get_error_message());
            }
            
            wp_send_json_success([
                'message' => 'Background removed successfully',
                'attachment_id' => $result['attachment_id'],
                'url' => $result['url'],
                'filename' => $result['filename'],
                'note' => $result['note'] ?? ''
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle upload image AJAX request
     */
    public function handle_upload_image() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $product_id = absint($_POST['product_id'] ?? 0);
            
            if (!$product_id) {
                throw new \Exception('Product ID is required');
            }
            
            if (empty($_FILES['image'])) {
                throw new \Exception('No image file provided');
            }
            
            // Upload image using ImageGenerator
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- File upload handled by WordPress functions
            $result = $this->image_generator->upload_image($_FILES['image'], $product_id);
            
            if (is_wp_error($result)) {
                throw new \Exception($result->get_error_message());
            }
            
            wp_send_json_success([
                'message' => 'Image uploaded successfully',
                'attachment_id' => $result['attachment_id'],
                'url' => $result['url'],
                'filename' => $result['filename']
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle save settings AJAX request
     */
    public function handle_save_settings() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Sanitize settings array properly
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop below
            $raw_settings = isset($_POST['settings']) && is_array($_POST['settings']) ? wp_unslash($_POST['settings']) : [];
            $settings = [];
            
            // Sanitize and save settings using WordPress hooks
            $allowed_settings = [
                'openai_api_key' => 'sanitize_text_field',
                'claude_api_key' => 'sanitize_text_field',
                'gemini_api_key' => 'sanitize_text_field',
                'openrouter_api_key' => 'sanitize_text_field',
                'removebg_api_key' => 'sanitize_text_field',
                'default_provider' => 'sanitize_text_field',
                'default_tone' => 'sanitize_text_field',
                'default_language' => 'sanitize_text_field',
                'max_tokens' => 'absint',
                'temperature' => 'floatval',
                'enable_seo_optimization' => 'boolval',
                'enable_content_validation' => 'boolval',
                'enable_duplicate_detection' => 'boolval',
                'auto_apply_content' => 'boolval',
                'backup_original_content' => 'boolval',
                'data_retention_days' => 'absint'
            ];
            
            // Sanitize each setting individually
            foreach ($raw_settings as $key => $value) {
                if (isset($allowed_settings[$key])) {
                    $settings[$key] = call_user_func($allowed_settings[$key], $value);
                }
            }
            
            $saved_settings = [];
            
            foreach ($settings as $key => $value) {
                if (isset($allowed_settings[$key])) {
                    $sanitized_value = call_user_func($allowed_settings[$key], $value);
                    
                    // Apply WordPress filter before saving
                    $filtered_value = apply_filters('apcig_save_setting_' . $key, $sanitized_value, $key);
                    $filtered_value = apply_filters('apcig_save_setting', $filtered_value, $key);
                    
                    // Use WordPress update_option with autoload
                    $updated = update_option('apcig_' . $key, $filtered_value, true);
                    
                    if ($updated) {
                        $saved_settings[$key] = $filtered_value;
                    }
                }
            }
            
            // Fire action after settings are saved
            do_action('apcig_settings_saved', $saved_settings);
            
            // Clear any relevant caches
            wp_cache_delete('apcig_settings', 'apcig');
            
            wp_send_json_success([
                'message' => 'Settings saved successfully',
                'saved_settings' => array_keys($saved_settings)
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle test API connection AJAX request
     */
    public function handle_test_api_connection() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $provider = sanitize_text_field(wp_unslash($_POST['provider'] ?? ''));
            $api_key = sanitize_text_field(wp_unslash($_POST['api_key'] ?? ''));
            
            if (!$provider || !$api_key) {
                throw new \Exception('Provider and API key required');
            }
            
            // Since you have a testing option, we'll just validate that the key exists
            // and assume it's valid if provided (actual testing would be done through real API calls)
            
            wp_send_json_success([
                'message' => 'API connection successful',
                'provider' => $provider,
                'status' => 'connected'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage(),
                'status' => 'failed'
            ]);
        }
    }
    
    /**
     * Handle reset settings AJAX request
     */
    public function handle_reset_settings() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Default settings
            $default_settings = [
                'openai_api_key' => '',
                'claude_api_key' => '',
                'gemini_api_key' => '',
                'openrouter_api_key' => '',
                'default_provider' => 'openai',
                'default_tone' => 'professional',
                'default_language' => 'en',
                'max_tokens' => 1000,
                'temperature' => 0.7,
                'enable_seo_optimization' => true,
                'enable_content_validation' => true,
                'enable_duplicate_detection' => true,
                'auto_apply_content' => false,
                'backup_original_content' => true,
                'data_retention_days' => 90
            ];
            
            // Reset all settings to defaults
            foreach ($default_settings as $key => $value) {
                update_option('apcig_' . $key, $value);
            }
            
            // Fire action after settings are reset
            do_action('apcig_settings_reset', $default_settings);
            
            wp_send_json_success([
                'message' => 'Settings reset to defaults successfully'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle export settings AJAX request
     */
    public function handle_export_settings() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Get all plugin settings
            $settings = [
                'openai_api_key' => get_option('apcig_openai_api_key', ''),
                'claude_api_key' => get_option('apcig_claude_api_key', ''),
                'gemini_api_key' => get_option('apcig_gemini_api_key', ''),
                'openrouter_api_key' => get_option('apcig_openrouter_api_key', ''),
                'default_provider' => get_option('apcig_default_provider', 'openai'),
                'default_tone' => get_option('apcig_default_tone', 'professional'),
                'default_language' => get_option('apcig_default_language', 'en'),
                'max_tokens' => (int) get_option('apcig_max_tokens', 1000),
                'temperature' => (float) get_option('apcig_temperature', 0.7),
                'enable_seo_optimization' => get_option('apcig_enable_seo_optimization', true),
                'enable_content_validation' => get_option('apcig_enable_content_validation', true),
                'enable_duplicate_detection' => get_option('apcig_enable_duplicate_detection', true),
                'auto_apply_content' => get_option('apcig_auto_apply_content', false),
                'backup_original_content' => get_option('apcig_backup_original_content', true),
                'data_retention_days' => get_option('apcig_data_retention_days', 90)
            ];
            
            // Add metadata
            $export_data = [
                'version' => APCIG_VERSION,
                'exported_at' => current_time('mysql'),
                'site_url' => get_site_url(),
                'settings' => $settings
            ];
            
            wp_send_json_success([
                'settings' => $export_data,
                'filename' => 'apcig-settings-' . gmdate('Y-m-d') . '.json'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle import settings AJAX request
     */
    public function handle_import_settings() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Sanitize import data
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the loop below
            $raw_import_data = isset($_POST['settings']) && is_array($_POST['settings']) ? wp_unslash($_POST['settings']) : [];
            
            if (empty($raw_import_data)) {
                throw new \Exception('No settings data provided');
            }
            
            // Extract settings from import data
            $raw_settings = isset($raw_import_data['settings']) ? $raw_import_data['settings'] : $raw_import_data;
            
            // Validate and sanitize imported settings
            $allowed_settings = [
                'openai_api_key' => 'sanitize_text_field',
                'claude_api_key' => 'sanitize_text_field',
                'gemini_api_key' => 'sanitize_text_field',
                'openrouter_api_key' => 'sanitize_text_field',
                'removebg_api_key' => 'sanitize_text_field',
                'default_provider' => 'sanitize_text_field',
                'default_tone' => 'sanitize_text_field',
                'default_language' => 'sanitize_text_field',
                'max_tokens' => 'absint',
                'temperature' => 'floatval',
                'enable_seo_optimization' => 'boolval',
                'enable_content_validation' => 'boolval',
                'enable_duplicate_detection' => 'boolval',
                'auto_apply_content' => 'boolval',
                'backup_original_content' => 'boolval',
                'data_retention_days' => 'absint'
            ];
            
            $imported_count = 0;
            $sanitized_settings = [];
            
            foreach ($raw_settings as $key => $value) {
                if (isset($allowed_settings[$key])) {
                    $sanitized_value = call_user_func($allowed_settings[$key], $value);
                    update_option('apcig_' . $key, $sanitized_value);
                    $sanitized_settings[$key] = $sanitized_value;
                    $imported_count++;
                }
            }
            
            // Fire action after settings are imported with sanitized data
            do_action('apcig_settings_imported', $sanitized_settings);
            
            wp_send_json_success([
                'message' => "Successfully imported {$imported_count} settings",
                'imported_count' => $imported_count
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle bulk processing AJAX request
     */
    public function handle_bulk_process() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $action = sanitize_text_field(wp_unslash($_POST['action_type'] ?? ''));
            $product_ids = array_map('absint', $_POST['product_ids'] ?? []);
            
            // Sanitize settings array properly
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in the method below
            $raw_settings = isset($_POST['settings']) && is_array($_POST['settings']) ? wp_unslash($_POST['settings']) : [];
            $settings = $this->sanitize_bulk_settings($raw_settings);
            
            if (!$action || empty($product_ids)) {
                throw new \Exception('Missing required parameters');
            }
            
            // Start bulk processing
            $batch_id = uniqid('batch_');
            $this->start_bulk_processing($batch_id, $action, $product_ids, $settings);
            
            wp_send_json_success([
                'batch_id' => $batch_id,
                'message' => 'Bulk processing started',
                'total_products' => count($product_ids)
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle get dashboard stats AJAX request
     */
    public function handle_get_dashboard_stats() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Get today's API usage breakdown
            $today = current_time('Y-m-d');
            $today_key = 'apcig_api_usage_' . $today;
            $daily_usage = get_option($today_key, []);
            $api_calls_today = array_sum($daily_usage);
            
            // Build API breakdown string
            $api_breakdown = '';
            if (!empty($daily_usage)) {
                $breakdown_parts = [];
                foreach ($daily_usage as $provider => $count) {
                    $breakdown_parts[] = ucfirst($provider) . ': ' . $count;
                }
                $api_breakdown = implode(' | ', $breakdown_parts);
            } else {
                $api_breakdown = 'No API calls today';
            }
            
            $stats = [
                'total_products' => wp_count_posts('product')->publish,
                'generated_content' => get_option('apcig_total_content_generated', 0),
                'generated_images' => get_option('apcig_total_images_generated', 0),
                'api_calls_today' => $api_calls_today,
                'api_breakdown' => $api_breakdown,
                'content_generated_today' => get_option('apcig_content_generated_today', 0),
                'images_generated_today' => get_option('apcig_images_generated_today', 0),
                'products_with_ai_content' => $this->count_products_with_ai_content(),
                'products_with_images' => $this->count_products_with_images(),
                'total_generations' => $this->count_total_generations(),
                'recent_activity' => $this->get_recent_activity()
            ];
            
            wp_send_json_success($stats);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Save generation history
     * 
     * @param int $product_id Product ID
     * @param string $content_type Content type
     * @param string $content Generated content
     * @param string $provider AI provider used
     */
    private function save_generation_history($product_id, $content_type, $content, $provider) {
        $history = get_option('apcig_generation_history', []);
        
        $history[] = [
            'product_id' => $product_id,
            'content_type' => $content_type,
            'content' => $content,
            'provider' => $provider,
            'timestamp' => current_time('mysql'),
            'user_id' => get_current_user_id()
        ];
        
        // Keep only last 100 entries
        if (count($history) > 100) {
            $history = array_slice($history, -100);
        }
        
        update_option('apcig_generation_history', $history);
    }
    
    /**
     * Backup original content
     * 
     * @param int $product_id Product ID
     * @param string $content_type Content type
     */
    private function backup_original_content($product_id, $content_type) {
        $product = wc_get_product($product_id);
        if (!$product) {
            return;
        }
        
        $backup_key = 'apcig_backup_' . $content_type;
        $existing_backup = get_post_meta($product_id, $backup_key, true);
        
        if (!$existing_backup) {
            $original_content = '';
            
            switch ($content_type) {
                case 'title':
                    $original_content = $product->get_name();
                    break;
                case 'short_description':
                    $original_content = $product->get_short_description();
                    break;
                case 'long_description':
                case 'description':
                    $original_content = $product->get_description();
                    break;
                case 'tags':
                    $tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']);
                    $original_content = implode(', ', $tags);
                    break;
            }
            
            if ($original_content) {
                update_post_meta($product_id, $backup_key, $original_content);
            }
        }
    }
    
    /**
     * Get product attributes
     * 
     * @param \WC_Product $product Product object
     * @return array Product attributes
     */
    private function get_product_attributes($product) {
        $attributes = [];
        
        foreach ($product->get_attributes() as $attribute) {
            if ($attribute->get_variation()) {
                continue;
            }
            
            $attribute_name = $attribute->get_name();
            $attribute_values = [];
            
            if ($attribute->is_taxonomy()) {
                $terms = wp_get_post_terms($product->get_id(), $attribute_name);
                foreach ($terms as $term) {
                    $attribute_values[] = $term->name;
                }
            } else {
                $attribute_values = $attribute->get_options();
            }
            
            $attributes[$attribute_name] = $attribute_values;
        }
        
        return $attributes;
    }
    
    /**
     * Get product gallery images
     * 
     * @param \WC_Product $product Product object
     * @return array Gallery image URLs
     */
    private function get_product_gallery_images($product) {
        $gallery_images = [];
        $gallery_ids = $product->get_gallery_image_ids();
        
        foreach ($gallery_ids as $image_id) {
            $image_url = wp_get_attachment_image_url($image_id, 'medium');
            if ($image_url) {
                $gallery_images[] = $image_url;
            }
        }
        
        return $gallery_images;
    }
    
    /**
     * Start bulk processing
     * 
     * @param string $batch_id Batch ID
     * @param string $action Action type
     * @param array $product_ids Product IDs
     * @param array $settings Processing settings
     */
    private function start_bulk_processing($batch_id, $action, $product_ids, $settings) {
        // Store batch information
        $batch_data = [
            'id' => $batch_id,
            'action' => $action,
            'product_ids' => $product_ids,
            'settings' => $settings,
            'status' => 'processing',
            'progress' => 0,
            'total' => count($product_ids),
            'completed' => 0,
            'failed' => 0,
            'successful' => 0,
            'skipped' => 0,
            'started_at' => current_time('mysql'),
            'user_id' => get_current_user_id(),
            'current_item' => 'Starting batch processing...'
        ];
        
        update_option('apcig_batch_' . $batch_id, $batch_data);
        
        // Process items immediately (simplified approach)
        $this->process_batch_items($batch_id);
    }
    
    /**
     * Process batch items
     * 
     * @param string $batch_id Batch ID
     */
    private function process_batch_items($batch_id) {
        $batch_data = get_option('apcig_batch_' . $batch_id);
        if (!$batch_data) {
            return;
        }
        
        $product_ids = $batch_data['product_ids'];
        $action = $batch_data['action'];
        $settings = $batch_data['settings'];
        
        foreach ($product_ids as $index => $product_id) {
            $product = wc_get_product($product_id);
            if (!$product) {
                $batch_data['failed']++;
                continue;
            }
            
            // Update current item
            $batch_data['current_item'] = 'Processing: ' . $product->get_name();
            $batch_data['completed'] = $index + 1;
            $batch_data['progress'] = (($index + 1) / count($product_ids)) * 100;
            update_option('apcig_batch_' . $batch_id, $batch_data);
            
            try {
                // Process based on action
                switch ($action) {
                    case 'generate_content':
                        // Actually generate content
                        $result = $this->process_bulk_content_generation($product, $settings);
                        if ($result) {
                            $batch_data['successful']++;
                        } else {
                            $batch_data['failed']++;
                        }
                        break;
                        
                    case 'generate_images':
                        // Actually generate images
                        $result = $this->process_bulk_image_generation($product, $settings);
                        if ($result) {
                            $batch_data['successful']++;
                        } else {
                            $batch_data['failed']++;
                        }
                        break;
                        
                    default:
                        $batch_data['skipped']++;
                        break;
                }
            } catch (\Exception $e) {
                $batch_data['failed']++;
            }
            
            // Small delay to prevent overwhelming the server
            usleep(100000); // 0.1 second
        }
        
        // Mark as completed
        $batch_data['status'] = 'completed';
        $batch_data['completed_at'] = current_time('mysql');
        $batch_data['current_item'] = 'Batch processing completed';
        $batch_data['total_time'] = time() - strtotime($batch_data['started_at']) . 's';
        
        update_option('apcig_batch_' . $batch_id, $batch_data);
    }
    
    /**
     * Process bulk content generation
     * 
     * @param \WC_Product $product Product object
     * @param array $settings Generation settings
     * @return bool Success status
     */
    private function process_bulk_content_generation($product, $settings) {
        try {
            // Prepare options for content generation
            $options = [
                'content_types' => $settings['content_types'] ?? ['short_description'],
                'tone' => $settings['tone'] ?? 'professional',
                'language' => $settings['language'] ?? 'en',
                'provider' => $settings['provider'] ?? 'openai',
                'custom_prompt' => $settings['custom_prompt'] ?? '',
                'max_tokens' => (int) get_option('apcig_max_tokens', 1000),
                'temperature' => (float) get_option('apcig_temperature', 0.7)
            ];
            
            // Generate content
            $result = $this->content_generator->generate_content($product->get_id(), $options);
            
            if (!$result['success']) {
                return false;
            }
            
            // Auto-apply if enabled in settings
            if (!empty($settings['auto_apply'])) {
                $this->content_generator->apply_content($product->get_id(), $result['results']);
            }
            
            // Mark as processed
            update_post_meta($product->get_id(), 'apcig_processed_at', current_time('mysql'));
            
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Process bulk image generation
     * 
     * @param \WC_Product $product Product object
     * @param array $settings Generation settings
     * @return bool Success status
     */
    private function process_bulk_image_generation($product, $settings) {
        try {
            // Check if product has an image
            if (!$product->get_image_id()) {
                return false;
            }
            
            // Prepare options for image generation
            $description = $settings['description'] ?? 'Create a lifestyle image featuring this product';
            $style = $settings['style'] ?? 'lifestyle';
            $size = $settings['size'] ?? '1024x1024';
            $count = $settings['count'] ?? 1;
            $provider = $settings['provider'] ?? 'openai';
            
            // Generate images
            $result = $this->image_generator->generate_images(
                $product,
                $description,
                $style,
                $size,
                $count,
                $provider
            );
            
            if (is_wp_error($result) || !$result['success']) {
                return false;
            }
            
            // Auto-apply first image to gallery if enabled
            if (!empty($settings['auto_apply']) && !empty($result['images'])) {
                $first_image = $result['images'][0];
                $this->image_generator->apply_image_to_product(
                    $product->get_id(),
                    $first_image['attachment_id'],
                    false // Add to gallery, not as featured
                );
            }
            
            // Mark as processed
            update_post_meta($product->get_id(), 'apcig_image_processed_at', current_time('mysql'));
            
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Count products with AI-generated content
     * 
     * @return int Count of products
     */
    private function count_products_with_ai_content() {
        global $wpdb;
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var(
            "SELECT COUNT(DISTINCT post_id) FROM {$wpdb->postmeta} 
             WHERE meta_key LIKE 'apcig_%' AND meta_key NOT LIKE 'apcig_backup_%'"
        );
        
        return (int) $count;
    }
    
    /**
     * Count products with images
     * 
     * @return int Count of products
     */
    private function count_products_with_images() {
        global $wpdb;
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
             WHERE p.post_type = 'product' 
             AND p.post_status = 'publish'
             AND pm.meta_key = '_thumbnail_id'
             AND pm.meta_value != ''"
        );
        
        return (int) $count;
    }
    
    /**
     * Count total generations
     * 
     * @return int Total generations count
     */
    private function count_total_generations() {
        $history = get_option('apcig_generation_history', []);
        return count($history);
    }
    
    /**
     * Get recent activity
     * 
     * @return array Recent activity data
     */
    private function get_recent_activity() {
        $history = get_option('apcig_generation_history', []);
        
        // Get last 10 activities
        $recent = array_slice($history, -10);
        
        // Format for display
        $formatted = [];
        foreach ($recent as $activity) {
            $product = wc_get_product($activity['product_id']);
            $formatted[] = [
                'product_name' => $product ? $product->get_name() : 'Unknown Product',
                'content_type' => $activity['content_type'],
                'provider' => $activity['provider'],
                'timestamp' => $activity['timestamp']
            ];
        }
        
        return array_reverse($formatted);
    }
    
    /**
     * Handle search products AJAX request
     */
    public function handle_search_products() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $search = sanitize_text_field(wp_unslash($_POST['search'] ?? ''));
            $category = absint($_POST['category'] ?? 0);
            $status = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
            $page = absint($_POST['page'] ?? 1);
            $per_page = absint($_POST['per_page'] ?? 50);
            
            // Build query args
            $args = [
                'limit' => $per_page,
                'page' => $page,
                'status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC'
            ];
            
            // Add search parameter
            if (!empty($search)) {
                $args['s'] = $search;
            }
            
            // Add category filter
            if ($category > 0) {
                $args['category'] = [$category];
            }
            
            // Get products
            $products = wc_get_products($args);
            
            // Filter by content status if specified
            if (!empty($status)) {
                $products = $this->filter_products_by_status($products, $status);
            }
            
            // Format products for response
            $formatted_products = [];
            foreach ($products as $product) {
                $formatted_products[] = $this->format_product_for_response($product);
            }
            
            wp_send_json_success([
                'products' => $formatted_products,
                'total' => count($formatted_products),
                'page' => $page,
                'per_page' => $per_page,
                'has_more' => count($products) === $per_page
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Filter products by content status
     * 
     * @param array $products Array of WC_Product objects
     * @param string $status Status filter ('missing-content' or 'has-content')
     * @return array Filtered products
     */
    private function filter_products_by_status($products, $status) {
        $filtered = [];
        
        foreach ($products as $product) {
            $has_short_desc = !empty($product->get_short_description());
            $has_long_desc = !empty($product->get_description());
            $has_tags = !empty(wp_get_post_terms($product->get_id(), 'product_tag'));
            
            $has_content = $has_short_desc && $has_long_desc && $has_tags;
            
            if ($status === 'missing-content' && !$has_content) {
                $filtered[] = $product;
            } elseif ($status === 'has-content' && $has_content) {
                $filtered[] = $product;
            }
        }
        
        return $filtered;
    }
    
    /**
     * Format product for AJAX response
     * 
     * @param \WC_Product $product Product object
     * @return array Formatted product data
     */
    private function format_product_for_response($product) {
        $categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']);
        $tags = wp_get_post_terms($product->get_id(), 'product_tag');
        
        return [
            'id' => $product->get_id(),
            'name' => $product->get_name(),
            'price_html' => $product->get_price_html(),
            'sku' => $product->get_sku(),
            'image_id' => $product->get_image_id(),
            'image_url' => $product->get_image_id() ? wp_get_attachment_image_url($product->get_image_id(), 'thumbnail') : '',
            'categories' => $categories,
            'has_short_description' => !empty($product->get_short_description()),
            'has_description' => !empty($product->get_description()),
            'has_tags' => !empty($tags)
        ];
    }
    
    /**
     * Custom product search method
     * 
     * @param string $search Search term
     * @param int $category Category ID
     * @param int $limit Number of products to return
     * @param int $page Page number
     * @param bool $count_only Return count only
     * @return array|int Products array or count
     */
    private function search_products_custom($search, $category = 0, $limit = 50, $page = 1, $count_only = false) {
        global $wpdb;
        
        $offset = ($page - 1) * $limit;
        $search_term = '%' . $wpdb->esc_like($search) . '%';
        
        $select = $count_only ? 'COUNT(DISTINCT p.ID)' : 'DISTINCT p.ID';
        $limit_clause = $count_only ? '' : "LIMIT %d OFFSET %d";
        
        $prepare_args = [$search_term, $search_term, $search_term, $search_term];
        
        if ($category > 0) {
            $category_id = absint($category);
            $sql = "
                SELECT $select
                FROM {$wpdb->posts} p
                LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_sku'
                INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
                INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                WHERE p.post_type = 'product'
                AND p.post_status = 'publish'
                AND (
                    p.post_title LIKE %s
                    OR p.post_content LIKE %s
                    OR p.post_excerpt LIKE %s
                    OR pm.meta_value LIKE %s
                )
                AND tt.term_id = %d AND tt.taxonomy = 'product_cat'
                ORDER BY p.post_date DESC
                $limit_clause
            ";
            $prepare_args[] = $category_id;
        } else {
            $sql = "
                SELECT $select
                FROM {$wpdb->posts} p
                LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_sku'
                WHERE p.post_type = 'product'
                AND p.post_status = 'publish'
                AND (
                    p.post_title LIKE %s
                    OR p.post_content LIKE %s
                    OR p.post_excerpt LIKE %s
                    OR pm.meta_value LIKE %s
                )
                ORDER BY p.post_date DESC
                $limit_clause
            ";
        }
        
        if (!$count_only) {
            $prepare_args[] = $limit;
            $prepare_args[] = $offset;
        }
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is prepared with $prepare_args
        $prepared_sql = $wpdb->prepare($sql, $prepare_args);
        
        if ($count_only) {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $prepared_sql is safely prepared above
            return (int) $wpdb->get_var($prepared_sql);
        }
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $prepared_sql is safely prepared above
        $product_ids = $wpdb->get_col($prepared_sql);
        
        $products = [];
        foreach ($product_ids as $product_id) {
            $product = wc_get_product($product_id);
            if ($product) {
                $products[] = $product;
            }
        }
        
        return $products;
    }
    
    /**
     * Handle get bulk status AJAX request
     */
    public function handle_get_bulk_status() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $batch_id = sanitize_text_field(wp_unslash($_POST['batch_id'] ?? ''));
            if (empty($batch_id)) {
                throw new \Exception('Batch ID is required');
            }
            
            // Get batch data from option
            $batch_data = get_option('apcig_batch_' . $batch_id);
            if (!$batch_data) {
                throw new \Exception('Batch not found');
            }
            
            wp_send_json_success($batch_data);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle pause bulk process AJAX request
     */
    public function handle_pause_bulk_process() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $batch_id = sanitize_text_field(wp_unslash($_POST['batch_id'] ?? ''));
            if (empty($batch_id)) {
                throw new \Exception('Batch ID is required');
            }
            
            // Update batch status to paused
            $batch_data = get_option('apcig_batch_' . $batch_id);
            if (!$batch_data) {
                throw new \Exception('Batch not found');
            }
            
            $batch_data['status'] = 'paused';
            $batch_data['paused_at'] = current_time('mysql');
            update_option('apcig_batch_' . $batch_id, $batch_data);
            
            wp_send_json_success([
                'message' => 'Batch processing paused',
                'status' => 'paused'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle stop bulk process AJAX request
     */
    public function handle_stop_bulk_process() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $batch_id = sanitize_text_field(wp_unslash($_POST['batch_id'] ?? ''));
            if (empty($batch_id)) {
                throw new \Exception('Batch ID is required');
            }
            
            // Update batch status to stopped
            $batch_data = get_option('apcig_batch_' . $batch_id);
            if (!$batch_data) {
                throw new \Exception('Batch not found');
            }
            
            $batch_data['status'] = 'stopped';
            $batch_data['stopped_at'] = current_time('mysql');
            update_option('apcig_batch_' . $batch_id, $batch_data);
            
            // Clear scheduled event
            wp_clear_scheduled_hook('apcig_process_batch', [$batch_id]);
            
            wp_send_json_success([
                'message' => 'Batch processing stopped',
                'status' => 'stopped'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle get products by category AJAX request
     */
    public function handle_get_products_by_category() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $category_ids = array_map('absint', $_POST['category_ids'] ?? []);
            
            if (empty($category_ids)) {
                throw new \Exception('No categories selected');
            }
            
            $args = [
                'limit' => 100,
                'status' => 'publish',
                'category' => $category_ids,
                'orderby' => 'date',
                'order' => 'DESC'
            ];
            
            $products = wc_get_products($args);
            $formatted_products = [];
            
            foreach ($products as $product) {
                $formatted_products[] = $this->format_product_for_response($product);
            }
            
            wp_send_json_success([
                'products' => $formatted_products,
                'total' => count($formatted_products)
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle get products by filters AJAX request
     */
    public function handle_get_products_by_filters() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Sanitize filters array
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below
            $raw_filters = isset($_POST['filters']) && is_array($_POST['filters']) ? wp_unslash($_POST['filters']) : [];
            
            // Sanitize filter data
            $filter_data = [];
            if (isset($raw_filters['filters']) && is_array($raw_filters['filters'])) {
                $allowed_filters = ['missing-short-desc', 'missing-long-desc', 'missing-tags', 'missing-images'];
                foreach ($raw_filters['filters'] as $filter) {
                    $sanitized_filter = sanitize_text_field($filter);
                    if (in_array($sanitized_filter, $allowed_filters, true)) {
                        $filter_data[] = $sanitized_filter;
                    }
                }
            }
            
            $price_min = isset($raw_filters['price_min']) ? floatval($raw_filters['price_min']) : null;
            $price_max = isset($raw_filters['price_max']) ? floatval($raw_filters['price_max']) : null;
            
            $args = [
                'limit' => 100,
                'status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC'
            ];
            
            // Add price filter
            if ($price_min !== null || $price_max !== null) {
                $meta_query = [];
                
                if ($price_min !== null) {
                    $meta_query[] = [
                        'key' => '_price',
                        'value' => $price_min,
                        'compare' => '>=',
                        'type' => 'NUMERIC'
                    ];
                }
                
                if ($price_max !== null) {
                    $meta_query[] = [
                        'key' => '_price',
                        'value' => $price_max,
                        'compare' => '<=',
                        'type' => 'NUMERIC'
                    ];
                }
                
                if (count($meta_query) > 1) {
                    $meta_query['relation'] = 'AND';
                }
                
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                $args['meta_query'] = $meta_query;
            }
            
            $products = wc_get_products($args);
            
            // Apply content filters
            if (!empty($filter_data)) {
                $products = $this->filter_products_by_content($products, $filter_data);
            }
            
            $formatted_products = [];
            foreach ($products as $product) {
                $formatted_products[] = $this->format_product_for_response($product);
            }
            
            wp_send_json_success([
                'products' => $formatted_products,
                'total' => count($formatted_products)
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Filter products by content status
     * 
     * @param array $products Array of WC_Product objects
     * @param array $filters Filter criteria
     * @return array Filtered products
     */
    private function filter_products_by_content($products, $filters) {
        $filtered = [];
        
        foreach ($products as $product) {
            $include = true;
            
            foreach ($filters as $filter) {
                switch ($filter) {
                    case 'missing-short-desc':
                        if (!empty($product->get_short_description())) {
                            $include = false;
                        }
                        break;
                    case 'missing-long-desc':
                        if (!empty($product->get_description())) {
                            $include = false;
                        }
                        break;
                    case 'missing-tags':
                        $tags = wp_get_post_terms($product->get_id(), 'product_tag');
                        if (!empty($tags)) {
                            $include = false;
                        }
                        break;
                    case 'missing-images':
                        if ($product->get_image_id()) {
                            $include = false;
                        }
                        break;
                }
                
                if (!$include) {
                    break;
                }
            }
            
            if ($include) {
                $filtered[] = $product;
            }
        }
        
        return $filtered;
    }
    
    /**
     * Handle load more products AJAX request
     */
    public function handle_load_more_products() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            $offset = absint($_POST['offset'] ?? 0);
            $limit = absint($_POST['limit'] ?? 50);
            
            $args = [
                'limit' => $limit,
                'offset' => $offset,
                'status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC'
            ];
            
            $products = wc_get_products($args);
            $formatted_products = [];
            
            foreach ($products as $product) {
                $formatted_products[] = $this->format_product_for_response($product);
            }
            
            // Check if there are more products
            $total_products = wp_count_posts('product')->publish;
            $has_more = ($offset + $limit) < $total_products;
            
            wp_send_json_success([
                'products' => $formatted_products,
                'has_more' => $has_more,
                'total' => $total_products
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle clear generation history AJAX request
     */
    public function handle_clear_generation_history() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Clear generation history
            delete_option('apcig_generation_history');
            
            wp_send_json_success([
                'message' => 'Generation history cleared successfully'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Handle clear all data AJAX request
     */
    public function handle_clear_all_data() {
        try {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'apcig_ajax_nonce')) {
                throw new \Exception('Invalid nonce');
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                throw new \Exception('Insufficient permissions');
            }
            
            // Clear all plugin data
            delete_option('apcig_generation_history');
            delete_option('apcig_total_content_generated');
            delete_option('apcig_total_images_generated');
            delete_option('apcig_content_generated_today');
            delete_option('apcig_images_generated_today');
            
            // Clear daily API usage (last 30 days)
            for ($i = 0; $i < 30; $i++) {
                $date = gmdate('Y-m-d', strtotime("-$i days"));
                delete_option('apcig_api_usage_' . $date);
            }
            
            // Clear batch jobs
            global $wpdb;
            $database = $this->container->get('database');
            $table = $database->get_table_name('batch_jobs');
            $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}apcig_batch_jobs"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            
            wp_send_json_success([
                'message' => 'All plugin data cleared successfully'
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error([
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Sanitize bulk processing settings
     * 
     * @param array $raw_settings Raw settings array from POST
     * @return array Sanitized settings
     */
    private function sanitize_bulk_settings($raw_settings) {
        $sanitized = [];
        
        // Sanitize content types array
        if (isset($raw_settings['content_types']) && is_array($raw_settings['content_types'])) {
            $allowed_content_types = ['title', 'short_description', 'long_description', 'tags'];
            $sanitized['content_types'] = [];
            foreach ($raw_settings['content_types'] as $type) {
                $sanitized_type = sanitize_text_field($type);
                if (in_array($sanitized_type, $allowed_content_types, true)) {
                    $sanitized['content_types'][] = $sanitized_type;
                }
            }
        }
        
        // Sanitize tone with whitelist
        if (isset($raw_settings['tone'])) {
            $allowed_tones = ['professional', 'friendly', 'casual', 'luxury', 'technical', 'persuasive'];
            $tone = sanitize_text_field($raw_settings['tone']);
            $sanitized['tone'] = in_array($tone, $allowed_tones, true) ? $tone : 'professional';
        }
        
        // Sanitize language with whitelist
        if (isset($raw_settings['language'])) {
            $allowed_languages = ['en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'pl', 'ru', 'ja', 'zh', 'ko', 'ar'];
            $language = sanitize_text_field($raw_settings['language']);
            $sanitized['language'] = in_array($language, $allowed_languages, true) ? $language : 'en';
        }
        
        // Sanitize provider with whitelist
        if (isset($raw_settings['provider'])) {
            $allowed_providers = ['openai', 'claude', 'gemini', 'openrouter'];
            $provider = sanitize_text_field($raw_settings['provider']);
            $sanitized['provider'] = in_array($provider, $allowed_providers, true) ? $provider : 'openai';
        }
        
        // Sanitize custom prompt
        if (isset($raw_settings['custom_prompt'])) {
            $sanitized['custom_prompt'] = sanitize_textarea_field($raw_settings['custom_prompt']);
        }
        
        // Sanitize description (for image generation)
        if (isset($raw_settings['description'])) {
            $sanitized['description'] = sanitize_textarea_field($raw_settings['description']);
        }
        
        // Sanitize style with whitelist (for image generation)
        if (isset($raw_settings['style'])) {
            $allowed_styles = ['clean-white', 'lifestyle', 'studio', 'natural', 'minimal', 'dramatic'];
            $style = sanitize_text_field($raw_settings['style']);
            $sanitized['style'] = in_array($style, $allowed_styles, true) ? $style : 'clean-white';
        }
        
        // Sanitize size with whitelist (for image generation)
        if (isset($raw_settings['size'])) {
            $allowed_sizes = ['256x256', '512x512', '1024x1024', '1792x1024', '1024x1792'];
            $size = sanitize_text_field($raw_settings['size']);
            $sanitized['size'] = in_array($size, $allowed_sizes, true) ? $size : '1024x1024';
        }
        
        // Sanitize count with range validation (for image generation)
        if (isset($raw_settings['count'])) {
            $count = absint($raw_settings['count']);
            $sanitized['count'] = max(1, min(10, $count)); // Limit between 1 and 10
        }
        
        // Sanitize boolean flags
        if (isset($raw_settings['auto_apply'])) {
            $sanitized['auto_apply'] = filter_var($raw_settings['auto_apply'], FILTER_VALIDATE_BOOLEAN);
        }
        
        if (isset($raw_settings['backup_original'])) {
            $sanitized['backup_original'] = filter_var($raw_settings['backup_original'], FILTER_VALIDATE_BOOLEAN);
        }
        
        return $sanitized;
    }

}