<?php
/**
 * Image Generator Class
 *
 * Handles AI-powered image generation and enhancement for products
 *
 * @package AIProductContentImageGenerator\Services
 * @since 1.0.0
 */

namespace AIProductContentImageGenerator\Services;

use AIProductContentImageGenerator\Services\AIProviderManager;

/**
 * ImageGenerator class for generating and enhancing product images
 */
class ImageGenerator {
    /**
     * AI Provider Manager instance
     *
     * @var AIProviderManager
     */
    private $ai_provider;

    /**
     * Available image styles
     *
     * @var array
     */
    private $image_styles = [
        'lifestyle' => [
            'name' => 'Lifestyle Image',
            'prompt_suffix' => 'in a realistic lifestyle setting, natural environment, showing product in use, authentic context, professional photography'
        ],
        'a-plus' => [
            'name' => 'A+ Content Image',
            'prompt_suffix' => 'professional marketing image, clean composition, highlighting product features, commercial quality, suitable for Amazon A+ content'
        ],
        'lifestyle-home' => [
            'name' => 'Home Lifestyle',
            'prompt_suffix' => 'in a beautiful home setting, interior design context, natural lighting, cozy atmosphere'
        ],
        'lifestyle-outdoor' => [
            'name' => 'Outdoor Lifestyle',
            'prompt_suffix' => 'in an outdoor setting, natural environment, daylight, active lifestyle context'
        ],
        'lifestyle-professional' => [
            'name' => 'Professional Use',
            'prompt_suffix' => 'in a professional workplace setting, business context, clean and modern environment'
        ],
        'custom' => [
            'name' => 'Custom Style',
            'prompt_suffix' => ''
        ]
    ];

    /**
     * Available image sizes
     *
     * @var array
     */
    private $image_sizes = [
        '512x512' => 'Square (512x512)',
        '1024x1024' => 'Large Square (1024x1024)',
        '1024x768' => 'Landscape (1024x768)',
        '768x1024' => 'Portrait (768x1024)',
        '1920x1080' => 'HD Landscape (1920x1080)',
        '1080x1920' => 'HD Portrait (1080x1920)'
    ];

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

    /**
     * Generate lifestyle/A+ images based on existing product image
     *
     * @param \WC_Product $product Product object
     * @param string $description Image description/context
     * @param string $style Image style (lifestyle or a-plus)
     * @param string $size Image size
     * @param int $count Number of images to generate
     * @param string $provider AI provider
     * @return array|\WP_Error
     */
    public function generate_images($product, $description, $style = 'lifestyle', $size = '1024x1024', $count = 1, $provider = 'openai') {
        if (!$product) {
            return new \WP_Error('invalid_product', 'Invalid product provided');
        }

        $product_image_id = $product->get_image_id();
        if (!$product_image_id) {
            return new \WP_Error('no_product_image', 'Product must have an existing image to generate lifestyle/A+ images');
        }

        $product_image_url = wp_get_attachment_image_url($product_image_id, 'full');
        if (!$product_image_url) {
            return new \WP_Error('invalid_image', 'Could not retrieve product image URL');
        }

        $prompt = $this->build_lifestyle_image_prompt($product, $description, $style);
        $request_data = $this->prepare_image_variation_request($provider, $prompt, $product_image_url, $size, $count, $style);
        
        if (is_wp_error($request_data)) {
            return $request_data;
        }

        // Make API request (use special handling for image edits)
        if ($provider === 'openai' && isset($request_data['endpoint']) && $request_data['endpoint'] === 'edits') {
            $response = $this->make_openai_edit_request($request_data);
        } else {
            $response = $this->ai_provider->make_request($provider, $request_data);
        }
        
        if (is_wp_error($response)) {
            return $response;
        }

        // Process response and download images
        $images = $this->process_image_response($provider, $response, $product->get_id());
        
        if (is_wp_error($images)) {
            return $images;
        }

        // Log API usage
        $this->log_api_usage($provider, 'lifestyle_image_generation', $count);

        $result = [
            'success' => true,
            'images' => $images,
            'product_id' => $product->get_id(),
            'prompt' => $prompt,
            'provider' => $provider,
            'source_image' => $product_image_url
        ];
        
        return $result;
    }

    /**
     * Enhance existing images
     *
     * @param array $image_urls Image URLs to enhance
     * @param array $enhancements Enhancement types
     * @param float $strength Enhancement strength
     * @param string $provider AI provider
     * @return array|\WP_Error
     */
    public function enhance_images($image_urls, $enhancements = ['upscale'], $strength = 0.7, $provider = 'openai') {
        if (empty($image_urls)) {
            return new \WP_Error('no_images', 'No images provided for enhancement');
        }

        $enhanced_images = [];
        
        foreach ($image_urls as $image_url) {
            $result = $this->enhance_single_image($image_url, $enhancements, $strength, $provider);
            
            if (is_wp_error($result)) {
                $enhanced_images[] = [
                    'original_url' => $image_url,
                    'error' => $result->get_error_message()
                ];
            } else {
                $enhanced_images[] = $result;
            }
        }

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

    /**
     * Build lifestyle/A+ image generation prompt
     *
     * @param \WC_Product $product Product object
     * @param string $description Base description/context
     * @param string $style Image style
     * @return string
     */
    private function build_lifestyle_image_prompt($product, $description, $style) {
        $product_name = $product->get_name();
        $categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']);
        $category = !empty($categories) ? $categories[0] : '';
        
        // Build context-aware prompt
        $prompt = "Create a lifestyle/marketing image featuring the {$product_name}";
        
        if ($category) {
            $prompt .= " ({$category})";
        }
        
        // Add user's custom context
        if (!empty($description)) {
            $prompt .= ". Context: {$description}";
        }

        // Add style-specific instructions
        if (isset($this->image_styles[$style]) && !empty($this->image_styles[$style]['prompt_suffix'])) {
            $prompt .= '. Style: ' . $this->image_styles[$style]['prompt_suffix'];
        }

        // Add quality and composition guidelines
        $prompt .= '. Requirements: maintain product visibility and recognition, high-quality composition, professional photography, 4K resolution, sharp focus, natural lighting';

        return $prompt;
    }
    
    /**
     * Build image generation prompt (legacy method for backward compatibility)
     *
     * @param \WC_Product $product Product object
     * @param string $description Base description
     * @param string $style Image style
     * @return string
     */
    private function build_image_prompt($product, $description, $style) {
        return $this->build_lifestyle_image_prompt($product, $description, $style);
    }

    /**
     * Prepare image edit request based on existing product image
     *
     * @param string $provider AI provider
     * @param string $prompt Image prompt
     * @param string $source_image_url Source product image URL
     * @param string $size Image size
     * @param int $count Number of images
     * @param string $style Image style
     * @return array|\WP_Error
     */
    private function prepare_image_variation_request($provider, $prompt, $source_image_url, $size, $count, $style) {
        switch ($provider) {
            case 'openai':
                // Download the source image to pass to the API
                $image_path = $this->download_temp_image($source_image_url);
                if (is_wp_error($image_path)) {
                    return $image_path;
                }
                
                // Use OpenAI Image Edit API to transform the product image
                return [
                    'endpoint' => 'edits', // Use the edits endpoint
                    'model' => 'gpt-image-1',
                    'image' => $image_path,
                    'prompt' => $prompt,
                    'size' => $this->convert_size_for_openai($size),
                    'input_fidelity' => 'high', // Preserve product details
                    'n' => min($count, 1), // Generate one at a time
                    'response_format' => 'b64_json'
                ];
                
            case 'stability':
                // Stability AI supports image-to-image generation
                return [
                    'text_prompts' => [
                        ['text' => $prompt, 'weight' => 1.0]
                    ],
                    'init_image' => $source_image_url,
                    'init_image_mode' => 'IMAGE_STRENGTH',
                    'image_strength' => 0.35, // Keep product recognizable
                    'cfg_scale' => 7,
                    'height' => (int) explode('x', $size)[1],
                    'width' => (int) explode('x', $size)[0],
                    'samples' => $count,
                    'steps' => 40
                ];
                
            default:
                return new \WP_Error('unsupported_provider', 'Lifestyle image generation not supported for this provider');
        }
    }
    
    /**
     * Download image temporarily for API upload
     *
     * @param string $image_url Image URL
     * @return string|WP_Error Temporary file path or error
     */
    private function download_temp_image($image_url) {
        $temp_file = wp_tempnam();
        
        $response = wp_remote_get($image_url, [
            'timeout' => 30,
            'stream' => true,
            'filename' => $temp_file
        ]);
        
        if (is_wp_error($response)) {
            wp_delete_file($temp_file);
            return $response;
        }
        
        if (wp_remote_retrieve_response_code($response) !== 200) {
            wp_delete_file($temp_file);
            return new \WP_Error('download_failed', 'Failed to download source image');
        }
        
        return $temp_file;
    }
    
    /**
     * Prepare image generation request (legacy method)
     *
     * @param string $provider AI provider
     * @param string $prompt Image prompt
     * @param string $size Image size
     * @param int $count Number of images
     * @return array|\WP_Error
     */
    private function prepare_image_request($provider, $prompt, $size, $count) {
        switch ($provider) {
            case 'openai':
                // Use DALL-E 3 for better quality
                return [
                    'model' => 'dall-e-3',
                    'prompt' => $prompt,
                    'n' => 1, // DALL-E 3 supports 1 image at a time
                    'size' => $this->convert_size_for_openai($size),
                    'quality' => 'hd',
                    'response_format' => 'url'
                ];
                
            case 'stability':
                return [
                    'text_prompts' => [
                        ['text' => $prompt, 'weight' => 1.0]
                    ],
                    'cfg_scale' => 7,
                    'height' => (int) explode('x', $size)[1],
                    'width' => (int) explode('x', $size)[0],
                    'samples' => $count,
                    'steps' => 30
                ];
                
            default:
                return new \WP_Error('unsupported_provider', 'Image generation not supported for this provider');
        }
    }

    /**
     * Convert size format for OpenAI
     *
     * @param string $size Size in WxH format
     * @return string
     */
    private function convert_size_for_openai($size) {
        // OpenAI DALL-E 3 supports specific sizes
        $dalle3_sizes = ['1024x1024', '1024x1792', '1792x1024'];
        
        if (in_array($size, $dalle3_sizes)) {
            return $size;
        }
        
        // Map common sizes to supported sizes
        $dimensions = explode('x', $size);
        $width = (int) $dimensions[0];
        $height = (int) $dimensions[1];
        
        // Determine aspect ratio
        if ($width > $height * 1.5) {
            // Wide landscape
            return '1792x1024';
        } elseif ($height > $width * 1.5) {
            // Tall portrait
            return '1024x1792';
        } else {
            // Square or close to square
            return '1024x1024';
        }
    }

    /**
     * Process image generation response
     *
     * @param string $provider AI provider
     * @param array $response API response
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    private function process_image_response($provider, $response, $product_id) {
        $images = [];
        
        switch ($provider) {
            case 'openai':
                if (isset($response['data']) && is_array($response['data'])) {
                    foreach ($response['data'] as $image_data) {
                        // Handle both URL and base64 responses
                        if (isset($image_data['b64_json'])) {
                            $downloaded = $this->save_base64_image($image_data['b64_json'], $product_id);
                            if (!is_wp_error($downloaded)) {
                                $images[] = $downloaded;
                            }
                        } elseif (isset($image_data['url'])) {
                            $downloaded = $this->download_and_save_image($image_data['url'], $product_id);
                            if (!is_wp_error($downloaded)) {
                                $images[] = $downloaded;
                            }
                        }
                    }
                }
                break;
                
            case 'stability':
                if (isset($response['artifacts']) && is_array($response['artifacts'])) {
                    foreach ($response['artifacts'] as $artifact) {
                        if (isset($artifact['base64'])) {
                            $downloaded = $this->save_base64_image($artifact['base64'], $product_id);
                            if (!is_wp_error($downloaded)) {
                                $images[] = $downloaded;
                            }
                        }
                    }
                }
                break;
        }
        
        if (empty($images)) {
            return new \WP_Error('no_images_generated', 'No images were generated');
        }
        
        return $images;
    }

    /**
     * Download and save image from URL
     *
     * @param string $image_url Image URL
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    private function download_and_save_image($image_url, $product_id) {
        // Download image with extended timeout
        $args = [
            'timeout' => 120,
            'headers' => [
                'User-Agent' => 'AI Product Content Generator'
            ],
            'sslverify' => false // Disable SSL verification to fix cURL error 60
        ];
        
        $response = wp_remote_get($image_url, $args);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        if ($response_code !== 200) {
            return new \WP_Error('download_failed', 'Failed to download image, HTTP code: ' . $response_code);
        }
        
        $image_data = wp_remote_retrieve_body($response);
        
        if (empty($image_data)) {
            return new \WP_Error('empty_image', 'Downloaded image is empty');
        }
        
        // Generate filename
        $filename = 'apcig-product-' . $product_id . '-' . uniqid() . '.png';
        
        // Save to WordPress uploads
        $upload = wp_upload_bits($filename, null, $image_data);
        
        if ($upload['error']) {
            return new \WP_Error('upload_failed', $upload['error']);
        }
        
        // Create attachment
        $attachment_id = $this->create_attachment($upload['file'], $upload['url'], $product_id);
        
        if (is_wp_error($attachment_id)) {
            return $attachment_id;
        }
        
        $result = [
            'attachment_id' => $attachment_id,
            'url' => $upload['url'],
            'filename' => $filename,
            'size' => strlen($image_data)
        ];
        
        return $result;
    }

    /**
     * Save base64 encoded image
     *
     * @param string $base64_data Base64 image data
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    private function save_base64_image($base64_data, $product_id) {
        $image_data = base64_decode($base64_data);
        if ($image_data === false) {
            return new \WP_Error('invalid_base64', 'Invalid base64 image data');
        }
        
        // Generate filename
        $filename = 'apcig-product-' . $product_id . '-' . uniqid() . '.png';
        
        // Save to WordPress uploads
        $upload = wp_upload_bits($filename, null, $image_data);
        
        if ($upload['error']) {
            return new \WP_Error('upload_failed', $upload['error']);
        }
        
        // Create attachment
        $attachment_id = $this->create_attachment($upload['file'], $upload['url'], $product_id);
        
        return [
            'attachment_id' => $attachment_id,
            'url' => $upload['url'],
            'filename' => $filename,
            'size' => strlen($image_data)
        ];
    }

    /**
     * Create WordPress attachment
     *
     * @param string $file_path File path
     * @param string $file_url File URL
     * @param int $product_id Product ID
     * @return int Attachment ID
     */
    private function create_attachment($file_path, $file_url, $product_id) {
        // Check if file exists
        if (!file_exists($file_path)) {
            return new \WP_Error('file_not_found', 'File does not exist: ' . $file_path);
        }
        
        $filetype = wp_check_filetype(basename($file_path), null);
        
        $attachment = [
            'post_mime_type' => $filetype['type'] ?: 'image/png',
            'post_title' => 'AI Generated Product Image',
            'post_content' => '',
            'post_status' => 'inherit',
            'post_parent' => $product_id
        ];
        
        $attachment_id = wp_insert_attachment($attachment, $file_path, $product_id);
        
        if (is_wp_error($attachment_id)) {
            return $attachment_id;
        }
        
        if (!$attachment_id || $attachment_id === 0) {
            return new \WP_Error('attachment_failed', 'Failed to create attachment');
        }
        
        // Generate attachment metadata
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        
        // Add custom meta
        update_post_meta($attachment_id, '_apcig_generated', true);
        update_post_meta($attachment_id, '_apcig_product_id', $product_id);
        update_post_meta($attachment_id, '_apcig_generated_date', current_time('mysql'));
        
        return $attachment_id;
    }

    /**
     * Enhance single image
     *
     * @param string $image_url Image URL
     * @param array $enhancements Enhancement types
     * @param float $strength Enhancement strength
     * @param string $provider AI provider
     * @return array|\WP_Error
     */
    private function enhance_single_image($image_url, $enhancements, $strength, $provider) {
        // For now, return a placeholder implementation
        // This would integrate with services like Real-ESRGAN, ESRGAN, or similar
        
        return new \WP_Error('not_implemented', 'Image enhancement not yet implemented');
    }

    /**
     * Apply image to product
     *
     * @param int $product_id Product ID
     * @param int $attachment_id Attachment ID
     * @param bool $set_as_featured Set as featured image
     * @return bool
     */
    public function apply_image_to_product($product_id, $attachment_id, $set_as_featured = false) {
        $product = wc_get_product($product_id);
        if (!$product) {
            return false;
        }

        if ($set_as_featured) {
            // Set as featured image
            $product->set_image_id($attachment_id);
        } else {
            // Add to gallery
            $gallery_ids = $product->get_gallery_image_ids();
            $gallery_ids[] = $attachment_id;
            $product->set_gallery_image_ids($gallery_ids);
        }

        $product->save();
        return true;
    }

    /**
     * Remove background from image
     *
     * @param int $attachment_id Attachment ID
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    public function remove_background($attachment_id, $product_id) {
        try {
            // Get the image file path
            $image_path = get_attached_file($attachment_id);
            if (!$image_path || !file_exists($image_path)) {
                throw new \Exception('Image file not found');
            }
            
            // Get image data
            $image_data = file_get_contents($image_path);
            if (!$image_data) {
                throw new \Exception('Failed to read image file');
            }
            
            // Check if remove.bg API key is configured
            $removebg_api_key = get_option('apcig_removebg_api_key', '');
            
            if (!empty($removebg_api_key)) {
                // Use remove.bg API
                $result = $this->remove_background_with_api($image_data, $removebg_api_key, $product_id);
            } else {
                // Use basic image processing (create transparent PNG)
                $result = $this->remove_background_basic($image_path, $product_id);
            }
            
            if (is_wp_error($result)) {
                return $result;
            }
            
            return $result;
            
        } catch (\Exception $e) {
            return new \WP_Error('background_removal_failed', $e->getMessage());
        }
    }
    
    /**
     * Remove background using remove.bg API
     *
     * @param string $image_data Image binary data
     * @param string $api_key Remove.bg API key
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    private function remove_background_with_api($image_data, $api_key, $product_id) {
        $response = wp_remote_post('https://api.remove.bg/v1.0/removebg', [
            'timeout' => 60,
            'headers' => [
                'X-Api-Key' => sanitize_text_field($api_key)
            ],
            'body' => [
                'image_file_b64' => base64_encode($image_data),
                'size' => 'auto'
            ],
            'sslverify' => true
        ]);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $body = wp_remote_retrieve_body($response);
            return new \WP_Error('api_error', 'Remove.bg API error: ' . $body);
        }
        
        $processed_image = wp_remote_retrieve_body($response);
        
        // Save the processed image
        $filename = 'bg-removed-' . uniqid() . '.png';
        $upload = wp_upload_bits($filename, null, $processed_image);
        
        if ($upload['error']) {
            return new \WP_Error('upload_failed', $upload['error']);
        }
        
        // Create attachment
        $attachment_id = $this->create_attachment($upload['file'], $upload['url'], $product_id);
        
        return [
            'attachment_id' => $attachment_id,
            'url' => $upload['url'],
            'filename' => $filename
        ];
    }
    
    /**
     * Basic background removal (creates white/transparent background)
     *
     * @param string $image_path Image file path
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    private function remove_background_basic($image_path, $product_id) {
        // Load image
        $image_info = getimagesize($image_path);
        if (!$image_info) {
            return new \WP_Error('invalid_image', 'Invalid image file');
        }
        
        $mime_type = $image_info['mime'];
        
        // Create image resource based on type
        switch ($mime_type) {
            case 'image/jpeg':
                $source = imagecreatefromjpeg($image_path);
                break;
            case 'image/png':
                $source = imagecreatefrompng($image_path);
                break;
            case 'image/gif':
                $source = imagecreatefromgif($image_path);
                break;
            case 'image/webp':
                if (function_exists('imagecreatefromwebp')) {
                    $source = imagecreatefromwebp($image_path);
                } else {
                    return new \WP_Error('unsupported_format', 'WebP support not available');
                }
                break;
            default:
                return new \WP_Error('unsupported_format', 'Unsupported image format');
        }
        
        if (!$source) {
            return new \WP_Error('image_load_failed', 'Failed to load image');
        }
        
        // Create a new image with transparency
        $width = imagesx($source);
        $height = imagesy($source);
        $dest = imagecreatetruecolor($width, $height);
        
        // Enable alpha blending
        imagealphablending($dest, false);
        imagesavealpha($dest, true);
        
        // Fill with transparent background
        $transparent = imagecolorallocatealpha($dest, 0, 0, 0, 127);
        imagefill($dest, 0, 0, $transparent);
        
        // Copy source to destination (this is a basic implementation)
        // In a real scenario, you'd use edge detection and color analysis
        imagecopy($dest, $source, 0, 0, 0, 0, $width, $height);
        
        // Save as PNG
        $filename = 'bg-removed-' . uniqid() . '.png';
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        imagepng($dest, $file_path);
        
        // Clean up - Check for both resource (PHP < 8) and GdImage object (PHP 8+)
        if (is_resource($source) || $source instanceof \GdImage) {
            imagedestroy($source);
        }
        if (is_resource($dest) || $dest instanceof \GdImage) {
            imagedestroy($dest);
        }
        
        // Create attachment
        $attachment_id = $this->create_attachment($file_path, $upload_dir['url'] . '/' . $filename, $product_id);
        
        return [
            'attachment_id' => $attachment_id,
            'url' => $upload_dir['url'] . '/' . $filename,
            'filename' => $filename,
            'note' => 'Basic background processing applied. For better results, configure remove.bg API key in settings.'
        ];
    }
    
    /**
     * Upload and process image
     *
     * @param array $file Uploaded file data from $_FILES
     * @param int $product_id Product ID
     * @return array|\WP_Error
     */
    public function upload_image($file, $product_id) {
        try {
            // Validate file
            if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
                throw new \Exception('Invalid file upload');
            }
            
            // Check file type
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
            $file_type = wp_check_filetype($file['name']);
            
            if (!in_array($file_type['type'], $allowed_types)) {
                throw new \Exception('Invalid file type. Only JPG, PNG, WebP, and GIF are allowed.');
            }
            
            // Check file size (max 10MB)
            if ($file['size'] > 10 * 1024 * 1024) {
                throw new \Exception('File size exceeds 10MB limit');
            }
            
            // Upload file
            $upload = wp_upload_bits(
                sanitize_file_name($file['name']),
                null,
                file_get_contents($file['tmp_name'])
            );
            
            if ($upload['error']) {
                throw new \Exception($upload['error']);
            }
            
            // Create attachment
            $attachment_id = $this->create_attachment($upload['file'], $upload['url'], $product_id);
            
            if (is_wp_error($attachment_id)) {
                throw new \Exception($attachment_id->get_error_message());
            }
            
            return [
                'success' => true,
                'attachment_id' => $attachment_id,
                'url' => $upload['url'],
                'filename' => basename($upload['file'])
            ];
            
        } catch (\Exception $e) {
            return new \WP_Error('upload_failed', $e->getMessage());
        }
    }

    /**
     * Make OpenAI image edit request
     *
     * @param array $request_data Request data
     * @return array|WP_Error Response data
     */
    private function make_openai_edit_request($request_data) {
        $api_key = get_option('apcig_openai_api_key');
        if (empty($api_key)) {
            return new \WP_Error('no_api_key', 'OpenAI API key not configured');
        }
        
        $image_path = $request_data['image'];
        
        // Prepare multipart form data
        $boundary = wp_generate_password(24, false);
        $body = '';
        
        // Add model
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"model\"\r\n\r\n";
        $body .= $request_data['model'] . "\r\n";
        
        // Add prompt
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"prompt\"\r\n\r\n";
        $body .= $request_data['prompt'] . "\r\n";
        
        // Add size
        if (isset($request_data['size'])) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"size\"\r\n\r\n";
            $body .= $request_data['size'] . "\r\n";
        }
        
        // Add input_fidelity
        if (isset($request_data['input_fidelity'])) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"input_fidelity\"\r\n\r\n";
            $body .= $request_data['input_fidelity'] . "\r\n";
        }
        
        // Add n (number of images)
        if (isset($request_data['n'])) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"n\"\r\n\r\n";
            $body .= $request_data['n'] . "\r\n";
        }
        
        // Add response_format
        if (isset($request_data['response_format'])) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"response_format\"\r\n\r\n";
            $body .= $request_data['response_format'] . "\r\n";
        }
        
        // Add image file
        $image_data = file_get_contents($image_path);
        $image_name = basename($image_path);
        
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"image[]\"; filename=\"{$image_name}\"\r\n";
        $body .= "Content-Type: image/png\r\n\r\n";
        $body .= $image_data . "\r\n";
        
        $body .= "--{$boundary}--\r\n";
        
        // Prepare request args
        $args = [
            'timeout' => 180,
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'multipart/form-data; boundary=' . $boundary
            ],
            'body' => $body
        ];
        
        // Disable SSL verification for local development
        // Check for local domains (.test, .local, localhost) or if WP_DEBUG is enabled
        $home_url = home_url();
        $is_local = (strpos($home_url, 'localhost') !== false || 
                     strpos($home_url, '.test') !== false || 
                     strpos($home_url, '.local') !== false ||
                     strpos($home_url, '127.0.0.1') !== false);
        
        if ($is_local || (defined('WP_DEBUG') && WP_DEBUG)) {
            $args['sslverify'] = false;
        }
        
        // Make request
        $response = wp_remote_post('https://api.openai.com/v1/images/edits', $args);
        
        // Clean up temp file
        wp_delete_file($image_path);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            return new \WP_Error('api_error', 'OpenAI API request failed: ' . $response_body);
        }
        
        $data = json_decode($response_body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new \WP_Error('invalid_response', 'Invalid JSON response from OpenAI');
        }
        
        return $data;
    }
    
    /**
     * 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
        // Reset daily counter at midnight if needed
        $last_reset = get_option('apcig_last_daily_reset', '');
        $today_date = current_time('Y-m-d');
        
        if ($last_reset !== $today_date) {
            update_option('apcig_content_generated_today', 0);
            update_option('apcig_images_generated_today', 0);
            update_option('apcig_last_daily_reset', $today_date);
        }
        
        $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 total counters
        $total_key = 'apcig_total_images_generated';
        $total = get_option($total_key, 0);
        update_option($total_key, $total + $count);
        
        // Update today's images generated
        $today_total = get_option('apcig_images_generated_today', 0);
        update_option('apcig_images_generated_today', $today_total + $count);
    }

    /**
     * Get available image styles
     *
     * @return array
     */
    public function get_image_styles() {
        return $this->image_styles;
    }

    /**
     * Get available image sizes
     *
     * @return array
     */
    public function get_image_sizes() {
        return $this->image_sizes;
    }

    /**
     * Get generated images for product
     *
     * @param int $product_id Product ID
     * @return array
     */
    public function get_product_generated_images($product_id) {
        $attachments = get_posts([
            'post_type' => 'attachment',
            'post_parent' => $product_id,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
            'meta_query' => [
                [
                    'key' => '_apcig_generated',
                    'value' => true,
                    'compare' => '='
                ]
            ],
            'posts_per_page' => -1
        ]);

        $images = [];
        foreach ($attachments as $attachment) {
            $images[] = [
                'id' => $attachment->ID,
                'url' => wp_get_attachment_url($attachment->ID),
                'title' => $attachment->post_title,
                'generated_date' => get_post_meta($attachment->ID, '_apcig_generated_date', true)
            ];
        }

        return $images;
    }
}