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

// Register the settings
add_action('admin_init', 'easy_gpt_settings_init');

function easy_gpt_settings_init() {
    // Register the plugin settings
    register_setting('easy_gpt_options_group', 'easy_gpt_options', 'easy_gpt_options_sanitize');

    add_settings_section(
        'easy_gpt_settings_section',
        'API Settings',
        'easy_gpt_settings_section_callback',
        'easy-gpt-settings'
    );

    add_settings_field(
        'easy_gpt_api_key',
        'OpenAI API Key',
        'easy_gpt_api_key_render',
        'easy-gpt-settings',
        'easy_gpt_settings_section'
    );

	add_settings_field(
		'easy_gpt_gemini_api_key',
		'Gemini API Key',
		'easy_gpt_gemini_api_key_render',
		'easy-gpt-settings',
		'easy_gpt_settings_section'
	);

	add_settings_field(
		'easy_gpt_deepseek_api_key',
		'DeepSeek API Key',
		'easy_gpt_deepseek_api_key_render',
		'easy-gpt-settings',
		'easy_gpt_settings_section'
	);

    add_settings_section(
        'easy_gpt_youtube_settings_section',
        'YouTube Settings',
        'easy_gpt_youtube_settings_section_callback',
        'easy-gpt-settings'
    );
    
    // Agregar campo para la API Key de YouTube
    add_settings_field(
        'easy_gpt_youtube_api_key',
        'YouTube API Key',
        'easy_gpt_youtube_api_key_render',
        'easy-gpt-settings',
        'easy_gpt_youtube_settings_section'
    );
    
    // Agregar checkbox para habilitar la inclusión de videos en los artículos
    add_settings_field(
        'easy_gpt_include_videos',
        'Include Videos in Articles',
        'easy_gpt_include_videos_render',
        'easy-gpt-settings',
        'easy_gpt_youtube_settings_section'
    );

    add_settings_field(
        'easy_gpt_video_position',
        'Video Position in Article',
        'easy_gpt_video_position_render',
        'easy-gpt-settings',
        'easy_gpt_youtube_settings_section'
    );

    add_settings_section(
        'easy_gpt_article_settings_section',
        'Article Generation Settings',
        'easy_gpt_article_settings_section_callback',
        'easy-gpt-settings'
    );

	add_settings_field(
		'easy_gpt_text_api_provider',
		'Text API Provider',
		'easy_gpt_text_api_provider_render',
		'easy-gpt-settings',
		'easy_gpt_article_settings_section'
	);
	
    add_settings_field(
        'easy_gpt_model',
        'Select GPT Model',
        'easy_gpt_model_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_temperature',
        'Temperature',
        'easy_gpt_temperature_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_default_author',
        'Default Author',
        'easy_gpt_default_author_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_default_language',
        'Default Language',
        'easy_gpt_default_language_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_min_words',
        'Minimum Number of Words',
        'easy_gpt_min_words_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_max_words',
        'Maximum Number of Words',
        'easy_gpt_max_words_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_num_subheadings',
        'Number of H2 Subheadings',
        'easy_gpt_num_subheadings_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_subheading_type',
        'Type of Aditional Subheadings',
        'easy_gpt_subheading_type_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_format_article',
        'Format Article',
        'easy_gpt_format_article_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );
	
	add_settings_field(
		'easy_gpt_include_citations',
		'Include Citations in Text',
		'easy_gpt_include_citations_render',
		'easy-gpt-settings',
		'easy_gpt_article_settings_section'
	);

    add_settings_field(
        'easy_gpt_include_links',
        'Include Links',
        'easy_gpt_include_links_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_include_bibliography',
        'Include Bibliography',
        'easy_gpt_include_bibliography_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );
    
    add_settings_field(
        'easy_gpt_auto_categories',
        'Automatically Set Categories',
        'easy_gpt_auto_categories_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_auto_tags',
        'Automatically Set Tags',
        'easy_gpt_auto_tags_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_auto_seo',
        'Enable SEO Optimization',
        'easy_gpt_auto_seo_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_section(
        'easy_gpt_image_settings_section',
        'Image Generation Settings',
        'easy_gpt_image_settings_section_callback',
        'easy-gpt-settings'
    );

	add_settings_field(
		'easy_gpt_image_api_provider',
		'Image API Provider',
		'easy_gpt_image_api_provider_render',
		'easy-gpt-settings',
		'easy_gpt_image_settings_section'
	);
	
    add_settings_field(
        'easy_gpt_image_model',
        'Choose Image Model',
        'easy_gpt_image_model_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );

    add_settings_field(
        'easy_gpt_auto_images',
        'Automatically Generate Images',
        'easy_gpt_auto_images_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );

    add_settings_field(
        'easy_gpt_num_images',
        'Number of Images per Post',
        'easy_gpt_num_images_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );

    add_settings_field(
        'easy_gpt_set_featured_image', 
        'Set First Generated Image as Featured', 
        'easy_gpt_set_featured_image_render', 
        'easy-gpt-settings', 
        'easy_gpt_image_settings_section' 
    );

    add_settings_field(
        'easy_gpt_image_size',
        'Select Image Size',
        'easy_gpt_image_size_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );

    add_settings_field(
        'easy_gpt_image_quality',
        'Choose Image Quality',
        'easy_gpt_image_quality_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );

    add_settings_field(
        'easy_gpt_writing_style',
        'Writing Style',
        'easy_gpt_writing_style_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_writing_tone',
        'Writing Tone',
        'easy_gpt_writing_tone_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

    add_settings_field(
        'easy_gpt_include_excerpt',
        'Include Excerpt',
        'easy_gpt_include_excerpt_render',
        'easy-gpt-settings',
        'easy_gpt_article_settings_section'
    );

	add_settings_field(
		'easy_gpt_final_review',
		'Final Review (Optional)',
		'easy_gpt_final_review_render',
		'easy-gpt-settings',
		'easy_gpt_article_settings_section'
	);

    add_settings_field(
        'easy_gpt_image_style',
        'Image Style',
        'easy_gpt_image_style_render',
        'easy-gpt-settings',
        'easy_gpt_image_settings_section'
    );


// --- ARTICLE REFRESHER SETTINGS SECTION ---
add_settings_section(
    'easy_gpt_refresher_settings_section',
    'Article Refresher Settings',
    'easy_gpt_refresher_settings_section_callback',
    'easy-gpt-settings'
);

add_settings_field(
    'easy_gpt_refresh_enabled',
    'Enable Auto Refresh',
    'render_easy_gpt_refresh_enabled',
    'easy-gpt-settings',
    'easy_gpt_refresher_settings_section'
);
	
add_settings_field(
    'easy_gpt_refresher_settings',
    '', // No label title (está dentro del grupo)
    'easy_gpt_refresher_settings_render',
    'easy-gpt-settings',
    'easy_gpt_refresher_settings_section'
);

	
    // --- TRANSLATION SETTINGS SECTION ---
    add_settings_section(
        'easy_gpt_translation_settings_section',
        'Translation Settings',
        'easy_gpt_translation_settings_section_callback',
        'easy-gpt-settings'
    );

    add_settings_field(
        'easy_gpt_enable_translation',
        'Enable Automatic Translation',
        'easy_gpt_enable_translation_render',
        'easy-gpt-settings',
        'easy_gpt_translation_settings_section'
    );

add_settings_field(
    'easy_gpt_translation_fields_wrapper',
    '', // sin etiqueta
    'easy_gpt_translation_fields_render',
    'easy-gpt-settings',
    'easy_gpt_translation_settings_section'
);

    // --- COMMENTS SETTINGS SECTION ---
    add_settings_section(
        'easy_gpt_comments_settings_section',
        'Comment Moderation & Replies Settings',
        'easy_gpt_comments_settings_section_callback',
        'easy-gpt-settings'
    );
    
    // --- Moderation Options ---
    add_settings_field(
        'easy_gpt_enable_moderation',
        'Enable Moderation',
        'easy_gpt_enable_moderation_render',
        'easy-gpt-settings',
        'easy_gpt_comments_settings_section'
    );
    
    add_settings_field(
        'easy_gpt_moderation_settings',
        '', // No title because the title is already provided above
        'easy_gpt_moderation_settings_render',
        'easy-gpt-settings',
        'easy_gpt_comments_settings_section'
    );
    
    // --- Replies Options ---
    add_settings_field(
        'easy_gpt_enable_replies',
        'Enable Auto Replies',
        'easy_gpt_enable_replies_render',
        'easy-gpt-settings',
        'easy_gpt_comments_settings_section'
    );
    
    add_settings_field(
        'easy_gpt_reply_settings',
        '', // No title because the title is already provided above
        'easy_gpt_reply_settings_render',
        'easy-gpt-settings',
        'easy_gpt_comments_settings_section'
    );
}

function easy_gpt_youtube_settings_section_callback() {
    echo '<p style="color: #555; max-width: 700px;">
	Configure YouTube API settings for embedding videos in generated articles.
	</p>';
}

function easy_gpt_youtube_api_key_render() {
    $options = get_option('easy_gpt_options');
    $api_key = $options['easy_gpt_youtube_api_key'] ?? '';

    // Máscara
    if (strlen($api_key) >= 4) {
        $last4 = substr($api_key, -4);
        $masked_key = str_repeat('*', strlen($api_key) - 4) . $last4;
    } else {
        $last4 = $api_key;
        $masked_key = str_repeat('*', strlen($api_key));
    }

    echo "<input type='text' id='easy_gpt_youtube_api_key' name='easy_gpt_options[easy_gpt_youtube_api_key]' value='" . esc_attr($masked_key) . "'>";
    // Nuevo hidden para poder identificar si vino enmascarada
    echo "<input type='hidden' name='easy_gpt_options[easy_gpt_youtube_api_key_last4]' value='" . esc_attr($last4) . "'>";

    echo "<p><small>Find your YouTube API Key <a href='https://console.cloud.google.com/apis/library/youtube.googleapis.com' target='_blank'>here</a>.</small></p>";

    echo "<div id='easy_gpt_youtube_api_key_validation' style='margin-top: 5px; font-weight: bold;'>";
    if (isset($options['youtube_api_key_valid'])) {
        switch ($options['youtube_api_key_valid']) {
            case 'valid':   echo "<span style='color: green;'>YouTube API Key is valid.</span>"; break;
            case 'invalid': echo "<span style='color: red;'>YouTube API Key is invalid.</span>"; break;
            case 'error':   echo "<span style='color: red;'>Error validating the YouTube API Key.</span>"; break;
            case 'empty':   echo "<span style='color: blue;'>YouTube API Key is empty.</span>"; break;
        }
    }
    echo "</div>";
}


function easy_gpt_include_videos_render() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_include_videos']) ? checked($options['easy_gpt_include_videos'], '1', false) : '';

    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_include_videos]' value='1' {$checked}>";
    echo "<small>Check this box to automatically include a relevant YouTube video in articles.</small>";
}

function easy_gpt_video_position_render() {
    $options = get_option('easy_gpt_options');
    $position = $options['easy_gpt_video_position'] ?? 'end';

    echo "<select name='easy_gpt_options[easy_gpt_video_position]' id='easy_gpt_video_position'>";
    echo "<option value='start' " . selected($position, 'start', false) . ">Start</option>";
    echo "<option value='end' " . selected($position, 'end', false) . ">End</option>";
    echo "<option value='random' " . selected($position, 'random', false) . ">Random</option>";
    echo "<option value='after_paragraph' " . selected($position, 'after_paragraph', false) . ">After X Paragraphs</option>";
    echo "</select>";

    echo "<p><small>Choose where to insert the YouTube video in the article.</small></p>";

    // Si se selecciona "after_paragraph", mostrar campo para ingresar el número de párrafos
    $paragraph_position = $options['easy_gpt_video_paragraph'] ?? 3;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_video_paragraph]' id='easy_gpt_video_paragraph' min='1' value='" . esc_attr($paragraph_position) . "' style='display:" . ($position === 'after_paragraph' ? 'inline' : 'none') . ";'>";
}

function easy_gpt_api_key_render() {
    $options = get_option('easy_gpt_options');
    $api_key = $options['easy_gpt_api_key'] ?? '';
    if (strlen($api_key) >= 4) {
        $masked_key = str_repeat('*', strlen($api_key) - 4) . substr($api_key, -4);
    } else {
        $masked_key = str_repeat('*', strlen($api_key));
    }

    echo "<input type='text' id='easy_gpt_api_key' name='easy_gpt_options[easy_gpt_api_key]' value='" . esc_attr($masked_key) . "'>";
    echo "<p><small>Find your API Key in your <a href='https://platform.openai.com/api-keys' target='_blank'>OpenAI account settings</a>.</small></p>";
    echo "<div id='easy_gpt_api_key_validation' style='margin-top: 5px; font-weight: bold;'>";

    // Mostrar el estado de validaci車n
    if (isset($options['api_key_valid'])) {
        switch ($options['api_key_valid']) {
            case 'valid':
                echo "<span style='color: green;'>API Key is valid.</span>";
                break;
            case 'invalid':
                echo "<span style='color: red;'>API Key is invalid.</span>";
                break;
            case 'error':
                echo "<span style='color: red;'>Error validating the API Key.</span>";
                break;
            case 'empty':
                echo "<span style='color: blue;'>API Key is empty.</span>";
                break;
        }
    }

    echo "</div>";
}

function easy_gpt_gemini_api_key_render() {
    $options = get_option('easy_gpt_options');
    $api_key = $options['easy_gpt_gemini_api_key'] ?? '';
    $masked_key = strlen($api_key) >= 4 ? str_repeat('*', strlen($api_key) - 4) . substr($api_key, -4) : str_repeat('*', strlen($api_key));

    echo "<input type='text' id='easy_gpt_gemini_api_key' name='easy_gpt_options[easy_gpt_gemini_api_key]' value='" . esc_attr($masked_key) . "'>";
    echo "<p><small>Find your API Key in your <a href='https://aistudio.google.com/app/apikey' target='_blank'>Google AI Studio</a>.</small></p>";
    echo "<div id='easy_gpt_gemini_api_key_validation' style='margin-top: 5px; font-weight: bold;'>";

    if (isset($options['gemini_api_key_valid'])) {
        switch ($options['gemini_api_key_valid']) {
            case 'valid':
                echo "<span style='color: green;'>Gemini API Key is valid.</span>";
                break;
            case 'invalid':
                echo "<span style='color: red;'>Gemini API Key is invalid.</span>";
                break;
            case 'error':
                echo "<span style='color: red;'>Error validating the Gemini API Key.</span>";
                break;
            case 'empty':
                echo "<span style='color: blue;'>Gemini API Key is empty.</span>";
                break;
        }
    }

    echo "</div>";
}

function easy_gpt_deepseek_api_key_render() {
    $options = get_option('easy_gpt_options');
    $api_key = $options['easy_gpt_deepseek_api_key'] ?? '';
    $masked_key = strlen($api_key) >= 4 ? str_repeat('*', strlen($api_key) - 4) . substr($api_key, -4) : str_repeat('*', strlen($api_key));

    echo "<input type='text' id='easy_gpt_deepseek_api_key' name='easy_gpt_options[easy_gpt_deepseek_api_key]' value='" . esc_attr($masked_key) . "'>";
        echo "<p><small>Find your API Key in your <a href='https://platform.deepseek.com/api_keys' target='_blank'>DeepSeek developer dashboard</a>.</small></p>";
    echo "<div id='easy_gpt_deepseek_api_key_validation' style='margin-top: 5px; font-weight: bold;'>";

    if (isset($options['deepseek_api_key_valid'])) {
        switch ($options['deepseek_api_key_valid']) {
            case 'valid':
                echo "<span style='color: green;'>DeepSeek API Key is valid.</span>";
                break;
            case 'invalid':
                echo "<span style='color: red;'>DeepSeek API Key is invalid.</span>";
                break;
            case 'error':
                echo "<span style='color: red;'>Error validating the DeepSeek API Key.</span>";
                break;
            case 'empty':
                echo "<span style='color: blue;'>DeepSeek API Key is empty.</span>";
                break;
        }
    }

    echo "</div>";
}


function easy_gpt_model_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $default_model = 'gpt-4o';

    echo "<select name='easy_gpt_options[easy_gpt_model]' id='easy_gpt_text_model'>";

    foreach ($easy_gpt_options['models'] as $model) {
        $selected = (isset($options['easy_gpt_model']) && $options['easy_gpt_model'] == $model) ? 'selected' : '';

        // Detectar el proveedor
        $provider = 'openai';
        if (strpos($model, 'gemini-') === 0) $provider = 'gemini';
        elseif (strpos($model, 'deepseek-') === 0) $provider = 'deepseek';

        // Seleccionar por defecto si no hay valor guardado
        if (!isset($options['easy_gpt_model']) && $model === $default_model) {
            $selected = 'selected';
        }

        echo "<option value='" . esc_attr($model) . "' data-api='" . esc_attr($provider) . "' " . esc_attr($selected) . ">" . esc_html($model) . "</option>";
    }

    echo "</select>";
}

function easy_gpt_temperature_render() {
    $options = get_option('easy_gpt_options');
    echo "<input type='number' name='easy_gpt_options[easy_gpt_temperature]' min='0' max='1' step='0.01' value='" . esc_attr($options['easy_gpt_temperature'] ?? '0.7') . "'>";
}

function easy_gpt_default_author_render() {
    $options = get_option('easy_gpt_options');
    $users = get_users();
    echo "<select name='easy_gpt_options[easy_gpt_default_author]'>";
    foreach ($users as $user) {
        echo "<option value='" . esc_attr($user->ID) . "' " . selected($options['easy_gpt_default_author'], $user->ID, false) . ">" . esc_html($user->display_name) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_default_language_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $default_locale = substr(get_locale(), 0, 2);
    $selected_language = $options['easy_gpt_default_language'] ?? $default_locale;

    asort($easy_gpt_options['languages']);
    echo "<select name='easy_gpt_options[easy_gpt_default_language]'>";
    foreach ($easy_gpt_options['languages'] as $code => $language) {
        echo "<option value='" . esc_attr($code) . "' " . selected($selected_language, $code, false) . ">" . esc_html($language) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_min_words_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_min_words']) ? $options['easy_gpt_min_words'] : '300';
    echo "<input type='range' id='easy_gpt_min_words' name='easy_gpt_options[easy_gpt_min_words]' min='100' max='1000' step='50' value='" . esc_attr($value) . "' oninput='this.nextElementSibling.value = this.value'> <output>" . esc_html($value) . "</output>";
}

function easy_gpt_max_words_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_max_words']) ? $options['easy_gpt_max_words'] : '1000';
    echo "<input type='range' id='easy_gpt_max_words' name='easy_gpt_options[easy_gpt_max_words]' min='500' max='5000' step='100' value='" . esc_attr($value) . "' oninput='this.nextElementSibling.value = this.value'> <output>" . esc_html($value) . "</output>";
}

function easy_gpt_num_subheadings_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_num_subheadings']) ? $options['easy_gpt_num_subheadings'] : '3';
    echo "<input type='number' name='easy_gpt_options[easy_gpt_num_subheadings]' min='1' max='10' value='" . esc_attr($value) . "'>";
}

function easy_gpt_subheading_type_render() {
    $options = get_option('easy_gpt_options');
    $h3_value = isset($options['easy_gpt_subheading_type_h3']) ? $options['easy_gpt_subheading_type_h3'] : '0';
    $h4_value = isset($options['easy_gpt_subheading_type_h4']) ? $options['easy_gpt_subheading_type_h4'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_subheading_type_h3]' value='1' " . checked($h3_value, '1', false) . "> H3<br>";
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_subheading_type_h4]' value='1' " . checked($h4_value, '1', false) . "> H4";
}


function easy_gpt_format_article_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_format_article']) ? $options['easy_gpt_format_article'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_format_article]' value='1' " . checked($value, '1', false) . "> <small>" . esc_html__('Format article with bold and italic text (e.g., bold, italic)', 'easy-gpt-for-wp') . "</small>";
}

function easy_gpt_include_links_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_include_links']) ? $options['easy_gpt_include_links'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_include_links]' value='1' " . checked($value, '1', false) . "> <small>" . esc_html__('Include relevant hyperlinks within the article content.', 'easy-gpt-for-wp') . "</small>";
}

function easy_gpt_include_bibliography_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_include_bibliography']) ? $options['easy_gpt_include_bibliography'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_include_bibliography]' value='1' " . checked($value, '1', false) . "> <small>" . esc_html__('Add a bibliography section at the end of the article with cited sources.', 'easy-gpt-for-wp') . "</small>";
}

function easy_gpt_auto_categories_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_auto_categories']) ? $options['easy_gpt_auto_categories'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_auto_categories]' value='1' " . checked($value, '1', false) . ">";
}

function easy_gpt_auto_tags_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_auto_tags']) ? $options['easy_gpt_auto_tags'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_auto_tags]' value='1' " . checked($value, '1', false) . ">";
}

function easy_gpt_auto_seo_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_auto_seo']) ? $options['easy_gpt_auto_seo'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_auto_seo]' value='1' " . checked($value, '1', false) . ">";
    echo "<small>" . esc_html__('Check this box to automatically fill in the SEO title and description if a compatible SEO plugin is installed.', 'easy-gpt-for-wp') . "</small>";
}
function easy_gpt_image_model_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $selected_model = $options['easy_gpt_image_model'] ?? '';

    echo "<select name='easy_gpt_options[easy_gpt_image_model]' id='easy_gpt_image_model'>";

    foreach ($easy_gpt_options['dall_e_models'] as $model) {
        // Detectar proveedor según prefijo
		if (str_starts_with($model, 'gemini-') || str_starts_with($model, 'imagen-')) {
			$provider = 'gemini';
		} elseif (str_starts_with($model, 'deepseek-')) {
			$provider = 'deepseek';
		} else {
			$provider = 'openai'; // default
		}

        echo "<option value='" . esc_attr($model) . "' data-api='" . esc_attr($provider) . "' " . selected($selected_model, $model, false) . ">" . esc_html($model) . "</option>";
    }

    echo "</select>";
}

function easy_gpt_auto_images_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_auto_images']) ? $options['easy_gpt_auto_images'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_auto_images]' value='1' " . checked($value, '1', false) . ">";
}

function easy_gpt_num_images_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_num_images']) ? $options['easy_gpt_num_images'] : '1';
    echo "<input type='number' name='easy_gpt_options[easy_gpt_num_images]' min='1' value='" . esc_attr($value) . "'> " . esc_html__('Number of images per post', 'easy-gpt-for-wp');
}

function easy_gpt_set_featured_image_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_set_featured_image']) ? $options['easy_gpt_set_featured_image'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_set_featured_image]' value='1' " . checked($value, '1', false) . ">";
}

function easy_gpt_image_size_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    echo "<select name='easy_gpt_options[easy_gpt_image_size]'>";
    foreach ($easy_gpt_options['image_sizes'] as $key => $size) {
        echo "<option value='" . esc_attr($key) . "' " . selected(isset($options['easy_gpt_image_size']) ? $options['easy_gpt_image_size'] : '', $key, false) . ">" . esc_html($size) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_image_quality_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    echo "<select name='easy_gpt_options[easy_gpt_image_quality]'>";
    foreach ($easy_gpt_options['image_qualities'] as $key => $quality) {
        echo "<option value='" . esc_attr($key) . "' " . selected(isset($options['easy_gpt_image_quality']) ? $options['easy_gpt_image_quality'] : '', $key, false) . ">" . esc_html($quality) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_writing_style_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    echo "<select name='easy_gpt_options[easy_gpt_writing_style]'>";
    foreach ($easy_gpt_options['writing_styles'] as $style) {
        echo "<option value='" . esc_attr($style) . "' " . selected(isset($options['easy_gpt_writing_style']) ? $options['easy_gpt_writing_style'] : '', $style, false) . ">" . esc_html($style) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_writing_tone_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    echo "<select name='easy_gpt_options[easy_gpt_writing_tone]'>";
    foreach ($easy_gpt_options['writing_tones'] as $tone) {
        echo "<option value='" . esc_attr($tone) . "' " . selected(isset($options['easy_gpt_writing_tone']) ? $options['easy_gpt_writing_tone'] : '', $tone, false) . ">" . esc_html($tone) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_include_excerpt_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_include_excerpt']) ? $options['easy_gpt_include_excerpt'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_include_excerpt]' value='1' " . checked($value, '1', false) . ">";
}

function easy_gpt_image_style_render() {
    $options = get_option('easy_gpt_options');
    echo "<input type='text' name='easy_gpt_options[easy_gpt_image_style]' value='" . esc_attr($options['easy_gpt_image_style'] ?? '') . "' placeholder='e.g., Realistic, Drawing, Anime'>";
}

// Callbacks for section descriptions
function easy_gpt_settings_section_callback() {
    echo '<div style="color: #555; max-width: 700px; font-size: 14px;">
        <p><strong>Note:</strong> You only need <u>one</u> API key for the plugin to work. You can choose any supported provider: OpenAI, Gemini or DeepSeek.</p>
        <p>To generate <strong>images</strong>, you need to provide an API Key from <strong>OpenAI</strong> or <strong>Gemini</strong>. <strong>DeepSeek</strong> currently does <u>not</u> support image generation.</p>
        <p>You can enter multiple keys — the plugin will use the one selected in the <em>"Article Generation Settings"</em> and <em>"Image Generation Settings"</em> sections.</p>
    </div>';
}


function easy_gpt_article_settings_section_callback() {
    echo '<p style="color: #555; max-width: 700px;">
	Configure the settings for article generation here. These values will be used as default settings for generating articles, but they can be edited individually for each use.
	</p>';
    echo '<div style="background: #f0f9ff; border-left: 5px solid #0ea5e9; padding: 10px 15px; margin-bottom: 15px; max-width: 700px;">
        <p><strong>Instructions:</strong> Select the API provider you want to use for text generation, then choose one of the available models from that provider. The plugin will use this configuration when generating articles, translations or refreshing content.</p>
        <p>You must have a valid API key entered in the <strong>API Settings</strong> tab for the selected provider.</p>
    </div>';
}

function easy_gpt_image_settings_section_callback() {
    echo '<p style="color: #555; max-width: 700px;">
        Configure the settings for image generation using models from OpenAI or Gemini.
    </p>';
    echo '<div style="background: #f0f9ff; border-left: 5px solid #0ea5e9; padding: 10px 15px; margin-bottom: 15px; max-width: 700px;">
        <p><strong>Instructions:</strong> Select the API provider you want to use for image generation, then choose one of the available models from that provider.</p>
        <p>The plugin will use this configuration when generating images for articles — whether during initial creation, content refreshing, or automatic translation.</p>
        <p>You must have a valid API key entered in the <strong>API Settings</strong> tab for the selected provider.</p>
    </div>';
}
function easy_gpt_admin_styles($hook) {
    if ($hook != 'toplevel_page_easy-gpt-settings' && $hook != 'easy-gpt-settings_page_easy-gpt-settings') {
        return;
    }

    // Define la URL base del plugin
    $plugin_url = plugin_dir_url(dirname(__FILE__));

    // Cargar estilos (opcional, si lo necesitas)
    wp_enqueue_style('easy_gpt_admin_css', $plugin_url . 'styles/admin-style.css');

    // Cargar el script JS con la ruta corregida
    wp_enqueue_script('easy_gpt_admin_js', $plugin_url . 'js/admin-script.js', ['jquery'], null, true);

    // Localizar datos para el script JS
    wp_localize_script('easy_gpt_admin_js', 'easyGptAjax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('validate_api_key_nonce'),
    ]);
}
add_action('admin_enqueue_scripts', 'easy_gpt_admin_styles');


function easy_gpt_options_sanitize($input) {
    error_log("Sanitizando...");
    $options = get_option('easy_gpt_options');

    // --- Claves API (OpenAI, Gemini, DeepSeek) ---
    if (isset($input['easy_gpt_api_key']) && strpos($input['easy_gpt_api_key'], '****') !== false) {
        $input['easy_gpt_api_key'] = $options['easy_gpt_api_key'];
    } else {
        $input['easy_gpt_api_key'] = sanitize_text_field($input['easy_gpt_api_key']);
    }

    if (!empty($input['easy_gpt_api_key'])) {
        $response = wp_remote_get('https://api.openai.com/v1/models', [
            'headers' => ['Authorization' => 'Bearer ' . $input['easy_gpt_api_key']],
        ]);
        $input['api_key_valid'] = is_wp_error($response) ? 'error' : (wp_remote_retrieve_response_code($response) === 200 ? 'valid' : 'invalid');
    } else {
        $input['api_key_valid'] = 'empty';
    }

    if (isset($input['easy_gpt_gemini_api_key']) && strpos($input['easy_gpt_gemini_api_key'], '****') !== false) {
        $input['easy_gpt_gemini_api_key'] = $options['easy_gpt_gemini_api_key'];
    } else {
        $input['easy_gpt_gemini_api_key'] = sanitize_text_field($input['easy_gpt_gemini_api_key']);
    }

    if (!empty($input['easy_gpt_gemini_api_key'])) {
        $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={$input['easy_gpt_gemini_api_key']}";
        $body = json_encode(["contents" => [["parts" => [["text" => "Hello from Easy GPT"]]]]]);
        $response = wp_remote_post($url, [
            'headers' => ['Content-Type' => 'application/json'],
            'body' => $body,
            'timeout' => 20,
        ]);
        $input['gemini_api_key_valid'] = is_wp_error($response) ? 'error' : (wp_remote_retrieve_response_code($response) === 200 ? 'valid' : 'invalid');
    } else {
        $input['gemini_api_key_valid'] = 'empty';
    }

    if (isset($input['easy_gpt_deepseek_api_key']) && strpos($input['easy_gpt_deepseek_api_key'], '****') !== false) {
        $input['easy_gpt_deepseek_api_key'] = $options['easy_gpt_deepseek_api_key'];
    } else {
        $input['easy_gpt_deepseek_api_key'] = sanitize_text_field($input['easy_gpt_deepseek_api_key']);
    }

    if (!empty($input['easy_gpt_deepseek_api_key'])) {
        $response = wp_remote_get('https://api.deepseek.com/v1/models', [
            'headers' => ['Authorization' => 'Bearer ' . $input['easy_gpt_deepseek_api_key']],
        ]);
        $input['deepseek_api_key_valid'] = is_wp_error($response) ? 'error' : (wp_remote_retrieve_response_code($response) === 200 ? 'valid' : 'invalid');
    } else {
        $input['deepseek_api_key_valid'] = 'empty';
    }

    // --- Checkbox fields ---
    $checkbox_fields = [
        'easy_gpt_subheading_type_h3',
        'easy_gpt_subheading_type_h4',
        'easy_gpt_format_article',
        'easy_gpt_include_links',
        'easy_gpt_include_bibliography',
        'easy_gpt_auto_categories',
        'easy_gpt_auto_tags',
        'easy_gpt_auto_seo',
        'easy_gpt_auto_images',
        'easy_gpt_include_excerpt',
        'easy_gpt_set_featured_image',
        'easy_gpt_include_citations',
        'easy_gpt_final_review',
        'easy_gpt_refresh_enabled',
        'easy_gpt_refresh_update_images',
        'easy_gpt_refresh_youtube_enabled',
        'easy_gpt_refresh_update_seo',
        'easy_gpt_refresh_update_post_date',
        'easy_gpt_enable_moderation',
        'easy_gpt_enable_replies',
        'easy_gpt_enable_translation',
        'easy_gpt_translate_posts',
        'easy_gpt_translate_products',
        'easy_gpt_translation_update_youtube',
        'easy_gpt_reply_in_comment_language',
        'easy_gpt_include_videos'
    ];

    error_log("[🔍 Checkbox fields]:");
    foreach ($checkbox_fields as $field) {
        error_log("$field => " . var_export($input[$field] ?? '(not set)', true));
        $input[$field] = isset($input[$field]) && $input[$field] ? '1' : '0';
        error_log("[DEBUG] $field = '{$input[$field]}'");
    }

    // --- Campos de texto y número ---
    $input['easy_gpt_model'] = sanitize_text_field($input['easy_gpt_model'] ?? '');
    $input['easy_gpt_temperature'] = floatval($input['easy_gpt_temperature'] ?? 0.7);
    $input['easy_gpt_default_author'] = intval($input['easy_gpt_default_author'] ?? 0);
    $input['easy_gpt_default_language'] = sanitize_text_field($input['easy_gpt_default_language'] ?? 'en');
    $input['easy_gpt_min_words'] = intval($input['easy_gpt_min_words'] ?? 300);
    $input['easy_gpt_max_words'] = intval($input['easy_gpt_max_words'] ?? 1000);
    $input['easy_gpt_num_subheadings'] = intval($input['easy_gpt_num_subheadings'] ?? 3);
    $input['easy_gpt_image_model'] = sanitize_text_field($input['easy_gpt_image_model'] ?? '');
    $input['easy_gpt_num_images'] = intval($input['easy_gpt_num_images'] ?? 0);
    $input['easy_gpt_image_size'] = sanitize_text_field($input['easy_gpt_image_size'] ?? '1024x1024');
    $input['easy_gpt_image_quality'] = sanitize_text_field($input['easy_gpt_image_quality'] ?? 'standard');
    $input['easy_gpt_writing_style'] = sanitize_text_field($input['easy_gpt_writing_style'] ?? '');
    $input['easy_gpt_writing_tone'] = sanitize_text_field($input['easy_gpt_writing_tone'] ?? '');
    $input['easy_gpt_image_style'] = sanitize_text_field($input['easy_gpt_image_style'] ?? '');
    

	// --- YouTube API ---
	$old_options = get_option('easy_gpt_options');
	$old_yt = $old_options['easy_gpt_youtube_api_key'] ?? '';
	$posted_yt = $input['easy_gpt_youtube_api_key'] ?? '';
	$posted_last4 = $input['easy_gpt_youtube_api_key_last4'] ?? '';

	$posted_yt = sanitize_text_field($posted_yt);
	$posted_last4 = sanitize_text_field($posted_last4);

	// ¿El usuario dejó la máscara (contiene '*') y coincide con los últimos 4 de la guardada?
	$looks_masked = strpos($posted_yt, '*') !== false;
	$matches_last4 = ($old_yt !== '' && $posted_last4 !== '' && substr($old_yt, -4) === $posted_last4);

	if ($looks_masked && $matches_last4) {
		// No cambió la clave → conserva la antigua y conserva también el estado de validación previo
		$input['easy_gpt_youtube_api_key'] = $old_yt;
		$input['youtube_api_key_valid'] = $old_options['youtube_api_key_valid'] ?? 'valid';
	} else {
		// El usuario pegó una clave nueva (o vació el campo): valida
		$input['easy_gpt_youtube_api_key'] = $posted_yt;

		if (!empty($input['easy_gpt_youtube_api_key'])) {
			$test_url = "https://www.googleapis.com/youtube/v3/videos?id=Ks-_Mh1QhMc&key={$input['easy_gpt_youtube_api_key']}&part=id";
			$response = wp_remote_get($test_url);
			$input['youtube_api_key_valid'] = is_wp_error($response) ? 'error' :
				(wp_remote_retrieve_response_code($response) === 200 ? 'valid' : 'invalid');
		} else {
			$input['youtube_api_key_valid'] = 'empty';
		}
	}

    
    // --- Video settings ---
    $valid_positions = ['start', 'end', 'random', 'after_paragraph'];
    $input['easy_gpt_video_position'] = in_array($input['easy_gpt_video_position'] ?? '', $valid_positions) ? $input['easy_gpt_video_position'] : 'end';
    $input['easy_gpt_video_paragraph'] = isset($input['easy_gpt_video_paragraph']) ? max(1, intval($input['easy_gpt_video_paragraph'])) : 3;
    
    // --- Comentarios y moderación ---
    $input['easy_gpt_moderation_model'] = sanitize_text_field($input['easy_gpt_moderation_model'] ?? '');
    $input['easy_gpt_prohibited_words'] = sanitize_textarea_field($input['easy_gpt_prohibited_words'] ?? '');
    $input['easy_gpt_reply_model'] = sanitize_text_field($input['easy_gpt_reply_model'] ?? '');
    $input['easy_gpt_daily_reply_limit'] = max(1, intval($input['easy_gpt_daily_reply_limit'] ?? 1));
    $input['easy_gpt_reply_tone'] = sanitize_text_field($input['easy_gpt_reply_tone'] ?? '');
    $input['easy_gpt_reply_style'] = sanitize_text_field($input['easy_gpt_reply_style'] ?? '');
    $input['easy_gpt_reply_delay'] = max(1, intval($input['easy_gpt_reply_delay'] ?? 1));
    $input['easy_gpt_reply_language'] = sanitize_text_field($input['easy_gpt_reply_language'] ?? '');
    $input['easy_gpt_moderation_prompt'] = sanitize_textarea_field($input['easy_gpt_moderation_prompt'] ?? '');
    $input['easy_gpt_reply_prompt'] = sanitize_textarea_field($input['easy_gpt_reply_prompt'] ?? '');
    $input['easy_gpt_reply_temperature'] = isset($input['easy_gpt_reply_temperature']) ? max(0, min(1, floatval($input['easy_gpt_reply_temperature']))) : 0.7;
    $input['easy_gpt_reply_default_author'] = intval($input['easy_gpt_reply_default_author'] ?? 0);
    $input['easy_gpt_reply_time_limit'] = max(1, intval($input['easy_gpt_reply_time_limit'] ?? 1));


    // --- Article Refresher ---
    $input['easy_gpt_refresh_interval'] = sanitize_text_field($input['easy_gpt_refresh_interval'] ?? 'daily');
    $input['easy_gpt_refresh_limit'] = intval($input['easy_gpt_refresh_limit'] ?? 5);
    $input['easy_gpt_refresh_min_age_days'] = intval($input['easy_gpt_refresh_min_age_days'] ?? 180);
    $input['easy_gpt_refresh_priority'] = sanitize_text_field($input['easy_gpt_refresh_priority'] ?? 'oldest_first');
    $input['easy_gpt_refresh_image_replace_existing'] = sanitize_text_field($input['easy_gpt_refresh_image_replace_existing'] ?? 'keep');
    $input['easy_gpt_refresh_image_add_new'] = intval($input['easy_gpt_refresh_image_add_new'] ?? 0);
    $input['easy_gpt_refresh_image_featured_behavior'] = sanitize_text_field($input['easy_gpt_refresh_image_featured_behavior'] ?? 'set_if_none');
    $input['easy_gpt_refresh_youtube_behavior'] = sanitize_text_field($input['easy_gpt_refresh_youtube_behavior'] ?? 'skip_if_exists');
    
    // --- Traducción ---
    $input['easy_gpt_translation_languages'] = array_map('sanitize_text_field', $input['easy_gpt_translation_languages'] ?? []);
    $input['easy_gpt_translation_limit_per_interval'] = max(1, intval($input['easy_gpt_translation_limit_per_interval'] ?? 1));
    $input['easy_gpt_translation_interval'] = sanitize_text_field($input['easy_gpt_translation_interval'] ?? 'daily');
    $input['easy_gpt_translation_priority'] = sanitize_text_field($input['easy_gpt_translation_priority'] ?? 'oldest_first');
    $input['easy_gpt_translation_image_behavior'] = sanitize_text_field($input['easy_gpt_translation_image_behavior'] ?? 'update_metadata');
    $input['easy_gpt_translation_publish_status'] = in_array(($input['easy_gpt_translation_publish_status'] ?? ''), ['draft', 'publish']) ? $input['easy_gpt_translation_publish_status'] : 'draft';
    
    // --- Proveedor API texto/imagen ---
    $input['easy_gpt_text_api_provider'] = sanitize_text_field($input['easy_gpt_text_api_provider'] ?? 'openai');
    $input['easy_gpt_image_api_provider'] = sanitize_text_field($input['easy_gpt_image_api_provider'] ?? 'openai');
    
    // --- Tipos de contenido a refrescar ---
    $allowed_post_types = ['post', 'page'];
    $input['easy_gpt_refresh_post_types'] = array_values(array_intersect($allowed_post_types, $input['easy_gpt_refresh_post_types'] ?? []));
    
    // --- IDs excluidos ---
    $raw_ids = explode(',', $input['easy_gpt_exclude_post_ids'] ?? '');
    $sanitized_ids = array_filter(array_map('intval', $raw_ids));
    $input['easy_gpt_exclude_post_ids'] = implode(',', $sanitized_ids);


    // --- Log final de prueba ---
    error_log('[✔️ FINAL easy_gpt_enable_moderation] = ' . $input['easy_gpt_enable_moderation']);

    return $input;
}



add_action('wp_ajax_validate_api_key', 'easy_gpt_validate_api_key');

function easy_gpt_validate_api_key() {
    error_log("Validando...");
    check_ajax_referer('validate_api_key_nonce', 'security');
    error_log("Validando... 2");

    $api_key = sanitize_text_field($_POST['api_key']);
    $response = wp_remote_get('https://api.openai.com/v1/models', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
        ],
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error(['message' => 'Error validating the API Key.']);
    }

    $status_code = wp_remote_retrieve_response_code($response);

    if ($status_code === 200) {
        wp_send_json_success(['message' => 'API Key is valid.']);
    } else {
        wp_send_json_error(['message' => 'API Key is invalid.']);
    }
}


add_action('wp_ajax_validate_gemini_api_key', 'easy_gpt_validate_gemini_api_key');
function easy_gpt_validate_gemini_api_key() {
    check_ajax_referer('validate_api_key_nonce', 'security');
    $api_key = sanitize_text_field($_POST['api_key']);

    $url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={$api_key}";

    $body = json_encode([
        "contents" => [[
            "parts" => [[ "text" => "Explain how AI works" ]]
        ]]
    ]);

    $response = wp_remote_post($url, [
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'body'    => $body,
        'timeout' => 20,
    ]);

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();

        // Handle timeout
        if (strpos($error_message, 'cURL error 28') !== false) {
            wp_send_json_error([
                'message' => 'Could not connect to the Gemini API (timeout). Your server may be blocking outgoing connections or responding too slowly.'
            ]);
        }

        wp_send_json_error([
            'message' => 'Error validating the Gemini API Key: ' . $error_message
        ]);
    }

    $code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);
    $decoded = json_decode($body, true);
    $api_error = $decoded['error']['message'] ?? null;

    if ($code === 200) {
        wp_send_json_success(['message' => 'Gemini API Key is valid.']);
    } else {
        $message = $api_error ? "$api_error (HTTP $code)" : "Gemini API Key is invalid (HTTP $code).";
        wp_send_json_error(['message' => '' . $message]);
    }
}



add_action('wp_ajax_validate_deepseek_api_key', 'easy_gpt_validate_deepseek_api_key');
function easy_gpt_validate_deepseek_api_key() {
    check_ajax_referer('validate_api_key_nonce', 'security');
    $api_key = sanitize_text_field($_POST['api_key']);

    $response = wp_remote_get('https://api.deepseek.com/v1/models', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
        ],
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error(['message' => 'Error validating the DeepSeek API Key.']);
    }

    $code = wp_remote_retrieve_response_code($response);
    if ($code === 200) {
        wp_send_json_success(['message' => 'DeepSeek API Key is valid.']);
    } else {
        wp_send_json_error(['message' => "DeepSeek API Key is invalid (HTTP $code)."]);
    }
}




add_action('admin_footer', 'easy_gpt_video_position_script');
function easy_gpt_video_position_script() {
    ?>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            let select = document.getElementById("easy_gpt_video_position");
            let paragraphInput = document.getElementById("easy_gpt_video_paragraph");

            function toggleParagraphInput() {
                paragraphInput.style.display = (select.value === "after_paragraph") ? "inline" : "none";
            }

            select.addEventListener("change", toggleParagraphInput);
            toggleParagraphInput();
        });
    </script>
    <?php
}

add_action('wp_ajax_validate_youtube_api_key', 'easy_gpt_validate_youtube_api_key');

function easy_gpt_validate_youtube_api_key() {
    check_ajax_referer('validate_api_key_nonce', 'security');

    $api_key = sanitize_text_field($_POST['api_key']);

    $test_url = "https://www.googleapis.com/youtube/v3/videos?id=Ks-_Mh1QhMc&key={$api_key}&part=id";
    $response = wp_remote_get($test_url);

    if (is_wp_error($response)) {
        wp_send_json_error(['message' => 'Error validating the YouTube API Key.']);
    }

    $status_code = wp_remote_retrieve_response_code($response);

    if ($status_code === 200) {
        wp_send_json_success(['message' => 'YouTube API Key is valid.']);
    } else {
        wp_send_json_error(['message' => 'YouTube API Key is invalid.']);
    }
}

add_action('admin_enqueue_scripts', 'easy_gpt_admin_youtube_styles');

function easy_gpt_admin_youtube_styles($hook) {
    if ($hook != 'toplevel_page_easy-gpt-settings' && $hook != 'easy-gpt-settings_page_easy-gpt-settings') {
        return;
    }

    $plugin_url = plugin_dir_url(dirname(__FILE__));

    wp_enqueue_script('easy_gpt_admin_youtube_js', $plugin_url . 'js/admin-youtube.js', ['jquery'], null, true);

    wp_localize_script('easy_gpt_admin_youtube_js', 'easyGptYoutubeAjax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('validate_api_key_nonce'),
    ]);
}

// Callback Functions para comentarios
function easy_gpt_comments_settings_section_callback() {
    echo '<p style="color: #555; max-width: 700px;">
	Configure AI-based moderation and reply settings for comments.
	</p>';
}

function easy_gpt_enable_moderation_render() {
    $options = get_option('easy_gpt_options');
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_enable_moderation]' value='1' " . checked(1, $options['easy_gpt_enable_moderation'] ?? 0, false) . ">";
}

function easy_gpt_moderation_model_render() {
	global $easy_gpt_options;
	$options = get_option('easy_gpt_options');
	$selected_model = $options['easy_gpt_moderation_model'] ?? '';

	// Detectar proveedor del modelo
	$detected_provider = 'openai';
	if (strpos($selected_model, 'gemini-') === 0) $detected_provider = 'gemini';
	elseif (strpos($selected_model, 'deepseek-') === 0) $detected_provider = 'deepseek';

	// Proveedor (no se guarda en DB)
	echo "<select id='easy_gpt_moderation_provider'>";
	echo "<option value='openai' " . selected($detected_provider, 'openai', false) . ">OpenAI</option>";
	echo "<option value='gemini' " . selected($detected_provider, 'gemini', false) . ">Gemini</option>";
	echo "<option value='deepseek' " . selected($detected_provider, 'deepseek', false) . ">DeepSeek</option>";
	echo "</select><br><br>";

	// Modelos
	echo "<select name='easy_gpt_options[easy_gpt_moderation_model]' id='easy_gpt_moderation_model'>";
	foreach ($easy_gpt_options['models'] as $model) {
		$provider = 'openai';
		if (str_starts_with($model, 'gemini-')) $provider = 'gemini';
		elseif (str_starts_with($model, 'deepseek-')) $provider = 'deepseek';

		echo "<option value='" . esc_attr($model) . "' data-api='" . esc_attr($provider) . "' " . selected($selected_model, $model, false) . ">" . esc_html($model) . "</option>";
	}
	echo "</select>";
	echo "<p><small>Select the AI model for comment moderation. The provider is auto-detected from the model on load.</small></p>";
}


function easy_gpt_prohibited_words_render() {
    $options = get_option('easy_gpt_options');
    echo "<textarea 
        name='easy_gpt_options[easy_gpt_prohibited_words]' 
        placeholder='e.g., spam, offensive words' 
        style='width: 100%; height: 100px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px;'>"
        . esc_textarea($options['easy_gpt_prohibited_words'] ?? '') . 
    "</textarea>";
    
    echo "<p style='color: #777; margin-top: 5px; font-size: 13px;'>
            <small>Enter prohibited words separated by commas. For example: <code>spam, offensive, badword</code></small>
         </p>";
}


function easy_gpt_enable_replies_render() {
    $options = get_option('easy_gpt_options');
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_enable_replies]' value='1' " . checked(1, $options['easy_gpt_enable_replies'] ?? 0, false) . ">";
}

function easy_gpt_reply_model_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $selected_model = $options['easy_gpt_reply_model'] ?? '';

    echo "<select id='easy_gpt_reply_provider'>";
    echo "<option value='openai'>OpenAI</option>";
    echo "<option value='gemini'>Gemini</option>";
    echo "<option value='deepseek'>DeepSeek</option>";
    echo "</select><br><br>";

    echo "<select name='easy_gpt_options[easy_gpt_reply_model]' id='easy_gpt_reply_model'>";
    foreach ($easy_gpt_options['models'] as $model) {
        $provider = 'openai';
        if (str_starts_with($model, 'gemini-')) {
            $provider = 'gemini';
        } elseif (str_starts_with($model, 'deepseek-')) {
            $provider = 'deepseek';
        }

        echo "<option value='" . esc_attr($model) . "' data-api='" . esc_attr($provider) . "' " . selected($selected_model, $model, false) . ">" . esc_html($model) . "</option>";
    }
    echo "</select>";
    echo "<p><small>Select the AI model for generating replies to comments. The provider is auto-detected from the model on load.</small></p>";
}

function easy_gpt_daily_reply_limit_render() {
    $options = get_option('easy_gpt_options');
    $limit = $options['easy_gpt_daily_reply_limit'] ?? '';

    echo "<input type='number' name='easy_gpt_options[easy_gpt_daily_reply_limit]' placeholder='No Limit' value='" . esc_attr($limit) . "'>";
    echo "<p><small>Leave blank or enter zero for no daily limit on replies.</small></p>";
}

function easy_gpt_reply_tone_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $selected_tone = $options['easy_gpt_reply_tone'] ?? 'friendly';

    echo "<select name='easy_gpt_options[easy_gpt_reply_tone]' style='padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px; width: 200px;'>";
    foreach ($easy_gpt_options['writing_tones'] as $tone) {
        echo "<option value='" . esc_attr($tone) . "' " . selected($selected_tone, $tone, false) . ">" . esc_html($tone) . "</option>";
    }
    echo "</select>";

    echo "<p style='color: #555; margin-top: 5px;'><small>Select the desired tone for AI-generated replies.</small></p>";
}

function easy_gpt_reply_style_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $selected_style = $options['easy_gpt_reply_style'] ?? 'Conversational';

    echo "<select name='easy_gpt_options[easy_gpt_reply_style]' style='padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px; width: 200px;'>";
    foreach ($easy_gpt_options['writing_styles'] as $style) {
        echo "<option value='" . esc_attr($style) . "' " . selected($selected_style, $style, false) . ">" . esc_html($style) . "</option>";
    }
    echo "</select>";

    echo "<p style='color: #555; margin-top: 5px;'><small>Select the writing style for AI-generated replies.</small></p>";
}

function easy_gpt_reply_delay_render() {
    $options = get_option('easy_gpt_options');
    echo "<input type='number' name='easy_gpt_options[easy_gpt_reply_delay]' min='1' value='" . esc_attr($options['easy_gpt_reply_delay'] ?? 10) . "'>";
}

function easy_gpt_reply_language_render() {
    global $easy_gpt_options;
    $options = get_option('easy_gpt_options');
    $default_locale = substr(get_locale(), 0, 2);
    $selected_language = $options['easy_gpt_reply_language'] ?? $default_locale;

    echo "<select name='easy_gpt_options[easy_gpt_reply_language]'>";
    foreach ($easy_gpt_options['languages'] as $code => $language) {
        echo "<option value='" . esc_attr($code) . "' " . selected($selected_language, $code, false) . ">" . esc_html($language) . "</option>";
    }
    echo "</select>";
    echo "<p><small>Select the default language for automatic replies. If the option below is enabled, this will be overridden based on the comment language.</small></p>";
}

// Renderizar checkbox para responder en el idioma del comentario
function easy_gpt_reply_in_comment_language_render() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_reply_in_comment_language']) ? checked($options['easy_gpt_reply_in_comment_language'], '1', false) : '';
    
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_reply_in_comment_language]' value='1' {$checked}>";
    echo "<p><small>Check this box to automatically detect the comment language and reply in the same language.</small></p>";
}

function easy_gpt_reply_temperature_render() {
    $options = get_option('easy_gpt_options');
    $temperature = $options['easy_gpt_reply_temperature'] ?? 0.7;

    echo "<input type='number' name='easy_gpt_options[easy_gpt_reply_temperature]' min='0' max='1' step='0.01' value='" . esc_attr($temperature) . "'>";
    echo "<p><small>Set the temperature for AI-generated replies. Values closer to <strong>0</strong> will make the output more deterministic, while values closer to <strong>1</strong> will make it more creative.</small></p>";
}

// Renderizar ajustes de moderación
function easy_gpt_moderation_settings_render() {
    $options = get_option('easy_gpt_options');
    $style = empty($options['easy_gpt_enable_moderation']) ? 'style="display:none;"' : '';

    echo "<div id='easy_gpt_moderation_fields' {$style}>";

    echo "<table class='form-table'><tbody>";

    echo "<tr>
            <th scope='row'><label for='easy_gpt_moderation_model'>Moderation Model</label></th>
            <td>";
                easy_gpt_moderation_model_render();
    echo    "</td>
          </tr>";

    echo "<tr>
            <th scope='row'><label for='easy_gpt_prohibited_words'>Prohibited Words</label></th>
            <td>";
                easy_gpt_prohibited_words_render();
    echo    "</td>
          </tr>";

    echo "<tr>
            <th scope='row'><label for='easy_gpt_moderation_prompt'>Custom Moderation Prompt</label></th>
            <td>";
                easy_gpt_moderation_prompt_render();
    echo    "</td>
          </tr>";

    echo "</tbody></table>";
    echo "</div>";
}

// Renderizar ajustes de respuestas
function easy_gpt_reply_settings_render() {
    $options = get_option('easy_gpt_options');
    $style = empty($options['easy_gpt_enable_replies']) ? 'style="display:none;"' : '';

    echo "<div id='easy_gpt_reply_fields' {$style}>";
    echo "<table class='form-table'><tbody>";
	
    // Default Reply Author (nuevo campo)
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_default_author'>Default Reply Author</label></th>
            <td>";
                easy_gpt_reply_default_author_render();
    echo    "</td>
          </tr>";
	
    // Reply in Comment Language
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_in_comment_language'>Reply in Comment Language</label></th>
            <td>";
                easy_gpt_reply_in_comment_language_render();
    echo    "</td>
          </tr>";

    // Reply Language
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_language'>Reply Language</label></th>
            <td>";
                easy_gpt_reply_language_render();
    echo    "</td>
          </tr>";

    // Reply Model
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_model'>Reply Model</label></th>
            <td>";
                easy_gpt_reply_model_render();
    echo    "</td>
          </tr>";

    // Custom Reply Prompt
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_prompt'>Custom Reply Prompt</label></th>
            <td>";
                easy_gpt_reply_prompt_render();
    echo    "</td>
          </tr>";

	// Reply Time Limit (days)
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_time_limit'>Reply Time Limit (days)</label></th>
            <td>";
                easy_gpt_reply_time_limit_render();
    echo    "</td>
          </tr>";

    // Daily Reply Limit
    echo "<tr>
            <th scope='row'><label for='easy_gpt_daily_reply_limit'>Daily Reply Limit</label></th>
            <td>";
                easy_gpt_daily_reply_limit_render();
    echo    "</td>
          </tr>";

    // Reply Temperature
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_temperature'>Reply Temperature</label></th>
            <td>";
                easy_gpt_reply_temperature_render();
    echo    "</td>
          </tr>";

    // Reply Tone
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_tone'>Reply Tone</label></th>
            <td>";
                easy_gpt_reply_tone_render();
    echo    "</td>
          </tr>";

    // Reply Style
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_style'>Reply Style</label></th>
            <td>";
                easy_gpt_reply_style_render();
    echo    "</td>
          </tr>";

    // Reply Delay
    echo "<tr>
            <th scope='row'><label for='easy_gpt_reply_delay'>Reply Delay (minutes)</label></th>
            <td>";
                easy_gpt_reply_delay_render();
    echo    "</td>
          </tr>";

    echo "</tbody></table>";
    echo "</div>";
}

// Renderizar campo de prompt para moderación
function easy_gpt_moderation_prompt_render() {
    $options = get_option('easy_gpt_options');
    echo "<textarea 
            name='easy_gpt_options[easy_gpt_moderation_prompt]' 
            placeholder='Optional: Provide specific instructions for moderation, or leave blank for default behavior...' 
            style='width: 100%; height: 100px; padding: 10px; border: 1px solid #ccc; border-radius: 4px;'>"
            . esc_textarea($options['easy_gpt_moderation_prompt'] ?? '') . 
        "</textarea>";
    echo "<p><small>If left blank, the AI will handle moderation based on general guidelines.</small></p>";
}

// Renderizar campo de prompt para respuestas
function easy_gpt_reply_prompt_render() {
    $options = get_option('easy_gpt_options');
    echo "<textarea 
            name='easy_gpt_options[easy_gpt_reply_prompt]' 
            placeholder='Optional: Provide specific instructions for replies, or leave blank for default behavior...' 
            style='width: 100%; height: 100px; padding: 10px; border: 1px solid #ccc; border-radius: 4px;'>"
            . esc_textarea($options['easy_gpt_reply_prompt'] ?? '') . 
        "</textarea>";
    echo "<p><small>If left blank, the AI will generate replies using its default approach.</small></p>";
}

// JavaScript para mostrar/ocultar opciones condicionales
add_action('admin_footer', function() {
    ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const moderationCheckbox = document.querySelector('input[name="easy_gpt_options[easy_gpt_enable_moderation]"]');
            const moderationSettings = document.getElementById('easy_gpt_moderation_fields');
        
            const repliesCheckbox = document.querySelector('input[name="easy_gpt_options[easy_gpt_enable_replies]"]');
            const replySettings = document.getElementById('easy_gpt_reply_fields');
        
            // Función para alternar visibilidad de los campos de moderación
            function toggleModerationFields() {
                moderationSettings.style.display = moderationCheckbox.checked ? 'block' : 'none';
            }
        
            // Función para alternar visibilidad de los campos de respuestas
            function toggleReplyFields() {
                replySettings.style.display = repliesCheckbox.checked ? 'block' : 'none';
            }
        
            // Inicializar visibilidad en base al estado actual
            toggleModerationFields();
            toggleReplyFields();
        
            // Escuchar cambios en los checkboxes
            moderationCheckbox.addEventListener('change', toggleModerationFields);
            repliesCheckbox.addEventListener('change', toggleReplyFields);
        });
    </script>
    <?php
});

function easy_gpt_reply_default_author_render() {
    $options = get_option('easy_gpt_options');
    $users = get_users();
    echo "<select name='easy_gpt_options[easy_gpt_reply_default_author]'>";
    foreach ($users as $user) {
        echo "<option value='" . esc_attr($user->ID) . "' " . selected($options['easy_gpt_reply_default_author'] ?? '', $user->ID, false) . ">" . esc_html($user->display_name) . "</option>";
    }
    echo "</select>";
}

function easy_gpt_reply_time_limit_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_reply_time_limit']) ? intval($options['easy_gpt_reply_time_limit']) : 7;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_reply_time_limit]' min='1' value='" . esc_attr($value) . "'>";
    echo "<p><small>Set the maximum age (in days) of a comment that will be processed for auto reply (default: 7 days).</small></p>";
}

function easy_gpt_include_citations_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_include_citations']) ? $options['easy_gpt_include_citations'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_include_citations]' value='1' " . checked($value, '1', false) . ">";
    echo "<small>Check this box to include in-text citations throughout the article.</small>";
}

function easy_gpt_final_review_render() {
    $options = get_option('easy_gpt_options');
    $value = isset($options['easy_gpt_final_review']) ? $options['easy_gpt_final_review'] : '0';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_final_review]' value='1' " . checked($value, '1', false) . ">";
    echo '<small>' . esc_html__('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>';

}

function render_easy_gpt_refresh_enabled() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_refresh_enabled']) ? checked(1, $options['easy_gpt_refresh_enabled'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_refresh_enabled]' value='1' $checked>";
    echo "<p style='color: #d63638; margin-top: 5px;'><strong>⚠️ Important:</strong> We recommend creating a backup before enabling automatic article updates, in case you want to revert the changes.</p>";
}


function render_easy_gpt_refresh_interval() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_interval'] ?? 'weekly';
    echo "<select name='easy_gpt_options[easy_gpt_refresh_interval]'>
            <option value='daily' ".selected($value, 'daily', false).">Daily</option>
            <option value='weekly' ".selected($value, 'weekly', false).">Weekly</option>
            <option value='monthly' ".selected($value, 'monthly', false).">Monthly</option>
        </select>";
}

function render_easy_gpt_refresh_limit() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_limit'] ?? 5;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_refresh_limit]' value='".esc_attr($value)."' min='1'>";
    echo "<p style='color: #cc0000; font-size: 13px; margin-top: 5px; max-width: 600px;'>
        ⚠️ Not recommended to exceed 250 refreshes per day, as it may cause server overload, timeouts, or cron issues.
    </p>";
}

function render_easy_gpt_refresh_min_age_days() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_min_age_days'] ?? 180;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_refresh_min_age_days]' value='".esc_attr($value)."' min='0'> <small>Minimum number of days since last update or publish date.</small>";
}

function render_easy_gpt_refresh_priority() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_priority'] ?? 'oldest_first';
    echo "<select name='easy_gpt_options[easy_gpt_refresh_priority]'>
            <option value='oldest_first' ".selected($value, 'oldest_first', false).">Oldest first</option>
            <option value='newest_first' ".selected($value, 'newest_first', false).">Newest first</option>
        </select>";
}

function render_easy_gpt_refresh_update_images() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_refresh_update_images']) ? checked(1, $options['easy_gpt_refresh_update_images'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_refresh_update_images]' value='1' $checked>";
}

function render_easy_gpt_refresh_image_replace_existing() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_image_replace_existing'] ?? 'keep';
    echo "<select name='easy_gpt_options[easy_gpt_refresh_image_replace_existing]'>
            <option value='replace' ".selected($value, 'replace', false).">Replace existing images</option>
            <option value='keep' ".selected($value, 'keep', false).">Keep existing images</option>
        </select>";
}

function render_easy_gpt_refresh_image_add_new() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_image_add_new'] ?? 0;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_refresh_image_add_new]' value='".esc_attr($value)."' min='0'>";
}

function render_easy_gpt_refresh_image_featured_behavior() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_image_featured_behavior'] ?? 'set_if_none';
    echo "<select name='easy_gpt_options[easy_gpt_refresh_image_featured_behavior]'>
            <option value='none' ".selected($value, 'none', false).">Do nothing</option>
            <option value='set_if_none' ".selected($value, 'set_if_none', false).">Set if none exists</option>
            <option value='always_replace' ".selected($value, 'always_replace', false).">Always replace featured image</option>
        </select>";
}

function render_easy_gpt_refresh_youtube_enabled() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_refresh_youtube_enabled']) ? checked(1, $options['easy_gpt_refresh_youtube_enabled'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_refresh_youtube_enabled]' value='1' $checked>";
}

function render_easy_gpt_refresh_youtube_behavior() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_refresh_youtube_behavior'] ?? 'skip_if_exists';
    echo "<select name='easy_gpt_options[easy_gpt_refresh_youtube_behavior]'>
            <option value='skip_if_exists' ".selected($value, 'skip_if_exists', false).">Do not add if one exists</option>
            <option value='replace_existing' ".selected($value, 'replace_existing', false).">Replace existing</option>
            <option value='add_also' ".selected($value, 'add_also', false).">Add even if one exists</option>
        </select>";
}


function render_easy_gpt_refresh_update_seo() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_refresh_update_seo']) ? checked(1, $options['easy_gpt_refresh_update_seo'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_refresh_update_seo]' value='1' $checked>";
}

function render_easy_gpt_refresh_update_post_date() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_refresh_update_post_date']) ? checked(1, $options['easy_gpt_refresh_update_post_date'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_refresh_update_post_date]' value='1' $checked>";
}

function easy_gpt_refresher_settings_section_callback() {
    echo '<p style="color: #555; max-width: 700px;">
        Automatically refresh old articles on a schedule. You can choose how many to refresh, update images, SEO, publish date, and more.
    </p>';
}

function easy_gpt_refresher_settings_render() {
    $options = get_option('easy_gpt_options');
    $style = empty($options['easy_gpt_refresh_enabled']) ? 'style="display:none;"' : '';

    echo "<div id='easy_gpt_refresher_fields' {$style}>";
    echo "<table class='form-table'><tbody>";

	echo "<tr><th scope='row'><label for='easy_gpt_refresh_post_types'>Content Types to Refresh</label></th><td>";
	render_easy_gpt_refresh_post_types();
	echo "</td></tr>";

	echo "<tr><th scope='row'><label for='easy_gpt_exclude_post_ids'>Exclude Posts/Pages (IDs)</label></th><td>";
	render_easy_gpt_exclude_post_ids();
	echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_interval'>Refresh Interval</label></th><td>";
    render_easy_gpt_refresh_interval();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_limit'>Posts per Interval</label></th><td>";
    render_easy_gpt_refresh_limit();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_min_age_days'>Minimum Age (days)</label></th><td>";
    render_easy_gpt_refresh_min_age_days();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_priority'>Refresh Priority</label></th><td>";
    render_easy_gpt_refresh_priority();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_update_images'>Update Images</label></th><td>";
    render_easy_gpt_refresh_update_images();
    echo "</td></tr>";

    // IMAGES: Rows wrapped with conditional IDs
    $img_toggle = empty($options['easy_gpt_refresh_update_images']) ? 'style="display:none;"' : '';
    echo "<tr id='refresh_image_replace_row' {$img_toggle}><th scope='row'><label for='easy_gpt_refresh_image_replace_existing'>Image Handling</label></th><td>";
    render_easy_gpt_refresh_image_replace_existing();
    echo "</td></tr>";

    echo "<tr id='refresh_image_add_row' {$img_toggle}><th scope='row'><label for='easy_gpt_refresh_image_add_new'>How Many New Images</label></th><td>";
    render_easy_gpt_refresh_image_add_new();
    echo "</td></tr>";

    echo "<tr id='refresh_image_featured_row' {$img_toggle}><th scope='row'><label for='easy_gpt_refresh_image_featured_behavior'>Featured Image Behavior</label></th><td>";
    render_easy_gpt_refresh_image_featured_behavior();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_youtube_enabled'>Add YouTube Video</label></th><td>";
    render_easy_gpt_refresh_youtube_enabled();
    echo "</td></tr>";

    // YOUTUBE: Row wrapped with conditional ID
    $yt_toggle = empty($options['easy_gpt_refresh_youtube_enabled']) ? 'style="display:none;"' : '';
    echo "<tr id='refresh_youtube_behavior_row' {$yt_toggle}><th scope='row'><label for='easy_gpt_refresh_youtube_behavior'>YouTube Handling</label></th><td>";
    render_easy_gpt_refresh_youtube_behavior();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_update_seo'>Update SEO</label></th><td>";
    render_easy_gpt_refresh_update_seo();
    echo "</td></tr>";

    echo "<tr><th scope='row'><label for='easy_gpt_refresh_update_post_date'>Update Publish Date</label></th><td>";
    render_easy_gpt_refresh_update_post_date();
    echo "</td></tr>";

    echo "</tbody></table>";
    echo "</div>";
}

add_action('admin_footer', function () {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const refreshToggle = document.querySelector('input[name="easy_gpt_options[easy_gpt_refresh_enabled]"]');
        const refreshFields = document.getElementById('easy_gpt_refresher_fields');

        const imageToggle = document.querySelector('input[name="easy_gpt_options[easy_gpt_refresh_update_images]"]');
        const imageRows = [
            document.querySelector('tr th label[for="easy_gpt_refresh_image_replace_existing"]')?.closest('tr'),
            document.querySelector('tr th label[for="easy_gpt_refresh_image_add_new"]')?.closest('tr'),
            document.querySelector('tr th label[for="easy_gpt_refresh_image_featured_behavior"]')?.closest('tr')
        ];

        const youtubeToggle = document.querySelector('input[name="easy_gpt_options[easy_gpt_refresh_youtube_enabled]"]');
        const youtubeRow = document.querySelector('tr th label[for="easy_gpt_refresh_youtube_behavior"]')?.closest('tr');

        function toggle(el, rows) {
            rows.forEach(row => {
                if (row) row.style.display = el?.checked ? 'table-row' : 'none';
            });
        }

        function updateUI() {
            if (refreshToggle && refreshFields) {
                refreshFields.style.display = refreshToggle.checked ? 'block' : 'none';
            }

            toggle(imageToggle, imageRows);
            toggle(youtubeToggle, [youtubeRow]);
        }

        [refreshToggle, imageToggle, youtubeToggle].forEach(el => {
            if (el) el.addEventListener('change', updateUI);
        });

        updateUI(); // Inicial
    });
    </script>
    <?php
});


//add_action('update_option_easy_gpt_options', 'easy_gpt_handle_refresh_cron_on_save', 10, 2);

function easy_gpt_handle_refresh_cron_on_save($new_value, $old_value) {
    error_log("🔧 Updating cron jobs...");

    // === REFRESH ===
    $refresh_hook = 'easy_gpt_run_article_refresh';
    $refresh_enabled_new = !empty($new_value['easy_gpt_refresh_enabled']);
    $refresh_enabled_old = !empty($old_value['easy_gpt_refresh_enabled']);

    if ($refresh_enabled_old && !$refresh_enabled_new) {
        wp_clear_scheduled_hook($refresh_hook);
        error_log('[EasyGPT] 🔴 Refresh cron unscheduled (disabled via settings)');
    } elseif (!$refresh_enabled_old && $refresh_enabled_new) {
        error_log('[EasyGPT] 🟢 Refresh cron scheduled (enabled via settings)');
        easy_gpt_schedule_refresher_cron();
    }

    // === TRANSLATION ===
    $translation_hook = 'easy_gpt_run_article_translation';
    $translation_enabled_new = !empty($new_value['easy_gpt_enable_translation']);
    $translation_enabled_old = !empty($old_value['easy_gpt_enable_translation']);

    $old_minutes = easy_gpt_get_translation_cron_frequency_minutes($old_value);
    $new_minutes = easy_gpt_get_translation_cron_frequency_minutes($new_value);

    // Desprogramar si cambia el intervalo o se desactiva
    if ($translation_enabled_old && (!$translation_enabled_new || $old_minutes !== $new_minutes)) {
        wp_clear_scheduled_hook($translation_hook);
        error_log("[EasyGPT] 🔴 Translation cron unscheduled (old interval: {$old_minutes} min)");
    }

    if ($translation_enabled_new) {
        if ($new_minutes && is_numeric($new_minutes) && $new_minutes > 0) {
            $key = 'easy_gpt_translation_' . $new_minutes;

            // Verificar si el intervalo ya está registrado
            $schedules = apply_filters('cron_schedules', []);
            if (!isset($schedules[$key])) {
                error_log("[EasyGPT] ⚠️ Interval '{$key}' not found in schedules. Registering manually...");
                add_filter('cron_schedules', function($schedules) use ($new_minutes, $key) {
                    $schedules[$key] = [
                        'interval' => $new_minutes * 60,
                        'display'  => "Translation every {$new_minutes} minutes"
                    ];
                    return $schedules;
                });
            }

            wp_schedule_event(time(), $key, $translation_hook);
            error_log("[EasyGPT] 🟢 Translation cron scheduled every {$new_minutes} minutes (settings saved)");
        } else {
            error_log('[EasyGPT] ⚠️ Translation not scheduled: invalid interval or missing frequency.');
        }
    }
}




add_action('admin_init', 'easy_gpt_check_settings_save');

add_action('admin_init', 'easy_gpt_check_settings_save');

function easy_gpt_check_settings_save() {
    if (isset($_POST['option_page']) && $_POST['option_page'] === 'easy_gpt_options_group') {
        $new_value = $_POST['easy_gpt_options'] ?? [];
        $old_value = get_option('easy_gpt_options', []);

        error_log("🔧 Updating cron jobs (admin_init triggered)");

        // Claves booleanas que podrían no venir si están desmarcadas
        $checkbox_fields = [
            'easy_gpt_refresh_enabled',
            'easy_gpt_enable_translation',
            'easy_gpt_enable_moderation',
            'easy_gpt_enable_replies',
        ];

        foreach ($checkbox_fields as $field) {
            if (!isset($new_value[$field])) {
                $new_value[$field] = '0';
                error_log("🟡 Checkbox {$field} not set in POST, defaulting to 0");
            } else {
                error_log("✅ Checkbox {$field} = {$new_value[$field]}");
            }
        }

        // Rellenar intervalos si no están en POST
        $interval_fallbacks = [
            'easy_gpt_auto_reply_cron_interval' => 60,
            'easy_gpt_moderation_cron_interval' => 60,
        ];

        foreach ($interval_fallbacks as $key => $default) {
            if (!isset($new_value[$key])) {
                $new_value[$key] = $old_value[$key] ?? $default;
                error_log("🟡 Interval {$key} not set in POST, using fallback: {$new_value[$key]}");
            } else {
                error_log("✅ Interval {$key} = {$new_value[$key]}");
            }
        }

        // Ejecutar lógica de cron
        easy_gpt_handle_refresh_cron_on_save($new_value, $old_value);
        error_log("🔁 Called easy_gpt_handle_refresh_cron_on_save");

        if (function_exists('easy_gpt_handle_comments_crons_on_save')) {
            easy_gpt_handle_comments_crons_on_save($new_value, $old_value);
            error_log("🔁 Called easy_gpt_handle_comments_crons_on_save");
        } else {
            error_log("❌ Function easy_gpt_handle_comments_crons_on_save does not exist");
        }
    }
}


function easy_gpt_handle_comments_crons_on_save($new_value, $old_value) {
    // === MODERATION CRON ===
    $moderation_hook = 'easy_gpt_moderation_cron';
    $moderation_enabled_new = !empty($new_value['easy_gpt_enable_moderation']);
    $moderation_enabled_old = !empty($old_value['easy_gpt_enable_moderation']);

    if ($moderation_enabled_old && !$moderation_enabled_new) {
        wp_clear_scheduled_hook($moderation_hook);
        error_log('[EasyGPT] 🔴 Moderation cron unscheduled (disabled via settings)');
    } elseif (!$moderation_enabled_old && $moderation_enabled_new) {
        $interval = intval($new_value['easy_gpt_moderation_cron_interval'] ?? 60);
        $key = 'easy_gpt_moderation_interval';

        add_filter('cron_schedules', function($schedules) use ($interval, $key) {
            $schedules[$key] = [
                'interval' => $interval * 60,
                'display' => "Moderation every {$interval} min"
            ];
            return $schedules;
        });

        wp_schedule_event(time(), $key, $moderation_hook);
        error_log("[EasyGPT] 🟢 Moderation cron scheduled every {$interval} minutes");
    }

    // === AUTO REPLIES CRON ===
    $reply_hook = 'easy_gpt_auto_reply_cron';
    $reply_enabled_new = !empty($new_value['easy_gpt_enable_replies']);
    $reply_enabled_old = !empty($old_value['easy_gpt_enable_replies']);

    if ($reply_enabled_old && !$reply_enabled_new) {
        wp_clear_scheduled_hook($reply_hook);
        error_log('[EasyGPT] 🔴 Auto Reply cron unscheduled (disabled via settings)');
    } elseif (!$reply_enabled_old && $reply_enabled_new) {
        $interval = intval($new_value['easy_gpt_auto_reply_cron_interval'] ?? 60);
        $key = 'easy_gpt_auto_reply_interval';

        add_filter('cron_schedules', function($schedules) use ($interval, $key) {
            $schedules[$key] = [
                'interval' => $interval * 60,
                'display' => "Auto replies every {$interval} min"
            ];
            return $schedules;
        });

        wp_schedule_event(time(), $key, $reply_hook);
        error_log("[EasyGPT] 🟢 Auto Reply cron scheduled every {$interval} minutes");
    }
}


function easy_gpt_translation_settings_section_callback() {
    echo '<p>Automatically translate posts to selected languages using AI, one at a time per execution.</p>';
}

function easy_gpt_enable_translation_render() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_enable_translation']) ? checked(1, $options['easy_gpt_enable_translation'], false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_enable_translation]' value='1' $checked>";
}

function easy_gpt_translation_languages_render() {
    if (!function_exists('pll_languages_list')) {
        echo "<p style='color: red;'>Polylang is not active.</p>";
        return;
    }

    $options = get_option('easy_gpt_options');
    $selected = $options['easy_gpt_translation_languages'] ?? [];
    $default_lang = pll_default_language();
    $languages = pll_languages_list(['fields' => 'slug']);

    echo "<select name='easy_gpt_options[easy_gpt_translation_languages][]' multiple style='height: 100px; width: 200px;'>";
    foreach ($languages as $lang) {
        if ($lang === $default_lang) continue;
        $label = strtoupper($lang);
        $is_selected = in_array($lang, $selected) ? 'selected' : '';
        echo "<option value='$lang' $is_selected>$label</option>";
    }
    echo "</select>";
    echo "<p><small>Hold Ctrl (Windows) or Command (Mac) to select multiple languages.</small></p>";
}

function render_easy_gpt_translation_limit_per_interval() {
    $options = get_option('easy_gpt_options');
    $limit = $options['easy_gpt_translation_limit_per_interval'] ?? 1;
    echo "<input type='number' name='easy_gpt_options[easy_gpt_translation_limit_per_interval]' value='" . esc_attr($limit) . "' min='1' style='width: 80px;'> <small>Articles to translate per interval</small>";
    echo "<p style='color: #cc0000; font-size: 13px; margin-top: 5px; max-width: 600px;'>
        ⚠️ Not recommended to exceed 250 translations per day, as it may cause server overload, timeouts, or cron issues.
    </p>";
}

function render_easy_gpt_translation_interval() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_translation_interval'] ?? 'daily';
    echo "<select name='easy_gpt_options[easy_gpt_translation_interval]'>
        <option value='daily' ".selected($value, 'daily', false).">Daily</option>
        <option value='weekly' ".selected($value, 'weekly', false).">Weekly</option>
        <option value='monthly' ".selected($value, 'monthly', false).">Monthly</option>
    </select>";
}

function render_easy_gpt_translation_priority() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_translation_priority'] ?? 'oldest_first';
    echo "<select name='easy_gpt_options[easy_gpt_translation_priority]'>
        <option value='oldest_first' ".selected($value, 'oldest_first', false).">Oldest first</option>
        <option value='newest_first' ".selected($value, 'newest_first', false).">Newest first</option>
    </select>";
}

function render_easy_gpt_translation_image_behavior() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_translation_image_behavior'] ?? 'keep';
    echo "<select name='easy_gpt_options[easy_gpt_translation_image_behavior]'>
        <option value='keep' ".selected($value, 'keep', false).">Keep original</option>
        <option value='update_metadata' ".selected($value, 'update_metadata', false).">Update title and alt</option>
        <option value='regenerate' ".selected($value, 'regenerate', false).">Generate new images</option>
    </select>";
}

function render_easy_gpt_translation_publish_status() {
    $options = get_option('easy_gpt_options');
    $value = $options['easy_gpt_translation_publish_status'] ?? 'draft';

    echo "<select name='easy_gpt_options[easy_gpt_translation_publish_status]'>
        <option value='draft' " . selected($value, 'draft', false) . ">Draft</option>
        <option value='publish' " . selected($value, 'publish', false) . ">Published</option>
    </select>";
    echo "<p><small>Choose whether translated articles are saved as drafts or published immediately.</small></p>";
}


function render_easy_gpt_translation_update_youtube() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_translation_update_youtube']) ? checked($options['easy_gpt_translation_update_youtube'], '1', false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_translation_update_youtube]' value='1' {$checked}> <small>Check to fetch a new YouTube video for the translated article</small>";
}

// --- Settings Render Functions ---
function easy_gpt_translate_posts_render() {
    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_translate_posts']) ? checked($options['easy_gpt_translate_posts'], '1', false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_translate_posts]' value='1' {$checked}> <small>Enable translation of blog posts.</small>";
}

function easy_gpt_translate_products_render() {
    /*if (!class_exists('PLL_WC')) {
        echo "<p style='color: #999;'>Requires <strong>Polylang for WooCommerce</strong> to be active.</p>";
        return;
    }

    $options = get_option('easy_gpt_options');
    $checked = isset($options['easy_gpt_translate_products']) ? checked($options['easy_gpt_translate_products'], '1', false) : '';
    echo "<input type='checkbox' name='easy_gpt_options[easy_gpt_translate_products]' value='1' {$checked}> <small>Enable translation of WooCommerce products.</small>";*/
}

function easy_gpt_text_api_provider_render() {
    $options = get_option('easy_gpt_options');
    $provider = $options['easy_gpt_text_api_provider'] ?? 'openai';
    $providers = [
        'openai' => 'OpenAI',
        'gemini' => 'Gemini',
        'deepseek' => 'DeepSeek',
    ];

    echo "<select name='easy_gpt_options[easy_gpt_text_api_provider]' id='easy_gpt_text_api_provider'>";
    foreach ($providers as $value => $label) {
        echo "<option value='{$value}' " . selected($provider, $value, false) . ">{$label}</option>";
    }
    echo "</select>";
}

function easy_gpt_image_api_provider_render() {
    $options = get_option('easy_gpt_options');
    $selected = $options['easy_gpt_image_api_provider'] ?? 'openai';

    echo "<select name='easy_gpt_options[easy_gpt_image_api_provider]' id='easy_gpt_image_api_provider'>";
    echo "<option value='openai' " . selected($selected, 'openai', false) . ">OpenAI</option>";
    echo "<option value='gemini' " . selected($selected, 'gemini', false) . ">Gemini</option>";
    echo "</select>";
    echo "<p><small>Select the provider to use for image generation.</small></p>";
}

function easy_gpt_translation_fields_render() {
    echo '<div id="easy_gpt_translation_fields">';
    echo '<table class="form-table"><tbody>';

    /*echo '<tr><th scope="row"><label for="easy_gpt_translate_posts">Translate Posts</label></th><td>';
    easy_gpt_translate_posts_render();
    echo '</td></tr>';*/

    /*echo '<tr><th scope="row"><label for="easy_gpt_translate_products">Translate Products</label></th><td>';
    easy_gpt_translate_products_render();
    echo '</td></tr>';*/

    echo '<tr><th scope="row"><label for="easy_gpt_translation_languages">Languages to Translate To</label></th><td>';
    easy_gpt_translation_languages_render();
    echo '</td></tr>';

    echo '<tr><th scope="row"><label for="easy_gpt_translation_publish_status">Publish Translated Articles As</label></th><td>';
    render_easy_gpt_translation_publish_status();
    echo '</td></tr>';

    echo '<tr><th scope="row"><label for="easy_gpt_translation_interval">Translation Interval</label></th><td>';
    render_easy_gpt_translation_interval();
    echo '</td></tr>';

    echo '<tr><th scope="row"><label for="easy_gpt_translation_limit_per_interval">Translations Per Interval</label></th><td>';
    render_easy_gpt_translation_limit_per_interval();
    echo '</td></tr>';	

    echo '<tr><th scope="row"><label for="easy_gpt_translation_priority">Translation Priority</label></th><td>';
    render_easy_gpt_translation_priority();
    echo '</td></tr>';

    echo '<tr><th scope="row"><label for="easy_gpt_translation_image_behavior">Image Handling</label></th><td>';
    render_easy_gpt_translation_image_behavior();
    echo '</td></tr>';

    echo '<tr><th scope="row"><label for="easy_gpt_translation_update_youtube">Update YouTube Video</label></th><td>';
    render_easy_gpt_translation_update_youtube();
    echo '</td></tr>';

    echo '</tbody></table>';
    echo '</div>';
}

function render_easy_gpt_refresh_post_types() {
    $options = get_option('easy_gpt_options');
    $selected = $options['easy_gpt_refresh_post_types'] ?? ['post'];
    ?>
    <label><input type="checkbox" name="easy_gpt_options[easy_gpt_refresh_post_types][]" value="post" <?php checked(in_array('post', $selected)); ?>> Posts</label><br>
    <label><input type="checkbox" name="easy_gpt_options[easy_gpt_refresh_post_types][]" value="page" <?php checked(in_array('page', $selected)); ?>> Pages</label>
    <?php
}

function render_easy_gpt_exclude_post_ids() {
    $options = get_option('easy_gpt_options');
    $value = esc_attr($options['easy_gpt_exclude_post_ids'] ?? '');
    ?>
    <input type="text" name="easy_gpt_options[easy_gpt_exclude_post_ids]" value="<?php echo $value; ?>" placeholder="e.g. 123,456,789" class="regular-text">
    <p class="description">Separate multiple post/page IDs with commas to exclude them from refresh.</p>
    <?php
}

add_action('admin_footer', function () {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const toggleCheckbox = document.querySelector('input[name="easy_gpt_options[easy_gpt_enable_translation]"]');
        const translationFields = document.getElementById('easy_gpt_translation_fields');

        function toggleTranslationFields() {
            if (toggleCheckbox.checked) {
                translationFields.style.display = 'block';
            } else {
                translationFields.style.display = 'none';
            }
        }

        toggleCheckbox.addEventListener('change', toggleTranslationFields);
        toggleTranslationFields();
    });
    </script>
    <?php
});
