<?php
/**
 * AI Auto Tool - AI Thumbnail Generator
 * 
 * Generates AI thumbnails using Pollinations API with AI-enhanced prompts
 * Extracted and optimized from image-scanner feature
 * 
 * @package AIAutoTool
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class AIAutoTool_Thumbnail_Generator {
    
    /**
     * Generate AI thumbnail using Pollinations API with AI-enhanced prompt
     * 
     * @param int $post_id Post ID
     * @param string $title Post title (optional, will fetch from post_id if not provided)
     * @param string $content Post content (optional, will fetch from post_id if not provided)
     * @param array $options Generation options (width, height, model, etc.)
     * @return int|false Attachment ID on success, false on failure
     */
    public static function generate_thumbnail($post_id, $title = '', $content = '', $options = array()) {
        // Get post if title or content not provided
        if (empty($title) || empty($content)) {
            $post = get_post($post_id);
            if (!$post) return false;
            
            if (empty($title)) {
                $title = get_the_title($post_id);
            }
            
            if (empty($content)) {
                $content = wp_trim_words(strip_tags($post->post_content), 50);
            }
        }
        
        // Default options
        $default_options = array(
            'width' => 1200,
            'height' => 630,
            'model' => 'flux',
            'enhance' => true,
            'nologo' => true,
            'max_retries' => 2,
            'timeout' => 30
        );
        
        $options = wp_parse_args($options, $default_options);
        
        // Use AI to generate optimized image prompt
        $image_prompt = self::generate_image_prompt_with_ai($title, $content);
        
        // Fallback to simple prompt if AI fails
        if (empty($image_prompt)) {
            $image_prompt = $title . ', professional illustration, high quality, detailed, modern design';
        }
        
        // Clean and encode prompt for Pollinations API
        $encoded_prompt = urlencode($image_prompt);
        
        // Build Pollinations API URL with parameters
        $api_params = array(
            'width' => $options['width'],
            'height' => $options['height'],
            'model' => $options['model']
        );
        
        if ($options['nologo']) {
            $api_params['nologo'] = 'true';
        }
        
        if ($options['enhance']) {
            $api_params['enhance'] = 'true';
        }
        
        $query_string = http_build_query($api_params);
        $api_url = "https://image.pollinations.ai/prompt/{$encoded_prompt}?{$query_string}";
        
        // Download image with retry mechanism
        $image_data = false;
        
        for ($i = 0; $i < $options['max_retries']; $i++) {
            $response = wp_remote_get($api_url, array(
                'timeout' => $options['timeout'],
                'sslverify' => false,
                'headers' => array(
                    'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . home_url()
                )
            ));
            
            if (!is_wp_error($response)) {
                $image_data = wp_remote_retrieve_body($response);
                if (!empty($image_data) && strlen($image_data) > 1000) {
                    break; // Success
                }
            }
            
            // Wait before retry
            if ($i < $options['max_retries'] - 1) {
                sleep(2);
            }
        }
        
        if (empty($image_data)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        // Save to uploads directory
        $upload_dir = wp_upload_dir();
        $safe_title = sanitize_file_name(substr($title, 0, 50));
        $filename = $safe_title . '_ai_thumb_' . time() . '.png';
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        $file_saved = file_put_contents($file_path, $image_data);
        
        if (!$file_saved || !file_exists($file_path)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        // Verify it's a valid image
        $image_size = @getimagesize($file_path);
        if ($image_size === false) {
            @unlink($file_path);
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        // Create WordPress attachment
        $filetype = wp_check_filetype($filename);
        $attachment = array(
            'guid' => $upload_dir['url'] . '/' . $filename,
            'post_mime_type' => $filetype['type'],
            'post_title' => $title,
            'post_content' => 'AI-generated thumbnail: ' . $image_prompt,
            'post_excerpt' => 'Generated by Pollinations AI',
            'post_status' => 'inherit'
        );
        
        $attachment_id = wp_insert_attachment($attachment, $file_path, $post_id);
        
        if (!$attachment_id) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        // Generate attachment metadata
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path);
        wp_update_attachment_metadata($attachment_id, $attach_data);
        
        // Set alt text for SEO
        update_post_meta($attachment_id, '_wp_attachment_image_alt', $title);
        
        // Store generation metadata
        update_post_meta($attachment_id, '_ai_image_prompt', $image_prompt);
        update_post_meta($attachment_id, '_ai_generated', 1);
        update_post_meta($attachment_id, '_ai_generator', 'pollinations');
        update_post_meta($attachment_id, '_ai_model', $options['model']);
        
        // Log success
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return $attachment_id;
    }
    
    /**
     * Generate optimized image prompt using AI
     * 
     * Uses Gemini/Bard to create detailed, optimized prompt for image generation
     * 
     * @param string $title Post title
     * @param string $content Post content excerpt
     * @return string AI-generated image prompt
     */
    private static function generate_image_prompt_with_ai($title, $content) {
        try {
            // Initialize Bard/Gemini content generator
            if (!class_exists('BardGenContent')) {
                $bard_file = plugin_dir_path(__FILE__) . 'bard.php';
                if (file_exists($bard_file)) {
                    require_once($bard_file);
                } else {
                    return '';
                }
            }
            
            $bardGenContent = new BardGenContent();
            
            // Create instruction for AI to generate image prompt
            $instruction = "Create a concise, visual description for a thumbnail image based on this article. 
Article Title: {$title}
Article Excerpt: {$content}

Generate a detailed image prompt (max 100 words) that describes:
- Main subject/theme
- Visual style (professional, modern, clean)
- Colors and mood
- Composition

Output ONLY the image prompt, no explanations. Make it suitable for AI image generation.";
            
            // Call AI to generate prompt
            $ai_response = $bardGenContent->bardcontentRaw($instruction, 'English');
            
            if (!empty($ai_response) && is_string($ai_response)) {
                // Clean up response
                $prompt = trim(strip_tags($ai_response));
                $prompt = preg_replace('/\s+/', ' ', $prompt);
                
                // Limit length
                if (strlen($prompt) > 300) {
                    $prompt = substr($prompt, 0, 300);
                }
                
                return $prompt;
            }
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
        }
        
        return '';
    }
    
    /**
     * Generate and set thumbnail for post
     * 
     * Convenience method that generates and sets the thumbnail in one call
     * 
     * @param int $post_id Post ID
     * @param string $title Post title (optional)
     * @param string $content Post content (optional)
     * @param array $options Generation options
     * @return bool True on success, false on failure
     */
    public static function generate_and_set_thumbnail($post_id, $title = '', $content = '', $options = array()) {
        $attachment_id = self::generate_thumbnail($post_id, $title, $content, $options);
        
        if ($attachment_id) {
            return set_post_thumbnail($post_id, $attachment_id);
        }
        
        return false;
    }
    
    /**
     * Check if post has thumbnail
     * 
     * @param int $post_id Post ID
     * @return bool True if has thumbnail, false otherwise
     */
    public static function has_thumbnail($post_id) {
        return has_post_thumbnail($post_id);
    }
    
    /**
     * Generate thumbnail only if post doesn't have one
     * 
     * @param int $post_id Post ID
     * @param string $title Post title (optional)
     * @param string $content Post content (optional)
     * @param array $options Generation options
     * @return int|bool Attachment ID on success, true if already has thumbnail, false on failure
     */
    public static function ensure_thumbnail($post_id, $title = '', $content = '', $options = array()) {
        // Check if post already has thumbnail
        if (self::has_thumbnail($post_id)) {
            return true;
        }
        
        // Generate new thumbnail
        return self::generate_thumbnail($post_id, $title, $content, $options);
    }
}

