<?php
/**
 * Content Generator Class
 *
 * Handles AI-powered content generation for products
 *
 * @package AIProductContentImageGenerator
 * @since 1.0.0
 */

namespace AIProductContentImageGenerator\Services;

use AIProductContentImageGenerator\Services\AIProviderManager;

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

/**
 * ContentGenerator class for generating product content
 */
class ContentGenerator {
    /**
     * AI Provider Manager instance
     *
     * @var AIProviderManager
     */
    private $ai_provider;

    /**
     * Available content tones
     *
     * @var array
     */
    private $tones = [
        'professional' => 'Professional and formal',
        'friendly' => 'Friendly and approachable',
        'casual' => 'Casual and conversational',
        'luxury' => 'Luxury and premium',
        'technical' => 'Technical and detailed',
        'persuasive' => 'Persuasive and compelling'
    ];

    /**
     * Available content types
     *
     * @var array
     */
    private $content_types = [
        'short_description' => [
            'name' => 'Short Description',
            'max_words' => 150,
            'field' => 'post_excerpt'
        ],
        'long_description' => [
            'name' => 'Long Description',
            'max_words' => 300,
            'field' => 'post_content'
        ],
        'title' => [
            'name' => 'Product Title',
            'max_words' => 10,
            'field' => 'post_title'
        ],
        'tags' => [
            'name' => 'Product Tags',
            'max_words' => 50,
            'field' => 'product_tag'
        ]
    ];

    /**
     * Constructor
     *
     * @param AIProviderManager $ai_provider
     */
    public function __construct(AIProviderManager $ai_provider) {
        $this->ai_provider = $ai_provider;
    }

    /**
     * Generate content for a product
     *
     * @param int $product_id
     * @param array $options
     * @return array
     */
    public function generate_content($product_id, $options = []) {
        $product = wc_get_product($product_id);
        if (!$product) {
            return [
                'success' => false,
                'error' => 'Product not found'
            ];
        }

        $defaults = [
            'content_types' => ['short_description'],
            'tone' => 'professional',
            'language' => 'en',
            'provider' => $this->ai_provider->get_default_provider(),
            'model' => null,
            'custom_prompt' => '',
            'max_tokens' => 1000,
            'temperature' => 0.7
        ];

        $options = array_merge($defaults, $options);
        $results = [];

        foreach ($options['content_types'] as $content_type) {
            $result = $this->generate_single_content($product, $content_type, $options);
            $results[$content_type] = $result;
        }

        return [
            'success' => true,
            'results' => $results
        ];
    }

    /**
     * Generate single content type
     *
     * @param WC_Product $product
     * @param string $content_type
     * @param array $options
     * @return array
     */
    private function generate_single_content($product, $content_type, $options) {
        if (!isset($this->content_types[$content_type])) {
            return [
                'success' => false,
                'error' => 'Invalid content type'
            ];
        }

        $type_config = $this->content_types[$content_type];
        $prompt = $this->build_prompt($product, $content_type, $options);

        $request_data = [
            'messages' => [
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ],
            'model' => $options['model'],
            'max_tokens' => min($options['max_tokens'], $type_config['max_words'] * 4),
            'temperature' => $options['temperature']
        ];

        $response = $this->ai_provider->make_request($options['provider'], $request_data);

        if (is_wp_error($response)) {
            return [
                'success' => false,
                'error' => $response->get_error_message()
            ];
        }

        $content = $this->ai_provider->extract_content($options['provider'], $response);
        $content = $this->post_process_content($content, $content_type);

        // Log API usage
        $this->log_api_usage($options['provider'], 'content_generation');
        
        // Update daily and total counters
        $this->update_generation_stats();

        return [
            'success' => true,
            'content' => $content,
            'word_count' => str_word_count($content),
            'type' => $content_type
        ];
    }

    /**
     * Build prompt for content generation
     *
     * @param WC_Product $product
     * @param string $content_type
     * @param array $options
     * @return string
     */
    private function build_prompt($product, $content_type, $options) {
        $type_config = $this->content_types[$content_type];
        $tone = $this->tones[$options['tone']] ?? 'professional';
        
        // Get product data
        $product_data = $this->extract_product_data($product);
        
        // Use custom prompt if provided
        if (!empty($options['custom_prompt'])) {
            return $this->replace_variables($options['custom_prompt'], $product_data);
        }

        // Build default prompt based on content type
        switch ($content_type) {
            case 'short_description':
                $prompt = "You are an expert e-commerce copywriter. Create a compelling short product description (maximum {$type_config['max_words']} words) for the following product:\n\n";
                $prompt .= "Product Name: {$product_data['name']}\n";
                $prompt .= "Category: {$product_data['category']}\n";
                $prompt .= "Price: {$product_data['price']}\n";
                if (!empty($product_data['attributes'])) {
                    $prompt .= "Key Features: {$product_data['attributes']}\n";
                }
                if (!empty($product_data['sku'])) {
                    $prompt .= "SKU: {$product_data['sku']}\n";
                }
                if (!empty($product_data['weight'])) {
                    $prompt .= "Weight: {$product_data['weight']}\n";
                }
                if (!empty($product_data['dimensions'])) {
                    $prompt .= "Dimensions: {$product_data['dimensions']}\n";
                }
                $prompt .= "\nWriting Style: {$tone}\n";
                $prompt .= "\nRequirements:\n";
                $prompt .= "- Focus on key benefits and unique selling points\n";
                $prompt .= "- Make it engaging and persuasive\n";
                $prompt .= "- Include relevant keywords for SEO\n";
                $prompt .= "- Write in a way that converts browsers into buyers\n";
                $prompt .= "- Keep it concise and impactful\n";
                $prompt .= "\nProvide ONLY the description text, no additional commentary.";
                break;

            case 'long_description':
                $prompt = "You are an expert e-commerce copywriter. Create a comprehensive product description (maximum {$type_config['max_words']} words) for:\n\n";
                $prompt .= "Product: {$product_data['name']}\n";
                $prompt .= "Category: {$product_data['category']}\n";
                $prompt .= "Price: {$product_data['price']}\n";
                if (!empty($product_data['attributes'])) {
                    $prompt .= "Features: {$product_data['attributes']}\n";
                }
                if (!empty($product_data['sku'])) {
                    $prompt .= "SKU: {$product_data['sku']}\n";
                }
                if (!empty($product_data['weight'])) {
                    $prompt .= "Weight: {$product_data['weight']}\n";
                }
                if (!empty($product_data['dimensions'])) {
                    $prompt .= "Dimensions: {$product_data['dimensions']}\n";
                }
                $prompt .= "\nWriting Style: {$tone}\n";
                $prompt .= "\nRequirements:\n";
                $prompt .= "- Start with an engaging opening that captures attention\n";
                $prompt .= "- Detail all key features and specifications\n";
                $prompt .= "- Explain benefits and how it solves customer problems\n";
                $prompt .= "- Include use cases and applications\n";
                $prompt .= "- Address potential customer questions\n";
                $prompt .= "- Use bullet points or short paragraphs for readability\n";
                $prompt .= "- Include relevant keywords naturally for SEO\n";
                $prompt .= "- End with a compelling call-to-action\n";
                $prompt .= "\nProvide ONLY the description text in HTML format with proper paragraph tags, no additional commentary.";
                break;

            case 'title':
                $prompt = "You are an SEO expert. Create an optimized product title (maximum {$type_config['max_words']} words) for:\n\n";
                $prompt .= "Current Title: {$product_data['name']}\n";
                $prompt .= "Category: {$product_data['category']}\n";
                if (!empty($product_data['attributes'])) {
                    $prompt .= "Key Features: {$product_data['attributes']}\n";
                }
                $prompt .= "\nRequirements:\n";
                $prompt .= "- Include the most important keywords\n";
                $prompt .= "- Make it descriptive and specific\n";
                $prompt .= "- Include key features or benefits if space allows\n";
                $prompt .= "- Make it compelling for both search engines and customers\n";
                $prompt .= "- Keep it under 70 characters if possible\n";
                $prompt .= "- Don't use ALL CAPS or excessive punctuation\n";
                $prompt .= "\nProvide ONLY the title text, no quotes or additional commentary.";
                break;

            case 'tags':
                $prompt = "You are an SEO expert. Generate relevant product tags (comma-separated, exactly 8-10 tags) for:\n\n";
                $prompt .= "Product: {$product_data['name']}\n";
                $prompt .= "Category: {$product_data['category']}\n";
                if (!empty($product_data['attributes'])) {
                    $prompt .= "Features: {$product_data['attributes']}\n";
                }
                $prompt .= "\nRequirements:\n";
                $prompt .= "- Include category-related tags\n";
                $prompt .= "- Include feature-based tags\n";
                $prompt .= "- Include use-case tags\n";
                $prompt .= "- Include relevant keywords for SEO\n";
                $prompt .= "- Use lowercase\n";
                $prompt .= "- Keep tags concise (1-3 words each)\n";
                $prompt .= "- Make them searchable and relevant\n";
                $prompt .= "\nProvide ONLY the comma-separated tags, no additional commentary.";
                break;

            default:
                $prompt = "Generate {$content_type} content for: {$product_data['name']}";
        }

        return $prompt;
    }

    /**
     * Extract product data for prompt building
     *
     * @param WC_Product $product
     * @return array
     */
    private function extract_product_data($product) {
        $data = [
            'name' => $product->get_name(),
            'price' => wc_price($product->get_price()),
            'category' => '',
            'attributes' => '',
            'sku' => $product->get_sku(),
            'weight' => $product->get_weight(),
            'dimensions' => $product->get_dimensions(false)
        ];

        // Get categories
        $categories = wp_get_post_terms($product->get_id(), 'product_cat');
        if (!empty($categories)) {
            $data['category'] = $categories[0]->name;
        }

        // Get attributes
        $attributes = [];
        foreach ($product->get_attributes() as $attribute) {
            if ($attribute->get_variation()) {
                continue;
            }
            $values = wc_get_product_terms($product->get_id(), $attribute->get_name(), ['fields' => 'names']);
            if (!empty($values)) {
                $attributes[] = $attribute->get_name() . ': ' . implode(', ', $values);
            }
        }
        $data['attributes'] = implode('; ', $attributes);

        return $data;
    }

    /**
     * Replace variables in custom prompt
     *
     * @param string $prompt
     * @param array $product_data
     * @return string
     */
    private function replace_variables($prompt, $product_data) {
        $variables = [
            '{product_name}' => $product_data['name'],
            '{category}' => $product_data['category'],
            '{price}' => $product_data['price'],
            '{attributes}' => $product_data['attributes'],
            '{sku}' => $product_data['sku'],
            '{weight}' => $product_data['weight'],
            '{dimensions}' => $product_data['dimensions']
        ];

        return str_replace(array_keys($variables), array_values($variables), $prompt);
    }

    /**
     * Post-process generated content
     *
     * @param string $content
     * @param string $content_type
     * @return string
     */
    private function post_process_content($content, $content_type) {
        // Remove quotes if present
        $content = trim($content, '"\'
');
        
        // Clean up extra whitespace
        $content = preg_replace('/\s+/', ' ', $content);
        
        // Specific processing by type
        switch ($content_type) {
            case 'tags':
                // Clean up tags format
                $content = str_replace([', ', '; ', ' ,', ' ;'], ',', $content);
                $tags = explode(',', $content);
                $tags = array_map('trim', $tags);
                $tags = array_filter($tags);
                $tags = array_slice($tags, 0, 10); // Limit to 10 tags
                $content = implode(', ', $tags);
                break;
                
            case 'title':
                // Ensure title is not too long
                if (strlen($content) > 100) {
                    $content = substr($content, 0, 97) . '...';
                }
                break;
        }

        return trim($content);
    }

    /**
     * Apply generated content to product
     *
     * @param int $product_id
     * @param array $content_data
     * @return bool
     */
    public function apply_content($product_id, $content_data) {
        $product = wc_get_product($product_id);
        if (!$product) {
            return false;
        }

        $applied_count = 0;
        $update_data = ['ID' => $product_id];
        
        foreach ($content_data as $content_type => $data) {
            // Check if data has success flag and content
            if (isset($data['success']) && !$data['success']) {
                continue;
            }
            
            if (empty($data['content'])) {
                continue;
            }

            $type_config = $this->content_types[$content_type] ?? null;
            if (!$type_config) {
                continue;
            }

            $content = $data['content'];
            
            switch ($content_type) {
                case 'short_description':
                    // Update via WooCommerce
                    $product->set_short_description($content);
                    // Also prepare for direct post update
                    $update_data['post_excerpt'] = $content;
                    $applied_count++;
                    break;
                    
                case 'long_description':
                    // Update via WooCommerce
                    $product->set_description($content);
                    // Also prepare for direct post update
                    $update_data['post_content'] = $content;
                    $applied_count++;
                    break;
                    
                case 'title':
                    // Update via WooCommerce
                    $product->set_name($content);
                    // Also prepare for direct post update
                    $update_data['post_title'] = $content;
                    $applied_count++;
                    break;
                    
                case 'tags':
                    $tags = explode(',', $content);
                    $tags = array_map('trim', $tags);
                    $tags = array_filter($tags); // Remove empty tags
                    
                    // Set tags using WordPress taxonomy function
                    $result = wp_set_post_terms($product_id, $tags, 'product_tag', false);
                    
                    if (!is_wp_error($result)) {
                        $applied_count++;
                    }
                    break;
            }
        }

        if ($applied_count > 0) {
            // First, save via WooCommerce to update meta
            $product->save();
            
            // Then, update post data directly if we have any post fields
            if (count($update_data) > 1) { // More than just ID
                wp_update_post($update_data, true);
            }
            
            // Update product meta to ensure changes are saved
            update_post_meta($product_id, '_edit_last', get_current_user_id());
            update_post_meta($product_id, '_edit_lock', time() . ':' . get_current_user_id());
            
            // Force cache clear
            clean_post_cache($product_id);
            wc_delete_product_transients($product_id);
            wp_cache_delete($product_id, 'posts');
            wp_cache_delete($product_id, 'post_meta');
            
            return true;
        }
        
        return false;
    }

    /**
     * Get available tones
     *
     * @return array
     */
    public function get_tones() {
        return $this->tones;
    }

    /**
     * Get available content types
     *
     * @return array
     */
    public function get_content_types() {
        return $this->content_types;
    }
    
    /**
     * Log API usage
     *
     * @param string $provider Provider name
     * @param string $request_type Request type
     * @param int $count Number of requests
     */
    private function log_api_usage($provider, $request_type, $count = 1) {
        // Update daily counters
        $today = current_time('Y-m-d');
        $daily_key = 'apcig_api_usage_' . $today;
        $daily_usage = get_option($daily_key, []);
        
        if (!isset($daily_usage[$provider])) {
            $daily_usage[$provider] = 0;
        }
        
        $daily_usage[$provider] += $count;
        update_option($daily_key, $daily_usage);
    }
    
    /**
     * Update generation statistics
     */
    private function update_generation_stats() {
        // Reset daily counter at midnight if needed
        $last_reset = get_option('apcig_last_daily_reset', '');
        $today = current_time('Y-m-d');
        
        if ($last_reset !== $today) {
            update_option('apcig_content_generated_today', 0);
            update_option('apcig_images_generated_today', 0);
            update_option('apcig_last_daily_reset', $today);
        }
        
        // Update total content generated
        $total = get_option('apcig_total_content_generated', 0);
        update_option('apcig_total_content_generated', $total + 1);
        
        // Update today's content generated
        $today_total = get_option('apcig_content_generated_today', 0);
        update_option('apcig_content_generated_today', $today_total + 1);
    }
}