<?php
add_action('init', function () {
    $has_license = get_option('easy_gpt_license_key');
    $has_popup_flag = get_option('easy_gpt_show_welcome_popup');

    //error_log("🔍 [init] License key is " . ($has_license ?: 'EMPTY'));
    //error_log("🔍 [init] Welcome popup flag is " . var_export($has_popup_flag, true));

    // Si no hay licencia y no existe la opción -> la creamos a 1
    if (empty($has_license) && $has_popup_flag === false) {
        update_option('easy_gpt_show_welcome_popup', 1);
        //error_log("🆕 [init] No license + no popup flag → setting popup to 1");
        return;
    }

    // Si hay licencia → aseguramos que no se muestre
    if (!empty($has_license)) {
        update_option('easy_gpt_show_welcome_popup', 0);
        //error_log("🛑 [init] License found. Wizard popup disabled.");
    } else {
        //error_log("🟢 [init] No license found. Wizard popup may be shown.");
    }
});

add_action('admin_footer', 'easy_gpt_show_welcome_popup');
function easy_gpt_show_welcome_popup() {
    if (!current_user_can('manage_options')) {
        //error_log("❌ User can't manage options");
        return;
    }

    $show_popup = get_option('easy_gpt_show_welcome_popup');
    //error_log("🔍 Option 'easy_gpt_show_welcome_popup': " . var_export($show_popup, true));

    if (!$show_popup) {
        //error_log("❌ Popup is disabled (value is falsy)");
        return;
    }

    //error_log("✅ Showing Easy GPT Welcome Popup...");

$nonce_license = wp_create_nonce("easy_gpt_dismiss_welcome");
$nonce_api = wp_create_nonce("validate_api_key_nonce");
    $masked_license_key = '';
    $stored_license = get_option('easy_gpt_license_key');
    if (!empty($stored_license)) {
        $masked_license_key = str_repeat('*', strlen($stored_license) - 4) . substr($stored_license, -4);
    }
    ?>
    <style>
    #easy-gpt-welcome-popup * {
        font-family: "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
        line-height: 1.6;
    }
    .easy-gpt-wizard-step h2 {
    font-size: 24px;
    margin-bottom: 10px;
    color: #2271b1;
}

.easy-gpt-wizard-step ul {
    padding-left: 20px;
    margin-top: 10px;
}

.easy-gpt-wizard-step li {
    margin-bottom: 6px;
}
#easy-gpt-welcome-popup .button {
    padding: 8px 18px;
    font-size: 14px;
}

#easy-gpt-welcome-popup .button-primary {
    background-color: #0073aa;
    border-color: #0073aa;
}

#easy-gpt-welcome-popup .button-primary:hover {
    background-color: #006799;
    border-color: #006799;
}
$('#easy-gpt-welcome-popup').fadeIn(300);
#easy-gpt-dismiss-welcome {
    font-size: 13px;
    color: #666;
}
</style>
    <div id="easy-gpt-welcome-popup" style="display: none;">
        <div style="background: white; padding: 40px; max-width: 720px; margin: 80px auto; border: 2px solid #2271b1; border-radius: 10px; box-shadow: 0 8px 30px rgba(0,0,0,0.25); font-size: 16px;">

            <!-- STEP 0 -->
            <div id="easy-gpt-wizard-step-0" class="easy-gpt-wizard-step">
                <h2>Welcome to Easy GPT for WP 🎉</h2>
                <p>This wizard will help you set up the essential settings to start generating articles with AI.</p>
                <ul style="margin-left:20px;">
                    <li>✅ Activate your license</li>
                    <li>✅ Choose your AI provider</li>
                    <li>✅ Configure basic generation options</li>
                    <li>✅ (Optional) Start your first article</li>
                </ul>
                <p style="margin-top:20px;"><button class="button button-primary" id="easy-gpt-start-wizard">Let’s get started</button></p>
				<p style="background: #e8f4fd; border-left: 4px solid #2b8cc4; padding: 12px 16px; font-size: 13px; margin-top: 20px; border-radius: 4px;">
					<strong>🎯 Don’t have a license or an API key?</strong><br>
					Try <a href="https://nocostaiwriter.com" target="_blank" style="color:#2b8cc4; font-weight: bold;">No Cost AI Writer</a> – our free web-based article generator.<br>
					No API, no subscription. Includes WordPress export, bulk generation, scheduling and translations.
				</p>
            </div>

            <!-- STEP 1 -->
            <div id="easy-gpt-wizard-step-1" class="easy-gpt-wizard-step" style="display:none;">
                <h2>Step 1: Enter your license</h2>
                <p>Enter your license key to begin using Easy GPT for WP:</p>
                <input type="text" id="easy_gpt_license_key" style="width:100%;" placeholder="Your license key" value="<?php echo esc_attr($masked_license_key); ?>">
                <div id="easy_gpt_license_status" style="margin-top: 10px;"></div>
                <p>
                    <a href="https://easygptforwp.com/pricing-plans/" target="_blank" class="button">Purchase a license or get a free trial</a>
                    <button class="button button-primary" id="easy-gpt-next-step-1">Validate</button>
                </p>
            </div>

            <!-- STEP 2 -->
            <div id="easy-gpt-wizard-step-2" class="easy-gpt-wizard-step" style="display:none;">
                <h2>Step 2: Choose your AI provider</h2>
                <label><input type="radio" name="easy_gpt_provider" value="openai"> OpenAI – Text ✅ / Images ✅</label><br>
                <label><input type="radio" name="easy_gpt_provider" value="gemini"> Gemini – Text ✅ / Images ✅</label><br>
                <label><input type="radio" name="easy_gpt_provider" value="deepseek"> DeepSeek – Text ✅ / Images ❌</label>

                <div id="easy-gpt-api-key-container" style="display:none; margin-top: 15px;">
                    <p>Enter your API key:</p>
                    <input type="text" id="easy_gpt_api_key" style="width:100%;" placeholder="API Key">
                    <div id="easy_gpt_api_help_openai" class="easy-gpt-api-help" style="display:none; margin-top:8px;">
                        <p><small>Find your API Key in your <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI account settings</a>.</small></p>
                    </div>
                    <div id="easy_gpt_api_help_gemini" class="easy-gpt-api-help" style="display:none; margin-top:8px;">
                        <p><small>Find your API Key in your <a href="https://aistudio.google.com/app/apikey" target="_blank">Google AI Studio</a>.</small></p>
                    </div>
                    <div id="easy_gpt_api_help_deepseek" class="easy-gpt-api-help" style="display:none; margin-top:8px;">
                        <p><small>Find your API Key in your <a href="https://platform.deepseek.com/api_keys" target="_blank">DeepSeek developer dashboard</a>.</small></p>
                    </div>
                </div>
                </br>

                <div style="display: flex; gap: 10px; align-items: center; margin-top: 10px;">
                    <button class="button button-secondary" id="easy-gpt-prev-step-2">Back</button>
                    <button class="button button-primary" id="easy-gpt-validate-api">Validate API Key</button>
                    <div id="easy_gpt_api_status"></div>
                </div>
            </div>

            <!-- STEP 3 -->
            <div id="easy-gpt-wizard-step-3" class="easy-gpt-wizard-step" style="display:none;">
                <h2>Step 3: Choose your models</h2>
            
                <label for="easy_gpt_text_model">Text model:</label><br>
                <?php easy_gpt_model_render(); ?>
                
                </br>
            
                <label><input type="checkbox" id="easy_gpt_no_images"> Do not include images</label>
                
                </br>
            
                <div id="image-model-section" style="margin-top:10px;">
                    <label for="easy_gpt_image_model">Image model:</label><br>
                    <?php easy_gpt_image_model_render(); ?>
                </div>
                
                </br>
            
                <button class="button button-secondary" id="easy-gpt-prev-step-3">Back</button>
                <button class="button button-primary"  id="easy-gpt-next-step-3">Next</button>
            </div>

            <!-- STEP 4 -->
            <div id="easy-gpt-wizard-step-4" class="easy-gpt-wizard-step" style="display:none;">
                
                    <?php
                        global $easy_gpt_options;
                    ?>
                <h2>Step 4: Text settings</h2>
            
                <!-- ──────────── Language (dinámico) ──────────── -->
                <label>Language:</label><br>
                <select id="easy_gpt_default_language" style="width:100%;margin-bottom:10px;">
                    <?php
                    // $easy_gpt_options está definido fuera de la plantilla
                    foreach ( $easy_gpt_options['languages'] as $code => $label ) {
                        echo '<option value="' . esc_attr( $code ) . '">' . esc_html( $label ) . '</option>';
                    }
                    ?>
                </select>
            
                <!-- ──────────── Author ──────────── -->
                <label>Author:</label><br>
                <select id="easy_gpt_default_author" style="width:100%;margin-bottom:10px;">
                    <?php
                    foreach ( get_users( [ 'who' => 'authors' ] ) as $user ) {
                        echo '<option value="' . esc_attr( $user->ID ) . '">' . esc_html( $user->display_name ) . '</option>';
                    }
                    ?>
                </select>
            
                <!-- ──────────── Word range (sliders) ──────────── -->
                <strong>Article length (words)</strong><br>
            
                <label style="display:block;margin-top:6px;">Min:
                    <output id="easy_gpt_min_words_out">300</output>
                </label>
                <input type="range"
                       id="easy_gpt_min_words"
                       min="100" max="3000" step="50"
                       value="300"
                       style="width:100%;">
            
                <label style="display:block;margin-top:10px;">Max:
                    <output id="easy_gpt_max_words_out">1000</output>
                </label>
                <input type="range"
                       id="easy_gpt_max_words"
                       min="200" max="6000" step="100"
                       value="1000"
                       style="width:100%;margin-bottom:10px;">
            
                <!-- ──────────── H2 headings ──────────── -->
                <label>Headings (h2):</label><br>
                <input type="number"
                       id="easy_gpt_num_headings"
                       value="3" min="1" max="10"
                       style="width:100%;margin-bottom:10px;">
            

                <!-- ──────────── Navigation ──────────── -->
                <button class="button button-secondary" id="easy-gpt-prev-step-4">Back</button>
                <button class="button button-primary"  id="easy-gpt-next-step-4">Next</button>
            </div>


            <!-- STEP 5 -->
            <div id="easy-gpt-wizard-step-5" class="easy-gpt-wizard-step" style="display:none;">
                <h2>Step 5: Image settings</h2>
                <label>Number of images per article:</label><br>
                <input type="number" id="easy_gpt_num_images" value="2" min="0" max="10" style="width:100%; margin-bottom:10px;">
                <label><input type="checkbox" id="easy_gpt_set_featured_image" checked> Set the first image as featured</label><br>

                <button class="button button-secondary" id="easy-gpt-prev-step-5">Back</button>
                <button class="button button-primary" id="easy-gpt-next-step-5">Next</button>
            </div>

            <!-- STEP 6 -->
            <div id="easy-gpt-wizard-step-6" class="easy-gpt-wizard-step" style="display:none;">
                <h2>All done! 🎉</h2>
                <p>Your initial configuration is complete.</p>
            
                <div id="easy-gpt-finish-msg" style="margin-bottom:12px;display:none;"></div>
            
                <p style="display:flex;flex-direction:column;gap:8px;max-width:260px;">
                    <a id="easy-gpt-btn-generate"
                       class="easy-gpt-save-then-go button button-primary"
                       href="<?php echo admin_url('post-new.php'); ?>">
                       Generate your first article
                    </a>
                    
                    <a id="easy-gpt-btn-bulk"
                       class="easy-gpt-save-then-go button"
                       href="<?php echo admin_url('admin.php?page=easy-gpt-bulk-generate-new'); ?>">
                       Start a bulk generation
                    </a>
                    
                    <a id="easy-gpt-btn-settings"
                       class="easy-gpt-save-then-go button"
                       href="<?php echo admin_url('admin.php?page=easy-gpt-settings'); ?>">
                       Explore advanced features
                    </a>
                </p>
            
                <!-- Terminar y guardar -->
                <button class="button button-primary" id="easy-gpt-finish-setup"
                        style="margin-top:12px;">Save & Close wizard</button>
            </div>

            <div style="text-align: center; margin-top: 20px;">
                <a href="#" id="easy-gpt-dismiss-welcome">Skip setup</a>
            </div>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        /* -------------------------------------------------
         * 1)  FILTRADO DE MODELOS POR PROVEEDOR
         * ------------------------------------------------- */
        let currentProvider = null;   // recordamos el proveedor seleccionado
    
        function filterWizardModels(provider) {
            if (!provider) return;
    
            /* ---- modelos de TEXTO ---- */
            $('#easy_gpt_text_model option').each(function () {
                const match = $(this).data('api') === provider;
                $(this).prop('hidden', !match).prop('disabled', !match);
            });
            $('#easy_gpt_text_model option:not([hidden]):first').prop('selected', true);
    
            /* ---- modelos de IMAGEN ---- */
            if (provider === 'deepseek') {
                $('#image-model-section').hide();
                $('#easy_gpt_no_images').prop('checked', true);
            } else {
                $('#image-model-section').show();
                $('#easy_gpt_no_images').prop('checked', false);
    
                $('#easy_gpt_image_model option').each(function () {
                    const match = $(this).data('api') === provider;
                    $(this).prop('hidden', !match).prop('disabled', !match);
                });
                $('#easy_gpt_image_model option:not([hidden]):first').prop('selected', true);
            }
        }

        /* ════════════════════════════════════════════════
         *   2.1  Recoger todos los campos del asistente
         * ════════════════════════════════════════════════*/
        function easyGptCollectWizard () {

            /* ─── proveedor elegido ─── */
            const provider = currentProvider            // lo actualizas en el change del radio
                            || $('input[name="easy_gpt_provider"]:checked').val()
                            || '';
                    
            return {
                action   : 'easy_gpt_save_wizard_settings',
                security : '<?php echo esc_js( wp_create_nonce( "easy_gpt_save_wizard" ) ); ?>',
        
                // Paso 2
                provider : $('input[name="easy_gpt_provider"]:checked').val() || '',
                api_key  : $('#easy_gpt_api_key').val().trim(),

                text_api_provider  : provider,
                image_api_provider : $('#easy_gpt_no_images').is(':checked') ? '' : provider,

        
                // Paso 3
                text_model  : $('#easy_gpt_text_model').val(),
                image_model : $('#easy_gpt_no_images').is(':checked') ? '' : $('#easy_gpt_image_model').val(),
        
                // Paso 4
                language   : $('#easy_gpt_default_language').val(),
                author     : $('#easy_gpt_default_author').val(),
                min_words  : $('#easy_gpt_min_words').val(),
                max_words  : $('#easy_gpt_max_words').val(),
                headings   : $('#easy_gpt_num_headings').val(),

                // Paso 5 (puede no existir si no hay imágenes)
                num_images        : $('#easy_gpt_num_images').val() || 0,
                auto_images: $('#easy_gpt_no_images').is(':checked') ? 1 : 0,
                set_featured_image: $('#easy_gpt_set_featured_image').is(':checked') ? 1 : 0
            };
        }
        
        /* ════════════════════════════════════════════════
         *   2.2  Guardar y ejecutar una acción al terminar
         * ════════════════════════════════════════════════*/
        function easyGptSaveWizard (afterSave) {
            $('#easy-gpt-finish-msg').text('Saving…').show();
        
            $.post(ajaxurl, easyGptCollectWizard(), function (resp) {
                if (resp.success) {
                    afterSave();
                } else {
                    $('#easy-gpt-finish-msg')
                        .text('Could not save settings ❌: ' + (resp.data || 'unknown error'));
                }
            }).fail(function () {
                $('#easy-gpt-finish-msg').text('Ajax error while saving settings ❌');
            });
        }

        $('.easy-gpt-save-then-go').on('click', function (e) {
            e.preventDefault();                     // cancelamos la redirección
            const url = $(this).attr('href');       // destino original
        
            easyGptSaveWizard(function () {
                window.location.href = url;         // redirigimos sólo si se guardó
            });
        });

        $('#easy-gpt-finish-setup').off('click').on('click', function () {
            $(this).prop('disabled', true);
        
            easyGptSaveWizard(function () {
                $('#easy-gpt-finish-msg').text('Settings saved ✅');
        
                setTimeout(function () {
                    $('#easy-gpt-welcome-popup, #easy-gpt-backdrop').fadeOut();
                }, 700);
            });
        });
        
        
    
        // Mostrar popup
        $('body').append('<div id="easy-gpt-backdrop" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#00000055;z-index:9998;"></div>');
        $('#easy-gpt-welcome-popup').css({
            'position': 'fixed',
            'top': '0', 'left': '0',
            'width': '100%', 'height': '100%',
            'z-index': '9999',
            'display': 'flex',
            'justify-content': 'center',
            'align-items': 'center'
        }).fadeIn();

        function goToStep(n) {
            $('.easy-gpt-wizard-step').hide();
            $('#easy-gpt-wizard-step-' + n).show();
            if (n === 3) filterWizardModels(currentProvider);
        }

        $('#easy-gpt-start-wizard').on('click', () => goToStep(1));
        $('#easy-gpt-prev-step-2').on('click', () => goToStep(1));
        $('#easy-gpt-next-step-2').on('click', () => goToStep(3));
        $('#easy-gpt-prev-step-3').on('click', () => goToStep(2));
        $('#easy-gpt-next-step-3').on('click', () => $('#easy_gpt_no_images').is(':checked') ? goToStep(4) : goToStep(4));
        $('#easy-gpt-prev-step-4').on('click', () => goToStep(3));
        $('#easy-gpt-next-step-4').on('click', () => $('#easy_gpt_no_images').is(':checked') ? goToStep(6) : goToStep(5));
        $('#easy-gpt-prev-step-5').on('click', () => goToStep(4));
        $('#easy-gpt-next-step-5').on('click', () => goToStep(6));

        $('#easy-gpt-dismiss-welcome').on('click', function(e) {
            e.preventDefault();
            $('#easy-gpt-welcome-popup, #easy-gpt-backdrop').fadeOut();
            $.post(ajaxurl, {
                action: 'easy_gpt_dismiss_welcome_popup',
                security: '<?php echo esc_js($nonce_license); ?>'
            });
        });

        $('#easy-gpt-next-step-1').on('click', function () {
            const license = $('#easy_gpt_license_key').val().trim();
            if (!license) {
                $('#easy_gpt_license_status').html('<span style="color:red;">Please enter your license key.</span>');
                return;
            }
            $('#easy_gpt_license_status').html('<em>Validating license...</em>');
            $.post(ajaxurl, {
                action: 'easy_gpt_validate_license_ajax',
                license_key: license,
                security: '<?php echo esc_js($nonce_license); ?>'
            }, function(response) {
                if (response.success) {
                    $('#easy_gpt_license_status').html('<span style="color:green;">License validated!</span>');
                    setTimeout(() => goToStep(2), 600);
                } else {
                    $('#easy_gpt_license_status').html('<span style="color:red;">' + response.data + '</span>');
                }
            });
        });

        $('input[name="easy_gpt_provider"]').on('change', function () {
            currentProvider = $(this).val();          // ▲ guardamos
            filterWizardModels(currentProvider); 
            $('#easy-gpt-api-key-container').slideDown();
            $('#easy_gpt_api_key').prop('disabled', false);
            const provider = $(this).val();
            if (provider === 'deepseek') {
                $('#image-model-section').hide();
                $('#easy_gpt_no_images').hide();
                $('#easy_gpt_no_images').closest('label').hide();
                $('#easy_gpt_no_images').prop('checked', true);
            } else {
                $('#image-model-section').show();
                $('#easy_gpt_no_images').show();
                $('#easy_gpt_no_images').closest('label').show();
                $('#easy_gpt_no_images').prop('checked', false);
            }
            $('.easy-gpt-api-help').hide();
            $('#easy_gpt_api_help_' + provider).show();
        });

        $('#easy_gpt_no_images').on('change', function () {
            if ($(this).is(':checked')) {
                $('#image-model-section').slideUp();
            } else {
                $('#image-model-section').slideDown();
            }
        });
        
        $('#easy_gpt_min_words, #easy_gpt_max_words')
            .on('input', () => {
                $('#easy_gpt_min_words_out').text($('#easy_gpt_min_words').val());
                $('#easy_gpt_max_words_out').text($('#easy_gpt_max_words').val());
            })
            .trigger('input');
        
        // valida rango antes de avanzar
        $('#easy-gpt-next-step-4').off('click').on('click', () => {
            const min = +$('#easy_gpt_min_words').val(),
                  max = +$('#easy_gpt_max_words').val();
            if (min > max) { alert('Minimum words cannot exceed maximum words.'); return; }
            goToStep($('#easy_gpt_no_images').is(':checked') ? 6 : 5);
        });

        $('#easy-gpt-validate-api').on('click', function () {
            const apiKey   = $('#easy_gpt_api_key').val().trim();
            const provider = $('input[name="easy_gpt_provider"]:checked').val();
        
            if (!apiKey || !provider) {
                $('#easy_gpt_api_status').html('<span style="color:red;">Please select a provider and enter an API key.</span>');
                return;
            }
        
            // 1️⃣ Elegimos la acción correcta
            let action = '';
            switch (provider) {
                case 'openai':
                    action = 'validate_api_key';            // add_action(... validate_api_key ...)
                    break;
                case 'gemini':
                    action = 'validate_gemini_api_key';     // add_action(... validate_gemini_api_key ...)
                    break;
                case 'deepseek':
                    action = 'validate_deepseek_api_key';   // add_action(... validate_deepseek_api_key ...)
                    break;
                default:
                    $('#easy_gpt_api_status').html('<span style="color:red;">Unknown provider.</span>');
                    return;
            }
        
            $('#easy_gpt_api_status').html('<em>Validating API key...</em>');
        
            // 2️⃣ Llamamos a la acción elegida
            $.post(ajaxurl, {
                action:   action,
                api_key:  apiKey,
                security: '<?php echo esc_js($nonce_api); ?>'
            }, function (response) {
                if (response.success) {
                    $('#easy_gpt_api_status').html('<span style="color:green;">' + response.data.message + '</span>');
                    filterWizardModels(currentProvider);
                    setTimeout(() => goToStep(3), 600);
                } else {
                    $('#easy_gpt_api_status').html('<span style="color:red;">' + response.data.message + '</span>');
                }
            });
        });
    });
    </script>
    <?php
}

add_action('wp_ajax_easy_gpt_validate_license_ajax', function () {
    check_ajax_referer('easy_gpt_dismiss_welcome', 'security');

    $license_key = sanitize_text_field($_POST['license_key'] ?? '');
    if (empty($license_key)) {
        //error_log("❌ License key is empty.");
        wp_send_json_error('Please enter a license key.');
    }

    $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
    //error_log("🔐 Validating license for domain: $domain and key: $license_key");

    $response = wp_remote_post('https://easygptforwp.com/wp-json/miapi/v1/verificar_licencia/', [
        'method' => 'POST',
        'headers' => [ 'Content-Type' => 'application/json' ],
        'body' => wp_json_encode([
            'licencia' => $license_key,
            'dominio' => $domain
        ]),
        'data_format' => 'body'
    ]);

    if (is_wp_error($response)) {
        //error_log("❌ HTTP error: " . $response->get_error_message());
        wp_send_json_error('Connection error.');
    }

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

    //error_log("🔍 License check response: $body_raw");

    if (
        isset($body['message']) && 
        (
            $body['message'] === 'Licencia verificada y dominio registrado correctamente.' ||
            $body['message'] === 'Este dominio ya esta registrado con esta licencia y sigue siendo valida.'
        )
    ) {
        //error_log("✅ License is valid.");
        update_option('easy_gpt_license_key', $license_key);
        update_option('easy_gpt_license_status', 'valid');
        update_option('easy_gpt_license_expires', sanitize_text_field($body['expires'] ?? ''));
        wp_send_json_success('License verified.');
    }

    //error_log("❌ License is invalid. Message: " . ($body['message'] ?? 'No message.'));
    wp_send_json_error($body['message'] ?? 'Invalid license.');
});

/* -------------------------------------------------------------------------
 *  Helper: sólo actualiza los campos que maneja el wizard
 * ------------------------------------------------------------------------*/
function easy_gpt_merge_wizard_options( array $old, array $new ) {

	$allowed = [
		// Paso 2
		'easy_gpt_api_key',
		'easy_gpt_text_api_provider',
		'easy_gpt_image_api_provider',

		// Paso 3
		'easy_gpt_model',
		'easy_gpt_image_model',

		// Paso 4
		'easy_gpt_default_language',
		'easy_gpt_default_author',
		'easy_gpt_min_words',
		'easy_gpt_max_words',
		'easy_gpt_num_subheadings',

		// Paso 5
		'easy_gpt_num_images',
		'easy_gpt_auto_images',
		'easy_gpt_set_featured_image',
	];

	// ─── DEBUG: estado inicial ────────────────────────────
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		//error_log( '🛠️ [merge] BEFORE : ' . print_r( $old, true ) );
	}

	foreach ( $allowed as $field ) {

		// Si el wizard no envía el campo → conservar valor previo
		if ( ! array_key_exists( $field, $new ) ) {
			continue;
		}

		$value = $new[ $field ];

		// saneado mínimo
		if ( str_contains( $field, '_num_' ) || str_contains( $field, '_min_' ) || str_contains( $field, '_max_' ) ) {
			$value = absint( $value );
		} elseif ( $field === 'easy_gpt_set_featured_image' ) {
			$value = $value == 1 ? '1' : '0';
		} else {
			$value = sanitize_text_field( $value );
		}

		$old[ $field ] = $value;

		// ─── DEBUG: cada campo procesado ──────────────────
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			//error_log( sprintf( '🧩 [merge] %s => %s', $field, $value ) );
		}
	}

	// ─── DEBUG: resultado final ───────────────────────────
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		//error_log( '🛠️ [merge] AFTER  : ' . print_r( $old, true ) );
	}

	return $old;
}



add_action( 'wp_ajax_easy_gpt_save_wizard_settings', function() {
    check_ajax_referer( 'easy_gpt_save_wizard', 'security' );

    $checkbox_fields = [
        '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_include_excerpt',
        'easy_gpt_include_citations',
        'easy_gpt_final_review',
        'easy_gpt_auto_images',
        'easy_gpt_set_featured_image',
    ];

    $wizard = [];

    foreach ( $checkbox_fields as $flag ) {
        $wizard[ $flag ] = '0'; // Valor por defecto
    }

    // Ajustes del wizard
    $wizard['easy_gpt_auto_images'] = ($_POST['auto_images'] ?? '1') === '1' ? '0' : '1';
    $wizard['easy_gpt_set_featured_image'] = isset($_POST['set_featured_image']) ? ($_POST['set_featured_image'] == '1' ? '1' : '0') : '0';

    $wizard['easy_gpt_auto_categories']    = '1';
    $wizard['easy_gpt_auto_seo']           = '1';
    $wizard['easy_gpt_format_article']     = '1';

    $wizard['easy_gpt_api_key']            = sanitize_text_field( $_POST['api_key']            ?? '' );
    $wizard['easy_gpt_text_api_provider']  = sanitize_text_field( $_POST['text_api_provider']  ?? 'openai' );
    $wizard['easy_gpt_image_api_provider'] = sanitize_text_field( $_POST['image_api_provider'] ?? 'openai' );
    $wizard['easy_gpt_model']              = sanitize_text_field( $_POST['text_model']         ?? '' );
    $wizard['easy_gpt_image_model']        = sanitize_text_field( $_POST['image_model']        ?? '' );
    $wizard['easy_gpt_default_language']   = sanitize_text_field( $_POST['language']           ?? 'en' );
    $wizard['easy_gpt_default_author']     = absint( $_POST['author']                         ?? 0 );
    $wizard['easy_gpt_min_words']          = absint( $_POST['min_words']                      ?? 300 );
    $wizard['easy_gpt_max_words']          = absint( $_POST['max_words']                      ?? 1000 );
    $wizard['easy_gpt_num_subheadings']    = absint( $_POST['headings']                       ?? 3 );
    $wizard['easy_gpt_num_images']         = absint( $_POST['num_images']                     ?? 0 );
    $wizard['easy_gpt_reply_language']   = sanitize_text_field( $_POST['language']           ?? 'en' );

    // Comportamiento por defecto de funciones opcionales
    $wizard['easy_gpt_enable_translation'] = '0';
    $wizard['easy_gpt_enable_moderation']  = '0';
    $wizard['easy_gpt_enable_replies']     = '0';

    if ( defined('WP_DEBUG') && WP_DEBUG ) {
        //error_log( '[🧠 Wizard] POST data: ' . print_r($_POST, true) );
        //error_log( '[🧠 Wizard] Wizard array (before sanitize): ' . print_r($wizard, true) );
    }

    // ✅ Sanitiza y guarda solo lo que envía el wizard
    $sanitized = easy_gpt_options_sanitize( $wizard );
    update_option( 'easy_gpt_options', $sanitized );
    update_option( 'easy_gpt_show_welcome_popup', 0 );

    wp_send_json_success();
} );

add_action('wp_ajax_easy_gpt_dismiss_welcome_popup', function () {
    check_ajax_referer('easy_gpt_dismiss_welcome', 'security');
    update_option('easy_gpt_show_welcome_popup', 0);
    wp_send_json_success();
});