<?php
// Prevent direct access to this file.
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

// Include the options file
include 'easy-gpt-options.php';

// Include jQuery UI styles and scripts
function easy_gpt_enqueue_bulk_scripts($hook) {
    if ($hook == 'easy-gpt_page_easy-gpt-bulk-generate-new') {
        wp_enqueue_style('bulk-generation-css', plugins_url('../styles/bulk-generation.css', __FILE__));
        wp_enqueue_script('bulk-generation-js', plugins_url('../js/bulk-generation.js', __FILE__), array('jquery'), false, true);
        wp_enqueue_script('jquery-ui-tabs');
        wp_enqueue_style('wp-jquery-ui-dialog');
    
        // 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/bulk-generation.js', __FILE__), ['jquery', 'tiny_mce'], false, true);

        add_action('admin_notices', 'easy_gpt_remove_other_notices', 1);
        // Custom admin styles for specific page
        wp_add_inline_style('bulk-generation-css', "
            .easy-gpt-license-alert {
                border-left: 4px solid #d63638; /* Red color side border */
                background-color: #ffe8e8; /* Light grey background for better contrast */
                padding: 15px 20px; /* Padding for better spacing */
                margin-bottom: 20px; /* Margin bottom for spacing from other elements */
                border-radius: 5px; /* Rounded corners */
                font-weight:bold;
            }
            .easy-gpt-license-alert strong {
                color: #d63638; /* Red color for emphasis */
            }
            .easy-gpt-license-alert a {
                color: #0073aa; /* Default WordPress link color */
                text-decoration: underline;
            }
        ");
    }
}
add_action('admin_enqueue_scripts', 'easy_gpt_enqueue_bulk_scripts');

function easy_gpt_remove_other_notices() {
    remove_all_actions('admin_notices');
    remove_all_actions('all_admin_notices');
}

function easy_gpt_bulk_generate_page() {

    $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 class="wrap"><h2>Bulk Generation for Easy GPT</h2>';
        echo '<div class="easy-gpt-license-alert">';
        echo '<p><strong>Attention:</strong> Your license is either invalid or has expired. If this is your first time using Easy GPT, 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></div>';
        return; // Exit function if license is not valid
    }
    
    global $easy_gpt_options; // Access global options array

    // Access global options array
    $options = get_option('easy_gpt_options');
    
    // Use default values from settings
$cost = $options['easy_gpt_cost'] ?? '0$';
$model = $options['easy_gpt_model'] ?? 'gpt-4o';
$temperature = $options['easy_gpt_temperature'] ?? '0.7';
$min_words = $options['easy_gpt_min_words'] ?? '300';
$max_words = $options['easy_gpt_max_words'] ?? '1000';
$num_subheadings = $options['easy_gpt_num_subheadings'] ?? '3';

$subheading_type_h3 = isset( $options['easy_gpt_subheading_type_h3'] ) ? $options['easy_gpt_subheading_type_h3'] : '0';
$subheading_type_h4 = isset( $options['easy_gpt_subheading_type_h4'] ) ? $options['easy_gpt_subheading_type_h4'] : '0';
$format_article = isset( $options['easy_gpt_format_article'] ) ? $options['easy_gpt_format_article'] : '0';
$auto_categories = isset( $options['easy_gpt_auto_categories'] ) ? $options['easy_gpt_auto_categories'] : '0';
$auto_tags = isset( $options['easy_gpt_auto_tags'] ) ? $options['easy_gpt_auto_tags'] : '0';
$auto_seo = isset( $options['easy_gpt_auto_seo'] ) ? $options['easy_gpt_auto_seo'] : '0';

$image_model = $options['easy_gpt_image_model'] ?? 'dall-e-3';
$auto_images = isset( $options['easy_gpt_auto_images'] ) ? $options['easy_gpt_auto_images'] : '0';
$num_images = $options['easy_gpt_num_images'] ?? '1';
$image_size = $options['easy_gpt_image_size'] ?? '1024x1024';
$image_quality = $options['easy_gpt_image_quality'] ?? 'standard';

$writing_style = $options['easy_gpt_writing_style'] ?? 'Formal';
$writing_tone = $options['easy_gpt_writing_tone'] ?? 'Neutral';
$image_style = $options['easy_gpt_image_style'] ?? '';

$include_excerpt = isset( $options['easy_gpt_include_excerpt'] ) ? $options['easy_gpt_include_excerpt'] : '0';
$default_language = $options['easy_gpt_default_language'] ?? 'en';
$set_featured_image = isset( $options['easy_gpt_set_featured_image'] ) ? $options['easy_gpt_set_featured_image'] : '0';
$include_links = isset( $options['easy_gpt_include_links'] ) ? $options['easy_gpt_include_links'] : '0';
$include_bibliography = isset( $options['easy_gpt_include_bibliography'] ) ? $options['easy_gpt_include_bibliography'] : '0';

$include_videos_bulk = isset($options['easy_gpt_include_videos']) ? $options['easy_gpt_include_videos'] : '0';
$video_position_bulk = isset($options['easy_gpt_video_position']) ? $options['easy_gpt_video_position'] : 'end';
$video_paragraph_bulk = isset($options['easy_gpt_video_paragraph']) ? $options['easy_gpt_video_paragraph'] : 3;
$include_citations_bulk = isset($options['easy_gpt_include_citations']) ? $options['easy_gpt_include_citations'] : '0';
$final_review_bulk = isset($options['easy_gpt_final_review']) ? $options['easy_gpt_final_review'] : '0';
	
$provider = $options['easy_gpt_text_api_provider'] ?? 'openai';

	

$image_provider = $options['easy_gpt_image_api_provider'] ?? 'openai';

	
	if (defined('WP_DEBUG') && WP_DEBUG) {
    //error_log('---- DEBUG EASY GPT BULK GENERATION PAGE ----');
    //error_log('easy_gpt_options: ' . print_r($options, true));
    //error_log('Selected text provider: ' . $provider);
    //error_log('Selected model: ' . $model);
    //error_log('Filtered models: ' . print_r($filtered_models, true));
    //error_log('Selected image provider: ' . $image_provider);
    //error_log('Selected image model: ' . $image_model);
    //error_log('Filtered image models: ' . print_r($filtered_image_models, true));
    //error_log('--------------------------------------------');
}
	
    ?>
<div class="wrap">
    <h2><?php esc_html_e( 'Bulk Generation for Easy GPT', 'easy-gpt-for-wp' ); ?></h2>
    <form id="easy-gpt-bulk-generation-form">
        <?php wp_nonce_field( 'save_bulk_generation_nonce', 'easy_gpt_nonce' ); ?>
        <div id="easy-gpt-tabs">
            <ul>
                <li><a href="#tab-1"><?php esc_html_e( 'Generate Articles', 'easy-gpt-for-wp' ); ?></a></li>
                <li><a href="#tab-2"><?php esc_html_e( 'Articles Settings', 'easy-gpt-for-wp' ); ?></a></li>
                <li><a href="#tab-3"><?php esc_html_e( 'Images Settings', 'easy-gpt-for-wp' ); ?></a></li>
            </ul>
            <div id="tab-1">
                <table class="form-table easy-gpt-table">
                    <tr>
                        <td class="easy-gpt-column" style="max-width: 300px;">
                            <!-- Toggle para elegir entre Articles y Products -->
                            <?php if ( class_exists( 'WooCommerce' ) ) : ?>
                                <div class="easy-gpt-field">
                                    <label for="content_type"><?php esc_html_e('Content Type:', 'easy-gpt-for-wp'); ?></label>
                                    <div class="toggle-container">
                                        <span class="toggle-label articles-label active">Articles</span>
                                        <label class="switch">
                                            <input type="checkbox" id="content_type_toggle">
                                            <span class="slider round"></span>
                                        </label>
                                        <span class="toggle-label products-label">Products</span>
                                        <input type="hidden" id="content_type" name="content_type" value="article">
                                    </div>
                                </div>
                            <?php endif; ?>


                            
                            <!-- Número de artículos/productos -->
                            <div class="easy-gpt-field">
                                <label for="easy_gpt_number_of_articles"><?php esc_html_e('Number of Items:', 'easy-gpt-for-wp'); ?></label>
                                <input type="number" id="easy_gpt_number_of_articles" name="easy_gpt_number_of_articles" min="1" max="50" step="1" value="1">
                            </div>
                            
                            <!-- Checkbox para habilitar la generación de precios (visible solo si se eligen productos) -->
                            <div class="easy-gpt-field" id="price-option-container" style="display: none;">
                                <label for="enable_product_prices"><?php esc_html_e('Generate with Prices?', 'easy-gpt-for-wp'); ?></label>
                                <label class="switch">
                                    <input type="checkbox" id="enable_product_prices" name="enable_product_prices">
                                    <span class="slider round"></span>
                                </label>
                            </div>
                            
                            <!-- Campo para especificar precios (visible solo si se activa la opción de precios) -->
                            <div class="easy-gpt-field" id="price-input-container" style="display: none;">
                                <label for="easy_gpt_product_prices"><?php esc_html_e('Specify Prices (one per line):', 'easy-gpt-for-wp'); ?></label>
                                <textarea id="easy_gpt_product_prices" name="easy_gpt_product_prices" rows="2" cols="50"></textarea>
                                <p class="description"><?php esc_html_e('Leave blank to let the AI generate the price automatically.', 'easy-gpt-for-wp'); ?></p>
                            </div>

                            <div class="easy-gpt-field">
                                <label for="easy_gpt_prompt"><?php esc_html_e( 'Prompt (one line per article): ', 'easy-gpt-for-wp' ); ?><span style="color: red;">*</span></label>
                                <textarea id="easy_gpt_prompt" name="easy_gpt_prompt" rows="4" cols="50" required></textarea>
                            </div>
                            <div class="easy-gpt-field">
                                <label for="easy_gpt_keywords"><?php esc_html_e( 'Keywords (one line per article): ', 'easy-gpt-for-wp' ); ?><span style="color: red;">*</span></label>
                                <textarea id="easy_gpt_keywords" name="easy_gpt_keywords" rows="4" cols="50" required></textarea>
                            </div>
                            <div class="easy-gpt-field">
                                <div id="generate-all-article">
                                    <button type="button" id="generate-all" class="button button-primary"><?php esc_html_e( 'Generate Articles', 'easy-gpt-for-wp' ); ?></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"><?php esc_html_e( 'Specific Instructions for Title (one line per article):', 'easy-gpt-for-wp' ); ?></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"><?php esc_html_e( 'Use as Title', 'easy-gpt-for-wp' ); ?></label>
                                </div>
                                <div class="easy-gpt-inline">
                                    <input type="checkbox" id="use_same_specific_title_instructions" name="use_same_specific_title_instructions" class="adjusted-checkbox">
                                    <label for="use_same_specific_title_instructions" class="normal-label"><?php esc_html_e( 'Use same Title instructions for all articles', 'easy-gpt-for-wp' ); ?></label>
                                </div>
                            </div>
                            <div class="easy-gpt-field">
                                <label for="easy_gpt_specific_instructions_outline"><?php esc_html_e( 'Specific Instructions for Outline (one line per article):', 'easy-gpt-for-wp' ); ?></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_same_specific_outline_instructions" name="use_same_specific_outline_instructions" class="adjusted-checkbox">
                                    <label for="use_same_specific_outline_instructions" class="normal-label"><?php esc_html_e( 'Use same Outline instructions for all articles', 'easy-gpt-for-wp' ); ?></label>
                                </div>
                            </div>
                            <div class="easy-gpt-field">
                                <label for="easy_gpt_specific_instructions_content"><?php esc_html_e( 'Specific Instructions for Content (one line per article):', 'easy-gpt-for-wp' ); ?></label>
                                <textarea id="easy_gpt_specific_instructions_content" name="easy_gpt_specific_instructions_content" rows="2" cols="50"></textarea>
                                <div class="easy-gpt-inline">
                                    <input type="checkbox" id="use_same_specific_content_instructions" name="use_same_specific_content_instructions" class="adjusted-checkbox">
                                    <label for="use_same_specific_content_instructions" class="normal-label"><?php esc_html_e( 'Use same Content instructions for all articles', 'easy-gpt-for-wp' ); ?></label>
                                </div>
                            </div>
                            <div class="easy-gpt-field">
                                <label for="easy_gpt_specific_instructions_excerpt" id="excerpt_instructions_label"><?php esc_html_e( 'Specific Instructions for Excerpt (one line per article):', 'easy-gpt-for-wp' ); ?></label>
                                <textarea id="easy_gpt_specific_instructions_excerpt" name="easy_gpt_specific_instructions_excerpt" rows="2" cols="50"></textarea>
                                <div class="easy-gpt-inline">
                                    <input type="checkbox" id="use_same_specific_excerpt_instructions" name="use_same_specific_excerpt_instructions" class="adjusted-checkbox">
                                    <label for="use_same_specific_excerpt_instructions" class="normal-label"><?php esc_html_e( 'Use same Excerpt instructions for all articles', 'easy-gpt-for-wp' ); ?></label>
                                </div>
                            </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 ); ?>">
                                            <?php
                                            /* translators: %d: image number */
                                            printf( esc_html__( 'Image %d', 'easy-gpt-for-wp' ), 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 ); ?>">
                                                <?php
                                                /* translators: %d: image number */
                                                printf( esc_html__( 'Image Prompt %d (one line per article):', 'easy-gpt-for-wp' ), 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>
                                        </div>
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <div id="publishing-options">
                                <h3><?php esc_html_e( 'Publishing Options', 'easy-gpt-for-wp' ); ?></h3>
                                <div class="easy-gpt-field">
                                    <label for="publish_action"><?php esc_html_e( 'Action after generation:', 'easy-gpt-for-wp' ); ?></label>
                                    <select id="publish_action" name="publish_action">
                                        <option value="publish_immediately"><?php esc_html_e( 'Publish Immediately', 'easy-gpt-for-wp' ); ?></option>
                                        <option value="save_draft"><?php esc_html_e( 'Save as Draft', 'easy-gpt-for-wp' ); ?></option>
                                        <option value="schedule"><?php esc_html_e( 'Schedule for Later', 'easy-gpt-for-wp' ); ?></option>
                                    </select>
                                </div>
                                <div id="schedule-options" style="display: none;">
                                    <div class="easy-gpt-field">
                                        <label for="publish_frequency"><?php esc_html_e( 'Frequency of Publication:', 'easy-gpt-for-wp' ); ?></label>
                                        <select id="publish_frequency" name="publish_frequency">
                                            <option value="daily"><?php esc_html_e( 'Daily', 'easy-gpt-for-wp' ); ?></option>
                                            <option value="weekly"><?php esc_html_e( 'Weekly', 'easy-gpt-for-wp' ); ?></option>
                                            <option value="monthly"><?php esc_html_e( 'Monthly', 'easy-gpt-for-wp' ); ?></option>
                                        </select>
                                    </div>
									<div class="easy-gpt-field" id="just_in_time_container">
										<label for="just_in_time_generation">
											<input type="checkbox" id="just_in_time_generation" name="just_in_time_generation" value="1">
											<?php esc_html_e('Generate each article just-in-time (on its scheduled time)', 'easy-gpt-for-wp'); ?>
										</label>
										<p class="description"><?php esc_html_e('Articles will be generated and published shortly after their scheduled time, when the background job runs.', 'easy-gpt-for-wp'); ?></p>
									</div>
                                    <div class="easy-gpt-field">
                                        <label for="start_date"><?php esc_html_e( 'Start Date:', 'easy-gpt-for-wp' ); ?></label>
                                        <input type="date" id="start_date" name="start_date">
                                    </div>
                                    <div class="easy-gpt-field">
                                        <label for="start_time"><?php esc_html_e( 'Start Time:', 'easy-gpt-for-wp' ); ?></label>
                                        <input type="time" id="start_time" name="start_time">
                                    </div>
                                    <div class="easy-gpt-field">
                                        <label for="articles_per_interval"><?php esc_html_e( 'Number of Articles per Interval:', 'easy-gpt-for-wp' ); ?></label>
                                        <input type="number" id="articles_per_interval" name="articles_per_interval" min="1" value="1">
                                    </div>
									<div class="easy-gpt-field" id="minutes_between_articles_container" style="display: none;">
										<label for="minutes_between_articles"><?php esc_html_e( 'Minutes Between Articles:', 'easy-gpt-for-wp' ); ?></label>
										<input type="number" id="minutes_between_articles" name="minutes_between_articles" min="1" value="30">
									</div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div id="tab-2">
				<p class="easy-gpt-field">
					<label for="easy_gpt_text_provider">Text API Provider</label>
					<select id="easy_gpt_text_provider" name="easy_gpt_text_provider">
						<option value="openai" <?php selected( $provider, 'openai' ); ?>>OpenAI</option>
						<option value="gemini" <?php selected( $provider, 'gemini' ); ?>>Gemini</option>
						<option value="deepseek" <?php selected( $provider, 'deepseek' ); ?>>DeepSeek</option>
					</select>
				</p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_model"><?php esc_html_e( 'GPT Model:', 'easy-gpt-for-wp' ); ?></label>
					<select id="easy_gpt_model" name="easy_gpt_model">
						<?php foreach ($easy_gpt_options['models'] as $model_option) :
							$model_provider = 'openai';
							if (strpos($model_option, 'gemini-') === 0) {
								$model_provider = 'gemini';
							} elseif (strpos($model_option, 'deepseek-') === 0) {
								$model_provider = 'deepseek';
							}
						?>
							<option value="<?php echo esc_attr($model_option); ?>" data-api="<?php echo esc_attr($model_provider); ?>" <?php selected($model, $model_option); ?>>
								<?php echo esc_html($model_option); ?>
							</option>
						<?php endforeach; ?>
					</select>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_temperature"><?php esc_html_e( 'Temperature:', 'easy-gpt-for-wp' ); ?></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_author_bulk"><?php _e('Author:', 'easy-gpt-for-wp'); ?></label>
                    <select id="easy_gpt_default_author_bulk" name="easy_gpt_default_author">
                        <?php
                        $users = get_users();
                        $selected_author = $options['easy_gpt_default_author'] ?? get_current_user_id();
                        foreach ( $users as $user ) {
                            printf(
                                '<option value="%d" %s>%s</option>',
                                $user->ID,
                                selected( $selected_author, $user->ID, false ),
                                esc_html( $user->display_name )
                            );
                        }
                        ?>
                    </select>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_default_language"><?php esc_html_e( 'Language:', 'easy-gpt-for-wp' ); ?></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( $default_language, $code ); ?>>
                                <?php echo esc_html( $language ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_min_words"><?php esc_html_e( 'Minimum Number of Words:', 'easy-gpt-for-wp' ); ?></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_html( $min_words ); ?></output>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_max_words"><?php esc_html_e( 'Maximum Number of Words:', 'easy-gpt-for-wp' ); ?></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_html( $max_words ); ?></output>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_num_subheadings"><?php esc_html_e( 'Number of H2 Subheadings:', 'easy-gpt-for-wp' ); ?></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_bulk" class="black-label"><?php esc_html_e( 'Include Citations in Text:', 'easy-gpt-for-wp' ); ?></label>
					<input type="checkbox" id="easy_gpt_include_citations_bulk" name="easy_gpt_include_citations_bulk" <?php checked( $include_citations_bulk, '1' ); ?> class="adjusted-checkbox">
					<small><?php esc_html_e( 'Insert blockquotes with author names when appropriate.', '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_bulk" class="black-label"><?php esc_html_e( 'Final AI-Based Review:', 'easy-gpt-for-wp' ); ?></label>
					<input type="checkbox" id="easy_gpt_final_review_bulk" name="easy_gpt_final_review_bulk" <?php checked( $final_review_bulk, '1' ); ?> class="adjusted-checkbox">
					<small><?php esc_html_e( 'Run a final AI review to improve coherence and style.', '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_bulk" class="black-label"><?php esc_html_e( 'Include Videos:', 'easy-gpt-for-wp' ); ?></label>
                    <input type="checkbox" id="easy_gpt_include_videos_bulk" name="easy_gpt_include_videos_bulk" <?php checked( $include_videos_bulk, '1' ); ?> class="adjusted-checkbox">
                    <small><?php esc_html_e( 'Check this box to include a YouTube video in each article.', 'easy-gpt-for-wp' ); ?></small>
                </p>
                
                <p class="easy-gpt-field">
                    <label for="easy_gpt_video_position_bulk"><?php esc_html_e( 'Video Position:', 'easy-gpt-for-wp' ); ?></label>
                    <select id="easy_gpt_video_position_bulk" name="easy_gpt_video_position_bulk">
                        <option value="start" <?php selected( $video_position_bulk, 'start' ); ?>><?php esc_html_e( 'Start', 'easy-gpt-for-wp' ); ?></option>
                        <option value="end" <?php selected( $video_position_bulk, 'end' ); ?>><?php esc_html_e( 'End', 'easy-gpt-for-wp' ); ?></option>
                        <option value="random" <?php selected( $video_position_bulk, 'random' ); ?>><?php esc_html_e( 'Random', 'easy-gpt-for-wp' ); ?></option>
                        <option value="after_paragraph" <?php selected( $video_position_bulk, '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 each article.', 'easy-gpt-for-wp' ); ?></small></p>
                </p>
                
                <p class="easy-gpt-field" id="easy_gpt_video_paragraph_container_bulk" style="display: <?php echo ( $video_position_bulk === 'after_paragraph' ) ? 'block' : 'none'; ?>;">
                    <label for="easy_gpt_video_paragraph_bulk"><?php esc_html_e( 'Number of Paragraphs:', 'easy-gpt-for-wp' ); ?></label>
                    <input type="number" id="easy_gpt_video_paragraph_bulk" name="easy_gpt_video_paragraph_bulk" min="1" value="<?php echo esc_attr( $video_paragraph_bulk ); ?>"></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_provider">Image API Provider</label>
					<select id="easy_gpt_image_provider" name="easy_gpt_image_provider">
						<option value="openai" <?php selected( $image_provider, 'openai' ); ?>>OpenAI</option>
						<option value="gemini" <?php selected( $image_provider, 'gemini' ); ?>>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) :
							$model_provider = 'openai';
							if (strpos($model_option, 'gemini-') === 0 || strpos($model_option, 'imagen-') === 0) {
								$model_provider = 'gemini';
							}
						?>
							<option value="<?php echo esc_attr($model_option); ?>" data-api="<?php echo esc_attr($model_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"><?php esc_html_e( 'Select Image Size:', 'easy-gpt-for-wp' ); ?></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( $image_size, $key ); ?>>
                                <?php echo esc_html( $size ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_image_quality"><?php esc_html_e( 'Choose Image Quality:', 'easy-gpt-for-wp' ); ?></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( $image_quality, $key ); ?>>
                                <?php echo esc_html( $quality ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </p>
                <p class="easy-gpt-field">
                    <label for="easy_gpt_image_style"><?php esc_html_e( 'Image Style:', 'easy-gpt-for-wp' ); ?></label>
                    <input type="text" id="easy_gpt_image_style" name="easy_gpt_image_style" value="<?php echo esc_attr( $image_style ); ?>" placeholder="<?php esc_attr_e( 'e.g., Realistic, Drawing, Anime', 'easy-gpt-for-wp' ); ?>">
                </p>
            </div>
        </div>
    </form>
</div>

    <?php
        wp_enqueue_script('bulk-generation-another-js', plugins_url('../js/bulk-generation-another.js', __FILE__), array('jquery'), false, true);
    ?>
    <?php
}

// Hook para WordPress AJAX para usuarios autenticados
add_action('wp_ajax_save_bulk_generation', 'easy_gpt_handle_save_bulk_generation');

function easy_gpt_handle_save_bulk_generation() {
    global $wpdb;
    
    //error_log("POST completo: " . print_r($_POST, true));

    // Verificar el nonce para seguridad
    check_ajax_referer('save_bulk_generation_nonce', 'nonce');

    // Inicializar el array de datos
    $data = array();

    // Obtener el ID del usuario actual
    $data['user_id'] = isset($_POST['user_id'])
    ? intval($_POST['user_id'])
    : get_current_user_id();  

    // Procesar y sanitizar cada campo individualmente
    $data['prompt'] = isset($_POST['prompt_article']) ? sanitize_textarea_field(wp_unslash($_POST['prompt_article'])) : '';
    $data['keywords'] = isset($_POST['keywords']) ? sanitize_textarea_field(wp_unslash($_POST['keywords'])) : '';
    $data['num_articles'] = isset($_POST['num_articles']) ? intval($_POST['num_articles']) : 0;
    $data['model'] = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : '';
    $data['temperature'] = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.0;
    $data['language'] = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
    $data['min_words'] = isset($_POST['min_words']) ? intval($_POST['min_words']) : 0;
    $data['max_words'] = isset($_POST['max_words']) ? intval($_POST['max_words']) : 0;
    $data['num_subheadings'] = isset($_POST['num_subheadings']) ? intval($_POST['num_subheadings']) : 0;
    $data['subheading_types'] = isset($_POST['subheading_types']) ? sanitize_text_field(wp_unslash($_POST['subheading_types'])) : '';
    $data['format_article'] = isset($_POST['format_article']) ? intval($_POST['format_article']) : 0;
    $data['include_links'] = isset($_POST['include_links']) ? intval($_POST['include_links']) : 0;
    $data['include_bibliography'] = isset($_POST['include_bibliography']) ? intval($_POST['include_bibliography']) : 0;
    $data['auto_categories'] = isset($_POST['auto_categories']) ? intval($_POST['auto_categories']) : 0;
    $data['auto_tags'] = isset($_POST['auto_tags']) ? intval($_POST['auto_tags']) : 0;
    $data['enable_seo'] = isset($_POST['enable_seo']) ? intval($_POST['enable_seo']) : 0;
    $data['writing_style'] = isset($_POST['writing_style']) ? sanitize_text_field(wp_unslash($_POST['writing_style'])) : '';
    $data['writing_tone'] = isset($_POST['writing_tone']) ? sanitize_text_field(wp_unslash($_POST['writing_tone'])) : '';
    $data['include_excerpt'] = isset($_POST['include_excerpt']) ? intval($_POST['include_excerpt']) : 0;
    $data['image_model'] = isset($_POST['image_model']) ? sanitize_text_field(wp_unslash($_POST['image_model'])) : '';
    $data['auto_images'] = isset($_POST['auto_images']) ? intval($_POST['auto_images']) : 0;
    $data['num_images'] = isset($_POST['num_images']) ? intval($_POST['num_images']) : 0;
    $data['image_size'] = isset($_POST['image_size']) ? sanitize_text_field(wp_unslash($_POST['image_size'])) : '';
    $data['image_quality'] = isset($_POST['image_quality']) ? sanitize_text_field(wp_unslash($_POST['image_quality'])) : '';
    $data['image_style'] = isset($_POST['image_style']) ? sanitize_text_field(wp_unslash($_POST['image_style'])) : '';
    $data['set_featured_image'] = isset($_POST['set_featured_image']) ? intval($_POST['set_featured_image']) : 0;
    $data['publish_action'] = isset($_POST['publish_action']) ? sanitize_text_field(wp_unslash($_POST['publish_action'])) : '';
    $data['publish_frequency'] = isset($_POST['publish_frequency']) ? sanitize_text_field(wp_unslash($_POST['publish_frequency'])) : '';
    $data['start_date'] = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : '';
    $data['start_time'] = isset($_POST['start_time']) ? sanitize_text_field(wp_unslash($_POST['start_time'])) : '';
    $data['articles_per_interval'] = isset($_POST['articles_per_interval']) ? intval($_POST['articles_per_interval']) : 0;
    $data['specific_instructions_title'] = isset($_POST['specific_instructions_title']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_title'])) : '';
    $data['use_specific_title_instructions'] = isset($_POST['use_specific_title_instructions']) ? intval($_POST['use_specific_title_instructions']) : 0;
    $data['use_same_specific_title_instructions'] = isset($_POST['use_same_specific_title_instructions']) ? intval($_POST['use_same_specific_title_instructions']) : 0;
    $data['specific_instructions_outline'] = isset($_POST['specific_instructions_outline']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_outline'])) : '';
    $data['use_same_specific_outline_instructions'] = isset($_POST['use_same_specific_outline_instructions']) ? intval($_POST['use_same_specific_outline_instructions']) : 0;
    $data['specific_instructions_content'] = isset($_POST['specific_instructions_content']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_content'])) : '';
    $data['use_same_specific_content_instructions'] = isset($_POST['use_same_specific_content_instructions']) ? intval($_POST['use_same_specific_content_instructions']) : 0;
    $data['specific_instructions_excerpt'] = isset($_POST['specific_instructions_excerpt']) ? sanitize_textarea_field(wp_unslash($_POST['specific_instructions_excerpt'])) : '';
    $data['use_same_specific_excerpt_instructions'] = isset($_POST['use_same_specific_excerpt_instructions']) ? intval($_POST['use_same_specific_excerpt_instructions']) : 0;
	
    


    // Procesar 'image_prompts' (array)
    if ( isset( $_POST['image_prompts'] ) && is_array( $_POST['image_prompts'] ) ) {
        // Sanitizar cada elemento directamente durante la asignaci��n
        $sanitized_image_prompts = array_map( 'sanitize_text_field', wp_unslash( $_POST['image_prompts'] ) );
    
        // Validar los datos si es necesario
        $sanitized_image_prompts = array_filter( $sanitized_image_prompts );
    
        // Asignar los datos sanitizados y serializados
        $data['image_prompts'] = maybe_serialize( $sanitized_image_prompts );
    } else {
        $data['image_prompts'] = '';
    }

    // Procesar 'use_same_image_prompts' (array)
    if ( isset( $_POST['use_same_image_prompts'] ) && is_array( $_POST['use_same_image_prompts'] ) ) {
        // Sanitizar cada elemento directamente durante la asignaci��n
        $sanitized_use_same_image_prompts = array_map( 'sanitize_text_field', wp_unslash( $_POST['use_same_image_prompts'] ) );
        
        // Validar los datos si es necesario
        $sanitized_use_same_image_prompts = array_filter( $sanitized_use_same_image_prompts );
    
        // Asignar los datos sanitizados y serializados
        $data['use_same_image_prompts'] = maybe_serialize( $sanitized_use_same_image_prompts );
    } else {
        $data['use_same_image_prompts'] = '';
    }
    
    //error_log("articulo o producto:");
    //error_log(isset($_POST['content_type']) ? sanitize_text_field($_POST['content_type']) : 'article');
    $data['content_type'] = isset($_POST['content_type']) ? sanitize_text_field($_POST['content_type']) : 'article';
    $data['enable_product_prices'] = isset($_POST['enable_product_prices']) ? intval($_POST['enable_product_prices']) : 0;
    $data['product_prices'] = isset($_POST['product_prices']) ? sanitize_textarea_field(wp_unslash($_POST['product_prices'])) : '';

    $data['include_videos_bulk'] = isset($_POST['easy_gpt_include_videos_bulk']) ? intval($_POST['easy_gpt_include_videos_bulk']) : 0;
    $data['video_position_bulk'] = isset($_POST['easy_gpt_video_position_bulk']) ? sanitize_text_field(wp_unslash($_POST['easy_gpt_video_position_bulk'])) : 'end';
    $data['video_paragraph_bulk'] = isset($_POST['easy_gpt_video_paragraph_bulk']) ? intval($_POST['easy_gpt_video_paragraph_bulk']) : 3;

$data['include_citations_bulk'] = isset($_POST['easy_gpt_include_citations_bulk']) ? intval($_POST['easy_gpt_include_citations_bulk']) : 0;
$data['final_review_bulk'] = isset($_POST['easy_gpt_final_review_bulk']) ? intval($_POST['easy_gpt_final_review_bulk']) : 0;
	$data['minutes_between_articles'] = isset($_POST['minutes_between_articles']) ? intval($_POST['minutes_between_articles']) : 0;
	$data['just_in_time_generation'] = isset($_POST['just_in_time_generation']) ? intval($_POST['just_in_time_generation']) : 0;





	
	//error_log('Valores recibidos para insert (easy_gpt_handle_save_bulk_generation):');
foreach ($data as $key => $value) {
    //error_log("$key => " . var_export($value, true));
}
    //error_log("vamos a insertar");
    // Inserción en la base de datos
    $table_name = $wpdb->prefix . 'bulk_generations';

    $format = array(
        '%d', // user_id
        '%s', // prompt
        '%s', // keywords
        '%d', // num_articles
        '%s', // model
        '%f', // temperature
        '%s', // language
        '%d', // min_words
        '%d', // max_words
        '%d', // num_subheadings
        '%s', // subheading_types
        '%d', // format_article
        '%d', // include_links
        '%d', // include_bibliography
        '%d', // auto_categories
        '%d', // auto_tags
        '%d', // enable_seo
        '%s', // writing_style
        '%s', // writing_tone
        '%d', // include_excerpt
        '%s', // image_model
        '%d', // auto_images
        '%d', // num_images
        '%s', // image_size
        '%s', // image_quality
        '%s', // image_style
        '%d', // set_featured_image
        '%s', // publish_action
        '%s', // publish_frequency
        '%s', // start_date
        '%s', // start_time
        '%d', // articles_per_interval
        '%s', // specific_instructions_title
        '%d', // use_specific_title_instructions
        '%d', // use_same_specific_title_instructions
        '%s', // specific_instructions_outline
        '%d', // use_same_specific_outline_instructions
        '%s', // specific_instructions_content
        '%d', // use_same_specific_content_instructions
        '%s', // specific_instructions_excerpt
        '%d', // use_same_specific_excerpt_instructions
        '%s', // image_prompts
        '%s', // use_same_image_prompts
        '%s', // content_type
        '%d', // enable_product_prices
        '%s', // product_prices
        '%d', // include_videos_bulk
        '%s', // video_position_bulk
        '%d', // video_paragraph_bulk
		'%d', // include_citations_bulk
		'%d',
		'%d',
		'%d', // just_in_time_generation
    );
    
    //error_log("vamos a insertar 1");

    $inserted = $wpdb->insert(
        $table_name,
        $data,
        $format
    );
    
    //error_log("🛑 SQL Error: " . $wpdb->last_error);
    //error_log("vamos a insertar 2");

    if ($inserted) {
        wp_send_json_success(['id' => $wpdb->insert_id]);
        //error_log("vamos a insertar 3");
    } else {
        wp_send_json_error('Failed to save.');
        //error_log("vamos a insertar 4");
    }
}
?>
