<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// Include the options file
include 'easy-gpt-options.php';

function easy_gpt_is_woocommerce_active() {
    return class_exists('WooCommerce');
}

// Add metaboxes
add_action('add_meta_boxes', 'easy_gpt_add_metaboxes');

function easy_gpt_add_metaboxes() {
    
    $post_types = ['post', 'page'];

    if (class_exists('WooCommerce')) {
        $post_types[] = 'product';
    }
     
    add_meta_box(
        'easy_gpt_metabox',            // ID de la metabox
        'Easy GPT Content Generator',  // Título de la metabox
        'easy_gpt_metabox_callback',   // Función de callback
        $post_types,                    // Pantallas donde se añadirá (entradas y páginas)
        'normal',                      // Contexto (ubicación)
        'high'                         // Prioridad
    );
}

// Include jQuery UI styles and scripts
add_action('admin_enqueue_scripts', 'easy_gpt_enqueue_scripts');
function easy_gpt_enqueue_scripts($hook) {
    if (in_array($hook, ['post.php', 'post-new.php'])) {
        wp_enqueue_script('jquery-ui-tabs');
        wp_enqueue_style('wp-jquery-ui-dialog');
        wp_enqueue_style('easy_gpt_admin_css', plugins_url('../styles/metabox-style.css', __FILE__));

        // Enqueue the TinyMCE library
        wp_enqueue_script('tiny_mce', includes_url('js/tinymce/tinymce.min.js'), [], false, true);

        // Enqueue the custom script that initializes TinyMCE
        wp_enqueue_script('easy_gpt_custom_js', plugins_url('../js/easy-gpt-custom.js', __FILE__), ['jquery', 'tiny_mce'], false, true);

        global $post;
        $post_id = $post ? $post->ID : null;

        if ($post_id) {
            // Obtener valores guardados de tokens y costos
            $prompt_tokens = get_post_meta($post_id, '_easy_gpt_prompt_tokens', true);
            $completion_tokens = get_post_meta($post_id, '_easy_gpt_completion_tokens', true);
            $total_tokens = get_post_meta($post_id, '_easy_gpt_total_tokens', true);
            $total_cost = get_post_meta($post_id, '_easy_gpt_total_cost', true);

            wp_localize_script('easy_gpt_custom_js', 'easyGPTData', array(
                'options' => get_option('easy_gpt_options'),
                'ajaxurl' => admin_url('admin-ajax.php'),
                'apiKey' => get_option('easy_gpt_options')['easy_gpt_api_key'],
                'promptTokens' => $prompt_tokens,
                'completionTokens' => $completion_tokens,
                'totalTokens' => $total_tokens,
                'totalCost' => $total_cost,
                'postId' => $post_id
            ));
        } else {
            wp_localize_script('easy_gpt_custom_js', 'easyGPTData', array(
                'options' => get_option('easy_gpt_options'),
                'ajaxurl' => admin_url('admin-ajax.php'),
                'apiKey' => get_option('easy_gpt_options')['easy_gpt_api_key'],
            ));
        }
    }
}

function easy_gpt_save_image_to_media_library() {
    // Verificar el nonce para seguridad
    if ( ! check_ajax_referer('easy_gpt_save_metabox_data', 'nonce', false) ) {
        //error_log('Invalid nonce.');
        wp_send_json_error(array('message' => 'Invalid nonce.'));
        wp_die();
    }

    // Obtener datos del POST
    $image_url = isset($_POST['image_url']) ? esc_url_raw(wp_unslash($_POST['image_url'])) : '';
    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : 'untitled';
    $alt = isset($_POST['alt']) ? sanitize_text_field(wp_unslash($_POST['alt'])) : '';

    // Log de datos recibidos
    //error_log("Received image URL: $image_url");
    //error_log("Received title: $title");
    //error_log("Received alt: $alt");

    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

    if (empty($image_url)) {
        //error_log('Image URL is empty.');
        wp_send_json_error(array('message' => 'Invalid image URL.'));
    }

    if (!isset($post_id)) {
        //error_log('Post ID is not set.');
        wp_send_json_error(array('message' => 'Invalid post ID.'));
    }

    // Descargar la imagen
    $response = wp_remote_get($image_url);
    if (is_wp_error($response)) {
        //error_log('Failed to download image: ' . $response->get_error_message());
        wp_send_json_error(array('message' => 'Failed to download image.'));
    }

    $image_data = wp_remote_retrieve_body($response);
    $content_type = wp_remote_retrieve_header($response, 'content-type');
    //error_log("Content type: $content_type");

    $file_extension = '';
    switch ($content_type) {
        case 'image/jpeg':
            $file_extension = 'jpg';
            break;
        case 'image/png':
            $file_extension = 'png';
            break;
        case 'image/gif':
            $file_extension = 'gif';
            break;
        default:
            //error_log('Invalid content type.');
            wp_send_json_error(array('message' => 'Invalid content type.'));
    }

    // Crear nombre del archivo basado en el título
    $upload_dir = wp_upload_dir();
    $sanitized_title = sanitize_file_name($title);
    //error_log("Sanitized title for filename: $sanitized_title");

    $filename = wp_unique_filename($upload_dir['path'], $sanitized_title . '.' . $file_extension);
    //error_log("Generated filename: $filename");

    $upload_file = wp_upload_bits($filename, null, $image_data);
    if ($upload_file['error']) {
        //error_log('Failed to upload image: ' . $upload_file['error']);
        wp_send_json_error(array('message' => 'Failed to upload image.'));
    }

    $wp_filetype = wp_check_filetype($filename, null);
    //error_log('File type: ' . print_r($wp_filetype, true));

    // Crear adjunto con título
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => $title,
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    $attachment_id = wp_insert_attachment($attachment, $upload_file['file'], $post_id);
    if (is_wp_error($attachment_id)) {
        //error_log('Failed to insert attachment: ' . $attachment_id->get_error_message());
        wp_send_json_error(array('message' => 'Failed to insert attachment.'));
    }

    // Metadatos y alt text
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_file['file']);
    wp_update_attachment_metadata($attachment_id, $attachment_data);

    if (!empty($alt)) {
        update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt);
        //error_log("Alt text updated for attachment ID $attachment_id: $alt");
    }

    $attachment_url = wp_get_attachment_url($attachment_id);
    //error_log("Image saved successfully with URL: $attachment_url");

    wp_send_json_success(array(
        'attachment_id' => $attachment_id,
        'url'           => $attachment_url
    ));

    wp_die();
}
add_action('wp_ajax_easy_gpt_save_image_to_media_library', 'easy_gpt_save_image_to_media_library');



function easy_gpt_metabox_callback($post) {
    
    $license_status = get_option('easy_gpt_license_status');
    $license_expires = get_option('easy_gpt_license_expires');
    $is_license_valid = $license_status === 'valid' && new DateTime($license_expires) > new DateTime();

    if (!$is_license_valid) {
        echo '<div style="margin-top: 20px; background-color: #f8d7da; color: #721c24; padding: 12px; border-left: 4px solid #f5c6cb;">';
        echo '<p><strong>Attention:</strong> Your license is either invalid or has expired. If this is your first time using EasyGPT for WP, you can <a href="https://easygptforwp.com/pricing-plans/" target="_blank">purchase a license here</a> or obtain a <a href="https://easygptforwp.com/pricing-plans/" target="_blank">free 5-day trial license</a> to start using the plugin features.</p>';
        echo '</div>';
        return; // Detiene la ejecución de más código si la licencia no es válida
    }

    global $easy_gpt_options; // Access global options array

    // Obtener los valores predeterminados de la configuración
    $options = get_option('easy_gpt_options');

    // Usar los valores predeterminados
$cost = get_post_meta($post->ID, '_easy_gpt_cost', true) ?: '0$';
$model = get_post_meta($post->ID, '_easy_gpt_model', true) ?: ($options['easy_gpt_model'] ?? 'gpt-4o');
$temperature = get_post_meta($post->ID, '_easy_gpt_temperature', true) ?: ($options['easy_gpt_temperature'] ?? '0.7');
$min_words = get_post_meta($post->ID, '_easy_gpt_min_words', true) ?: ($options['easy_gpt_min_words'] ?? '300');
$max_words = get_post_meta($post->ID, '_easy_gpt_max_words', true) ?: ($options['easy_gpt_max_words'] ?? '1000');
$num_subheadings = get_post_meta($post->ID, '_easy_gpt_num_subheadings', true) ?: ($options['easy_gpt_num_subheadings'] ?? '3');

$subheading_type_h3 = get_post_meta($post->ID, '_easy_gpt_subheading_type_h3', true);
if ($subheading_type_h3 === '') {
    $subheading_type_h3 = isset($options['easy_gpt_subheading_type_h3']) ? $options['easy_gpt_subheading_type_h3'] : '0';
}

$subheading_type_h4 = get_post_meta($post->ID, '_easy_gpt_subheading_type_h4', true);
if ($subheading_type_h4 === '') {
    $subheading_type_h4 = isset($options['easy_gpt_subheading_type_h4']) ? $options['easy_gpt_subheading_type_h4'] : '0';
}

$format_article = get_post_meta($post->ID, '_easy_gpt_format_article', true);
if ($format_article === '') {
    $format_article = isset($options['easy_gpt_format_article']) ? $options['easy_gpt_format_article'] : '0';
}

$auto_categories = get_post_meta($post->ID, '_easy_gpt_auto_categories', true);
if ($auto_categories === '') {
    $auto_categories = isset($options['easy_gpt_auto_categories']) ? $options['easy_gpt_auto_categories'] : '0';
}

$auto_tags = get_post_meta($post->ID, '_easy_gpt_auto_tags', true);
if ($auto_tags === '') {
    $auto_tags = isset($options['easy_gpt_auto_tags']) ? $options['easy_gpt_auto_tags'] : '0';
}

$auto_seo = get_post_meta($post->ID, '_easy_gpt_auto_seo', true);
if ($auto_seo === '') {
    $auto_seo = isset($options['easy_gpt_auto_seo']) ? $options['easy_gpt_auto_seo'] : '0';
}

$image_model = get_post_meta($post->ID, '_easy_gpt_image_model', true) ?: ($options['easy_gpt_image_model'] ?? 'dall-e-3');

$auto_images = get_post_meta($post->ID, '_easy_gpt_auto_images', true);
if ($auto_images === '') {
    $auto_images = isset($options['easy_gpt_auto_images']) ? $options['easy_gpt_auto_images'] : '0';
}

$num_images = get_post_meta($post->ID, '_easy_gpt_num_images', true) ?: ($options['easy_gpt_num_images'] ?? '1');
$image_size = get_post_meta($post->ID, '_easy_gpt_image_size', true) ?: ($options['easy_gpt_image_size'] ?? '1024x1024');
$image_quality = get_post_meta($post->ID, '_easy_gpt_image_quality', true) ?: ($options['easy_gpt_image_quality'] ?? 'standard');
$writing_style = get_post_meta($post->ID, '_easy_gpt_writing_style', true) ?: ($options['easy_gpt_writing_style'] ?? 'Formal');
$writing_tone = get_post_meta($post->ID, '_easy_gpt_writing_tone', true) ?: ($options['easy_gpt_writing_tone'] ?? 'Neutral');
$image_style = get_post_meta($post->ID, '_easy_gpt_image_style', true) ?: ($options['easy_gpt_image_style'] ?? '');

$include_excerpt = get_post_meta($post->ID, '_easy_gpt_include_excerpt', true);
if ($include_excerpt === '') {
    $include_excerpt = isset($options['easy_gpt_include_excerpt']) ? $options['easy_gpt_include_excerpt'] : '0';
}

$default_language = get_post_meta($post->ID, '_easy_gpt_default_language', true) ?: ($options['easy_gpt_default_language'] ?? 'en');

$set_featured_image = get_post_meta($post->ID, '_easy_gpt_set_featured_image', true);
if ($set_featured_image === '') {
    $set_featured_image = isset($options['easy_gpt_set_featured_image']) ? $options['easy_gpt_set_featured_image'] : '0';
}

$include_links = get_post_meta($post->ID, '_easy_gpt_include_links', true);
if ($include_links === '') {
    $include_links = isset($options['easy_gpt_include_links']) ? $options['easy_gpt_include_links'] : '0';
}
	
$include_citations = get_post_meta($post->ID, '_easy_gpt_include_citations', true);
if ($include_citations === '') {
    $include_citations = isset($options['easy_gpt_include_citations']) ? $options['easy_gpt_include_citations'] : '0';
}

$final_review = get_post_meta($post->ID, '_easy_gpt_final_review', true);
if ($final_review === '') {
    $final_review = isset($options['easy_gpt_final_review']) ? $options['easy_gpt_final_review'] : '0';
}

$include_bibliography = get_post_meta($post->ID, '_easy_gpt_include_bibliography', true);
if ($include_bibliography === '') {
    $include_bibliography = isset($options['easy_gpt_include_bibliography']) ? $options['easy_gpt_include_bibliography'] : '0';
}

$include_videos = get_post_meta($post->ID, '_easy_gpt_include_videos_per_post', true);
if ($include_videos === '') {
    $include_videos = isset($options['easy_gpt_include_videos']) ? $options['easy_gpt_include_videos'] : '0';
}

$video_position = get_post_meta($post->ID, '_easy_gpt_video_position_per_post', true);
if ($video_position === '') {
    $video_position = isset($options['easy_gpt_video_position']) ? $options['easy_gpt_video_position'] : 'end';
}

$video_paragraph = get_post_meta($post->ID, '_easy_gpt_video_paragraph_per_post', true);
if ($video_paragraph === '') {
    $video_paragraph = isset($options['easy_gpt_video_paragraph']) ? $options['easy_gpt_video_paragraph'] : 3;
}


    // Nonce field for security
    wp_nonce_field('easy_gpt_save_metabox_data', 'easy_gpt_nonce');

    // Contenido de la metabox
    ?>
    <div class="error-message" id="error-message"></div>
    <div id="easy-gpt-tabs">
        <ul>
            <li><a href="#tab-1">Generate Article</a></li>
            <li><a href="#tab-2">Article Settings</a></li>
            <li><a href="#tab-3">Image Settings</a></li>
        </ul>
        <div id="tab-1">
            <table class="form-table easy-gpt-table">
                <tr>
                    <td class="easy-gpt-column" style="max-width: 300px;">
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_prompt">Prompt: <span style="color: red;">*</span></label>
                            <textarea id="easy_gpt_prompt" name="easy_gpt_prompt" rows="4" cols="50"></textarea>
                        </div>
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_keywords">Keywords: <span style="color: red;">*</span></label>
                            <input type="text" id="easy_gpt_keywords" name="easy_gpt_keywords" value="">
                        </div>
                        <div class="easy-gpt-field">
                            <button type="button" id="generate-title" class="button button-primary">Generate Title</button>
                            <button type="button" id="generate-outline" class="button button-primary">Generate Outline</button>
                            <button type="button" id="generate-article" class="button button-primary">Generate Article</button>
                            <button type="button" id="generate-excerpt" class="button button-primary" style="display: none;">Generate Excerpt</button>
                            <button type="button" id="generate-seo" class="button button-primary" style="display: none;">Generate SEO</button>
                            <div id="generate-all-article">
                                <button type="button" id="generate-all" class="button button-primary">Generate Full Content</button>
                            </div>

                            <div id="loading-bar-container" class="loading-bar-container" style="display:none;">
                                <span id="loading-bar-fill" class="loading-bar-fill"></span>
                            </div>
                        </div>
                    </td>
                    <td class="vertical-separator"></td>
                    <td class="easy-gpt-column">
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_specific_instructions_title">Specific Instructions for Title:</label>
                            <textarea id="easy_gpt_specific_instructions_title" name="easy_gpt_specific_instructions_title" rows="2" cols="50"></textarea>
                            <div class="easy-gpt-inline">
                                <input type="checkbox" id="use_specific_title_instructions" name="use_specific_title_instructions" class="adjusted-checkbox">
                                <label for="use_specific_title_instructions" class="normal-label">Use as Title</label>
                            </div>
                        </div>
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_specific_instructions_outline">Specific Instructions for Outline:</label>
                            <textarea id="easy_gpt_specific_instructions_outline" name="easy_gpt_specific_instructions_outline" rows="2" cols="50"></textarea>
                            <div class="easy-gpt-inline">
                                <input type="checkbox" id="use_specific_outline_instructions" name="use_specific_outline_instructions" class="adjusted-checkbox">
                                <label for="use_specific_outline_instructions" class="normal-label">Use as Outline</label>
                            </div>
                        </div>
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_specific_instructions_content">Specific Instructions for Content:</label>
                            <textarea id="easy_gpt_specific_instructions_content" name="easy_gpt_specific_instructions_content" rows="2" cols="50"></textarea>
                        </div>
                        <div class="easy-gpt-field">
                            <label for="easy_gpt_specific_instructions_excerpt" id="excerpt_instructions_label">Specific Instructions for Excerpt:</label>
                            <textarea id="easy_gpt_specific_instructions_excerpt" name="easy_gpt_specific_instructions_excerpt" rows="2" cols="50"></textarea>
                        </div>
                    </td>
                    <td class="vertical-separator"></td>
                    <td class="easy-gpt-column">
                        <div id="easy-gpt-image-tabs">
                            <ul id="easy-gpt-image-tabs-list">
                                <?php for ($i = 1; $i <= $num_images; $i++) : ?>
                                    <li><a href="#image-tab-<?php echo esc_attr( $i ); ?>">Image <?php echo esc_html( $i ); ?></a></li>
                                <?php endfor; ?>
                            </ul>
                            <?php for ($i = 1; $i <= $num_images; $i++) : ?>
                                <div id="image-tab-<?php echo esc_attr( $i ); ?>">
                                    <div class="easy-gpt-field">
                                        <label for="easy_gpt_image_prompt_<?php echo esc_attr( $i ); ?>">Image Prompt <?php echo esc_html( $i ); ?>:</label>
                                        <textarea id="easy_gpt_image_prompt_<?php echo esc_attr( $i ); ?>" name="easy_gpt_image_prompt_<?php echo esc_attr( $i ); ?>" rows="2" cols="50"></textarea>
                                        <button type="button" id="generate-image-<?php echo esc_attr( $i ); ?>" class="button button-primary" style="margin-top:10px;">Generate Image <?php echo esc_html( $i ); ?></button>
                                    </div>
                                </div>
                            <?php endfor; ?>
                        </div>
                        <div id="easy-gpt-images-info">
                            <small>Optionally, provide a prompt for each image. If left blank, images will be generated automatically based on the article content when the article is generated. If you prefer, you can generate each image individually by providing a specific prompt and clicking the "Generate Image" button.</small>
                            <h4 style="margin-top:10px; margin-bottom:10px;">Images Preview</h4>
                        </div>
                        <div id="easy-gpt-images-preview">
                            <?php for ($i = 1; $i <= $num_images; $i++) : ?>
                                <div id="easy_gpt_generated_image_preview_<?php echo esc_attr( $i ); ?>" class="easy-gpt-image-preview"></div>
                            <?php endfor; ?>
                        </div>
                    </td>
                </tr>
            </table>
            <hr>
            <div id="easy-gpt-title-preview">
                <h4>Title Preview</h4>
                <textarea  id="easy_gpt_generated_title_preview" class="easy-gpt-preview-box"></textarea >
            </div>
            <div id="easy-gpt-outline-preview">
                <h4>Outline Preview</h4>
                <textarea  id="easy_gpt_generated_outline_preview" class="easy-gpt-preview-box" placeholder="Please format the outline as follows (make sure there is a space between # and the heading title):
        # H2 Heading
        ## H3 Subheading
        ### H4 Subheading"></textarea >
            </div>
            <div id="easy-gpt-preview">
                <h4>Article Preview</h4>
                <div id="easy_gpt_generated_preview" class="easy-gpt-preview-box"></div>
            </div>
            <div id="easy-gpt-category-preview" style="display: none;">
                <h4>Category Preview</h4>
                <textarea id="easy_gpt_generated_category_preview" class="easy-gpt-preview-box"></textarea>
            </div>
            <div id="easy-gpt-tag-preview" style="display: none;">
                <h4>Tag Preview</h4>
                <textarea id="easy_gpt_generated_tag_preview" class="easy-gpt-preview-box"></textarea>
            </div>
            <div id="easy-gpt-excerpt-preview">
                <h4>Excerpt Preview</h4>
                <textarea  id="easy_gpt_generated_excerpt_preview" class="easy-gpt-preview-box"></textarea >
            </div>
            <div id="easy-gpt-seo-preview" style="display: none;">
                <h4>SEO Title Preview</h4>
                <textarea  id="easy_gpt_generated_seo_title_preview" class="easy-gpt-preview-box"></textarea >
                <h4>SEO Description Preview</h4>
                <textarea  id="easy_gpt_generated_seo_description_preview" class="easy-gpt-preview-box"></textarea >
            </div>
            <button type="button" id="accept-insert-article" class="button button-primary">Accept and Insert Article</button>
            <div style="float: right; margin-top: -2px;">
                    <b>Prompt Tokens: </b>
                    <input type="text" id="easy_gpt_prompt_tokens" name="easy_gpt_prompt_tokens" value="" readonly>
                    <b>Completion Tokens: </b>
                    <input type="text" id="easy_gpt_completion_tokens" name="easy_gpt_completion_tokens" value="" readonly>
                    <b>Total Tokens: </b>
                    <input type="text" id="easy_gpt_total_tokens" name="easy_gpt_total_tokens" value="" readonly>
                    <b>Cost: </b>
                    <input type="text" id="easy_gpt_cost" name="easy_gpt_cost" value="<?php echo esc_attr($cost); ?>" readonly>
                </p>
            </div>
        </div>
        <div id="tab-2">
			<p class="easy-gpt-field">
				<label for="easy_gpt_text_api_provider_per_post">Text API Provider:</label>
				<select id="easy_gpt_text_api_provider_per_post" name="easy_gpt_text_api_provider_per_post">
					<option value="openai" <?php selected('openai', get_post_meta($post->ID, '_easy_gpt_text_api_provider_per_post', true) ?: ($options['easy_gpt_text_api_provider'] ?? 'openai')); ?>>OpenAI</option>
					<option value="gemini" <?php selected('gemini', get_post_meta($post->ID, '_easy_gpt_text_api_provider_per_post', true) ?: ($options['easy_gpt_text_api_provider'] ?? 'openai')); ?>>Gemini</option>
					<option value="deepseek" <?php selected('deepseek', get_post_meta($post->ID, '_easy_gpt_text_api_provider_per_post', true) ?: ($options['easy_gpt_text_api_provider'] ?? 'openai')); ?>>DeepSeek</option>
				</select>
			</p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_model">GPT Model:</label>
                <select id="easy_gpt_model" name="easy_gpt_model">
					<?php foreach ($easy_gpt_options['models'] as $model_option) :
						$provider = 'openai';
						if (strpos($model_option, 'gemini-') === 0) {
							$provider = 'gemini';
						} elseif (strpos($model_option, 'deepseek-') === 0) {
							$provider = 'deepseek';
						}
					?>
						<option value="<?php echo esc_attr($model_option); ?>" data-api="<?php echo esc_attr($provider); ?>" <?php selected($model_option, $model); ?>>
							<?php echo esc_html($model_option); ?>
						</option>
					<?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_temperature">Temperature:</label>
                <input type="number" id="easy_gpt_temperature" name="easy_gpt_temperature" min="0" max="1" step="0.01" value="<?php echo esc_attr($temperature); ?>">
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_default_language">Language:</label>
                <select id="easy_gpt_default_language" name="easy_gpt_default_language">
                    <?php foreach ($easy_gpt_options['languages'] as $code => $language) : ?>
                        <option value="<?php echo esc_attr($code); ?>" <?php selected($code, $default_language); ?>>
                            <?php echo esc_html($language); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_min_words">Minimum Number of Words:</label>
                <input type="range" id="easy_gpt_min_words" name="easy_gpt_min_words" min="100" max="1000" step="50" value="<?php echo esc_attr($min_words); ?>" oninput="this.nextElementSibling.value = this.value"> <output><?php echo esc_attr($min_words); ?></output>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_max_words">Maximum Number of Words:</label>
                <input type="range" id="easy_gpt_max_words" name="easy_gpt_max_words" min="500" max="5000" step="100" value="<?php echo esc_attr($max_words); ?>" oninput="this.nextElementSibling.value = this.value"> <output><?php echo esc_attr($max_words); ?></output>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_num_subheadings">Number of H2 Subheadings:</label>
                <input type="number" id="easy_gpt_num_subheadings" name="easy_gpt_num_subheadings" min="1" max="10" value="<?php echo esc_attr($num_subheadings); ?>">
            </p>
             <p class="easy-gpt-field">
                <label><?php esc_html_e( 'Type of Additional Subheadings:', 'easy-gpt-for-wp' ); ?></label><br>
                <input type="checkbox" id="easy_gpt_subheading_type_h3" name="easy_gpt_subheading_type_h3" <?php checked( $subheading_type_h3 ); ?> class="adjusted-checkbox"> <?php esc_html_e( 'H3', 'easy-gpt-for-wp' ); ?><br>
                <input type="checkbox" id="easy_gpt_subheading_type_h4" name="easy_gpt_subheading_type_h4" <?php checked( $subheading_type_h4 ); ?> class="adjusted-checkbox"> <?php esc_html_e( 'H4', 'easy-gpt-for-wp' ); ?>
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_format_article" class="black-label"><?php esc_html_e( 'Format Article:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_format_article" name="easy_gpt_format_article" <?php checked( $format_article ); ?> class="adjusted-checkbox">
                <small><?php esc_html_e( 'Format article with bold and italic text (e.g., bold, italic)', 'easy-gpt-for-wp' ); ?></small>
            </p>
			<p class="easy-gpt-field easy-gpt-inline-bold">
				<label for="easy_gpt_include_citations" class="black-label"><?php esc_html_e( 'Include Citations in Text:', 'easy-gpt-for-wp' ); ?></label>
				<input type="checkbox" id="easy_gpt_include_citations" name="easy_gpt_include_citations" <?php checked( $include_citations ); ?> class="adjusted-checkbox">
				<small><?php esc_html_e( 'Insert citations within the body of the article.', 'easy-gpt-for-wp' ); ?></small>
			</p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_include_links" class="black-label"><?php esc_html_e( 'Automatically Insert Links:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_include_links" name="easy_gpt_include_links" <?php checked( $include_links ); ?> class="adjusted-checkbox">
                <small><?php esc_html_e( 'Include relevant hyperlinks within the article content.', 'easy-gpt-for-wp' ); ?></small>
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_include_bibliography" class="black-label"><?php esc_html_e( 'Include Bibliography:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_include_bibliography" name="easy_gpt_include_bibliography" <?php checked( $include_bibliography ); ?> class="adjusted-checkbox">
                <small><?php esc_html_e( 'Add a bibliography section at the end of the article with cited sources. Note: The bibliography will only be included if there is enough complete and accurate information available. If specific data is missing, such as author names, titles, publication dates, or URLs, the bibliography may not be generated.', 'easy-gpt-for-wp' ); ?></small>
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_auto_categories" class="black-label"><?php esc_html_e( 'Automatically Set Categories:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_auto_categories" name="easy_gpt_auto_categories" <?php checked( $auto_categories ); ?> class="adjusted-checkbox">
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_auto_tags" class="black-label"><?php esc_html_e( 'Automatically Set Tags:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_auto_tags" name="easy_gpt_auto_tags" <?php checked( $auto_tags ); ?> class="adjusted-checkbox">
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_auto_seo" class="black-label"><?php esc_html_e( 'Enable SEO Optimization:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_auto_seo" name="easy_gpt_auto_seo" <?php checked( $auto_seo ); ?> class="adjusted-checkbox">
                <small><?php esc_html_e( 'Automatically fill in the SEO title and description if a compatible SEO plugin is installed.', 'easy-gpt-for-wp' ); ?></small>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_writing_style"><?php esc_html_e( 'Writing Style:', 'easy-gpt-for-wp' ); ?></label>
                <select id="easy_gpt_writing_style" name="easy_gpt_writing_style">
                    <?php foreach ( $easy_gpt_options['writing_styles'] as $style ) : ?>
                        <option value="<?php echo esc_attr( $style ); ?>" <?php selected( $writing_style, $style ); ?>>
                            <?php echo esc_html( $style ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_writing_tone"><?php esc_html_e( 'Writing Tone:', 'easy-gpt-for-wp' ); ?></label>
                <select id="easy_gpt_writing_tone" name="easy_gpt_writing_tone">
                    <?php foreach ( $easy_gpt_options['writing_tones'] as $tone ) : ?>
                        <option value="<?php echo esc_attr( $tone ); ?>" <?php selected( $writing_tone, $tone ); ?>>
                            <?php echo esc_html( $tone ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_include_excerpt" class="black-label"><?php esc_html_e( 'Include Excerpt:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_include_excerpt" name="easy_gpt_include_excerpt" <?php checked( $include_excerpt ); ?> class="adjusted-checkbox">
            </p>
			<p class="easy-gpt-field easy-gpt-inline-bold">
				<label for="easy_gpt_final_review" class="black-label"><?php esc_html_e( 'Final AI-Based Review:', 'easy-gpt-for-wp' ); ?></label>
				<input type="checkbox" id="easy_gpt_final_review" name="easy_gpt_final_review" <?php checked( $final_review ); ?> class="adjusted-checkbox">
				<small><?php esc_html_e( 'Request a final AI-based review for the article (it may correct minor errors in the text but slightly increases the API cost).', 'easy-gpt-for-wp' ); ?></small>
			</p>
			
            <h3><?php esc_html_e( 'Video Settings', 'easy-gpt-for-wp' ); ?></h3>
        
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_include_videos_per_post" class="black-label"><?php esc_html_e( 'Include Videos:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_include_videos_per_post" name="easy_gpt_include_videos_per_post" <?php checked( $include_videos, '1' ); ?> class="adjusted-checkbox">
                <small><?php esc_html_e( 'Check this box to include a YouTube video in this article.', 'easy-gpt-for-wp' ); ?></small>
            </p>
            
            <p class="easy-gpt-field">
                <label for="easy_gpt_video_position_per_post"><?php esc_html_e( 'Video Position:', 'easy-gpt-for-wp' ); ?></label>
                <select id="easy_gpt_video_position_per_post" name="easy_gpt_video_position_per_post">
                    <option value="start" <?php selected( $video_position, 'start' ); ?>><?php esc_html_e( 'Start', 'easy-gpt-for-wp' ); ?></option>
                    <option value="end" <?php selected( $video_position, 'end' ); ?>><?php esc_html_e( 'End', 'easy-gpt-for-wp' ); ?></option>
                    <option value="random" <?php selected( $video_position, 'random' ); ?>><?php esc_html_e( 'Random', 'easy-gpt-for-wp' ); ?></option>
                    <option value="after_paragraph" <?php selected( $video_position, 'after_paragraph' ); ?>><?php esc_html_e( 'After X Paragraphs', 'easy-gpt-for-wp' ); ?></option>
                </select>
                <p><small><?php esc_html_e( 'Choose where to insert the YouTube video in the article.', 'easy-gpt-for-wp' ); ?></small></p>
            </p>
            
            <p class="easy-gpt-field" id="easy_gpt_video_paragraph_container" style="display: <?php echo ( $video_position === 'after_paragraph' ) ? 'block' : 'none'; ?>;">
                <label for="easy_gpt_video_paragraph"><?php esc_html_e( 'Number of Paragraphs:', 'easy-gpt-for-wp' ); ?></label>
                <input type="number" id="easy_gpt_video_paragraph" name="easy_gpt_video_paragraph_per_post" min="1" value="<?php echo esc_attr( $video_paragraph ); ?>"></br>
                <small><?php esc_html_e( 'Insert the video after this number of paragraphs.', 'easy-gpt-for-wp' ); ?></small>
            </p>
            </div>
            <div id="tab-3">
			<p class="easy-gpt-field">
				<label for="easy_gpt_image_api_provider_per_post">Image API Provider:</label>
				<select id="easy_gpt_image_api_provider_per_post" name="easy_gpt_image_api_provider_per_post">
					<option value="openai" <?php selected('openai', get_post_meta($post->ID, '_easy_gpt_image_api_provider_per_post', true) ?: ($options['easy_gpt_image_api_provider'] ?? 'openai')); ?>>OpenAI</option>
					<option value="gemini" <?php selected('gemini', get_post_meta($post->ID, '_easy_gpt_image_api_provider_per_post', true) ?: ($options['easy_gpt_image_api_provider'] ?? 'openai')); ?>>Gemini</option>
				</select>
			</p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_image_model"><?php esc_html_e( 'Choose Image Model:', 'easy-gpt-for-wp' ); ?></label>
                <select id="easy_gpt_image_model" name="easy_gpt_image_model">
					<?php foreach ( $easy_gpt_options['dall_e_models'] as $model_option ) :
						$provider = 'openai';
						if (strpos($model_option, 'gemini-') === 0 || strpos($model_option, 'imagen-') === 0) {
							$provider = 'gemini';
						} elseif (strpos($model_option, 'deepseek-') === 0) {
							$provider = 'deepseek';
						}
					?>
						<option value="<?php echo esc_attr( $model_option ); ?>" data-api="<?php echo esc_attr( $provider ); ?>" <?php selected( $image_model, $model_option ); ?>>
							<?php echo esc_html( $model_option ); ?>
						</option>
					<?php endforeach; ?>

                </select>
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_auto_images" class="black-label"><?php esc_html_e( 'Automatically Generate Images:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_auto_images" name="easy_gpt_auto_images" <?php checked( $auto_images ); ?> class="adjusted-checkbox">
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_num_images"><?php esc_html_e( 'Number of Images:', 'easy-gpt-for-wp' ); ?></label>
                <input type="number" id="easy_gpt_num_images" name="easy_gpt_num_images" min="1" value="<?php echo esc_attr( $num_images ); ?>">
            </p>
            <p class="easy-gpt-field easy-gpt-inline-bold">
                <label for="easy_gpt_set_featured_image" class="black-label"><?php esc_html_e( 'Set first generated image as featured:', 'easy-gpt-for-wp' ); ?></label>
                <input type="checkbox" id="easy_gpt_set_featured_image" name="easy_gpt_set_featured_image" <?php checked( $set_featured_image ); ?> class="adjusted-checkbox">
            </p>

            <p class="easy-gpt-field">
                <label for="easy_gpt_image_size">Select Image Size:</label>
                <select id="easy_gpt_image_size" name="easy_gpt_image_size">
                    <?php foreach ($easy_gpt_options['image_sizes'] as $key => $size) : ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($key, $image_size); ?>>
                            <?php echo esc_html($size); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_image_quality">Choose Image Quality:</label>
                <select id="easy_gpt_image_quality" name="easy_gpt_image_quality">
                    <?php foreach ($easy_gpt_options['image_qualities'] as $key => $quality) : ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($key, $image_quality); ?>>
                            <?php echo esc_html($quality); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            <p class="easy-gpt-field">
                <label for="easy_gpt_image_style">Image Style:</label>
                <input type="text" id="easy_gpt_image_style" name="easy_gpt_image_style" value="<?php echo esc_attr($image_style); ?>" placeholder="e.g., Realistic, Drawing, Anime">
            </p>
        </div>
    </div>
    <?php
}

// Save the metabox data
add_action('save_post', 'easy_gpt_save_metabox_data');

function easy_gpt_save_metabox_data($post_id) {
    // Verificar si nuestro nonce está establecido.
    if (!isset($_POST['easy_gpt_nonce'])) {
        return $post_id;
    }

    $nonce = isset($_POST['easy_gpt_nonce']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_nonce'])) : '';

    // Verificar que el nonce es válido.
    if (!wp_verify_nonce($nonce, 'easy_gpt_save_metabox_data')) {
        return $post_id;
    }

    // Si es un autosave, no hacemos nada.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    // Verificar permisos del usuario.
    $post_type = isset($_POST['post_type']) ? sanitize_text_field(wp_unslash($_POST['post_type'])) : '';

    if ('page' === $post_type) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } else {
        if (!current_user_can('edit_post', $post_id)) {
            return $post_id;
        }
    }

    if (isset($_POST['easy_gpt_cost'])) {
        update_post_meta($post_id, '_easy_gpt_cost', sanitize_text_field(wp_unslash($_POST['easy_gpt_cost'])));
    }

    // Sanitizar la entrada del usuario.
    $new_prompt = isset($_POST['easy_gpt_prompt']) ? sanitize_textarea_field(wp_unslash($_POST['easy_gpt_prompt'])) : '';
    $new_keywords = isset($_POST['easy_gpt_keywords']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_keywords'])) : '';
    $new_model = isset($_POST['easy_gpt_model']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_model'])) : '';
	$new_text_api_provider = isset($_POST['easy_gpt_text_api_provider_per_post']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_text_api_provider_per_post'])) : '';
	$new_image_api_provider = isset($_POST['easy_gpt_image_api_provider_per_post']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_image_api_provider_per_post'])) : '';
    $new_temperature = isset($_POST['easy_gpt_temperature']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_temperature'])) : '';
    $new_min_words = isset($_POST['easy_gpt_min_words']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_min_words'])) : '';
    $new_max_words = isset($_POST['easy_gpt_max_words']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_max_words'])) : '';
    $new_num_subheadings = isset($_POST['easy_gpt_num_subheadings']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_num_subheadings'])) : '';
    $new_subheading_type_h3 = isset($_POST['easy_gpt_subheading_type_h3']) ? '1' : '0';
    $new_subheading_type_h4 = isset($_POST['easy_gpt_subheading_type_h4']) ? '1' : '0';
    $new_format_article = isset($_POST['easy_gpt_format_article']) ? '1' : '0';
    $new_auto_categories = isset($_POST['easy_gpt_auto_categories']) ? '1' : '0';
    $new_auto_tags = isset($_POST['easy_gpt_auto_tags']) ? '1' : '0';
    $new_auto_seo = isset($_POST['easy_gpt_auto_seo']) ? '1' : '0';
    $new_image_model = isset($_POST['easy_gpt_image_model']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_image_model'])) : '';
    $new_auto_images = isset($_POST['easy_gpt_auto_images']) ? '1' : '0';
    $new_num_images = isset($_POST['easy_gpt_num_images']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_num_images'])) : '';
    $new_image_size = isset($_POST['easy_gpt_image_size']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_image_size'])) : '';
    $new_image_quality = isset($_POST['easy_gpt_image_quality']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_image_quality'])) : '';
    $new_writing_style = isset($_POST['easy_gpt_writing_style']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_writing_style'])) : '';
    $new_writing_tone = isset($_POST['easy_gpt_writing_tone']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_writing_tone'])) : '';
    $new_image_style = isset($_POST['easy_gpt_image_style']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_image_style'])) : '';
    $new_include_excerpt = isset($_POST['easy_gpt_include_excerpt']) ? '1' : '0';
    $new_default_language = isset($_POST['easy_gpt_default_language']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_default_language'])) : '';
    $new_set_featured_image = isset($_POST['easy_gpt_set_featured_image']) ? '1' : '0';
    $new_include_links = isset($_POST['easy_gpt_include_links']) ? '1' : '0';
    $new_include_bibliography = isset($_POST['easy_gpt_include_bibliography']) ? '1' : '0';
    $new_include_videos_per_post = isset($_POST['easy_gpt_include_videos_per_post']) ? '1' : '0';
    $new_video_position_per_post = isset($_POST['easy_gpt_video_position_per_post']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_video_position_per_post'])) : 'end';
    $new_video_paragraph_per_post = isset($_POST['easy_gpt_video_paragraph_per_post']) ? intval($_POST['easy_gpt_video_paragraph_per_post']) : 3;
	$new_include_citations = isset($_POST['easy_gpt_include_citations']) ? '1' : '0';
	$new_final_review = isset($_POST['easy_gpt_final_review']) ? '1' : '0';

    // Actualizar los campos meta en la base de datos.
    update_post_meta($post_id, '_easy_gpt_prompt', $new_prompt);
    update_post_meta($post_id, '_easy_gpt_keywords', $new_keywords);
    update_post_meta($post_id, '_easy_gpt_model', $new_model);
    update_post_meta($post_id, '_easy_gpt_temperature', $new_temperature);
    update_post_meta($post_id, '_easy_gpt_min_words', $new_min_words);
    update_post_meta($post_id, '_easy_gpt_max_words', $new_max_words);
    update_post_meta($post_id, '_easy_gpt_num_subheadings', $new_num_subheadings);
    update_post_meta($post_id, '_easy_gpt_subheading_type_h3', $new_subheading_type_h3);
    update_post_meta($post_id, '_easy_gpt_subheading_type_h4', $new_subheading_type_h4);
    update_post_meta($post_id, '_easy_gpt_format_article', $new_format_article);
    update_post_meta($post_id, '_easy_gpt_auto_categories', $new_auto_categories);
    update_post_meta($post_id, '_easy_gpt_auto_tags', $new_auto_tags);
    update_post_meta($post_id, '_easy_gpt_auto_seo', $new_auto_seo);
    update_post_meta($post_id, '_easy_gpt_image_model', $new_image_model);
    update_post_meta($post_id, '_easy_gpt_auto_images', $new_auto_images);
    update_post_meta($post_id, '_easy_gpt_num_images', $new_num_images);
    update_post_meta($post_id, '_easy_gpt_image_size', $new_image_size);
    update_post_meta($post_id, '_easy_gpt_image_quality', $new_image_quality);
    update_post_meta($post_id, '_easy_gpt_writing_style', $new_writing_style);
    update_post_meta($post_id, '_easy_gpt_writing_tone', $new_writing_tone);
    update_post_meta($post_id, '_easy_gpt_image_style', $new_image_style);
    update_post_meta($post_id, '_easy_gpt_include_excerpt', $new_include_excerpt);
    update_post_meta($post_id, '_easy_gpt_default_language', $new_default_language);
    update_post_meta($post_id, '_easy_gpt_set_featured_image', $new_set_featured_image);
    update_post_meta($post_id, '_easy_gpt_include_links', $new_include_links);
    update_post_meta($post_id, '_easy_gpt_include_bibliography', $new_include_bibliography);
    update_post_meta($post_id, '_easy_gpt_include_videos_per_post', $new_include_videos_per_post);
    update_post_meta($post_id, '_easy_gpt_video_position_per_post', $new_video_position_per_post);
    update_post_meta($post_id, '_easy_gpt_video_paragraph_per_post', $new_video_paragraph_per_post);
	update_post_meta($post_id, '_easy_gpt_include_citations', $new_include_citations);
	update_post_meta($post_id, '_easy_gpt_final_review', $new_final_review);
	update_post_meta($post_id, '_easy_gpt_text_api_provider_per_post', $new_text_api_provider);
	update_post_meta($post_id, '_easy_gpt_image_api_provider_per_post', $new_image_api_provider);

}


add_action('wp_ajax_generate_title', 'easy_gpt_generate_title');

function easy_gpt_generate_title() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    try {
        $use_specific_instructions = isset($_POST['use_specific_instructions']) && $_POST['use_specific_instructions'] === 'true';


        if ($use_specific_instructions && !empty($_POST['specific_instructions'])) {
            $specific_instructions = sanitize_textarea_field(wp_unslash($_POST['specific_instructions']));
            wp_send_json_success(array(
                'text' => esc_html($specific_instructions),
                'prompt_tokens' => 0,
                'completion_tokens' => 0,
                'total_tokens' => 0
            ));
        } else {
            // Recolectar parámetros
            $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
            $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
            $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
            $specific_instructions = isset($_POST['specific_instructions']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions'])) : '';

            $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

            $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
            $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
            $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
            $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
            $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';
            
            $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
            $is_product = ($post_type === 'product');
            
            $entity_type = $is_product ? "product" : "article";
            
            $full_prompt = "Title Generation for a {$entity_type}: Using the prompt '$prompt', keywords '$keywords', and specific instructions '$specific_instructions', generate a title that fits the style '$writing_style' and tone '$writing_tone' in '$language' language. Only return the title without enclosing it in quotes.";

            $response = easy_gpt_call_openai_api($full_prompt, $model, $temperature, $api_key, $post_id);
            wp_send_json_success($response);
        }
    } catch (Exception $e) {
        // Enviar respuesta de error detallada al frontend
        wp_send_json_error(array('message' => $e->getMessage()));
    }

    wp_die(); // Terminar correctamente la ejecución
}
add_action('wp_ajax_generate_outline', 'easy_gpt_generate_outline');

function easy_gpt_generate_outline() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    if (isset($_POST['use_specific_instructions']) && $_POST['use_specific_instructions'] === 'true' && !empty($_POST['specific_instructions'])) {
        $specific_instructions = sanitize_textarea_field(wp_unslash($_POST['specific_instructions']));
        wp_send_json_success(array('text' => esc_html($specific_instructions), 'prompt_tokens' => 0, 'completion_tokens' => 0, 'total_tokens' => 0));
    } else {
        $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
        $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $specific_instructions = isset($_POST['specific_instructions']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions'])) : '';
        $num_subheadings = isset($_POST['num_subheadings']) ? intval($_POST['num_subheadings']) : 0;
        $type_subheadings = isset($_POST['type_subheadings']) ? sanitize_text_field(wp_unslash($_POST['type_subheadings'])) : '';
        $min_words = isset($_POST['min_words']) ? intval($_POST['min_words']) : 0;
        $max_words = isset($_POST['max_words']) ? intval($_POST['max_words']) : 0;
        $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
        $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
        $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
        $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
        $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';

        // Construcción dinámica de las instrucciones de subencabezados
        $subheading_instructions = '';
        if (strpos($type_subheadings, 'H3') !== false) {
            $subheading_instructions .= "Mark 'H3' subheadings with a '## ' prefix. ";
        }
        if (strpos($type_subheadings, 'H4') !== false) {
            $subheading_instructions .= "Mark 'H4' subheadings with '### ' prefix. ";
        }

        if (strpos($type_subheadings, 'H4') === false && strpos($type_subheadings, 'H3') === false) {
            $type_subheadings = "Only use H2";
        }

        $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
        $is_product = ($post_type === 'product');
        $entity_type = $is_product ? "product" : "article";
        
        $full_prompt = "Generate an outline for a {$entity_type} titled '{$title}' with the following details (only return the headings, don't explain anything, do not include an introduction or conclusion):\n" .
                       "Prompt: {$prompt}\n" .
                       "Keywords: {$keywords}\n" .
                       "Specific instructions: {$specific_instructions}\n" .
                       "Number of H2 Subheadings: {$num_subheadings} (create only {$num_subheadings} h2 subheadings) \n" .
                       "Total Words for the {$entity_type}: Minimum {$min_words} words, Maximum {$max_words} words.\n" .
                       "Ensure the outline and the number of sections are appropriate for the total word count of the {$entity_type}.\n" .
                       "Type of Additional Subheadings you can use (only if necessary): {$type_subheadings} (Place each subheading on a new line. Mark 'H2' subheadings with a '# ' prefix. {$subheading_instructions})\n" .
                       "Language: {$language}\n" .
                       "Writing Style: {$writing_style}\n" .
                       "Tone: {$writing_tone}\n" .
                       "Incorporate the keyword '{$keywords}' naturally in about half of the headings. Ensure the headings are varied and do not repeat the keyword in each heading.";


        $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];
        $response = easy_gpt_call_openai_api($full_prompt, $model, $temperature, $api_key, $post_id);
        wp_send_json_success($response);
    }
    wp_die();
}

function easy_gpt_clean_response_text($text) {
    // 0. Eliminar bloques de código tipo ```html y ```
    $text = preg_replace('/^```html\s*/i', '', $text); 
    $text = preg_replace('/^```\s*/i', '', $text);     
    $text = preg_replace('/```$/i', '', $text);

    // 1. Eliminar introducciones como "Here’s the refined version..."
    $text = preg_replace('/^Here[^:]*?:\s*-+\s*/i', '', $text);

    // 2. Eliminar secciones finales tipo "Key Improvements"
    $text = preg_replace('/---\s*###\s*Key Improvements:.*/is', '', $text);

    // 3. (Opcional) Quitar espacios extra o líneas vacías al final
    $text = trim($text);

    return $text;
}

//add_action('wp_ajax_generate_article', 'easy_gpt_generate_article');

function easy_gpt_generate_article_sync( $payload ) {
    
    //error_log("Generando articulo...");
    //check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');
    extract( $payload );

    // Sanitizar y validar los datos recibidos
    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';
    $specific_instructions_content = isset($_POST['specific_instructions_content']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_content'])) : '';

    $min_words = isset($_POST['min_words']) ? intval($_POST['min_words']) : 0;
    $max_words = isset($_POST['max_words']) ? intval($_POST['max_words']) : 0;
    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
    $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';

    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

    $format_article = isset($_POST['easy_gpt_format_article']) && $_POST['easy_gpt_format_article'] === 'true';
    $includeBibliography = isset($_POST['easy_gpt_includeBibliography']) && $_POST['easy_gpt_includeBibliography'] === 'true';
    $includeLinks = isset($_POST['easy_gpt_includeLinks']) && $_POST['easy_gpt_includeLinks'] === 'true';

    $include_video = isset($_POST['easy_gpt_include_videos_per_post']) ? '1' : '0';
    $video_position = isset($_POST['easy_gpt_video_position_per_post']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_video_position_per_post'])) : 'end';
    $after_paragraph = isset($_POST['easy_gpt_video_paragraph_per_post']) ? max(1, intval($_POST['easy_gpt_video_paragraph_per_post'])) : 3;

$include_citations = isset($_POST['easy_gpt_include_citations']) ? '1' : '0';
$final_review = isset($_POST['easy_gpt_final_review']) ? '1' : '0';


    // Construir instrucciones adicionales
    $links_instructions = $includeLinks
        ? " You can insert links using <a> </a> tags to justify data or claims, recommendations in the middle of the text. For example, 'according to a study made by <a>...'</a>. If possible, use the name for the link, but do not say 'for more information'."
        : "";

    $bibliography_instructions = $includeBibliography
        ? " Include a bibliography at the end of the article using Chicago style. If the source is an online medium, include the link using <a> </a> tags. Use <h2> as a header for the bibliography section. The bibliography must only include entries with complete and real data. If specific data is missing (e.g., author name, title, publication date, URL), do not include that entry. The bibliography should not exceed 200 words. Return both the conclusion and the bibliography, and if you don't have enough data to generate a proper bibliography, omit the bibliography section entirely."
        : "(only return the conclusion)";

    $format_instructions = $format_article
        ? " and use <i>italic</i> tags for scientific terms or foreign words, and <b>bold</b> tags for significant phrases or parts of sentences that emphasize major findings, novel ideas, or critical points, characteristics, facts, or also to make the lecture easy."
        : "";
        

    // Llamar a la función para obtener el video de YouTube
    $video_result = easy_gpt_get_youtube_video_url($title, $keywords, $language, $include_video);
    
    $video_url = isset($video_result['video_url']) ? $video_result['video_url'] : '';


    // Generar la introducción
    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $is_product = ($post_type === 'product');
    $entity_type = $is_product ? "product" : "article";
    
    $intro_prompt = "Generate an introduction for a {$entity_type} titled '{$title}' with the following details, formatted with <p> tags for each paragraph{$format_instructions}, do not include the title in the introducction, do not use # or * and <html> tag, (only return the introduction):\n" .
                    "Prompt: {$prompt}\n" .
                    "Keywords: {$keywords}\n" .
                    "Language: {$language}\n" .
                    "Writing Style: {$writing_style}\n" .
                    "Tone: {$writing_tone}\n" .
                    "Maximum Words for the introduction: 200 words.\n";


    $intro_response = easy_gpt_call_openai_api($intro_prompt, $model, $temperature, $api_key, $post_id);

    if (!$intro_response) {
        wp_send_json_error(['message' => "Failed to generate introduction"]);
        wp_die();
    }

    $responses = [$intro_response['text']];
    
    if (!empty($video_url) && $include_video) {
        if ($video_position === 'start') {
            $responses[0] .= "$video_url"; // Después de la introducción
        }
    }

    // Procesar el esquema para obtener las secciones H2
    $sections = explode("\n", $outline);
    $h2_sections = [];
    $current_h2 = null;

    foreach ($sections as $section) {
        $section = trim($section);

        if (substr($section, 0, 2) === '# ') {
            if ($current_h2) {
                $h2_sections[] = $current_h2;
            }
            $current_h2 = [$section];
        } elseif ($current_h2) {
            $current_h2[] = $section;
        }
    }

    if ($current_h2) {
        $h2_sections[] = $current_h2;
    }

    $num_sections = count($h2_sections);
    if ($num_sections === 0) {
        wp_send_json_error(['message' => "No sections found in outline"]);
        //wp_die();
    }
    
    $insert_video_after_section = ($video_position === 'random' && $num_sections > 0) ? rand(0, $num_sections - 1) : null;

    $min_words_per_section = $num_sections > 0 ? $min_words / $num_sections : $min_words;
    $max_words_per_section = $num_sections > 0 ? $max_words / $num_sections : $max_words;


	
	$citation_instructions = $include_citations
    ? " and blockquotes (`<i>`) (blockquotes only if necesary) with the autor name (like real) where relevant." 
    : ".";
	
	$citation_instructions2 = $include_citations
    ? ", blockquotes (with the person of the quote), " 
    : " ";	
	 
	
	
    foreach ($h2_sections as $index => $h2_section) {
        //error_log("Generando sección...");
        
        $h2_title = array_shift($h2_section);
        //error_log($h2_title);
        $h3_h4 = implode("\n", $h2_section);
        if (empty($h3_h4)) {
            $h3_h4 = "do not use any subheading.";
        }

		////error_log("Contenido previo - ". $index . ": ". $previous_content);
		$previous_content = implode("\n", $responses); // Unir todo lo generado hasta el momento
		

$section_prompt = "Continue writing the article about {$entity_type} titled '{$title}', ensuring a smooth transition from the previous sections. Avoid repeating general information already covered.

Previously written sections:\n{$previous_content}\n

Generate a detailed section with the following details:

- Section Title: {$h2_title}
- Subheadings: {$h3_h4}
- Format: Use proper HTML tags, like <h2> for section titles, <h3>, <h4> for subheadings, <p> for paragraphs, and <ul><li> for lists, and <blockquote> for quotes. {$format_instructions}.  
  - Do not use # and <html> tag.
  - Important: In the section Apply bold <b> for key concepts, important phrases, and crucial data.  
  - Apply italics <i> to scientific terms, foreign words...  
  - Incorporate lists (`<ul><li>`){$citation_instructions}
  - Ensure these formatting elements appear naturally throughout the entire section, not just in the introduction or conclusion.
  - Before introducing any `<h3>` or `<h4>`, ensure there is a short introductory paragraph (2-3 sentences) explaining what will be covered in the subsection.

---

Refining Introductions and Transitions:
* Vary how the section starts: Instead of beginning with a direct statement about the topic, consider alternative openings:  
   - Ask a rhetorical question to engage the reader.  
   - Use an intriguing fact or statistic to draw attention.  
   - Introduce a brief anecdote or historical reference (if relevant).  
   - Make a comparison or contrast with another related concept.  
*Avoid starting multiple sections or paragraphs with the same noun or phrase. Instead, use synonyms, rephrase, or introduce the idea in a different way.  
*Make transitions natural and fluid, do not use always the same, variety
*Ensure logical connections between subtopics, so the article flows smoothly rather than feeling fragmented.  

---

The section must begin with a short, engaging introduction that: 
   - Do not start by repeating the article’s main topic.  
   - Introduce the section in a natural and engaging way to maintain reader interest.  
   - Avoid generic phrasing—connect the section to the broader article context.  
   - You can use a rhetorical question.

Detailed Section Development
- Expand each subheading into 2-4 paragraphs.  
- Use lists{$citation_instructions2}or tables when appropriate to improve readability.  
- Introduce new insights rather than restating previous content.  
- Add real-world examples, statistics, or historical context where relevant.  
- {$links_instructions}

---

### Enhancing Readability and Style
- Avoid repetitive sentence structures (e.g., multiple paragraphs starting with the same noun or phrase).  
- If a keyword (singular or plural) appeared in the first 20 words of the last 3 paragraphs, avoid it in the new paragraph.
- Diversify sentence structures: Mix short and long sentences, use subordinate clauses, and include comparisons or rhetorical questions.
- Ensure a smooth, engaging flow that keeps the reader interested.  
- Use proper linking phrases for smooth transitions between subtopics. 

---

Formatting Consistency
Ensure proper distribution of formatting elements:  
  - Bold (`<b>`) should emphasize key facts, not entire sentences.  
  - Italics (`<i>`) should highlight technical terms and foreign words.  
  - Lists and blockquotes should naturally complement the content, rather than being forced in.  
  - Dont use ** or *, use <b> or <i> insteed

---

- Prompt: {$prompt}  
- Keywords: {$keywords}  
- Specific Instructions: {$specific_instructions_content}  
- Language: {$language}  
- Style: {$writing_style}  
- Tone: {$writing_tone}  

- Do not forget Apply bold <b> for key concepts, important phrases, and crucial data. 
- Word Limit: Between {$min_words_per_section} and {$max_words_per_section} words.  

{$links_instructions}";



		////error_log($section_prompt);

        $response = easy_gpt_call_openai_api($section_prompt, $model, $temperature, $api_key, $post_id);

        if (!$response) {
            wp_send_json_error(['message' => "Failed to generate section for '{$h2_title}'"]);
            wp_die();
        }

        $responses[] = $response['text'];

        // Insertar video si la opción es 'random' y esta es la sección seleccionada
        if (!empty($video_url) && $include_video && $video_position === 'random' && $index === $insert_video_after_section) {
            $responses[] .= "$video_url";
        }
    }

    // Generar la conclusión

    if (!empty($video_url) && $include_video && $video_position === 'end') {
        $responses[] .= "$video_url";
    }

	$previous_content = implode("\n", $responses); // Unir todo el contenido generado antes de la conclusión

	$conclusion_prompt = "Generate a strong conclusion for a {$entity_type} titled '{$title}'. The conclusion should summarize the main insights without repeating detailed information already covered. Ensure a natural and engaging closing statement.

	Previously written content:\n{$previous_content}\n

	Consider the key points from this outline: {$outline}. Format the conclusion with <p> tags for each paragraph{$format_instructions}. Provide a <h2> heading that naturally summarizes the key message of the conclusion, avoiding generic titles like 'Conclusion'.\n

	Prompt: {$prompt}\n
	Keywords: {$keywords}\n
	Language: {$language}\n
	Writing Style: {$writing_style}\n
	Tone: {$writing_tone}\n
	Maximum Words for the conclusion: 200 words.\n
	{$bibliography_instructions}";

    //error_log("Generando conclusion...");

    $conclusion_response = easy_gpt_call_openai_api($conclusion_prompt, $model, $temperature, $api_key, $post_id);

    if (!$conclusion_response) {
        wp_send_json_error(['message' => "Failed to generate conclusion"]);
        wp_die();
    }

    $responses[] = $conclusion_response['text'];


	$full_article = implode("\n", $responses);
	
	$is_deepseek = strpos($model, 'deepseek-') === 0;

	if ($final_review && !$is_deepseek) {
		// 📌 **Paso adicional: Revisar el artículo después de la conclusión pero antes del video**
		$review_prompt = "Here is a complete article about {$entity_type} titled '{$title}'. Review and refine it to improve coherence, eliminate redundancies, and ensure a more natural flow.

	Previously written content:\n{$full_article}\n

	Instructions for Refinement:
	- Each section (H2) must start with a short, engaging introduction (2-3 sentences) if missing.
	- Ensure a logical transition between sections and subheadings (H3, H4).
	- Avoid repetitive sentence structures: Do not start multiple paragraphs with the same noun or phrase.
	- Reword initial sentences to introduce variety while keeping the meaning intact.
	- Do not add new information—only refine and optimize existing content.
	- Summarize the conclusion concisely without repeating details already covered.
	- Use bold (`<b>`) for key concepts, important phrases, and crucial data.  
	- Apply italics (`<i>`) to scientific terms, foreign words... 
	- Use <a> for links
	- If there are ** or * change per <b> or <i> tags

	Formatting Instructions:
	- Maintain proper structure using <h2> for section titles, <h3> and <h4> for subheadings, <p> for paragraphs, and <ul><li> for lists and  <i> for quotes, {$format_instructions}, do not write <html> tag.
	- If a YouTube URL is present, leave it unchanged.

	Only return the review article, whithout any notes

	Article for Review:
	{$full_article}"; 


		$review_response = easy_gpt_call_openai_api($review_prompt, $model, $temperature, $api_key, $post_id);

		if (!$review_response) {
			wp_send_json_error(['message' => "Failed to review the article"]);
			wp_die();
		}

		// Reemplazar el contenido con la versión revisada
		$full_article = easy_gpt_clean_response_text($review_response['text']);

	}
	else{
		$full_article = easy_gpt_clean_response_text($full_article);
	}

	// 📌 **Solo ahora, insertar el video si corresponde**
	if (!empty($video_url) && $include_video && $video_position === 'after_paragraph') {
		$paragraphs = preg_split('/(<p\b[^>]*>.*?<\/p>)/i', $full_article, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

		//error_log("Total paragraphs found: " . count($paragraphs));
		//error_log("After paragraph number: " . $after_paragraph);

		// Validar el número de párrafos
		if ($after_paragraph > 0 && $after_paragraph <= count($paragraphs)) {
			// Insertar el video después del párrafo especificado
			$insert_index = $after_paragraph;
			if (isset($paragraphs[$insert_index])) {
				array_splice($paragraphs, $insert_index, 0, "\n<p>{$video_url}</p>\n");
				//error_log("Inserted video after paragraph {$after_paragraph}.");
			} else {
				$paragraphs[] = "\n<p>{$video_url}</p>\n";
				//error_log("Paragraph index {$insert_index} not found. Inserted video at the end.");
			}
		} else {
			$paragraphs[] = "\n<p>{$video_url}</p>\n";
			//error_log("After paragraph number {$after_paragraph} exceeds paragraph count. Inserted video at the end.");
		}

		$full_article = implode("", $paragraphs);
	}
	
	//error_log("Artículo generado...");

    return [
        'article' => $full_article,
        'prompt_tokens' => $conclusion_response['prompt_tokens'],
        'completion_tokens' => $conclusion_response['completion_tokens'],
        'total_tokens' => $conclusion_response['total_tokens'],
        'total_cost' => $conclusion_response['total_cost'],
    ];
    wp_die();
}


add_action('wp_ajax_generate_excerpt', 'easy_gpt_generate_excerpt');

function easy_gpt_generate_excerpt() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';
    $specific_instructions_excerpt = isset($_POST['specific_instructions_excerpt']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_excerpt'])) : '';

    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
    $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';

    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $is_product = ($post_type === 'product');
    $entity_type = $is_product ? "product" : "article";
    
    $full_prompt = "Generate an excerpt for a {$entity_type} titled '{$title}' with the following details:\n" .
                   "Prompt: {$prompt}\n" .
                   "Keywords: {$keywords}\n" .
                   "Outline: {$outline}\n" .
                   "Specific Instructions for Excerpt: {$specific_instructions_excerpt}\n" .
                   "Language: {$language}\n" .
                   "Writing Style: {$writing_style}\n" .
                   "Tone: {$writing_tone}\n" .
                   "Maximum Words for the excerpt: 60 words. Do not include the title in the excerpt.";
    

    $response = easy_gpt_call_openai_api($full_prompt, $model, $temperature, $api_key, $post_id);
	
	if ($response && !empty($response['text'])) {
		$response['text'] = preg_replace('/^\*\*Excerpt:\*\*\s*/i', '', $response['text']);
		$response['text'] = trim($response['text']);
	}
	
    if (!$response) {
        wp_send_json_error(['message' => "Failed to generate excerpt"]);
        wp_die();
    }

    wp_send_json_success($response);
    wp_die();
}

add_action('wp_ajax_generate_seo', 'easy_gpt_generate_seo');

function easy_gpt_generate_seo() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';

    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
    $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';

    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $is_product = ($post_type === 'product');
    $entity_type = $is_product ? "product" : "article";

    $prompt_title = "Generate an SEO-friendly metatitle for a {$entity_type} with the following details, ensuring the metatitle does not exceed 60 characters (only return the metatitle without enclosing it in quotes):\n" .
                    "Title: {$title}\n" .
                    "Prompt: {$prompt}\n" .
                    "Keywords: {$keywords}\n" .
                    "Outline: {$outline}\n" .
                    "Language: {$language}\n" .
                    "Writing Style: {$writing_style}\n" .
                    "Tone: {$writing_tone}";
    
    $prompt_description = "Generate an SEO-friendly metadescription for a {$entity_type} with the following details, ensuring the metadescription does not exceed 155 characters (only return the metadescription without enclosing it in quotes):\n" .
                          "Title: {$title}\n" .
                          "Prompt: {$prompt}\n" .
                          "Keywords: {$keywords}\n" .
                          "Outline: {$outline}\n" .
                          "Language: {$language}\n" .
                          "Writing Style: {$writing_style}\n" .
                          "Tone: {$writing_tone}";


    $title_response = easy_gpt_call_openai_api($prompt_title, $model, $temperature, $api_key, $post_id);
    $description_response = easy_gpt_call_openai_api($prompt_description, $model, $temperature, $api_key, $post_id);

    if (!$title_response || !$description_response) {
        wp_send_json_error(['message' => "Failed to generate SEO data"]);
        wp_die();
    }

    wp_send_json_success([
        'seo_title' => $title_response['text'],
        'seo_description' => $description_response['text'],
        'prompt_tokens' => $description_response['prompt_tokens'],
        'completion_tokens' => $description_response['completion_tokens'],
        'total_tokens' => $description_response['total_tokens'],
        'total_cost' => $description_response['total_cost']
    ]);
    wp_die();
}

add_action('wp_ajax_generate_categories', 'easy_gpt_generate_categories');

function easy_gpt_generate_categories() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';
    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';



    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';

    // Determinar la taxonomía correcta
    $taxonomy = ($post_type === 'product') ? 'product_cat' : 'category';

    //error_log("Post Type recibido: " . $post_type);
    //error_log("Taxonomía utilizada: " . $taxonomy);

    // Obtener categorías de la taxonomía correcta
    $categories = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]);

    
    $category_names = array_map(function($cat) {
        return $cat->name;
    }, $categories);
    $category_list = implode(", ", $category_names);

    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $is_product = ($post_type === 'product');
    
    $entity_type = $is_product ? "product" : "article";

    $full_prompt = "Given the existing categories: {$category_list}. Suggest only 1 category for a {$entity_type} titled '{$title}' with details:\n" .
                   "Prompt: {$prompt}\n" .
                   "Outline: {$outline}\n" .
                   "Keywords: {$keywords}\n" .
                   "Language: {$language}\n" .
                   "Only return the name of the category";
                   
    //error_log($full_prompt);

    $response = easy_gpt_call_openai_api($full_prompt, $model, $temperature, $api_key, $post_id);

    if (!$response) {
        wp_send_json_error(['message' => "Failed to generate category"]);
        wp_die();
    }

    wp_send_json_success($response);
    wp_die();
}


add_action('wp_ajax_generate_tags', 'easy_gpt_generate_tags');

function easy_gpt_generate_tags() {
    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';
    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';

    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];

    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $is_product = ($post_type === 'product');
    $entity_type = $is_product ? "product" : "article";
    
    $full_prompt = "Suggest 3 tags for a {$entity_type} titled '{$title}' with details:\n" .
                   "Prompt: {$prompt}\n" .
                   "Outline: {$outline}\n" .
                   "Keywords: {$keywords}\n" .
                   "Language: {$language}\n" .
                   "Only return the 3 tags separated by commas without the # symbol.";


    $response = easy_gpt_call_openai_api($full_prompt, $model, $temperature, $api_key, $post_id);

    if (!$response) {
        wp_send_json_error(['message' => "Failed to generate tags"]);
        wp_die();
    }

    wp_send_json_success($response);
    wp_die();
}


add_action('wp_ajax_generate_image', 'easy_gpt_generate_image');

function easy_gpt_generate_image() {
    //error_log("Iniciando generación de imagen");

    check_ajax_referer('easy_gpt_save_metabox_data', 'nonce');

    $prompt = isset($_POST['prompt']) ? sanitize_text_field(wp_unslash($_POST['prompt'])) : '';
    $keywords = isset($_POST['keywords']) ? sanitize_text_field(wp_unslash($_POST['keywords'])) : '';
    $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $outline = isset($_POST['outline']) ? sanitize_textarea_field(wp_unslash($_POST['outline'])) : '';
    $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $text_model = isset($_POST['text_model']) ? sanitize_text_field(wp_unslash($_POST['text_model'])) : '';
    $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
    $image_size = isset($_POST['image_size']) ? sanitize_text_field(wp_unslash($_POST['image_size'])) : '';
    $image_quality = isset($_POST['image_quality']) ? sanitize_text_field(wp_unslash($_POST['image_quality'])) : '';
    $image_style = isset($_POST['image_style']) ? sanitize_text_field(wp_unslash($_POST['image_style'])) : '';
    $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $writing_style = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
    $writing_tone = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $image_index = isset($_POST['image_index']) ? intval($_POST['image_index']) : 0;
    $total_images = isset($_POST['total_images']) ? intval($_POST['total_images']) : 1;
    
    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];
    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    $entity_type = ($post_type === 'product') ? "product" : "article";

    // Proceso de selección del subtítulo
    $selected_subtitle = '';
    if ($image_index == 1) {
        $selected_subtitle = $title;
    } else {
        $subtitles = array_filter(array_map('trim', explode("\n", $outline)));
        $total_subtitles = count($subtitles);

        if ($total_subtitles > 0) {
            $block_size = ceil($total_subtitles / ($total_images - 1));
            $start_index = max(0, ($image_index - 2) * $block_size);
            $end_index = min($total_subtitles, $start_index + $block_size);

            $available_subtitles = array_slice($subtitles, $start_index, $end_index - $start_index);
            $selected_subtitle = $available_subtitles[array_rand($available_subtitles)];
        } else {
            $selected_subtitle = $title;
        }
    }

    // 1. Generar TITLE
    //error_log("Generando title para la imagen {$image_index}");
    $title_prompt = "Generate an original, unique, and concise title for an image of an article. The title should reflect a specific aspect or detail of the image and be relevant to the following context:\n" .
                    "Selected Subtitle or Title: {$selected_subtitle}\n" .
                    "Image Prompt: {$prompt}\n" .
                    "Keywords: {$keywords}\n" .
                    "Language: {$language}\n" .
                    "Writing Style: {$writing_style}\n" .
                    "Writing Tone: {$writing_tone}\n" .
                    "Ensure the title is specific, creative, and clearly distinguishes this image from others in the same article. Only return the title itself, do not include any explanation, commentary, or additional text. Return just the pure title.";

    $title_response = easy_gpt_call_openai_api($title_prompt, $text_model, $temperature, $api_key, $post_id);
    //error_log("Respuesta del título: " . print_r($title_response, true));

    if (!$title_response || empty($title_response['text'])) {
        $error_message = isset($title_response['error']['message']) ? $title_response['error']['message'] : 'No error message provided.';
        //error_log("Failed to generate title text. Error: {$error_message}");
        wp_send_json_error(['message' => "Failed to generate title text"]);
        wp_die();
    }

    $title_text = trim($title_response['text']);
	
	// Limpiar TITLE
	$title_text = preg_replace('/^\*+\s*"([^"]+)"\s*\*+/i', '$1', $title_text);
	$title_text = preg_replace('/^"(.+)"$/', '$1', $title_text);
	$title_text = trim($title_text);
	
    //error_log("Título generado: {$title_text}");

    // 2. Generar ALT usando el TÍTULO generado
    $alt_prompt = "Generate an alt text short for an image based on the following details, dont say image, only return de alt text:\n" .
                  "Image Title: {$title_text}\n" .
                  "Prompt: {$prompt}\n" .
                  "Keywords: {$keywords}\n" .
                  "Language: {$language}\n" .
                  "Writing Style: {$writing_style}\n" .
                  "Writing Tone: {$writing_tone}\n";

    $alt_response = easy_gpt_call_openai_api($alt_prompt, $text_model, $temperature, $api_key, $post_id);
    //error_log("Respuesta del alt: " . print_r($alt_response, true));

    if (!$alt_response || empty($alt_response['text'])) {
        $error_message = isset($alt_response['error']['message']) ? $alt_response['error']['message'] : 'No error message provided.';
        //error_log("Failed to generate alt text. Error: {$error_message}");
        wp_send_json_error(['message' => "Failed to generate alt text"]);
        wp_die();
    }

    $alt_text = trim($alt_response['text']);

	$alt_text = preg_replace('/^\*+\s*"([^"]+)"\s*\*+/i', '$1', $alt_text);
	$alt_text = preg_replace('/^"(.+)"$/', '$1', $alt_text);
	$alt_text = trim($alt_text);
	
    //error_log("ALT generado: {$alt_text}");

    // 3. Generar Imagen usando ALT y TITLE en el prompt
    $full_prompt = "Generate an image for a {$entity_type} titled '{$title_text}' with the following details. Do not include text in the image:\n" .
                   "Image Title: {$title_text}\n" .
                   "Alt Text: {$alt_text}\n" .
                   "Prompt: {$prompt}\n" .
                   "Keywords: {$keywords}\n" .
                   "Image Size: {$image_size}\n" .
                   "Image Quality: {$image_quality}\n" .
                   "Image Style: {$image_style}\n" .
                   "Only return the image URL.";

	try {
		$image_response = easy_gpt_call_openai_image_api($full_prompt, $model, $image_size, $image_quality, $api_key, $post_id);
		//error_log("Respuesta de la imagen: " . print_r($image_response, true));

		if (!$image_response || empty($image_response['image_url'])) {
			$error_message = 'No image URL returned.';
			//error_log("Failed to generate image. Error: {$error_message}");
			wp_send_json_error(['message' => "Failed to generate image: {$error_message}"]);
			wp_die();
		}

		wp_send_json_success([
			'image_url' => $image_response['image_url'],
			'alt_text' => sanitize_text_field($alt_text),
			'title_text' => sanitize_text_field($title_text)
		]);

	} catch (Exception $e) {
		$error_message = $e->getMessage();
		//error_log("Failed to generate image. Exception: {$error_message}");
		wp_send_json_error(['message' => "Failed to generate image: {$error_message}"]);
		wp_die();
	}
}



function easy_gpt_call_openai_image_api($prompt, $model, $image_size, $image_quality, $api_key, $post_id) {
    global $easy_gpt_options;

	 $options = get_option('easy_gpt_options');
	
    // Sanitizar y validar los parámetros
    $prompt = sanitize_text_field($prompt);
    
    //error_log( '[EasyGPT][IMG] Prompt length: ' . strlen( $prompt ) );
//error_log( '[EasyGPT][IMG] Prompt (truncated to 300): ' . $prompt);

    $model = sanitize_text_field($model);
    $api_key = sanitize_text_field($api_key);
    $post_id = intval($post_id);
	
	$provider = 'openai';
	if (strpos($model, 'gemini-') === 0 || strpos($model, 'imagen-') === 0) {
		$provider = 'gemini';
	}

	// Obtener la API Key correcta para el proveedor
	switch ($provider) {
		case 'gemini':
			$api_key = $options['easy_gpt_gemini_api_key'] ?? '';
			break;
		case 'deepseek':
			$api_key = $options['easy_gpt_deepseek_api_key'] ?? '';
			break;
		case 'openai':
		default:
			$api_key = $options['easy_gpt_api_key'] ?? '';
			break;
	}

	switch ($provider) {
		case 'gemini':
			if (strpos($model, 'imagen-') === 0) {
				// Es un modelo de imagen
				$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:predict?key={$api_key}";
				$request_body = [
					"instances" => [
						["prompt" => $prompt]
					],
					"parameters" => [
						"sampleCount" => 1
					]
				];
			} else {
				// Es Gemini normal
				$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";
				$request_body = [
					"contents" => [[
						"parts" => [[ "text" => $prompt ]]
					]],
				];
			}
			break;

		case 'openai':
		default:
			$url = "https://api.openai.com/v1/images/generations";
			$request_body = [
				'model' => $model,
				'prompt' => $prompt
			];
			break;
	}

	$args = [
		'method'  => 'POST',
		'headers' => [
			'Content-Type' => 'application/json',
		],
		'body'    => wp_json_encode($request_body),
		'timeout' => 300,
	];

	// Solo añadir Authorization si es openai
	if ($provider === 'openai') {
		$args['headers']['Authorization'] = 'Bearer ' . $api_key;
	}

	$response = wp_remote_post($url, $args);

	if (is_wp_error($response)) {
		throw new Exception('Request error: ' . esc_html($response->get_error_message()));
	}

	$response_code = wp_remote_retrieve_response_code($response);
	$response_body = wp_remote_retrieve_body($response);
	$decodedResponse = json_decode($response_body, true); // <- ¡Aquí!

	if ($response_code != 200) {
		$error_message = 'Unknown error';
		if (!empty($decodedResponse['error']['message'])) {
			$error_message = $decodedResponse['error']['message'];
		} elseif (!empty($response_body)) {
			$error_message = $response_body; // Mostrar body entero si no hay error message
		}

		//error_log("[EasyGPT] API Error - Code: {$response_code} - Message: {$error_message}");
		//error_log("[EasyGPT] API Full Response: " . print_r($decodedResponse, true));

		throw new Exception('Request error: Response code ' . intval($response_code) . ' - ' . esc_html($error_message));
	}

	
    $response_body = wp_remote_retrieve_body($response);
    $decodedResponse = json_decode($response_body, true);
    
    if (isset($decodedResponse['error'])) {
        throw new Exception('API error: ' . esc_html($decodedResponse['error']['message']));
    }

    // Validar la respuesta de la API
	$image_url = '';

	if ($provider === 'openai') {
		if (!isset($decodedResponse['data'][0]['url'])) {
			throw new Exception('Invalid API response: No image URL found.');
		}
		$image_url = esc_url_raw($decodedResponse['data'][0]['url']);
	} elseif ($provider === 'gemini') {
		if (strpos($model, 'imagen-') === 0) {
			// Para modelos de imagen tipo imagen-3.0-generate-002
			if (!isset($decodedResponse['predictions'][0]['bytesBase64Encoded'])) {
				throw new Exception('Invalid API response: No image data found in Imagen model response.');
			}

			$base64_image = $decodedResponse['predictions'][0]['bytesBase64Encoded'];
		} else {
			// Para modelos de Gemini normales (que devuelven inline_data)
			if (!isset($decodedResponse['candidates'][0]['content']['parts'][0]['inline_data']['data'])) {
				throw new Exception('Invalid API response: No image data found in Gemini response.');
			}

			$base64_image = $decodedResponse['candidates'][0]['content']['parts'][0]['inline_data']['data'];
		}

		// Decodificar base64
		$image_data = base64_decode($base64_image);

		if ($image_data === false) {
			throw new Exception('Failed to decode base64 image from Gemini/Imagen response.');
		}

		// Guardar temporalmente la imagen y obtener URL temporal
		$upload_dir = wp_upload_dir();
		$filename = 'gemini_image_' . uniqid() . '.png';
		$file_path = trailingslashit($upload_dir['path']) . $filename;
		$file_url = trailingslashit($upload_dir['url']) . $filename;

		file_put_contents($file_path, $image_data);

		$image_url = esc_url_raw($file_url);
	} else {
		throw new Exception('Unsupported provider: ' . esc_html($provider));
	}



    // Las imágenes no usan tokens, así que los establecemos en 0 para esta operación
    $new_prompt_tokens = 0;
    $new_completion_tokens = 0;
    $new_total_tokens = 0;

    $image_cost = 0.0;
    
    // Verificar si el modelo seleccionado es un modelo de generación de imágenes
	if (in_array($model, ['dall-e-3', 'dall-e-2', 'imagen-3.0-generate-002'])) {
		if (isset($easy_gpt_options['model_costs'][$model]['image'])) {
			if ($model === 'dall-e-3') {
				if (isset($easy_gpt_options['model_costs'][$model]['image'][$image_quality][$image_size])) {
					$image_cost = floatval($easy_gpt_options['model_costs'][$model]['image'][$image_quality][$image_size]);
				} else {
					$image_cost = 0.0;
				}
			} elseif ($model === 'dall-e-2' || $model === 'imagen-3.0-generate-002') {
				if (isset($easy_gpt_options['model_costs'][$model]['image'][$image_size])) {
					$image_cost = floatval($easy_gpt_options['model_costs'][$model]['image'][$image_size]);
				} else {
					$image_cost = 0.0;
				}
			}
		}
	} else {
        // Manejar modelos de texto
        $output_cost_per_token = isset($easy_gpt_options['model_costs'][$model]['output']) ? floatval($easy_gpt_options['model_costs'][$model]['output']) : 0.0;
        $image_cost = $output_cost_per_token;
    }

    $total_cost = 0.0;

    if ($post_id) {
        // Obtener valores actuales de los metadatos del post
        $current_prompt_tokens = (int) get_post_meta($post_id, '_easy_gpt_prompt_tokens', true);
        $current_completion_tokens = (int) get_post_meta($post_id, '_easy_gpt_completion_tokens', true);
        $current_total_tokens = (int) get_post_meta($post_id, '_easy_gpt_total_tokens', true);
        $current_cost = (float) get_post_meta($post_id, '_easy_gpt_total_cost', true);

        // Actualizar el coste total
        $total_cost = $current_cost + $image_cost;

        // Actualizar los metadatos del post
        update_post_meta($post_id, '_easy_gpt_prompt_tokens', $current_prompt_tokens);
        update_post_meta($post_id, '_easy_gpt_completion_tokens', $current_completion_tokens);
        update_post_meta($post_id, '_easy_gpt_total_tokens', $current_total_tokens);
        update_post_meta($post_id, '_easy_gpt_total_cost', $total_cost);
    } else {
        if (!session_id()) {
            session_start();
        }
        if (!isset($_SESSION['token_usage'])) {
            $_SESSION['token_usage'] = [
                'prompt_tokens' => 0,
                'completion_tokens' => 0,
                'total_tokens' => 0,
                'total_cost' => 0.0
            ];
        }

        // Actualizar el coste total en la sesión
        $_SESSION['token_usage']['total_cost'] = isset($_SESSION['token_usage']['total_cost']) ? floatval($_SESSION['token_usage']['total_cost']) + $image_cost : $image_cost;
        $total_cost = isset($_SESSION['token_usage']['total_cost']) ? floatval($_SESSION['token_usage']['total_cost']) : $image_cost;
    }

    // Verificar si los índices existen antes de usarlos
    $session_prompt_tokens = isset($_SESSION['token_usage']['prompt_tokens']) ? intval($_SESSION['token_usage']['prompt_tokens']) : 0;
    $session_completion_tokens = isset($_SESSION['token_usage']['completion_tokens']) ? intval($_SESSION['token_usage']['completion_tokens']) : 0;
    $session_total_tokens = isset($_SESSION['token_usage']['total_tokens']) ? intval($_SESSION['token_usage']['total_tokens']) : 0;

    return [
        'image_url' => $image_url,
        'prompt_tokens' => $post_id ? $current_prompt_tokens : $session_prompt_tokens,
        'completion_tokens' => $post_id ? $current_completion_tokens : $session_completion_tokens,
        'total_tokens' => $post_id ? $current_total_tokens : $session_total_tokens,
        'total_cost' => $total_cost
    ];
}


function easy_gpt_call_openai_api($prompt, $model, $temperature, $api_key, $post_id) {
    global $easy_gpt_options;

	 $options = get_option('easy_gpt_options');
	
    $allowed_tags = array(
        'b' => array(),
        'i' => array(),
        'h2' => array(),
        'h3' => array(),
        'h4' => array(),
        'a' => array(
            'href' => array(),
            'title' => array(),
            'rel' => array(),
            'target' => array(),
        ),
        'ul' => array(),
        'ol' => array(),
        'li' => array(),
        'p' => array(),
    );

    // Sanitizar y validar los parámetros de entrada
    $prompt = wp_kses($prompt, $allowed_tags);
    $model = sanitize_text_field($model);
    $temperature = floatval($temperature);
    $post_id = intval($post_id);

	if (strpos($model, 'gemini-') === 0 || strpos($model, 'imagen-') === 0) {
		$provider = 'gemini';
	} elseif (strpos($model, 'deepseek-') === 0) {
		$provider = 'deepseek';
	} else {
		$provider = 'openai';
	}	

	// Obtener la API Key correcta para el proveedor
	switch ($provider) {
		case 'gemini':
			$api_key = $options['easy_gpt_gemini_api_key'] ?? '';
			break;
		case 'deepseek':
			$api_key = $options['easy_gpt_deepseek_api_key'] ?? '';
			break;
		case 'openai':
		default:
			$api_key = $options['easy_gpt_api_key'] ?? '';
			break;
	}

    $input_cost_per_token = isset($easy_gpt_options['model_costs'][$model]['input']) ? floatval($easy_gpt_options['model_costs'][$model]['input']) : 0.0;
    $output_cost_per_token = isset($easy_gpt_options['model_costs'][$model]['output']) ? floatval($easy_gpt_options['model_costs'][$model]['output']) : 0.0;
    
     if(strpos($model, 'gpt-5') !== false || strpos($model, 'o1') !== false  || strpos($model, 'o3') !== false || strpos($model, 'o4') !== false)
    {
        $temperature = 1;
    }

    // Determinar el endpoint correcto basado en el modelo
	switch ($provider) {
		case 'gemini':
			$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";
			$request_body = [
				"contents" => [[
					"parts" => [[ "text" => $prompt ]]
				]],
			];
			break;

		case 'deepseek':
			$url = "https://api.deepseek.com/v1/chat/completions";
			$request_body = [
				'model' => $model,
				'messages' => [['role' => 'user', 'content' => $prompt]],
				'temperature' => $temperature
			];
			break;

		case 'openai':
		default:
			if (strpos($model, 'gpt-5') !== false || strpos($model, 'gpt-4o') !== false || strpos($model, 'gpt-3.5-turbo') !== false || strpos($model, 'gpt-4') !== false || strpos($model, 'o1') !== false || strpos($model, 'o3') !== false || strpos($model, 'gpt-4.1') !== false || strpos($model, 'o4') !== false) {
				$url = "https://api.openai.com/v1/chat/completions";
				$request_body = [
					'model' => $model,
					'messages' => [['role' => 'user', 'content' => $prompt]],
					'temperature' => $temperature
				];
			} else {
				$url = "https://api.openai.com/v1/completions";
				$request_body = [
					'model' => $model,
					'prompt' => $prompt,
					'temperature' => $temperature
				];
			}
			break;
	}


	$args = [
		'method' => 'POST',
		'headers' => [
			'Content-Type' => 'application/json',
		],
		'body' => wp_json_encode($request_body),
		'timeout' => 300,
	];

	if ($provider === 'openai' || $provider === 'deepseek') {
		$args['headers']['Authorization'] = 'Bearer ' . $api_key;
	}

    $response = wp_remote_post($url, $args);

if (is_wp_error($response)) {
    throw new Exception('Request error: ' . esc_html($response->get_error_message()));
}

$response_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
$decodedResponse = json_decode($response_body, true);
if ($response_code != 200) {
    if ($response_code == 401) {
        throw new Exception(
            'Request error: Response code 401 - Invalid Authentication. This typically indicates an issue with your API key. Please verify that your API key is correct, has the necessary permissions, and belongs to the correct account or organization.'
        );
    }
    $error_message = isset($decodedResponse['error']['message']) ? $decodedResponse['error']['message'] : 'Unknown error';
    throw new Exception('Request error: Response code ' . intval($response_code) . ' - ' . esc_html($error_message));
    
}

    $response_body = wp_remote_retrieve_body($response);
    $decodedResponse = json_decode($response_body, true);

    if (isset($decodedResponse['error'])) {
        throw new Exception('API error: ' . esc_html($decodedResponse['error']['message']));
    }

	if ($provider === 'gemini') {
		$text_response = isset($decodedResponse['candidates'][0]['content']['parts'][0]['text'])
			? trim($decodedResponse['candidates'][0]['content']['parts'][0]['text'])
			: 'No content received from Gemini API.';

		return [
			'text' => $text_response,
			'prompt_tokens' => 0,
			'completion_tokens' => 0,
			'total_tokens' => 0,
			'total_cost' => 0.0
		];
	}

    // Manejo de tokens y metadatos
    if (isset($decodedResponse['usage'])) {
        // Validar y asegurar que los tokens sean enteros
        $new_prompt_tokens = isset($decodedResponse['usage']['prompt_tokens']) ? intval($decodedResponse['usage']['prompt_tokens']) : 0;
        $new_completion_tokens = isset($decodedResponse['usage']['completion_tokens']) ? intval($decodedResponse['usage']['completion_tokens']) : 0;
        $new_total_tokens = isset($decodedResponse['usage']['total_tokens']) ? intval($decodedResponse['usage']['total_tokens']) : 0;

        if ($post_id) {
            $current_prompt_tokens = (int) get_post_meta($post_id, '_easy_gpt_prompt_tokens', true);
            $current_completion_tokens = (int) get_post_meta($post_id, '_easy_gpt_completion_tokens', true);
            $current_total_tokens = (int) get_post_meta($post_id, '_easy_gpt_total_tokens', true);
            $current_cost = (float) get_post_meta($post_id, '_easy_gpt_total_cost', true);

            // Calcular los costes adicionales de esta llamada
            $input_cost = ($new_prompt_tokens / 1000) * $input_cost_per_token;
            $output_cost = ($new_completion_tokens / 1000) * $output_cost_per_token;
            $additional_cost = $input_cost + $output_cost;

            // Asegurar que los costos sean flotantes
            $additional_cost = floatval($additional_cost);

            // Actualizar el coste total acumulado
            $total_cost = $current_cost + $additional_cost;

            // Actualizar los metadatos del post con los valores acumulados
            update_post_meta($post_id, '_easy_gpt_prompt_tokens', $current_prompt_tokens + $new_prompt_tokens);
            update_post_meta($post_id, '_easy_gpt_completion_tokens', $current_completion_tokens + $new_completion_tokens);
            update_post_meta($post_id, '_easy_gpt_total_tokens', $current_total_tokens + $new_total_tokens);
            update_post_meta($post_id, '_easy_gpt_total_cost', $total_cost);
        } else {
            // Asegúrate de que la sesión esté iniciada
            if (!session_id()) {
                session_start();
            }
            if (!isset($_SESSION['token_usage'])) {
                $_SESSION['token_usage'] = [
                    'prompt_tokens' => 0,
                    'completion_tokens' => 0,
                    'total_tokens' => 0,
                    'total_cost' => 0.0
                ];
            }

            // Actualizar las variables de sesión
            $_SESSION['token_usage']['prompt_tokens'] += $new_prompt_tokens;
            $_SESSION['token_usage']['completion_tokens'] += $new_completion_tokens;
            $_SESSION['token_usage']['total_tokens'] += $new_total_tokens;

            // Calcular los costes adicionales de esta llamada
            $input_cost = ($new_prompt_tokens / 1000) * $input_cost_per_token;
            $output_cost = ($new_completion_tokens / 1000) * $output_cost_per_token;
            $additional_cost = $input_cost + $output_cost;

            // Asegurar que el costo adicional sea flotante
            $additional_cost = floatval($additional_cost);

            // Actualizar el coste total acumulado
            $_SESSION['token_usage']['total_cost'] += $additional_cost;
        }

        // Obtener la respuesta de texto
        $text_response = isset($decodedResponse['choices'][0]['message']['content'])
            ? trim($decodedResponse['choices'][0]['message']['content'])
            : (isset($decodedResponse['choices'][0]['text']) ? trim($decodedResponse['choices'][0]['text']) : '');

        // Verificar y asignar valores por defecto si las variables de sesión no existen
        $session_prompt_tokens = isset($_SESSION['token_usage']['prompt_tokens']) ? intval($_SESSION['token_usage']['prompt_tokens']) : 0;
        $session_completion_tokens = isset($_SESSION['token_usage']['completion_tokens']) ? intval($_SESSION['token_usage']['completion_tokens']) : 0;
        $session_total_tokens = isset($_SESSION['token_usage']['total_tokens']) ? intval($_SESSION['token_usage']['total_tokens']) : 0;
        $total_cost_session = isset($_SESSION['token_usage']['total_cost']) ? floatval($_SESSION['token_usage']['total_cost']) : 0.0;

        return [
            'text' => $text_response ?: "No content received from API.",
            'prompt_tokens' => $post_id ? $current_prompt_tokens + $new_prompt_tokens : $session_prompt_tokens,
            'completion_tokens' => $post_id ? $current_completion_tokens + $new_completion_tokens : $session_completion_tokens,
            'total_tokens' => $post_id ? $current_total_tokens + $new_total_tokens : $session_total_tokens,
            'total_cost' => $post_id ? $total_cost : $total_cost_session
        ];
    } else {
        return [
            'text' => "No token usage data received.",
            'prompt_tokens' => 0,
            'completion_tokens' => 0,
            'total_tokens' => 0,
            'total_cost' => 0.0
        ];
    }
}


add_action( 'wp_ajax_generate_article_init', 'easy_gpt_generate_article_init' );
function easy_gpt_generate_article_init() {
    check_ajax_referer( 'easy_gpt_save_metabox_data', 'nonce' );

    $job_id = uniqid( 'easygpt_', true );
    //error_log("[EasyGPT] 🔄 Job INIT: $job_id");

    set_transient( "easygpt_$job_id", [
        'status' => 'pending',
        'payload' => wp_unslash( $_POST )
    ], 15 * MINUTE_IN_SECONDS );

    wp_schedule_single_event( time() + 5, 'easygpt_run_job', [ $job_id ] );
    //error_log("[EasyGPT] 🕒 Scheduled job: $job_id");

    wp_send_json_success([ 'job_id' => $job_id ]);
}

add_action( 'easygpt_run_job', 'easygpt_run_job_cb' );
function easygpt_run_job_cb( $job_id ) {
    $job = get_transient( "easygpt_$job_id" );
    if ( ! $job || $job['status'] !== 'pending' ) return;

    $_POST = $job['payload']; // restaurar payload en $_POST si se mantiene así

    try {
        $result = easy_gpt_generate_article_sync( $job['payload'] );
        set_transient( "easygpt_$job_id", [
            'status' => 'done',
            'result' => $result
        ], 15 * MINUTE_IN_SECONDS );
    } catch (Throwable $e) {
        //error_log("[EasyGPT] ❌ Error in job $job_id: " . $e->getMessage());
        set_transient( "easygpt_$job_id", [
            'status' => 'done',
            'result' => [
                'success' => false,
                'message' => 'Error during article generation: ' . $e->getMessage()
            ]
        ], 15 * MINUTE_IN_SECONDS );
    }
}

add_action( 'wp_ajax_check_article_status', 'easygpt_check_article_status' );
function easygpt_check_article_status() {

    $job_id = sanitize_text_field( $_POST['job_id'] ?? '' );
    $job    = get_transient( "easygpt_$job_id" );

    //error_log("[EasyGPT] 🔍 Polling job: $job_id");

    // ↳ 1. Job no existe ⟶ error
    if ( ! $job ) {
        //error_log("[EasyGPT] ❌ Job $job_id not found");
        wp_send_json_error( [ 'status' => 'not_found' ] );
    }

    // ↳ 2. Job terminado ⟶ devolvemos resultado
    if ( $job['status'] === 'done' ) {
        //error_log("[EasyGPT] ✅ Job $job_id completed");
        wp_send_json_success( [
            'status' => 'done',
            'result' => $job['result']
        ] );
    }

    /*------------------------------------------------------------
     | 3. Job pendiente → comprobamos si su cron sigue programado |
     ------------------------------------------------------------*/
    if ( $job['status'] === 'pending' ) {

        // ¿Hay un evento programado para este job?
        $next = wp_next_scheduled( 'easygpt_run_job', [ $job_id ] );

        // Si no lo hay (p.ej. WP-Cron deshabilitado o se “perdió” el evento) lo re-programamos.
        if ( ! $next ) {
            //error_log( "[EasyGPT] 🚑 Job $job_id had no pending event – scheduling backup run" );
            wp_schedule_single_event( time() + 5, 'easygpt_run_job', [ $job_id ] );
        } 

        wp_send_json_success( [ 'status' => 'pending' ] );
    }

    // Fallback: algo no esperado
    wp_send_json_error( [ 'status' => 'unknown_state' ] );
}


add_action('init', 'easy_gpt_start_session', 1);
function easy_gpt_start_session() {
    /*if (!session_id()) {
        session_start();
    }*/
}

function easy_gpt_check_new_post() {
    // Asegurarse de que estamos en el área de administración
    if (is_admin()) {
        // Acceder a la pantalla actual de administración
        $screen = get_current_screen();

        // Comprobar si estamos creando una nueva entrada o página
        if ($screen && $screen->base === 'post' && ($screen->action === 'add' || (isset($_GET['action']) && $_GET['action'] === 'edit' && empty($_GET['post'])))) {
            if (!session_id()) {
                session_start();
            }
            // Restablecer los valores de la sesión para el seguimiento de costos y tokens
            $_SESSION['token_usage'] = [
                'prompt_tokens' => 0,
                'completion_tokens' => 0,
                'total_tokens' => 0,
                'total_cost' => 0.0
            ];
        }
    }
}
add_action('admin_head', 'easy_gpt_check_new_post');


add_action('wp_ajax_update_tokens_and_costs', 'easy_gpt_update_tokens_and_costs_handler');

function easy_gpt_update_tokens_and_costs_handler() {
    check_ajax_referer('easy_gpt_nonce', 'nonce');

    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    if (!$post_id) {
        wp_send_json_error(['message' => 'Invalid post ID']);
        wp_die();
    }

    $new_prompt_tokens = isset($_POST['new_prompt_tokens']) ? intval($_POST['new_prompt_tokens']) : 0;
    $new_completion_tokens = isset($_POST['new_completion_tokens']) ? intval($_POST['new_completion_tokens']) : 0;
    $new_total_tokens = isset($_POST['new_total_tokens']) ? intval($_POST['new_total_tokens']) : 0;
    $total_cost = isset($_POST['total_cost']) ? floatval($_POST['total_cost']) : 0.0;

    update_post_meta($post_id, '_easy_gpt_prompt_tokens', $new_prompt_tokens);
    update_post_meta($post_id, '_easy_gpt_completion_tokens', $new_completion_tokens);
    update_post_meta($post_id, '_easy_gpt_total_tokens', $new_total_tokens);
    update_post_meta($post_id, '_easy_gpt_total_cost', $total_cost);

    wp_send_json_success(['message' => 'Tokens and costs updated successfully']);
    wp_die();
}


add_action('load-post-new.php', 'easy_gpt_reset_tokens_and_costs');
function easy_gpt_reset_tokens_and_costs() {
    // Aquí estamos en la pantalla de creación de un nuevo post, restablecemos los valores de la sesión
    if (!session_id()) {
        session_start();
    }
    $_SESSION['token_usage'] = [
        'prompt_tokens' => 0,
        'completion_tokens' => 0,
        'total_tokens' => 0,
        'total_cost' => 0.0,
    ];
}

function easy_gpt_get_youtube_video_url($title, $keywords, $language, $include_video) {
    // Obtener opciones del plugin
    $options = get_option('easy_gpt_options');
    $api_key = $options['easy_gpt_youtube_api_key'] ?? '';


    // Verificar si la API Key está configurada y si el usuario ha habilitado la opción de incluir videos
    if (empty($api_key)) {
        //error_log("YouTube API Key is missing.");
        return ['video_url' => ''];
    }

    if ($include_video !== '1') {
        //error_log("YouTube video inclusion is disabled.");
        return ['video_url' => ''];
    }

    // Refinar palabras clave para mejorar la búsqueda
    $search_query = $keywords;
    $encoded_query = urlencode("\"{$search_query}\"");

    // Construir la URL con parámetros mejorados
$api_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q={$encoded_query}&type=video&maxResults=3&order=relevance&videoDuration=long&relevanceLanguage=" . strtolower($language) . "&key={$api_key}";

    //error_log("YouTube API Request: " . urldecode($api_url)); // Log para depuración

    // Hacer la solicitud a la API de YouTube
    $response = wp_remote_get($api_url);

    if (is_wp_error($response)) {
        //error_log("YouTube API Request failed: " . $response->get_error_message());
        return ['error' => 'YouTube API Request failed.'];
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['error'])) {
        //error_log("YouTube API Error: " . json_encode($data['error']));
        return ['error' => 'YouTube API Error: ' . $data['error']['message']];
    }

    // Comprobar si hay resultados
    if (!isset($data['items']) || empty($data['items'])) {
        return ['error' => 'No videos found.'];
    }

    // Iterar sobre los resultados y verificar si el video es embebible
    foreach ($data['items'] as $item) {
        $video_id = $item['id']['videoId'] ?? '';
        if (!$video_id) {
            continue;
        }

        // Consultar los detalles del video para verificar si se puede embeber
        $video_details_url = "https://www.googleapis.com/youtube/v3/videos?part=status&id={$video_id}&key={$api_key}";
        $video_response = wp_remote_get($video_details_url);

        if (is_wp_error($video_response)) {
            //error_log("Failed to retrieve video details: " . $video_response->get_error_message());
            continue;
        }

        $video_body = wp_remote_retrieve_body($video_response);
        $video_data = json_decode($video_body, true);

        if (isset($video_data['items'][0]['status']['embeddable']) && $video_data['items'][0]['status']['embeddable']) {
            $video_url = "<p>\nhttps://www.youtube.com/watch?v={$video_id}\n</p>";
            //error_log("Selected Video: {$video_url}");
            return ['video_url' => $video_url];
        }
    }

    return ['video_url' => ''];
}

add_action('admin_footer', 'easy_gpt_video_position_per_post_script');
function easy_gpt_video_position_per_post_script() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            // Seleccionar los elementos
            var select = $('#easy_gpt_video_position_per_post');
            var paragraphContainer = $('#easy_gpt_video_paragraph_container');

            // Función para mostrar u ocultar el campo de párrafos
            function toggleParagraphInput() {
                if (select.val() === 'after_paragraph') {
                    paragraphContainer.show();
                } else {
                    paragraphContainer.hide();
                }
                console.log("Video Position Changed to:", select.val());
            }

            // Inicializar el estado al cargar la página
            toggleParagraphInput();

            // Escuchar el cambio en el select
            select.on('change', toggleParagraphInput);
        });
    </script>
    <?php
}

?>