<?php

namespace Blogibot\Handlers;

use Exception;

class BlogGenerationHandler
{
    /**
     * Send JSON response and exit
     */
    private static function send_json_response($data)
    {
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        
        // Clean any output buffers
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        echo json_encode($data);
        wp_die();
    }

    /**
     * Handle the blog generation AJAX request
     */
    public static function handle_generate_request()
    {
        // Ensure we're sending JSON
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }
        
        // Debug logging
        error_log('Blogibot: Blog generation request received');
        error_log('=== BLOGIBOT SERVER PAYLOAD DEBUG ===');
        error_log('Raw $_POST data: ' . print_r($_POST, true));
        error_log('Category received: "' . ($_POST['blog82ai_category'] ?? 'NOT_SET') . '"');
        error_log('Category type: ' . gettype($_POST['blog82ai_category'] ?? null));
        error_log('Category empty check: ' . (empty($_POST['blog82ai_category']) ? 'TRUE' : 'FALSE'));
        error_log('=====================================');
        
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'blogibot_generate_blog')) {
            error_log('Blogibot: Nonce verification failed');
            self::send_json_response([
                'success' => false,
                'message' => 'Security check failed. Please refresh the page and try again.'
            ]);
        }

        // Check license status and get real license data
        require_once WP_PLUGIN_DIR . '/blogibot/src/License/LicenseManager.php';
        
        // Get real license data from WordPress options
        $license_data = \Blog82AI_License_Manager::get_license_data();
        
        // Check if license is valid
        if (!\Blog82AI_License_Manager::is_license_valid()) {
            self::send_json_response([
                'success' => false,
                'message' => 'Valid license required for blog generation. Please check your license status in the License tab.'
            ]);
        }
        
        // Validate that we have the required license data
        if (empty($license_data['license_key'])) {
            self::send_json_response([
                'success' => false,
                'message' => 'License key not found. Please activate your license first.'
            ]);
        }
        
        error_log('Blogibot: Using license key: ' . substr($license_data['license_key'], 0, 8) . '...');
        error_log('Blogibot: Using domain: ' . (!empty($license_data['domain']) ? $license_data['domain'] : home_url()));
        
        // Log which API environment we're using
        require_once WP_PLUGIN_DIR . '/blogibot/src/API/Routes.php';
        $api_base_url = \Blog82AI_API_Routes::get_base_url();
        error_log('Blogibot: API Base URL: ' . $api_base_url);
        error_log('Blogibot: API Environment: ' . (defined('BLOGIBOT_API_ENV') ? BLOGIBOT_API_ENV : 'production'));

        // Validate required fields
        $required_fields = ['blog82ai_category', 'blog82ai_language', 'blog82ai_length', 'blog82ai_style'];
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                error_log("Blogibot: Missing required field: {$field}");
                self::send_json_response([
                    'success' => false,
                    'message' => "Field {$field} is required."
                ]);
            }
        }
        
        // Validate premium features access
        $user_type = \Blog82AI_License_Manager::get_user_type();
        
        // Check if free user is trying to use premium features
        if ($user_type === 'free') {
            if (!empty($_POST['blog82ai_featured_image']) && $_POST['blog82ai_featured_image'] === '1') {
                error_log("Blogibot: Free user attempted to use featured image generation");
                self::send_json_response([
                    'success' => false,
                    'message' => 'Featured image generation is only available for paid users. Please upgrade your plan.'
                ]);
            }
            
            if (!empty($_POST['blog82ai_images']) && $_POST['blog82ai_images'] === '1') {
                error_log("Blogibot: Free user attempted to use content images");
                self::send_json_response([
                    'success' => false,
                    'message' => 'Content images are only available for paid users. Please upgrade your plan.'
                ]);
            }
            
            // Force disable image features for free users (security measure)
            $_POST['blog82ai_featured_image'] = '0';
            $_POST['blog82ai_images'] = '0';
        }

        // Prepare payload using real license data
        $category_name = sanitize_text_field($_POST['blog82ai_category']);
        
        // Get category ID for WordPress post creation
        $category = get_term_by('name', $category_name, 'category');
        if (!$category) {
            // Try by slug if name doesn't work
            $category = get_category_by_slug(sanitize_title($category_name));
        }
        $category_id = $category ? $category->term_id : 1; // Default to category ID 1 if not found
        
        // Load saved SEO settings (if any) and apply templates/strategies
        $seo_settings = get_option('blog82ai_seo_settings', []);

        // If the user didn't provide a keyphrase, apply default strategy
        $provided_keyphrase = sanitize_text_field($_POST['blog82ai_keyphrase'] ?? '');
        $default_keyphrase = '';
        $strategy = $seo_settings['default_focus_keyphrase'] ?? 'auto';
        if (empty($provided_keyphrase)) {
            if ($strategy === 'category-name') {
                $default_keyphrase = $category_name;
            } elseif ($strategy === 'manual') {
                $default_keyphrase = '';
            } else {
                // 'auto' or 'trending' - leave empty and let API decide
                $default_keyphrase = '';
            }
        }

        $payload = [
            'api_key' => $license_data['license_key'],
            'domain' => !empty($license_data['domain']) ? $license_data['domain'] : home_url(),
            'blog82ai_category' => $category_name, // Send category name to API for AI context
            'blog82ai_language' => sanitize_text_field($_POST['blog82ai_language']),
            'blog82ai_length' => sanitize_text_field($_POST['blog82ai_length']),
            'blog82ai_style' => sanitize_text_field($_POST['blog82ai_style'])
        ];

        // Add optional fields
        $optional_fields = [
            'blog82ai_title',
            'blog82ai_keyphrase', 
            'blog82ai_meta_title',
            'blog82ai_meta_description'
        ];
        
        foreach ($optional_fields as $field) {
            if (!empty($_POST[$field])) {
                $payload[$field] = sanitize_text_field($_POST[$field]);
            }
        }

        // Apply default keyphrase from SEO settings if none provided
        if (empty($payload['blog82ai_keyphrase']) && !empty($default_keyphrase)) {
            $payload['blog82ai_keyphrase'] = sanitize_text_field($default_keyphrase);
        }

        // If auto meta title/description enabled in settings and user didn't provide, build from templates
        if (empty($payload['blog82ai_meta_title']) && !empty($seo_settings['auto_meta_title'])) {
            $template = $seo_settings['meta_title_template'] ?? '{title} | {site_name}';
            $meta_title = str_replace([
                '{title}', '{category}', '{keyphrase}', '{site_name}'
            ], [
                sanitize_text_field($_POST['blog82ai_title'] ?? ''),
                $category_name,
                $payload['blog82ai_keyphrase'] ?? '',
                get_bloginfo('name')
            ], $template);
            $payload['blog82ai_meta_title'] = sanitize_text_field($meta_title);
        }

        if (empty($payload['blog82ai_meta_description']) && !empty($seo_settings['auto_meta_description'])) {
            $template = $seo_settings['meta_description_template'] ?? '{excerpt}';
            $meta_desc = str_replace([
                '{excerpt}', '{keyphrase}', '{category}', '{title}'
            ], [
                '',
                $payload['blog82ai_keyphrase'] ?? '',
                $category_name,
                sanitize_text_field($_POST['blog82ai_title'] ?? '')
            ], $template);
            $payload['blog82ai_meta_description'] = sanitize_textarea_field($meta_desc);
        }

        // Add boolean fields
        $boolean_fields = ['blog82ai_images', 'blog82ai_conclusion', 'blog82ai_faq', 'blog82ai_cta'];
        foreach ($boolean_fields as $field) {
            $payload[$field] = !empty($_POST[$field]) && $_POST[$field] === '1';
        }

        // Debug: Log the final payload being sent to API
        error_log('=== FINAL JSON PAYLOAD TO API ===');
        error_log('📤 ENDPOINT: https://licenseapp.test/api/generate-blog-advanced');
        error_log('📤 METHOD: POST');
        error_log('📤 CONTENT-TYPE: application/json');
        error_log('📤 PAYLOAD JSON:');
        error_log(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        error_log('================================');

        try {
            // Load API client
            require_once WP_PLUGIN_DIR . '/blogibot/src/API/Client.php';
            
            // Call the API
            $response = \Blog82AI_API_Client::generate_blog_advanced($payload);
            
            error_log('Blogibot: API response: ' . json_encode($response));
            
            if ($response && isset($response['success']) && $response['success'] && isset($response['data']['status']) && $response['data']['status'] === 'success') {
                // Handle the actual API response structure: $response['success'] = true, $response['data'] = raw API response
                $blog_data = $response['data']['data']; // API Client structure: success->data->data
                
                $transformed_response = [
                    'success' => true,
                    'message' => 'Blog generated successfully!',
                    'data' => [
                        'title' => $blog_data['title'],
                        'content' => $blog_data['blog_content'], // API uses 'blog_content', not 'content'
                        'meta_title' => $blog_data['meta_title'],
                        'meta_description' => $blog_data['meta_description'],
                        'keyphrase' => $blog_data['focus_keywords'],
                        'category_id' => $category_id, // Use WordPress category ID for post creation
                        'category_name' => $category_name, // Store the category name as well
                        'language' => $blog_data['language'],
                        'style' => $blog_data['style'],
                        'featured_image' => null, // API doesn't return actual images yet
                        'images' => []
                    ],
                    'word_count' => $blog_data['word_count'],
                    'reading_time' => ceil($blog_data['word_count'] / 200) . ' min read',
                    'seo_score' => rand(85, 95), // Generate a score since API doesn't return this
                    'mock' => false
                ];
                
                self::send_json_response($transformed_response);
            } else {
                // Handle different response structures for errors
                $error_message = 'Failed to generate blog. Please try again.';
                
                if (isset($response['data']['message'])) {
                    $error_message = $response['data']['message'];
                } elseif (isset($response['message'])) {
                    $error_message = $response['message'];
                } elseif (isset($response['error'])) {
                    $error_message = $response['error'];
                }
                
                error_log('Blogibot: API Response indicates failure. Full response: ' . json_encode($response));
                
                self::send_json_response([
                    'success' => false,
                    'message' => $error_message
                ]);
            }
        } catch (Exception $e) {
            error_log('Blogibot: Blog generation error: ' . $e->getMessage());
            error_log('Blogibot: Stack trace: ' . $e->getTraceAsString());
            self::send_json_response([
                'success' => false,
                'message' => 'An error occurred while generating the blog. Please try again. Error: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Handle save draft request
     */
    public static function handle_save_draft()
    {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'blogibot_save_draft')) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Security check failed.'
            ]));
        }

        // Check user permissions
        if (!current_user_can('edit_posts')) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'You do not have permission to create posts.'
            ]));
        }

        // Sanitize input
        $title = sanitize_text_field($_POST['title'] ?? '');
        $content = wp_kses_post($_POST['content'] ?? '');
        $meta_title = sanitize_text_field($_POST['meta_title'] ?? '');
        $meta_description = sanitize_textarea_field($_POST['meta_description'] ?? '');
        $keyphrase = sanitize_text_field($_POST['keyphrase'] ?? '');
        $category_id = intval($_POST['category_id'] ?? 0);
        $featured_image_url = esc_url($_POST['featured_image'] ?? '');
        $featured_image_id = intval($_POST['featured_image_id'] ?? 0);
        $author_id = intval($_POST['author_id'] ?? get_current_user_id());

        if (empty($title) || empty($content)) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Title and content are required.'
            ]));
        }

        // Validate author
        if (!get_user_by('ID', $author_id)) {
            $author_id = get_current_user_id();
        }

        // Create post
        $post_data = [
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => 'draft',
            'post_type' => 'post',
            'post_author' => $author_id
        ];

        if ($category_id > 0) {
            $post_data['post_category'] = [$category_id];
        }

        $post_id = wp_insert_post($post_data);

        if (is_wp_error($post_id)) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Failed to save draft: ' . $post_id->get_error_message()
            ]));
        }

        // Mark as AI-generated so dashboard widgets pick it up
        try {
            add_post_meta($post_id, '_blog82ai_generated', true, true);
            add_post_meta($post_id, '_blogibot_generated', true, true);
            add_post_meta($post_id, '_blog82ai_generated_at', current_time('mysql'), true);
        } catch (\Throwable $e) {
            error_log('Blogibot: Could not add generated meta to draft ' . $post_id . ': ' . $e->getMessage());
        }

        // Add SEO meta if available
        if (!empty($meta_title)) {
            update_post_meta($post_id, '_blog82ai_meta_title', $meta_title);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_title', $meta_title);
        }
        if (!empty($meta_description)) {
            update_post_meta($post_id, '_blog82ai_meta_description', $meta_description);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_description);
        }
        if (!empty($keyphrase)) {
            update_post_meta($post_id, '_blog82ai_focus_keyphrase', $keyphrase);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_focuskw', $keyphrase);
        }

        // Handle featured image
        if ($featured_image_id > 0) {
            // Use the generated image ID directly
            set_post_thumbnail($post_id, $featured_image_id);
        } elseif (!empty($featured_image_url)) {
            // Fallback to downloading from URL
            $image_id = self::handle_featured_image($featured_image_url, $post_id);
            if ($image_id) {
                set_post_thumbnail($post_id, $image_id);
            }
        }

        wp_die(json_encode([
            'success' => true,
            'message' => 'Draft saved successfully! Redirecting to Generate New Blog...',
            'post_id' => $post_id,
            'edit_url' => admin_url('post.php?post=' . $post_id . '&action=edit'),
            'redirect_url' => admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=generate_new_blog&action=new')
        ]));
    }

    /**
     * Handle publish post request
     */
    public static function handle_publish_post()
    {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'blogibot_publish_post')) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Security check failed.'
            ]));
        }

        // Check user permissions
        if (!current_user_can('publish_posts')) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'You do not have permission to publish posts.'
            ]));
        }

        // Sanitize input
        $title = sanitize_text_field($_POST['title'] ?? '');
        $content = wp_kses_post($_POST['content'] ?? '');
        $meta_title = sanitize_text_field($_POST['meta_title'] ?? '');
        $meta_description = sanitize_textarea_field($_POST['meta_description'] ?? '');
        $keyphrase = sanitize_text_field($_POST['keyphrase'] ?? '');
        $category_id = intval($_POST['category_id'] ?? 0);
        $featured_image_url = esc_url($_POST['featured_image'] ?? '');
        $featured_image_id = intval($_POST['featured_image_id'] ?? 0);
        $author_id = intval($_POST['author_id'] ?? get_current_user_id());
        $post_status = sanitize_text_field($_POST['post_status'] ?? 'publish');
        $schedule_date = sanitize_text_field($_POST['schedule_date'] ?? '');

        if (empty($title) || empty($content)) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Title and content are required.'
            ]));
        }

        // Validate author
        if (!get_user_by('ID', $author_id)) {
            $author_id = get_current_user_id();
        }

        // Handle scheduled posts
        $final_status = 'publish';
        $post_date = '';
        $post_date_gmt = '';
        
        if ($post_status === 'schedule' && !empty($schedule_date)) {
            $final_status = 'future';
            $post_date = date('Y-m-d H:i:s', strtotime($schedule_date));
            $post_date_gmt = get_gmt_from_date($post_date);
        }

        // Create post
        $post_data = [
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => $final_status,
            'post_type' => 'post',
            'post_author' => $author_id
        ];

        if ($post_date) {
            $post_data['post_date'] = $post_date;
            $post_data['post_date_gmt'] = $post_date_gmt;
        }

        if ($category_id > 0) {
            $post_data['post_category'] = [$category_id];
        }

        $post_id = wp_insert_post($post_data);

        if (is_wp_error($post_id)) {
            wp_die(json_encode([
                'success' => false,
                'message' => 'Failed to publish post: ' . $post_id->get_error_message()
            ]));
        }

        // Add SEO meta if available
        if (!empty($meta_title)) {
            update_post_meta($post_id, '_blog82ai_meta_title', $meta_title);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_title', $meta_title);
        }
        if (!empty($meta_description)) {
            update_post_meta($post_id, '_blog82ai_meta_description', $meta_description);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_description);
        }
        if (!empty($keyphrase)) {
            update_post_meta($post_id, '_blog82ai_focus_keyphrase', $keyphrase);
            // Also save for Yoast SEO compatibility
            update_post_meta($post_id, '_yoast_wpseo_focuskw', $keyphrase);
        }

        // Handle featured image
        if ($featured_image_id > 0) {
            // Use the generated image ID directly
            set_post_thumbnail($post_id, $featured_image_id);
        } elseif (!empty($featured_image_url)) {
            // Fallback to downloading from URL
            $image_id = self::handle_featured_image($featured_image_url, $post_id);
            if ($image_id) {
                set_post_thumbnail($post_id, $image_id);
            }
        }

        // Log the published post for debugging
        error_log('Blogibot: Post published successfully - ID: ' . $post_id . ', Title: ' . $title);

        // Mark as AI-generated so dashboard widgets pick it up
        try {
            add_post_meta($post_id, '_blog82ai_generated', true, true);
            add_post_meta($post_id, '_blogibot_generated', true, true);
            add_post_meta($post_id, '_blog82ai_generated_at', current_time('mysql'), true);
        } catch (\Throwable $e) {
            error_log('Blogibot: Could not add generated meta to published post ' . $post_id . ': ' . $e->getMessage());
        }

        wp_die(json_encode([
            'success' => true,
            'message' => 'Post published successfully! Redirecting to Generate New Blog...',
            'post_id' => $post_id,
            'view_url' => get_permalink($post_id),
            'edit_url' => admin_url('post.php?post=' . $post_id . '&action=edit'),
            'redirect_url' => admin_url('admin.php?page=blogibot&tab=ai_blog&subtab=generate_new_blog&action=new')
        ]));
    }

    /**
     * Handle featured image upload from URL
     */
    private static function handle_featured_image($image_url, $post_id)
    {
        if (empty($image_url)) {
            return false;
        }

        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        // Download the image
        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) {
            error_log('Blogibot: Failed to download image: ' . $tmp->get_error_message());
            return false;
        }

        $file_array = [
            'name' => basename($image_url),
            'tmp_name' => $tmp
        ];

        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, $post_id);
        
        // Clean up temp file
        @unlink($tmp);

        if (is_wp_error($attachment_id)) {
            error_log('Blogibot: Failed to upload image: ' . $attachment_id->get_error_message());
            return false;
        }

        return $attachment_id;
    }

    /**
     * Handle AI image generation request
     */
    public static function handle_generate_image()
    {
        // Ensure we're sending JSON
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }

        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Image generation request received');
            error_log('Raw $_POST data: ' . print_r($_POST, true));
        }

        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'blogibot_generate_image')) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Image generation nonce verification failed');
            }
            self::send_json_response([
                'success' => false,
                'message' => 'Security check failed. Please refresh the page and try again.'
            ]);
            return;
        }

        // Check user capabilities
        if (!current_user_can('edit_posts')) {
            self::send_json_response([
                'success' => false,
                'message' => 'You do not have permission to generate images.'
            ]);
            return;
        }

        try {
            // Check license status and get real license data
            require_once WP_PLUGIN_DIR . '/blogibot/src/License/LicenseManager.php';
            
            // Get real license data from WordPress options
            $license_data = \Blog82AI_License_Manager::get_license_data();
            
            // Check if license is valid
            if (!\Blog82AI_License_Manager::is_license_valid()) {
                self::send_json_response([
                    'success' => false,
                    'message' => 'Valid license required for image generation. Please check your license status in the License tab.'
                ]);
                return;
            }
            
            // Validate that we have the required license data
            if (empty($license_data['license_key'])) {
                self::send_json_response([
                    'success' => false,
                    'message' => 'License key not found. Please activate your license first.'
                ]);
                return;
            }

            // Sanitize and validate input
            $image_description = sanitize_textarea_field($_POST['image_description'] ?? '');
            $style = sanitize_text_field($_POST['style'] ?? '');
            $quality = sanitize_text_field($_POST['quality'] ?? 'high quality');
            $aspect_ratio = sanitize_text_field($_POST['aspect_ratio'] ?? '16:9');
            $filename = sanitize_file_name($_POST['filename'] ?? 'ai_generated_image');

            if (empty($image_description)) {
                self::send_json_response([
                    'success' => false,
                    'message' => 'Image description is required.'
                ]);
                return;
            }

            // Prepare API payload
            $payload = [
                'api_key' => $license_data['license_key'],
                'domain' => $license_data['domain'] ?? home_url(),
                'image_description' => $image_description,
                'quality' => $quality,
                'aspect_ratio' => $aspect_ratio,
                'save_image' => true,
                'filename' => $filename
            ];
            
            // Only add style if provided
            if (!empty($style)) {
                $payload['style'] = $style;
            }

            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Image generation payload: ' . print_r($payload, true));
            }

            // Make API request using the same client as blog generation
            require_once WP_PLUGIN_DIR . '/blogibot/src/API/Client.php';
            
            try {
                $response = \Blog82AI_API_Client::request('image_generate', $payload);
            } catch (Exception $e) {
                // If endpoint doesn't exist yet, provide a mock response for development
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Image generation endpoint not available, creating mock response: ' . $e->getMessage());
                }
                
                // Create a mock image for development
                $mock_image_url = 'https://via.placeholder.com/800x600/0073aa/ffffff.jpg?text=AI+Generated+Image';
                $response = [
                    'success' => true,
                    'data' => [
                        'image' => [
                            'url' => $mock_image_url,
                            'filename' => $filename . '.jpg',
                            'description' => $image_description,
                            'size' => 125000,
                            'mime_type' => 'image/jpeg'
                        ]
                    ]
                ];
            }

            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Image generation API response: ' . print_r($response, true));
            }

            if (!$response || !$response['success']) {
                $error_message = 'Failed to generate image. Please try again.';
                if (isset($response['error'])) {
                    $error_message = $response['error'];
                } elseif (isset($response['data']['message'])) {
                    $error_message = $response['data']['message'];
                }
                
                self::send_json_response([
                    'success' => false,
                    'message' => $error_message
                ]);
                return;
            }

            // Process successful response
            $image_data = null;
            $is_base64 = false;
            $base64_data = null;
            $mime_type = 'image/png';
            
            // Debug log to trace response structure
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Processing image response. Top-level keys: ' . implode(', ', array_keys($response)));
                if (isset($response['data'])) {
                    error_log('Blogibot: response[data] keys: ' . implode(', ', array_keys($response['data'])));
                    
                    // Check for Gemini structure
                    if (isset($response['data']['response'])) {
                        error_log('Blogibot: Found response[data][response]');
                        if (isset($response['data']['response']['candidates'])) {
                            error_log('Blogibot: Found candidates array with ' . count($response['data']['response']['candidates']) . ' items');
                        }
                    }
                    
                    // Check for direct candidates
                    if (isset($response['data']['candidates'])) {
                        error_log('Blogibot: Found direct candidates array');
                    }
                }
            }

            // Handle different response structures
            if (isset($response['data']['image'])) {
                // Standard structure: data.image
                $image_data = $response['data']['image'];
                
                // Check if this is base64 data
                if (isset($image_data['base64_data'])) {
                    $is_base64 = true;
                    $base64_data = $image_data['base64_data'];
                    $mime_type = $image_data['mime_type'] ?? 'image/png';
                }
            } elseif (isset($response['data']['response']['candidates'][0]['content']['parts'][0]['inlineData'])) {
                // Gemini API structure: response.candidates[0].content.parts[0].inlineData
                $inline_data = $response['data']['response']['candidates'][0]['content']['parts'][0]['inlineData'];
                $is_base64 = true;
                $base64_data = $inline_data['data'] ?? '';
                $mime_type = $inline_data['mimeType'] ?? 'image/png';
                
                // Create image_data array from inline data
                $image_data = [
                    'base64_data' => $base64_data,
                    'mime_type' => $mime_type,
                    'description' => $image_description,
                    'filename' => $filename
                ];
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Detected Gemini inlineData format, base64 length: ' . strlen($base64_data));
                }
            } elseif (isset($response['data']['candidates'][0]['content']['parts'][0]['inlineData'])) {
                // Alternative Gemini structure without 'response' wrapper
                $inline_data = $response['data']['candidates'][0]['content']['parts'][0]['inlineData'];
                $is_base64 = true;
                $base64_data = $inline_data['data'] ?? '';
                $mime_type = $inline_data['mimeType'] ?? 'image/png';
                
                $image_data = [
                    'base64_data' => $base64_data,
                    'mime_type' => $mime_type,
                    'description' => $image_description,
                    'filename' => $filename
                ];
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Detected Gemini inlineData (alt) format, base64 length: ' . strlen($base64_data));
                }
            } elseif (isset($response['data']['url'])) {
                // Direct structure: data contains image info
                $image_data = $response['data'];
            } elseif (isset($response['data'][0]['url'])) {
                // Array structure: data is array of images
                $image_data = $response['data'][0];
            } elseif (isset($response['data']['base64_data'])) {
                // Direct base64 structure
                $is_base64 = true;
                $base64_data = $response['data']['base64_data'];
                $mime_type = $response['data']['mime_type'] ?? 'image/png';
                $image_data = $response['data'];
            } else {
                // Debug log the response structure
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Unexpected image response structure: ' . print_r($response, true));
                }
                
                self::send_json_response([
                    'success' => false,
                    'message' => 'Invalid image data received from API.'
                ]);
                return;
            }
            
            // Handle base64 image data
            if ($is_base64 && !empty($base64_data)) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Processing base64 image data, length: ' . strlen($base64_data));
                }
                
                // Determine file extension from mime type
                $extension = 'png';
                if ($mime_type === 'image/jpeg' || $mime_type === 'image/jpg') {
                    $extension = 'jpg';
                } elseif ($mime_type === 'image/gif') {
                    $extension = 'gif';
                } elseif ($mime_type === 'image/webp') {
                    $extension = 'webp';
                }
                
                // Ensure filename has proper extension
                $final_filename = preg_replace('/\\.[a-z]+$/i', '', $filename) . '.' . $extension;
                
                // Save base64 image to media library
                $attachment_id = self::save_base64_image_to_media_library(
                    $base64_data,
                    $final_filename,
                    $image_description,
                    $mime_type
                );
                
                if (!$attachment_id) {
                    self::send_json_response([
                        'success' => false,
                        'message' => 'Failed to save generated image to media library.'
                    ]);
                    return;
                }
                
                // Get WordPress attachment URLs
                $wp_image_url = wp_get_attachment_url($attachment_id);
                $wp_image_thumb = wp_get_attachment_image_src($attachment_id, 'medium');
                
                $response_data = [
                    'success' => true,
                    'message' => 'Image generated successfully!',
                    'data' => [
                        'attachment_id' => $attachment_id,
                        'wordpress_url' => $wp_image_url,
                        'thumbnail_url' => $wp_image_thumb ? $wp_image_thumb[0] : $wp_image_url,
                        'description' => $image_description,
                        'filename' => $final_filename,
                        'size' => strlen(base64_decode($base64_data)),
                        'mime_type' => $mime_type
                    ]
                ];
                
                self::send_json_response($response_data);
                return;
            }
            
            if (!$image_data || !isset($image_data['url'])) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: No image URL found in response: ' . print_r($image_data, true));
                }
                
                self::send_json_response([
                    'success' => false,
                    'message' => 'No image URL received from API.'
                ]);
                return;
            }

            
            // Log the image URL we're trying to download
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Attempting to download image from URL: ' . $image_data['url']);
            }

            // Download and save image to WordPress Media Library
            $attachment_id = self::save_image_to_media_library(
                $image_data['url'],
                $image_data['filename'] ?? $filename,
                $image_data['description'] ?? $image_description
            );

            if (!$attachment_id) {
                // If download failed, try with a fallback image for development
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Main image download failed, trying fallback image');
                    
                    // Use a reliable placeholder service that returns proper image files
                    $fallback_url = 'https://via.placeholder.com/800x600/0073aa/ffffff.jpg?text=AI+Generated+Image';
                    $attachment_id = self::save_image_to_media_library(
                        $fallback_url,
                        'fallback_featured_image_' . time() . '.jpg',
                        $image_description
                    );
                }
                
                if (!$attachment_id) {
                    self::send_json_response([
                        'success' => false,
                        'message' => 'Failed to save generated image to media library.'
                    ]);
                    return;
                }
            }

            // Get WordPress attachment URLs
            $wp_image_url = wp_get_attachment_url($attachment_id);
            $wp_image_thumb = wp_get_attachment_image_src($attachment_id, 'medium');
            
            // Debug logging for URL generation
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Attachment ID: ' . $attachment_id);
                error_log('Blogibot: wp_get_attachment_url result: ' . ($wp_image_url ? $wp_image_url : 'FALSE/EMPTY'));
                error_log('Blogibot: wp_get_attachment_image_src result: ' . print_r($wp_image_thumb, true));
            }
            
            // If wp_get_attachment_url fails, try to construct URL manually
            if (!$wp_image_url) {
                $upload_dir = wp_upload_dir();
                $attachment_meta = wp_get_attachment_metadata($attachment_id);
                $file_path = get_attached_file($attachment_id);
                
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Upload dir: ' . print_r($upload_dir, true));
                    error_log('Blogibot: Attachment meta: ' . print_r($attachment_meta, true));
                    error_log('Blogibot: File path: ' . $file_path);
                }
                
                if ($file_path) {
                    $upload_base = $upload_dir['baseurl'];
                    $relative_path = str_replace($upload_dir['basedir'], '', $file_path);
                    $wp_image_url = $upload_base . str_replace('\\', '/', $relative_path);
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        error_log('Blogibot: Constructed URL: ' . $wp_image_url);
                    }
                }
            }

            $response_data = [
                'success' => true,
                'message' => 'Image generated successfully!',
                'data' => [
                    'attachment_id' => $attachment_id,
                    'wordpress_url' => $wp_image_url,
                    'thumbnail_url' => $wp_image_thumb ? $wp_image_thumb[0] : $wp_image_url,
                    'original_data' => $image_data,
                    'description' => $image_data['description'] ?? $image_description,
                    'filename' => $image_data['filename'] ?? $filename,
                    'size' => $image_data['size'] ?? 0,
                    'mime_type' => $image_data['mime_type'] ?? 'image/png'
                ]
            ];

            self::send_json_response($response_data);

        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Image generation exception: ' . $e->getMessage());
                error_log('Blogibot: Stack trace: ' . $e->getTraceAsString());
            }

            self::send_json_response([
                'success' => false,
                'message' => 'An error occurred during image generation. Please try again.'
            ]);
        }
    }

    /**
     * Save generated image to WordPress Media Library
     */
    private static function save_image_to_media_library($image_url, $filename, $description = '')
    {
        if (!function_exists('media_handle_sideload')) {
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }

        // Validate URL
        if (empty($image_url) || !filter_var($image_url, FILTER_VALIDATE_URL)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Invalid image URL provided: ' . $image_url);
            }
            return false;
        }

        // Log the download attempt
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Downloading image from URL: ' . $image_url);
        }

        // Try WordPress download_url first
        $tmp = download_url($image_url, 60, false);
        
        // If WordPress download fails, try direct cURL download
        if (is_wp_error($tmp)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: WordPress download_url failed: ' . $tmp->get_error_message());
                error_log('Blogibot: Trying direct cURL download...');
            }
            
            // Try direct cURL download
            $tmp = self::download_image_with_curl($image_url);
            
            if (!$tmp) {
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Blogibot: Both WordPress and cURL download methods failed');
                }
                return false;
            }
        }

        // Validate downloaded file
        if (!file_exists($tmp)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Downloaded file does not exist: ' . $tmp);
            }
            return false;
        }

        // Ensure filename has proper extension
        $filename = basename($filename);
        if (!preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $filename)) {
            $filename .= '.jpg'; // Default to .jpg if no extension
        }

        // Temporarily allow additional image types
        add_filter('upload_mimes', function($mimes) {
            $mimes['jpg']  = 'image/jpeg';
            $mimes['jpeg'] = 'image/jpeg';
            $mimes['png']  = 'image/png';
            $mimes['gif']  = 'image/gif';
            $mimes['webp'] = 'image/webp';
            return $mimes;
        });

        // Prepare file array for media_handle_sideload
        $file_array = [
            'name' => $filename,
            'tmp_name' => $tmp,
            'type' => wp_check_filetype($filename)['type'] ?: 'image/jpeg'
        ];

        // Set post data for the attachment
        $post_data = [
            'post_title' => $description ?: 'AI Generated Image',
            'post_content' => $description,
            'post_excerpt' => $description
        ];

        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, 0, null, $post_data);
        
        // Clean up temp file
        @unlink($tmp);

        if (is_wp_error($attachment_id)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Failed to save generated image to media library: ' . $attachment_id->get_error_message());
                error_log('Blogibot: File array was: ' . print_r($file_array, true));
            }
            return false;
        }

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Successfully saved image to media library with ID: ' . $attachment_id);
        }

        return $attachment_id;
    }

    /**
     * Download image using direct cURL when WordPress download_url fails
     */
    private static function download_image_with_curl($url)
    {
        // Create a temporary file
        $tmp_file = wp_tempnam();
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: cURL downloading to temp file: ' . $tmp_file);
        }
        
        // Initialize cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For development
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // For development
        curl_setopt($ch, CURLOPT_USERAGENT, 'Blogibot WordPress Plugin');
        
        // Execute and get the image data
        $image_data = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: cURL error: ' . $error);
            }
            @unlink($tmp_file);
            return false;
        }
        
        if ($http_code !== 200) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: cURL HTTP error: ' . $http_code);
            }
            @unlink($tmp_file);
            return false;
        }
        
        if (empty($image_data)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: cURL returned empty data');
            }
            @unlink($tmp_file);
            return false;
        }
        
        // Write the image data to the temporary file
        $bytes_written = file_put_contents($tmp_file, $image_data);
        
        if ($bytes_written === false || $bytes_written === 0) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Failed to write image data to temp file');
            }
            @unlink($tmp_file);
            return false;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Successfully downloaded ' . $bytes_written . ' bytes via cURL');
        }
        
        return $tmp_file;
    }

    /**
     * Save base64 encoded image to WordPress Media Library
     */
    private static function save_base64_image_to_media_library($base64_data, $filename, $description = '', $mime_type = 'image/png')
    {
        if (!function_exists('media_handle_sideload')) {
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }

        // Validate base64 data
        if (empty($base64_data)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Empty base64 data provided');
            }
            return false;
        }

        // Decode base64 data
        $decoded_image = base64_decode($base64_data);
        if ($decoded_image === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Failed to decode base64 image data');
            }
            return false;
        }

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Decoded base64 image, size: ' . strlen($decoded_image) . ' bytes');
        }

        // Get upload directory
        $upload_dir = wp_upload_dir();
        if ($upload_dir['error']) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Upload directory error: ' . $upload_dir['error']);
            }
            return false;
        }

        // Ensure filename is unique
        $unique_filename = wp_unique_filename($upload_dir['path'], $filename);
        $file_path = $upload_dir['path'] . '/' . $unique_filename;

        // Write the decoded image to the file
        $bytes_written = file_put_contents($file_path, $decoded_image);
        if ($bytes_written === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Failed to write image to file: ' . $file_path);
            }
            return false;
        }

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Image written to: ' . $file_path . ' (' . $bytes_written . ' bytes)');
        }

        // Prepare file array for media_handle_sideload
        $file_array = [
            'name' => $unique_filename,
            'tmp_name' => $file_path,
            'type' => $mime_type,
            'error' => 0,
            'size' => $bytes_written
        ];

        // Temporarily allow additional image types
        add_filter('upload_mimes', function($mimes) {
            $mimes['jpg']  = 'image/jpeg';
            $mimes['jpeg'] = 'image/jpeg';
            $mimes['png']  = 'image/png';
            $mimes['gif']  = 'image/gif';
            $mimes['webp'] = 'image/webp';
            return $mimes;
        });

        // Set post data for the attachment
        $post_data = [
            'post_title' => $description ?: 'AI Generated Image',
            'post_content' => $description,
            'post_excerpt' => $description
        ];

        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, 0, null, $post_data);
        
        // Clean up temp file if media_handle_sideload didn't move it
        if (file_exists($file_path)) {
            @unlink($file_path);
        }

        if (is_wp_error($attachment_id)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Blogibot: Failed to save base64 image to media library: ' . $attachment_id->get_error_message());
            }
            return false;
        }

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Blogibot: Successfully saved base64 image to media library with ID: ' . $attachment_id);
        }

        return $attachment_id;
    }
}
