<?php
// includes/media-handler.php
if (!defined('ABSPATH')) exit;

// Ensure UTF-8 encoding for this file
if (!headers_sent()) {
    header('Content-Type: text/html; charset=utf-8');
}

if (!function_exists('vmo_media_handler_build_image_placeholder')) {
    function vmo_media_handler_build_image_placeholder($desc) {
        $desc = sanitize_text_field($desc ?: 'Premium website image');
        $media_id = 'media_' . wp_generate_password(8, false);

        return '<div class="vmo-media-placeholder vmo-media-placeholder-image" data-type="image" data-media-id="'
            . esc_attr($media_id)
            . '" aria-label="'
            . esc_attr($desc)
            . '" data-vmo-generate="true" data-vmo-prompt="'
            . esc_attr($desc)
            . '"><span>Image<br><small>' . esc_html($desc) . '</small></span></div>';
    }
}

if (!function_exists('vmo_media_handler_replace_with_pending_placeholder')) {
    function vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc) {
        if (preg_match('/^\[GENERATED_IMAGE/i', (string) $tag)) {
            return str_replace($tag, vmo_media_handler_build_image_placeholder($desc), $html);
        }

        return $html;
    }
}

/**
 * Replaces [GENERATED_IMAGE: ...] placeholders in HTML with real GPT Image 1 images.
 * Downloads the image, saves it in the Media Library, records to plugin DB, and returns updated HTML.
 *
 * @param string $html    The HTML content containing placeholders.
 * @param array  $headers HTTP headers for OpenAI API.
 * @param array  $context Optional context: ['session_id' => string, 'page_type' => string, 'user_id' => int, 'project_id' => int]
 */
function vmo_generate_images_and_replace($html, $headers, $context = array()) {
    if (function_exists('set_time_limit')) {
        @set_time_limit(0);
    }
    if (function_exists('ignore_user_abort')) {
        @ignore_user_abort(true);
    }
    if (function_exists('ini_set')) {
        @ini_set('memory_limit', '512M');
    }

    preg_match_all('/\[GENERATED_IMAGE(?::\s*(.+?))?\]/i', $html, $inline_matches, PREG_SET_ORDER);
    preg_match_all('/background-image\s*:\s*url\(\s*\[GENERATED_IMAGE(?::\s*(.+?))?\]\s*\)/i', $html, $bg_matches, PREG_SET_ORDER);
    $matches = array_merge($inline_matches, $bg_matches);

    // Default to queued placeholders; the media queue generates one asset per worker request.
    $max_images_per_page = apply_filters('vmo_max_images_per_page', 0);
    $generation_start = time();
    $max_generation_time = apply_filters('vmo_max_image_generation_time', 120);
    $images_generated = 0;

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

    // Resolve context
    $session_id = isset($context['session_id']) ? sanitize_text_field($context['session_id']) : '';
    $page_type  = isset($context['page_type']) ? sanitize_text_field($context['page_type']) : '';
    $user_id    = isset($context['user_id']) ? intval($context['user_id']) : get_current_user_id();
    $project_id = isset($context['project_id']) ? intval($context['project_id']) : 0;

    foreach ($matches as $match) {
        $tag = $match[0];
        $desc = trim($match[1] ?? 'Creative visual');

        // ✅ BOTTLENECK GUARD: Stop generating if we've hit the cap or time limit
        if ($images_generated >= $max_images_per_page) {
            error_log("VMO Image Cap: Reached {$max_images_per_page} images for page '{$page_type}'. Leaving remaining image placeholders pending for queue completion.");
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }
        if ((time() - $generation_start) > $max_generation_time) {
            error_log("VMO Image Timeout: Exceeded {$max_generation_time}s time limit for page '{$page_type}'. Leaving image placeholders pending for queue completion.");
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }

        // ✅ TOKEN DEDUCTION v8.1.0: Charge for GPT Image 1 generation (960 tokens = ~$0.64)
        // GPT Image 1 costs ~$0.08 per image, so 960 tokens at $0.000667 = $0.64 (8x markup)
        if (function_exists('vmo_deduct_tokens_for_operation')) {
            $deducted = vmo_deduct_tokens_for_operation($user_id, 'dalle_image');
            if (!$deducted) {
                $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
                continue;
            }
        } elseif (function_exists('vmo_deduct_tokens')) {
            // Fallback to direct deduction
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('dalle_image') : 1080;
            $deducted = vmo_deduct_tokens($user_id, $token_cost, 'gpt_image', 'AI image generation: ' . substr($desc, 0, 100));
            if (!$deducted) {
                $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
                continue;
            }
        }

        $prompt = "High-quality ultra-realistic photo: $desc. Shot on Canon EOS R5, editorial lighting, clean background, web branding.";

        $img_response = wp_remote_post('https://api.openai.com/v1/images/generations', [
            'headers' => $headers,
            'body' => json_encode([
                'prompt' => $prompt,
                'model' => 'gpt-image-1',
                'size' => '1024x1024',
                'n' => 1,
                'response_format' => 'url'
            ]),
            'timeout' => 90
        ]);

        if (is_wp_error($img_response)) {
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }

        $img_data = json_decode(wp_remote_retrieve_body($img_response), true);
        $img_url = $img_data['data'][0]['url'] ?? '';

        if (!$img_url) {
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }

        $tmp = download_url($img_url);
        if (is_wp_error($tmp)) {
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }

        $filename = sanitize_file_name(str_replace(' ', '-', strtolower($desc)) . '-' . time() . '.jpg');
        $file_array = ['name' => $filename, 'tmp_name' => $tmp];
        $attach_id = media_handle_sideload($file_array, 0);

        if (is_wp_error($attach_id)) {
            @unlink($tmp);
            $html = vmo_media_handler_replace_with_pending_placeholder($html, $tag, $desc);
            continue;
        }

        $local_url = wp_get_attachment_url($attach_id);

        // Enrich attachment metadata
        if ($user_id) {
            wp_update_post(array('ID' => $attach_id, 'post_author' => $user_id));
        }
        if (!empty($desc)) {
            update_post_meta($attach_id, '_wp_attachment_image_alt', $desc);
        }

        // Persist a record in plugin database (for AI reuse/manipulation)
        try {
            if (!class_exists('VMO_Consultation_Database')) {
                $consultation_db_file = plugin_dir_path(__FILE__) . 'class-vmo-consultation-database.php';
                if (file_exists($consultation_db_file) && is_readable($consultation_db_file)) {
                    try {
                        require_once $consultation_db_file;
                    } catch (Exception $e) {
                        if (defined('WP_DEBUG') && WP_DEBUG) {
                            error_log('VMO: Failed to load consultation database in media-handler: ' . $e->getMessage());
                        }
                    }
                }
            }
            if (class_exists('VMO_Consultation_Database')) {
                $db = new VMO_Consultation_Database();
                $consultation_id = 0;
                if ($session_id && method_exists($db, 'get_consultation_by_session')) {
                    $row = $db->get_consultation_by_session($session_id);
                    if ($row && isset($row->id)) { $consultation_id = intval($row->id); }
                }
                // Build rich context JSON
                $ctx = array(
                    'source' => 'generated_dalle',
                    'prompt' => $desc,
                    'attachment_id' => $attach_id,
                    'page_type' => $page_type,
                    'session_id' => $session_id,
                    'project_id' => $project_id,
                    'user_id' => $user_id,
                    'created_via' => 'media-handler'
                );
                $db->save_consultation_media($consultation_id, array(
                    'url' => $local_url,
                    'type' => 'image',
                    'title' => $desc,
                    'context' => $ctx
                ));
            }
        } catch (\Throwable $e) {
            error_log('VMO media DB record failed: ' . $e->getMessage());
        }

        // Replace placeholder
        if (preg_match('/^\[GENERATED_IMAGE/', $tag)) {
            $html = str_replace($tag, '<img src="' . esc_url($local_url) . '" alt="' . esc_attr($desc) . '" />', $html);
        }

        // Replace CSS background placeholder
        if (preg_match('/background-image/', $tag)) {
            $css_url = "background-image: url('" . esc_url($local_url) . "')";
            $html = str_replace($tag, $css_url, $html);
        }

        $images_generated++; // ✅ BOTTLENECK FIX: Track generated count for per-page cap
    }

    return $html;
}