<?php
/**
 * Plugin Name:       Media Team AI Content Wizard Pro+
 * Description:       AI-powered content generator with reliable live AJAX processing and complete Q&A functionality.
 * Version:           6.7
 * Author:            Media Team
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       media-team-ai-wizard
 */

if (!defined('WPINC')) { die; }

// 1. ADMIN MENU PAGE
add_action('admin_menu', function() {
    add_menu_page('Media Team AI Wizard Pro+', 'Media Team AI Pro+', 'manage_options', 'media_team_ai_wizard', 'mtaw_admin_page_html', 'dashicons-superhero-alt', 20);
});

// 2. RENDER CATEGORY CHECKLIST
function mtaw_render_category_checklist($parent_id = 0, $level = 0) {
    $categories = get_categories(['hide_empty' => false, 'parent' => $parent_id]);
    if ($categories) {
        foreach ($categories as $category) {
            $indent = str_repeat('— ', $level);
            echo '<label class="mtaw-category-label" style="display: block;"><input type="checkbox" name="post_categories[]" value="' . esc_attr($category->term_id) . '"> ' . esc_html($indent . $category->name) . '</label>';
            mtaw_render_category_checklist($category->term_id, $level + 1);
        }
    }
}

// 3. ADMIN PAGE HTML
function mtaw_admin_page_html() {
    if (!current_user_can('manage_options')) return;
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <p>This version uses live on-screen processing and includes expanded content options.</p>

        <form id="mtaw-generator-form">
            <?php wp_nonce_field('mtaw_ajax_nonce', 'mtaw_nonce'); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="ai_provider">AI Provider</label></th>
                    <td>
                        <select id="ai_provider" name="ai_provider">
                            <option value="openai">OpenAI</option>
                            <option value="gemini">Google Gemini</option>
                        </select>
                    </td>
                </tr>
                <!-- MTAW-MODIFICATION: Added a separate row for Gemini models -->
                <tr valign="top" id="openai_model_row">
                    <th scope="row"><label for="openai_model">OpenAI Model</label></th>
                    <td>
                        <select id="openai_model" name="openai_model">
                            <option value="gpt-4-turbo-preview">GPT-4 Turbo</option>
                            <option value="gpt-3.5-turbo-1106">GPT-3.5 Turbo</option>
                        </select>
                    </td>
                </tr>
                <tr valign="top" id="gemini_model_row" style="display: none;">
                    <th scope="row"><label for="gemini_model">Gemini Model</label></th>
                    <td>
                        <select id="gemini_model" name="gemini_model">
                            <option value="gemini-1.5-flash-latest">Gemini 1.5 Flash</option>
                            <option value="gemini-1.0-pro-latest">Gemini 1.0 Pro</option>
                        </select>
                         <p class="description">Gemini 1.5 Flash is recommended for speed and cost-effectiveness.</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><label for="post_topics">Post Topics</label></th>
                    <td><textarea id="post_topics" name="post_topics" rows="10" style="width: 100%; max-width: 450px;" placeholder="Enter one topic per line..."></textarea></td>
                </tr>
                <tr valign="top">
                    <th scope="row">Content Options</th>
                    <td>
                        <fieldset>
                             <label style="display: block; margin-bottom: 8px;"><input type="number" name="include_images" min="0" max="5" value="2"> Number of images (0-5)</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="include_qa" value="1" checked> Include Q&A section</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="include_video" value="1" id="include_video_checkbox"> Include YouTube video</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="generate_tags" value="1" checked> Generate 5 related tags</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="generate_excerpt" value="1" checked> Generate post excerpt</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="include_internal_links" value="1" checked> Include 3-5 internal link placeholders</label>
                            <label style="display: block; margin-bottom: 8px;"><input type="checkbox" name="include_external_links" value="1" checked> Include 3 external link placeholders</label>
                            <label style="display: block; margin-top: 10px;">
                                Article Length:
                                <select name="article_length">
                                    <option value="short">Short (~500 words)</option>
                                    <option value="medium" selected>Medium (~1000 words)</option>
                                    <option value="long">Long (~2000 words)</option>
                                    <option value="very_long">Very Long (~5000 words)</option>
                                </select>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><label for="post_status">Post Status</label></th>
                    <td>
                        <select id="post_status" name="post_status">
                            <option value="draft">Draft</option>
                            <option value="publish">Publish</option>
                            <option value="future">Schedule</option>
                        </select>
                    </td>
                </tr>
                <tr valign="top" id="schedule_fields" style="display: none;">
                    <th scope="row"><label for="schedule_date">Schedule Date & Time</label></th>
                    <td>
                        <input type="date" id="schedule_date" name="schedule_date" value="<?php echo date('Y-m-d'); ?>">
                        <input type="time" id="schedule_time" name="schedule_time" value="<?php echo date('H:i'); ?>">
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><label for="mtaw_category_search">Assign Categories</label></th>
                    <td>
                        <input type="search" id="mtaw_category_search" placeholder="Search categories..." style="width: 100%; max-width: 450px; margin-bottom: 5px;">
                        <div id="mtaw_category_checklist" style="height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; max-width: 450px;">
                            <?php mtaw_render_category_checklist(); ?>
                        </div>
                    </td>
                </tr>
            </table>
            <?php submit_button('Generate Posts'); ?>
        </form>

        <div id="mtaw-progress-container" style="display: none; margin-top: 20px;">
            <h2>Generation Progress</h2>
            <div id="mtaw-progress-bar-container" style="height: 28px; background: #eee; border: 1px solid #ccc; border-radius: 4px; overflow: hidden;">
                <div id="mtaw-progress-bar" style="height: 100%; width: 0%; background: #0073aa; color: white; text-align: center; line-height: 28px; transition: width 0.5s;">0%</div>
            </div>
            <div id="mtaw-progress-log" style="background: #fafafa; border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; margin-top: 10px; font-family: monospace; white-space: pre-wrap;"></div>
        </div>
        
        <hr>
        <h2>API Settings</h2>
        <form method="post" action="options.php">
            <?php settings_fields('mtaw_settings_group'); do_settings_sections('media_team_ai_wizard'); submit_button('Save API Keys'); ?>
        </form>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        // MTAW-MODIFICATION: Show/hide model selectors based on AI provider
        $('#ai_provider').on('change', function() {
            if ($(this).val() === 'openai') {
                $('#openai_model_row').show();
                $('#gemini_model_row').hide();
            } else {
                $('#openai_model_row').hide();
                $('#gemini_model_row').show();
            }
        }).trigger('change');

        // Toggle schedule fields based on post status
        $('#post_status').on('change', function() {
            $('#schedule_fields').toggle($(this).val() === 'future');
        }).trigger('change');

        // Handle the main form submission for generating posts
        $('#mtaw-generator-form').on('submit', function(e) {
            e.preventDefault();
            
            const topics = $('#post_topics').val().split('\n').filter(topic => topic.trim() !== '');
            if (!topics.length) {
                alert('Please enter at least one topic.');
                return;
            }

            const progressContainer = $('#mtaw-progress-container');
            const progressBar = $('#mtaw-progress-bar');
            const progressLog = $('#mtaw-progress-log');
            
            progressContainer.show();
            progressLog.html('');
            progressBar.css('width', '0%').text('0%').css('background', '#0073aa');

            let hasError = false;
            let completed = 0;
            const total = topics.length;

            function processNextTopic() {
                if (topics.length === 0) {
                    if (hasError) {
                        progressLog.append('⚠️ Processing complete. One or more posts encountered errors.\n');
                    } else {
                        progressLog.append('✅ All posts generated successfully!\n');
                        progressBar.css('background', '#4caf50');
                    }
                    return;
                }

                const topic = topics.shift().trim();
                const formData = $('#mtaw-generator-form').serialize();
                const postData = formData + '&action=mtaw_generate_single_post&topic=' + encodeURIComponent(topic);
                
                progressLog.append(`▶️ Starting generation for: "${topic}"...\n`);

                $.post(ajaxurl, postData, function(response) {
                    completed++;
                    const percent = Math.round((completed / total) * 100);
                    progressBar.css('width', percent + '%').text(percent + '%');
                    
                    if (response.success) {
                        progressLog.append(`   ✅ SUCCESS: Post created! <a href="${response.data.edit_link}" target="_blank">Edit Post</a>\n\n`);
                    } else {
                        hasError = true;
                        progressLog.append(`   ❌ ERROR: ${response.data.message}\n\n`);
                        progressBar.css('background', '#f44336');
                    }
                    
                    processNextTopic();

                }).fail(function() {
                    completed++;
                    hasError = true;
                    const percent = Math.round((completed / total) * 100);
                    progressBar.css('width', percent + '%').text(percent + '%');
                    progressLog.append(`   ❌ FATAL ERROR: The server returned an unexpected error for "${topic}".\n\n`);
                    progressBar.css('background', '#f44336');

                    processNextTopic(); 
                });
            }
            
            processNextTopic();
        });

        // Live search filter for categories
        $('#mtaw_category_search').on('keyup', function() {
            const searchTerm = $(this).val().toLowerCase();
            $('#mtaw_category_checklist .mtaw-category-label').each(function() {
                const categoryName = $(this).text().toLowerCase();
                $(this).toggle(categoryName.includes(searchTerm));
            });
        });
    });
    </script>
    <?php
}

// 4. API SETTINGS REGISTRATION
add_action('admin_init', function() {
    register_setting('mtaw_settings_group', 'mtaw_settings');
    add_settings_section('mtaw_settings_section', 'API Keys', null, 'media_team_ai_wizard');
    add_settings_field('mtaw_openai_api_key', 'OpenAI API Key', function() { $options = get_option('mtaw_settings'); echo "<input type='text' name='mtaw_settings[mtaw_openai_api_key]' value='" . esc_attr($options['mtaw_openai_api_key'] ?? '') . "' style='width: 450px;'><p class='description'>For generating text content.</p>"; }, 'media_team_ai_wizard', 'mtaw_settings_section');
    add_settings_field('mtaw_gemini_api_key', 'Google Gemini API Key', function() { $options = get_option('mtaw_settings'); echo "<input type='text' name='mtaw_settings[mtaw_gemini_api_key]' value='" . esc_attr($options['mtaw_gemini_api_key'] ?? '') . "' style='width: 450px;'><p class='description'>Alternative for generating text content.</p>"; }, 'media_team_ai_wizard', 'mtaw_settings_section');
    add_settings_field('mtaw_pexels_api_key', 'Pexels API Key (for Images)', function() { $options = get_option('mtaw_settings'); echo "<input type='text' name='mtaw_settings[mtaw_pexels_api_key]' value='" . esc_attr($options['mtaw_pexels_api_key'] ?? '') . "' style='width: 450px;'><p class='description'>Required if you want to include images in posts.</p>"; }, 'media_team_ai_wizard', 'mtaw_settings_section');
    add_settings_field('mtaw_youtube_api_key', 'YouTube Data API v3 Key (for Video)', function() { $options = get_option('mtaw_settings'); echo "<input type='text' name='mtaw_settings[mtaw_youtube_api_key]' value='" . esc_attr($options['mtaw_youtube_api_key'] ?? '') . "' style='width: 450px;'><p class='description'>Required if you want to include videos in posts.</p>"; }, 'media_team_ai_wizard', 'mtaw_settings_section');
});

// 5. AJAX ACTION HOOK
add_action('wp_ajax_mtaw_generate_single_post', 'mtaw_handle_ajax_generation');
function mtaw_handle_ajax_generation() {
    check_ajax_referer('mtaw_ajax_nonce', 'mtaw_nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error(['message' => 'Permission denied.']); }
    
    $topic = sanitize_text_field(urldecode($_POST['topic']));
    $post_status = sanitize_text_field($_POST['post_status']);
    $schedule_date = sanitize_text_field($_POST['schedule_date']);
    $schedule_time = sanitize_text_field($_POST['schedule_time']);
    $selected_categories = isset($_POST['post_categories']) ? array_map('intval', $_POST['post_categories']) : [];
    $ai_provider = sanitize_text_field($_POST['ai_provider']);
    
    // MTAW-MODIFICATION: Get the correct model based on the provider
    $openai_model = sanitize_text_field($_POST['openai_model']);
    $gemini_model = sanitize_text_field($_POST['gemini_model']);
    
    $content_options = [
        'include_images' => isset($_POST['include_images']) ? intval($_POST['include_images']) : 0,
        'include_qa' => isset($_POST['include_qa']),
        'include_video' => isset($_POST['include_video']),
        'generate_tags' => isset($_POST['generate_tags']),
        'generate_excerpt' => isset($_POST['generate_excerpt']),
        'include_internal_links' => isset($_POST['include_internal_links']),
        'include_external_links' => isset($_POST['include_external_links']),
        'article_length' => isset($_POST['article_length']) ? sanitize_text_field($_POST['article_length']) : 'medium',
    ];

    // MTAW-MODIFICATION: Pass the gemini model to the generation function
    $result = mtaw_generate_post($topic, $post_status, $schedule_date, $schedule_time, $selected_categories, $content_options, $ai_provider, $openai_model, $gemini_model, get_current_user_id());

    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    } else {
        wp_send_json_success(['post_id' => $result, 'edit_link' => get_edit_post_link($result, 'raw')]);
    }
    wp_die();
}

// 6. HELPER FUNCTIONS
function mtaw_get_youtube_video_embed_code($topic, $api_key) {
    if (empty($api_key)) return '';
    $search_query = urlencode($topic . ' video');
    $api_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q={$search_query}&type=video&key={$api_key}&maxResults=1&videoEmbeddable=true";
    $response = wp_remote_get($api_url, ['timeout' => 20]);
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) return '';
    $body = json_decode(wp_remote_retrieve_body($response), true);
    $video_id = $body['items'][0]['id']['videoId'] ?? null;
    if ($video_id) {
        return '<div class="mtaw-video-embed" style="margin: 20px 0;"><div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"><iframe src="https://www.youtube.com/embed/' . esc_attr($video_id) . '" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" frameborder="0" allowfullscreen></iframe></div></div>';
    }
    return '';
}
function mtaw_remove_duplicate_title($content, $topic) {
    if (preg_match('/^\s*<h[12]>(.*?)<\/h[12]>/i', $content, $matches)) {
        if (sanitize_title(strip_tags($matches[1])) === sanitize_title($topic)) {
            return preg_replace('/^\s*<h[12]>(.*?)<\/h[12]>\s*/i', '', $content, 1);
        }
    }
    return $content;
}

// 7. CORE GENERATION FUNCTION
// MTAW-MODIFICATION: Added $gemini_model parameter and the entire Gemini API logic branch.
function mtaw_generate_post($topic, $post_status, $schedule_date, $schedule_time, $selected_categories, $content_options, $ai_provider, $openai_model, $gemini_model, $user_id) {
    $options = get_option('mtaw_settings');
    $pexels_key  = $options['mtaw_pexels_api_key'] ?? '';
    $youtube_key = $options['mtaw_youtube_api_key'] ?? '';
    $ai_key = ($ai_provider === 'gemini') ? ($options['mtaw_gemini_api_key'] ?? '') : ($options['mtaw_openai_api_key'] ?? '');

    if (empty($ai_key)) return new WP_Error('api_key_missing', 'AI API key is missing. Please save it in the settings.');
    if ($content_options['include_images'] > 0 && empty($pexels_key)) return new WP_Error('pexels_key_missing', 'Pexels API key is required for images.');
    if ($content_options['include_video'] && empty($youtube_key)) return new WP_Error('youtube_key_missing', 'YouTube API key is required for video.');

    // --- Build Universal Prompt ---
    $length_map = ['short' => '3-4', 'medium' => '4-6', 'long' => '6-8', 'very_long' => '15-20'];
    $article_structure = 'an introduction, '.($length_map[$content_options['article_length']] ?? '4-6').' main sections each under an <h2> heading, and a conclusion';
    $json_keys = ['"post_content"'];
    // MTAW-MODIFICATION: Removed "categories" from required keys as Gemini can be less reliable with it. We handle it gracefully.
    
    $prompt = "Generate a blog post package for the topic: \"{$topic}\". Return only a single, valid JSON object and nothing else. The JSON should be clean and ready for parsing.\n";
    $prompt .= "For the \"post_content\" key: Write a well-structured and engaging blog post. DO NOT include a main H1 title in the content. The post structure must be: {$article_structure}.\n";
    
    if ($content_options['include_images'] > 0) $prompt .= "Inside the post_content HTML, insert placeholders like `[IMAGE_1_HERE]`, `[IMAGE_2_HERE]`, etc., where images would be contextually appropriate.\n";
    if ($content_options['include_video']) $prompt .= "Inside the post_content HTML, insert a single `[YOUTUBE_VIDEO_HERE]` placeholder where a video would be most relevant.\n";
    if ($content_options['include_qa']) $prompt .= "In the post_content HTML, after the conclusion, add an <h3> titled 'Frequently Asked Questions'. Follow it with 3-5 question-and-answer pairs. Each pair must be inside its own `<p>` tag, with the question wrapped in a `<strong>` tag. Example: `<p><strong>Is this a question?</strong> This is the answer.</p>`\n";
    if ($content_options['include_internal_links']) $prompt .= "In the post_content HTML, naturally weave in 3-5 internal link placeholders formatted like `<a href=\"#internal-link\">relevant anchor text</a>`.\n";
    if ($content_options['include_external_links']) $prompt .= "In the post_content HTML, naturally weave in 3 external link placeholders formatted like `<a href=\"#external-link\" rel=\"nofollow\">relevant anchor text</a>`.\n";
    if ($content_options['generate_excerpt']) { $json_keys[] = '"excerpt"'; $prompt .= "For the \"excerpt\" key: Create a concise and compelling meta description or summary (around 150 characters).\n"; }
    if ($content_options['generate_tags']) { $json_keys[] = '"tags"'; $prompt .= "For the \"tags\" key: Provide a JSON array of 5 relevant string keywords.\n"; }
    
    $prompt .= "The final JSON object MUST have these keys: " . implode(', ', $json_keys) . ".";

    $ai_response_body = '';

    // --- API Call Logic ---
    if ($ai_provider === 'gemini') {
        // --- GEMINI API LOGIC ---
        $api_url = "https://generativelanguage.googleapis.com/v1beta/models/{$gemini_model}:generateContent?key={$ai_key}";
        $request_body = json_encode([
            'contents' => [['parts' => [['text' => $prompt]]]],
            'generationConfig' => [
                'response_mime_type' => 'application/json',
            ]
        ]);
        
        $api_response = wp_remote_post($api_url, [
            'body'    => $request_body,
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 300,
        ]);

        if (is_wp_error($api_response)) return new WP_Error('gemini_error', 'Gemini API Error: ' . $api_response->get_error_message());
        
        $body = json_decode(wp_remote_retrieve_body($api_response), true);

        if (isset($body['error'])) return new WP_Error('gemini_error', 'Gemini API Error: ' . $body['error']['message']);
        
        // Extract the raw text, which should be our JSON string
        $ai_response_body = $body['candidates'][0]['content']['parts'][0]['text'] ?? '';

    } else {
        // --- OPENAI API LOGIC (Original) ---
        $api_url = 'https://api.openai.com/v1/chat/completions';
        $request_body = json_encode([
            'model' => $openai_model, 
            'messages' => [['role' => 'user', 'content' => $prompt]], 
            'response_format' => ['type' => 'json_object']
        ]);

        $api_response = wp_remote_post($api_url, [
            'body' => $request_body,
            'headers' => ['Authorization' => 'Bearer ' . $ai_key, 'Content-Type' => 'application/json'], 
            'timeout' => 300,
        ]);

        if (is_wp_error($api_response)) return new WP_Error('openai_error', 'OpenAI API Error: ' . $api_response->get_error_message());
        
        $body = json_decode(wp_remote_retrieve_body($api_response), true);
        
        if (isset($body['error'])) return new WP_Error('openai_error', 'OpenAI API Error: ' . $body['error']['message']);
        
        $ai_response_body = $body['choices'][0]['message']['content'] ?? '';
    }

    // --- Process Response (Universal) ---
    if (empty($ai_response_body)) return new WP_Error('ai_no_content', 'The AI provider returned an empty response. Check API key and model compatibility.');
    
    // Sometimes the AI wraps the JSON in ```json ... ```, so we strip that.
    $ai_response_body = preg_replace('/^```json\s*|\s*```$/', '', trim($ai_response_body));
    
    $ai_data = json_decode($ai_response_body, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return new WP_Error('json_decode_error', 'Failed to decode AI JSON response. Error: ' . json_last_error_msg());
    }

    $post_content = $ai_data['post_content'] ?? '';
    if (empty($post_content)) return new WP_Error('ai_no_content', 'The AI response did not contain the expected "post_content" field.');
    
    $post_content = mtaw_remove_duplicate_title($post_content, $topic);

    $new_post = [
        'post_title'   => ucwords($topic), 
        'post_content' => $post_content, 
        'post_author'  => $user_id,
        'post_status'  => $post_status, 
        'post_excerpt' => sanitize_text_field($ai_data['excerpt'] ?? ''),
    ];
    if ($post_status === 'future') {
        $new_post['post_date'] = $schedule_date . ' ' . $schedule_time . ':00';
        $new_post['post_date_gmt'] = get_gmt_from_date($new_post['post_date']);
    }

    if (!empty($selected_categories)) {
        $new_post['post_category'] = $selected_categories;
    }

    $post_id = wp_insert_post($new_post, true);
    if (is_wp_error($post_id)) return $post_id;

    // --- Sideload Images and Embed Video ---
    $final_content = get_post($post_id)->post_content;
    $image_attachments = [];

    if ($content_options['include_images'] > 0 && !empty($pexels_key)) {
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $num_images_to_fetch = $content_options['include_images'];
        $pexels_api_url = "https://api.pexels.com/v1/search?query=" . urlencode($topic) . "&per_page=" . $num_images_to_fetch . "&orientation=landscape";
        $pexels_response = wp_remote_get($pexels_api_url, ['headers' => ['Authorization' => $pexels_key]]);
        $pexels_photos = [];
        if (!is_wp_error($pexels_response) && ($pexels_body = json_decode(wp_remote_retrieve_body($pexels_response), true))) {
            $pexels_photos = $pexels_body['photos'] ?? [];
        }
        for ($i = 1; $i <= $num_images_to_fetch; $i++) {
            $placeholder = "[IMAGE_{$i}_HERE]";
            if (strpos($final_content, $placeholder) !== false) {
                if (isset($pexels_photos[$i - 1])) {
                    $image_url = $pexels_photos[$i - 1]['src']['large2x'];
                    $attachment_id = media_sideload_image($image_url, $post_id, $topic, 'id');
                    if (!is_wp_error($attachment_id)) {
                        $image_html = wp_get_attachment_image($attachment_id, 'large', false, ['class' => 'aligncenter size-large']);
                        $final_content = str_replace($placeholder, $image_html, $final_content);
                        $image_attachments[] = $attachment_id;
                    }
                } else {
                    $final_content = str_replace($placeholder, "", $final_content);
                }
            }
        }
    }
    
    if ($content_options['include_video'] && !empty($youtube_key) && strpos($final_content, '[YOUTUBE_VIDEO_HERE]') !== false) {
        $video_embed_code = mtaw_get_youtube_video_embed_code($topic, $youtube_key);
        $final_content = str_replace('[YOUTUBE_VIDEO_HERE]', $video_embed_code, $final_content);
    }

    wp_update_post(['ID' => $post_id, 'post_content' => wp_kses_post($final_content)]);
    
    if (!empty($ai_data['tags'])) wp_set_post_tags($post_id, $ai_data['tags']);
    if (!empty($image_attachments)) set_post_thumbnail($post_id, $image_attachments[0]);
    
    return $post_id;
}