<?php
if (!defined('ABSPATH')) {
    exit; // Esci se si accede direttamente al file
}

// Verifica che l'utente corrente abbia i permessi di amministratore
if (!current_user_can('manage_options')) {
    wp_die(
        esc_html__('You do not have sufficient permissions to access this page.', 'chatbot-ai-free-models'),
        esc_html__('Access Denied', 'chatbot-ai-free-models'),
        array(
            'response' => 403,
            'back_link' => true,
        )
    );
}

// Definisci le costanti per i nomi dei nonce
define( 'NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION', 'newcodebyte_chatbot_settings_save' );
define( 'NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD', 'newcodebyte_chatbot_settings_nonce' );

define( 'NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_ACTION', 'newcodebyte_chatbot_messages_save' );
define( 'NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_FIELD', 'newcodebyte_chatbot_messages_nonce' );

define( 'NEWCODEBYTE_CHATBOT_GUIDE_NONCE_ACTION', 'newcodebyte_chatbot_guide_save' );
define( 'NEWCODEBYTE_CHATBOT_GUIDE_NONCE_FIELD', 'newcodebyte_chatbot_guide_nonce' );

/**
 * Funzione per validare un codice colore esadecimale.
 *
 * @param string $color_code Codice colore da validare.
 * @return bool True se valido, False altrimenti.
 */
function newcodebyte_chatbot_is_valid_color_code( $color_code ) {
    return preg_match( '/^#([A-Fa-f0-9]{3}){1,2}$/', $color_code );
}

/**
 * Funzione per mostrare una notifica di errore amministrativa.
 *
 * @param string $message Messaggio di errore da mostrare.
 */
function newcodebyte_chatbot_display_admin_error_notice( $newcodebyte_message ) {
    add_action( 'admin_notices', function() use ( $newcodebyte_message ) {
        ?>
        <div class="notice notice-error is-dismissible">
            <p><?php echo esc_html( $newcodebyte_message ); ?></p>
        </div>
        <?php
    } );
}

// ===================================================================================
// INIZIO BLOCCO DI ELABORAZIONE DEI FORM
// Tutta la logica di salvataggio dei dati (da $_POST) è centralizzata qui,
// prima che qualsiasi output HTML venga inviato al browser.
// Questo previene errori "headers already sent" e assicura che la pagina
// mostri i dati aggiornati dopo il salvataggio.
// ===================================================================================

if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {

    // --- Gestione Salvataggio TAB "SETTINGS" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_settings'])) {

        if ( ! isset( $_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD] ) ), NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION ) ) {
            wp_die( esc_html__( 'Security check failed.', 'chatbot-ai-free-models' ), esc_html__( 'Error', 'chatbot-ai-free-models' ), ['response' => 403, 'back_link' => true] );
        }

        $newcodebyte_has_error_settings = false;
        $newcodebyte_error_messages_settings = array();

        $newcodebyte_chatbot_title = isset( $_POST['chatbot_title'] ) ? sanitize_text_field(wp_unslash( $_POST['chatbot_title'] )) : get_option( 'newcodebyte_chatbot_title', 'Chatbot AI Free Models' );
        $newcodebyte_chatbot_welcome_message = isset( $_POST['chatbot_welcome_message'] ) ? sanitize_text_field(wp_unslash($_POST['chatbot_welcome_message'])) : get_option( 'newcodebyte_chatbot_welcome_message', __( 'Hello! How can I assist you today?', 'chatbot-ai-free-models' ) );
        $newcodebyte_chatbot_api_key = isset( $_POST['chatbot_api_key'] ) ? sanitize_text_field(wp_unslash($_POST['chatbot_api_key'])) : get_option( 'newcodebyte_chatbot_api_key', '' );
        $newcodebyte_chatbot_model = isset( $_POST['chatbot_model'] ) ? sanitize_text_field(wp_unslash($_POST['chatbot_model'])) : get_option( 'newcodebyte_chatbot_model', 'google/gemma-3-27b-it:free' );
        $newcodebyte_chatbot_responses_info = isset( $_POST['chatbot_responses_info'] ) ? sanitize_textarea_field(wp_unslash($_POST['chatbot_responses_info'])) : get_option( 'newcodebyte_chatbot_responses_info', '' );
        $newcodebyte_chatbot_behavior_type = isset( $_POST['chatbot_behavior_type'] ) ? sanitize_textarea_field(wp_unslash($_POST['chatbot_behavior_type'])) : get_option( 'newcodebyte_chatbot_behavior_type', '' );

        // Validazione del modello
        global $newcodebyte_chatbot_models_for_validation; // Usiamo una variabile globale per i modelli
        $newcodebyte_chatbot_models_for_validation = newcodebyte_get_openrouter_models(); // Recuperiamo i modelli per la validazione
        if (!empty($newcodebyte_chatbot_models_for_validation) && !empty($newcodebyte_chatbot_model)) {
            $valid_models_ids = array_column($newcodebyte_chatbot_models_for_validation, 'id');
            if (!in_array($newcodebyte_chatbot_model, $valid_models_ids)) {
                $newcodebyte_has_error_settings = true;
                $newcodebyte_error_messages_settings[] = esc_html__('Invalid model selected. Please choose a valid model from the list.', 'chatbot-ai-free-models');
            }
        }

        if ( ! $newcodebyte_has_error_settings ) {
            update_option( 'newcodebyte_chatbot_title', $newcodebyte_chatbot_title );
            update_option( 'newcodebyte_chatbot_welcome_message', $newcodebyte_chatbot_welcome_message );
            update_option( 'newcodebyte_chatbot_api_key', $newcodebyte_chatbot_api_key );
            update_option( 'newcodebyte_chatbot_model', $newcodebyte_chatbot_model );
            update_option( 'newcodebyte_chatbot_responses_info', $newcodebyte_chatbot_responses_info );
            update_option( 'newcodebyte_chatbot_behavior_type', $newcodebyte_chatbot_behavior_type );
            update_option('newcodebyte_chatbot_enable_prechat_form', isset($_POST['chatbot_enable_prechat_form']) ? '1' : '0');
            update_option('newcodebyte_chatbot_prechat_title', isset($_POST['chatbot_prechat_title']) ? sanitize_text_field($_POST['chatbot_prechat_title']) : '');
            update_option('newcodebyte_chatbot_prechat_description', isset($_POST['chatbot_prechat_description']) ? sanitize_textarea_field($_POST['chatbot_prechat_description']) : '');
            update_option('newcodebyte_chatbot_enable_proactive_message', isset($_POST['chatbot_enable_proactive_message']) ? '1' : '0');
            update_option('newcodebyte_chatbot_proactive_message_text', isset($_POST['chatbot_proactive_message_text']) ? sanitize_textarea_field($_POST['chatbot_proactive_message_text']) : '');
            update_option('newcodebyte_chatbot_proactive_message_delay', isset($_POST['chatbot_proactive_message_delay']) ? absint($_POST['chatbot_proactive_message_delay']) : 5);
        if (isset($_POST['chatbot_display_mode'])) {
            $display_mode = sanitize_text_field($_POST['chatbot_display_mode']);
            // Controllo di sicurezza per accettare solo i valori previsti
            if (in_array($display_mode, ['widget', 'shortcode'])) {
                update_option('newcodebyte_chatbot_display_mode', $display_mode);
            }
        }                                    
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully.', 'chatbot-ai-free-models' ) . '</p></div>';
        } else {
            foreach ($newcodebyte_error_messages_settings as $error_message) {
                newcodebyte_chatbot_display_admin_error_notice($error_message);
            }
        }
    }

    // --- Gestione Salvataggio TAB "STYLE" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_style'])) {

        if ( ! isset( $_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD] ) ), NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION ) ) {
            wp_die( esc_html__( 'Security check failed.', 'chatbot-ai-free-models' ), esc_html__( 'Error', 'chatbot-ai-free-models' ), ['response' => 403, 'back_link' => true] );
        }

        $has_error_style = false;
        $error_messages_style = array();

        $color_fields_to_validate = [
            'chatbot_header_bg_color'           => [esc_html__( 'Invalid Header Background Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#038AF9'],
            'chatbot_header_text_color'         => [esc_html__( 'Invalid Header Text Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#fff'],
            'chatbot_chatbox_bg_color'          => [esc_html__( 'Invalid Chatbox Background Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#fff'],
            'chatbot_user_message_bg_color'     => [esc_html__( 'Invalid User Message Background Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#add8e6'],
            'chatbot_user_message_text_color'   => [esc_html__( 'Invalid User Message Text Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#000'],
            'chatbot_bot_message_bg_color'      => [esc_html__( 'Invalid Bot Message Background Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#ffc0cb'],
            'chatbot_bot_message_text_color'    => [esc_html__( 'Invalid Bot Message Text Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#000'],
            'chatbot_send_button_bg_color'      => [esc_html__( 'Invalid Send Button Background Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#dc3232'],
            'chatbot_send_button_text_color'    => [esc_html__( 'Invalid Send Button Text Color format. Please use a valid hex color code (e.g., #RRGGBB).', 'chatbot-ai-free-models' ), '#fff'],
        ];

        $validated_colors = [];

        foreach ($color_fields_to_validate as $field_name => $data) {
            $error_message = $data[0];
            $default_value = $data[1];
            $submitted_value = isset($_POST[$field_name]) ? sanitize_text_field(wp_unslash($_POST[$field_name])) : $default_value;

            if (newcodebyte_chatbot_is_valid_color_code($submitted_value)) {
                $validated_colors[$field_name] = $submitted_value;
            } else {
                $has_error_style = true;
                $error_messages_style[] = $error_message;
                $validated_colors[$field_name] = get_option('newcodebyte_' . $field_name, $default_value); // Mantieni il vecchio valore se non valido
            }
        }

$window_height = isset($_POST['chatbot_window_height']) ? absint($_POST['chatbot_window_height']) : 600;
// Controllo per assicurarsi che il valore sia nei limiti
if ($window_height < 300) $window_height = 300;
if ($window_height > 1000) $window_height = 1000;
update_option('newcodebyte_chatbot_window_height', $window_height);        

        if ( ! $has_error_style ) {
            foreach ($validated_colors as $field_name => $value) {
                update_option('newcodebyte_' . $field_name, $value);
            }
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully.', 'chatbot-ai-free-models' ) . '</p></div>';
        } else {
            foreach ($error_messages_style as $error_message) {
                newcodebyte_chatbot_display_admin_error_notice($error_message);
            }
        }
    }
    // --- Gestione Salvataggio CHAT POSITION ---
     if (isset($_POST['chatbot_position'])) {
        $position = sanitize_text_field($_POST['chatbot_position']);
        if (in_array($position, ['left', 'right'])) {
            update_option('newcodebyte_chatbot_position', $position);
        }
    }   

    // --- Gestione Salvataggio TAB "IMAGES" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_images'])) {

        if (!isset($_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD]) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD])), NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION)) {
            wp_die( esc_html__('Security check failed.', 'chatbot-ai-free-models'), esc_html__('Error', 'chatbot-ai-free-models'), ['response' => 403, 'back_link' => true] );
        }

        $image_fields = [
            'chatbot_user_avatar_url', 'chatbot_bot_avatar_url', 'chatbot_icon_open_url', 'chatbot_icon_closed_url'
        ];
        $has_error = false;
        
        foreach ($image_fields as $field) {
            $option_name = 'newcodebyte_' . $field;
            if (isset($_POST[$field])) {
                $new_url = esc_url_raw(wp_unslash($_POST[$field]));
                // Solo un semplice update, la validazione della mime type è complessa qui
                // e meglio gestita dallo script JS che apre il media uploader.
                // Si assume che l'URL dal media uploader sia fidato.
                update_option($option_name, $new_url);
            }
        }
        
        if (!$has_error) {
             echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Settings saved successfully.', 'chatbot-ai-free-models') . '</p></div>';
        }
    }

    // --- Gestione Salvataggio TAB "SOUNDS" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_sounds'])) {

        if (!isset($_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD]) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST[NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD])), NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION)) {
            wp_die( esc_html__('Security check failed.', 'chatbot-ai-free-models'), esc_html__('Error', 'chatbot-ai-free-models'), ['response' => 403, 'back_link' => true] );
        }

        $notification_sound_url = isset($_POST['chatbot_notification_sound_url']) ? esc_url_raw(wp_unslash($_POST['chatbot_notification_sound_url'])) : '';
        // La validazione del mime type è complessa e richiede una richiesta remota,
        // meglio affidarsi allo script JS del media uploader che limita i tipi di file.
        update_option('newcodebyte_chatbot_notification_sound_url', $notification_sound_url);

        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Settings saved successfully.', 'chatbot-ai-free-models') . '</p></div>';
    }

    // --- Gestione Salvataggio TAB "MESSAGES" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_messages'])) {
        if ( ! isset( $_POST[NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_FIELD] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_FIELD] ) ), NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_ACTION ) ) {
            wp_die( esc_html__( 'Security check failed.', 'chatbot-ai-free-models' ), esc_html__( 'Error', 'chatbot-ai-free-models' ), ['response' => 403, 'back_link' => true] );
        }
        $save_messages = isset( $_POST['chatbot_save_messages'] ) && $_POST['chatbot_save_messages'] === '1' ? '1' : '0';
        update_option( 'newcodebyte_chatbot_save_messages', $save_messages );
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully.', 'chatbot-ai-free-models' ) . '</p></div>';
    }

    // --- Gestione Salvataggio TAB "GUIDE" ---
    if (isset($_POST['newcodebyte_chatbot_save_settings_tab_guide'])) {
        if ( ! isset( $_POST[NEWCODEBYTE_CHATBOT_GUIDE_NONCE_FIELD] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[NEWCODEBYTE_CHATBOT_GUIDE_NONCE_FIELD] ) ), NEWCODEBYTE_CHATBOT_GUIDE_NONCE_ACTION ) ) {
            wp_die( esc_html__( 'Security check failed.', 'chatbot-ai-free-models' ), esc_html__( 'Error', 'chatbot-ai-free-models' ), ['response' => 403, 'back_link' => true] );
        }
        $show_powered_by = isset( $_POST['chatbot_show_powered_by'] ) && $_POST['chatbot_show_powered_by'] === '1' ? '1' : '0';
        update_option( 'newcodebyte_chatbot_show_powered_by', $show_powered_by );
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully.', 'chatbot-ai-free-models' ) . '</p></div>';
    }

} // Fine del blocco di elaborazione dei form

// ===================================================================================
// INIZIO BLOCCO DI RECUPERO DATI E VISUALIZZAZIONE
// Ora che tutti i dati sono stati eventualmente salvati, recuperiamo i valori
// più recenti dal database per mostrarli correttamente nei campi del form.
// ===================================================================================

// Recuperiamo le impostazioni correnti
$newcodebyte_chatbot_title = get_option('newcodebyte_chatbot_title', 'Chatbot AI Free Models');
$newcodebyte_chatbot_api_key = get_option('newcodebyte_chatbot_api_key', '');
$newcodebyte_chatbot_welcome_message = get_option('newcodebyte_chatbot_welcome_message',  __('Hello! How can I assist you today?', 'chatbot-ai-free-models'));
$newcodebyte_chatbot_model = get_option('newcodebyte_chatbot_model', 'google/gemma-3-27b-it:free');
$newcodebyte_chatbot_responses_info = get_option('newcodebyte_chatbot_responses_info', '');
if (empty($newcodebyte_chatbot_responses_info)) {
    $newcodebyte_chatbot_responses_info = __("Please insert all the information about your blog in this text box. This will be the knowledge base for the bot to answer user queries.", 'chatbot-ai-free-models');
}
$newcodebyte_chatbot_behavior_type = get_option('newcodebyte_chatbot_behavior_type', '');
if (empty($newcodebyte_chatbot_behavior_type)) {
    $newcodebyte_chatbot_behavior_type = __('Provide detailed instructions on how the bot should respond to user queries. For example, specify its tone, style, and any specific knowledge or expertise it should demonstrate.', 'chatbot-ai-free-models');
}

// Recuperiamo le opzioni di stile
$newcodebyte_chatbot_header_bg_color = get_option('newcodebyte_chatbot_header_bg_color', '#038AF9');
$newcodebyte_chatbot_header_text_color = get_option('newcodebyte_chatbot_header_text_color', '#fff');
$newcodebyte_chatbot_chatbox_bg_color = get_option('newcodebyte_chatbot_chatbox_bg_color', '#fff');
$newcodebyte_chatbot_user_message_bg_color = get_option('newcodebyte_chatbot_user_message_bg_color', '#add8e6');
$newcodebyte_chatbot_user_message_text_color = get_option('newcodebyte_chatbot_user_message_text_color', '#000');
$newcodebyte_chatbot_bot_message_bg_color = get_option('newcodebyte_chatbot_bot_message_bg_color', '#ffc0cb');
$newcodebyte_chatbot_bot_message_text_color = get_option('newcodebyte_chatbot_bot_message_text_color', '#000');
$newcodebyte_chatbot_send_button_bg_color = get_option('newcodebyte_chatbot_send_button_bg_color', '#dc3232');
$newcodebyte_chatbot_send_button_text_color = get_option('newcodebyte_chatbot_send_button_text_color', '#fff');

// Recuperiamo le opzioni delle immagini
$newcodebyte_chatbot_user_avatar_url = get_option('newcodebyte_chatbot_user_avatar_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-user.png');
$newcodebyte_chatbot_bot_avatar_url = get_option('newcodebyte_chatbot_bot_avatar_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-bot.png');
$newcodebyte_chatbot_icon_open_url = get_option('newcodebyte_chatbot_icon_open_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-open.png');
$newcodebyte_chatbot_icon_closed_url = get_option('newcodebyte_chatbot_icon_closed_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-closed.gif');

// Recupera URL suono notifica personalizzato
$newcodebyte_chatbot_notification_sound_url = get_option('newcodebyte_chatbot_notification_sound_url', '');

// Recuperiamo l'opzione per il link powered by
$newcodebyte_chatbot_show_powered_by = get_option('newcodebyte_chatbot_show_powered_by', '0');

// Recuperiamo l'opzione per il salvataggio messaggi
$newcodebyte_chatbot_save_messages = get_option('newcodebyte_chatbot_save_messages', '0');

// translators: %1$s: Number of characters, %2$s: Estimated number of tokens
$newcodebyte_translated_string = __( 'Characters: %1$s / Tokens (estimate): %2$s', 'chatbot-ai-free-models' );

// Funzione per ottenere i modelli disponibili da OpenRouter
function newcodebyte_get_openrouter_models() {
    $cache_key = 'newcodebyte_openrouter_models';
    $cached_models = get_transient($cache_key);

    if (false !== $cached_models) {
        return $cached_models;
    }

    $newcodebyte_api_key = get_option('newcodebyte_chatbot_api_key', '');
    if (empty($newcodebyte_api_key)) {
        return []; // Non fare la chiamata API se la chiave è vuota
    }

    $newcodebyte_server_url = 'https://openrouter.ai/api/v1/models';
    $newcodebyte_response = wp_remote_get($newcodebyte_server_url, array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $newcodebyte_api_key,
            'HTTP-Referer' => home_url(),
            'X-Title' => get_bloginfo('name')
        ),
        'timeout' => 15
    ));

    if (is_wp_error($newcodebyte_response)) {
        return array();
    }

    $newcodebyte_response_body = wp_remote_retrieve_body($newcodebyte_response);
    $newcodebyte_response_data = json_decode($newcodebyte_response_body, true);

    if (isset($newcodebyte_response_data['data'])) {
        set_transient($cache_key, $newcodebyte_response_data['data'], HOUR_IN_SECONDS); // Cache per 1 ora
        return $newcodebyte_response_data['data'];
    }

    return array();
}

$newcodebyte_chatbot_models = newcodebyte_get_openrouter_models();

?>

<div class="wrap">
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px;">
        <div>
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        </div>
        <div align="left"><a href="https://www.buymeacoffee.com/codebytewp" target="_blank"><img src="<?php echo esc_url(NCB_CHATBOT_PLUGIN_URL . 'assets/images/buymeacoffee.gif'); ?>" alt="Buy me a coffee" width="200" height="40" /></a><br />
            <b><?php esc_html_e( 'Enjoying the plugin? Click the button!', 'chatbot-ai-free-models' ); ?></b>
        </div>
    </div>
    <h2 class="nav-tab-wrapper">
        <a href="#tab-settings" class="nav-tab nav-tab-active"><?php esc_html_e( 'Settings', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-messages" class="nav-tab"><?php esc_html_e( 'Messages', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-style" class="nav-tab"><?php esc_html_e( 'Style', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-images" class="nav-tab"><?php esc_html_e( 'Images', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-sounds" class="nav-tab"><?php esc_html_e( 'Sounds', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-guide" class="nav-tab"><?php esc_html_e( 'Guide', 'chatbot-ai-free-models' ); ?></a>
        <a href="#tab-more-plugins" class="nav-tab"><?php esc_html_e( 'NewCodeByte Apps', 'chatbot-ai-free-models' ); ?></a>
    </h2>

    <div id="tab-settings" class="tab-content">
        <form method="post">
            <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION, NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD ); ?>
            <table class="form-table">
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Display Mode', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <?php
            // Leggiamo l'opzione salvata UNA SOLA VOLTA e la mettiamo in una variabile
            $current_display_mode = get_option('newcodebyte_chatbot_display_mode', 'widget');
        ?>
        <fieldset>
            <label>
                <input type="radio" name="chatbot_display_mode" value="widget" <?php checked($current_display_mode, 'widget'); ?> />
                <?php esc_html_e( 'Floating Widget on all pages', 'chatbot-ai-free-models' ); ?>
            </label>
            <br>
            <label>
                <input type="radio" name="chatbot_display_mode" value="shortcode" <?php checked($current_display_mode, 'shortcode'); ?> />
                <?php esc_html_e( 'Embedded via Shortcode', 'chatbot-ai-free-models' ); ?>
            </label>
        </fieldset>
        <p class="description">
            <?php esc_html_e( 'Choose "Embedded via Shortcode" and use', 'chatbot-ai-free-models' ); ?>
            <code>[newcodebyte_chatbot]</code>
            <?php esc_html_e( 'to display the chatbot inside a specific page or post.', 'chatbot-ai-free-models' ); ?>
        </p>
    </td>
</tr>                
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Window Title', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_title" value="<?php echo esc_attr($newcodebyte_chatbot_title); ?>" class="regular-text"></td>
                </tr>
                 <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Welcome Message', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_welcome_message" value="<?php echo esc_attr($newcodebyte_chatbot_welcome_message); ?>" class="regular-text"></td>
                </tr>

<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Enable Proactive Message', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <label>
            <input type="checkbox" name="chatbot_enable_proactive_message" value="1" 
                   <?php checked(get_option('newcodebyte_chatbot_enable_proactive_message', '0'), '1'); ?> />
            <?php esc_html_e( 'Yes, show a welcome bubble next to the chat button.', 'chatbot-ai-free-models' ); ?>
        </label>
    </td>
</tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Proactive Message Text', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <textarea name="chatbot_proactive_message_text" rows="3" class="regular-text" style="width: 100%; max-width: 400px;"><?php 
            echo esc_textarea(get_option('newcodebyte_chatbot_proactive_message_text', __("Have a question?\nAsk me!", 'chatbot-ai-free-models'))); 
        ?></textarea>
        <p class="description"><?php esc_html_e( 'This message will appear in a bubble next to the chat icon. You can use line breaks to format the text.', 'chatbot-ai-free-models' ); ?></p>
    </td>
</tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Proactive Message Delay', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <input type="number" name="chatbot_proactive_message_delay" min="0" step="1" 
               value="<?php echo esc_attr(get_option('newcodebyte_chatbot_proactive_message_delay', '5')); ?>" 
               class="small-text" /> <?php esc_html_e('seconds', 'chatbot-ai-free-models'); ?>
        <p class="description"><?php esc_html_e( 'Delay in seconds before the proactive message appears. Use 0 to show it immediately.', 'chatbot-ai-free-models' ); ?></p>
    </td>
</tr>

                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Api provider', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <b>Openrouter.ai</b>
                        <a href="https://openrouter.ai/sign-up?redirect_url=https%3A%2F%2Fopenrouter.ai%2Fsettings%2Fkeys" target="_blank" style="margin-left: 10px;"><?php esc_html_e( 'Get your API Key for free', 'chatbot-ai-free-models' ); ?></a>
                    </td>
                </tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'API Key', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <!-- 1. Contenitore per l'input e l'icona -->
        <div class="newcodebyte-password-field">
            <!-- 2. L'input ora è di tipo "password" e ha un id -->
            <input type="password" id="chatbot_api_key_field" name="chatbot_api_key" value="<?php echo esc_attr($newcodebyte_chatbot_api_key); ?>" class="regular-text" autocomplete="off">
            <!-- 3. L'icona "occhio" per mostrare/nascondere -->
            <span class="toggle-api-key dashicons dashicons-visibility" title="<?php esc_attr_e('Show/Hide API Key', 'chatbot-ai-free-models'); ?>"></span>
        </div>
    </td>
</tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Model', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <select name="chatbot_model">
                            <?php if (empty($newcodebyte_chatbot_models)): ?>
                                <option value=""><?php esc_html_e( 'No models available. Please enter a valid API Key and save.', 'chatbot-ai-free-models' ); ?></option>
                                <option value="<?php echo esc_attr($newcodebyte_chatbot_model); ?>" selected><?php echo esc_html($newcodebyte_chatbot_model); ?> (<?php esc_html_e( 'Saved', 'chatbot-ai-free-models' ); ?>)</option>
                            <?php else: ?>
                                <?php foreach ($newcodebyte_chatbot_models as $model): ?>
                                    <option value="<?php echo esc_attr($model['id']); ?>" <?php selected($newcodebyte_chatbot_model, $model['id']); ?>>
                                        <?php echo esc_html($model['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Information for responses', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <textarea name="chatbot_responses_info" rows="5" cols="120" id="chatbot_responses_info_textarea"><?php echo esc_textarea($newcodebyte_chatbot_responses_info); ?></textarea>
                        <div id="chatbot_responses_info_counter"></div>
                        <?php printf( esc_html( $newcodebyte_translated_string ), '<span id="chatbox-responses-characters">0</span>', '<span id="response-tokens">0</span>' ); ?>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Behavior type', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <textarea name="chatbot_behavior_type" rows="5" cols="120" id="chatbot_behavior_type_textarea"><?php echo esc_textarea($newcodebyte_chatbot_behavior_type); ?></textarea>
                        <div id="chatbot_behavior_type_counter"></div>
                        <?php printf( esc_html( $newcodebyte_translated_string ), '<span id="behavior-chars">0</span>', '<span id="token-count">0</span>' ); ?>
                    </td>
                </tr>
<tr valign="top">
    <th scope="row" colspan="2"><h3><?php esc_html_e( 'Pre-Chat Form Settings', 'chatbot-ai-free-models' ); ?></h3></th>
</tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Enable Pre-Chat Form', 'chatbot-ai-free-models' ); ?></th>
    <td>
        <label>
            <input type="checkbox" name="chatbot_enable_prechat_form" value="1" <?php checked(get_option('newcodebyte_chatbot_enable_prechat_form', '0'), '1'); ?> />
            <?php esc_html_e( 'Yes, ask for user name and email before starting the chat.', 'chatbot-ai-free-models' ); ?>
        </label>
    </td>
</tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Form Title', 'chatbot-ai-free-models' ); ?></th>
    <td><input type="text" name="chatbot_prechat_title" value="<?php echo esc_attr(get_option('newcodebyte_chatbot_prechat_title', 'Before we proceed…')); ?>" class="regular-text"></td>
</tr>
<tr valign="top">
    <th scope="row"><?php esc_html_e( 'Form Description', 'chatbot-ai-free-models' ); ?></th>
    <td><textarea name="chatbot_prechat_description" rows="3" class="regular-text"><?php echo esc_textarea(get_option('newcodebyte_chatbot_prechat_description', 'Please supply the following details:')); ?></textarea></td>
</tr>                
            </table>
            <input type="submit" name="newcodebyte_chatbot_save_settings_tab_settings" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>
    </div>

    <div id="tab-messages" class="tab-content" style="display:none;">
        <form method="post">
            <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_ACTION, NEWCODEBYTE_CHATBOT_MESSAGES_NONCE_FIELD ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">
                        <div style="min-width: 250px;">
                            <?php esc_html_e( 'Save Messages?', 'chatbot-ai-free-models' ); ?>
                        </div>
                    </th>
                    <td>
                        <label>
                            <input type="hidden" name="chatbot_save_messages" value="0">
                            <input type="checkbox" name="chatbot_save_messages" value="1" <?php checked($newcodebyte_chatbot_save_messages, '1'); ?> />
                            <?php esc_html_e( 'Yes, save chat messages to the database.', 'chatbot-ai-free-models' ); ?>
                        </label>
                        <p class="description"><?php esc_html_e( 'If enabled, chat messages will be stored in the database. Disabling this will prevent new messages from being saved.', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
            </table>
            <input type="submit" name="newcodebyte_chatbot_save_settings_tab_messages" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>

        <div style="margin-top: 20px; display: flex; align-items: center;">
            <button id="chatbot-delete-messages" class="button button-secondary" style="margin-right: 10px;"><?php esc_html_e( 'Delete all messages', 'chatbot-ai-free-models' ); ?></button>
            <select id="chatbot-export-format" class="regular-text" style="margin-right: 10px;">
                <option value=""><?php esc_html_e( 'Select format', 'chatbot-ai-free-models' ); ?></option>
                <option value="txt">TXT</option>
                <option value="csv">CSV</option>
                <option value="md">MD</option>
                <option value="html">HTML</option>
            </select>
            <button id="chatbot-export" class="button button-secondary"><?php esc_html_e( 'Export', 'chatbot-ai-free-models' ); ?></button>
        </div>

<div style="margin-top: 20px;">
    <table class="wp-list-table widefat fixed striped" id="chatbot-conversations-table">
        <thead>
            <tr>
                <th style="width: 25%;"><?php esc_html_e( 'User / Email', 'chatbot-ai-free-models' ); ?></th>
                <th style="width: 15%;"><?php esc_html_e( 'IP Address', 'chatbot-ai-free-models' ); ?></th>
                <th style="width: 25%;"><?php esc_html_e( 'Conversation Start', 'chatbot-ai-free-models' ); ?></th>
                <th style="width: 15%;"><?php esc_html_e( 'Message Count', 'chatbot-ai-free-models' ); ?></th>
                <th style="width: 20%;"><?php esc_html_e( 'Conversation ID', 'chatbot-ai-free-models' ); ?></th>
            </tr>
        </thead>
<tbody>
    <?php
    global $wpdb;
    $messages_table = $wpdb->prefix . 'newcodebyte_chatbot_messages';
    $conversations_table = $wpdb->prefix . 'newcodebyte_chatbot_conversations';

    // Step 1: Ottieni gli ID di tutte le conversazioni che hanno messaggi, ordinate dalla più recente.
    $conversation_ids = $wpdb->get_col("
        SELECT DISTINCT conversation_id 
        FROM {$messages_table} 
        WHERE conversation_id > 0 
        ORDER BY id DESC
    ");

    if (empty($conversation_ids)) {
        echo '<tr><td colspan="5">' . esc_html__('No messages found.', NCB_CHATBOT_TEXT_DOMAIN) . '</td></tr>';
    } else {
        foreach ($conversation_ids as $conv_id) :
            // Step 2: Per ogni ID, recupera i dettagli aggregati.
            $conv_details = $wpdb->get_row($wpdb->prepare(
                "SELECT 
                    MIN(date) as start_date, 
                    COUNT(id) as message_count, 
                    MIN(is_read) as is_read 
                FROM {$messages_table} 
                WHERE conversation_id = %d",
                $conv_id
            ), ARRAY_A);

            // Step 3: Recupera le informazioni del primo utente.
            $user_info = $wpdb->get_row($wpdb->prepare(
                "SELECT user_name, user_email, ip FROM {$messages_table} WHERE conversation_id = %d AND sender = 'User' ORDER BY date ASC LIMIT 1",
                $conv_id
            ), ARRAY_A);

            $display_name = '';
            $user_details = '';
            if (!empty($user_info['user_name'])) { $display_name = esc_html($user_info['user_name']); }
            if (!empty($user_info['user_email'])) {
                if ($display_name) { $user_details = '<br><small>' . esc_html($user_info['user_email']) . '</small>'; } 
                else { $display_name = esc_html($user_info['user_email']); }
            }
            if (!$display_name) { $display_name = esc_html__('Anonymous User', NCB_CHATBOT_TEXT_DOMAIN); }
            
            $row_class = 'conversation-row';
            if (isset($conv_details['is_read']) && intval($conv_details['is_read']) === 0) { $row_class .= ' unread'; }
    ?>
            <tr class="<?php echo esc_attr($row_class); ?>" data-conv-id="<?php echo esc_attr($conv_id); ?>" title="<?php esc_attr_e('Click to view messages', NCB_CHATBOT_TEXT_DOMAIN); ?>" >
                <td><?php echo $display_name . $user_details; ?></td>
                <td><?php echo esc_html($user_info['ip'] ?? 'N/A'); ?></td>
                <td><?php echo esc_html($conv_details['start_date']); ?></td>
                <td><?php echo esc_html($conv_details['message_count']); ?></td>
                <td><?php echo 'Chat_' . esc_html($conv_id); ?></td>
            </tr>
            <tr class="messages-container" id="messages-for-<?php echo esc_attr($conv_id); ?>" style="display: none;">
                <td colspan="5">
                    <div class="inner-messages-box">
                        <div class="loading-messages"><?php esc_html_e('Loading messages...', NCB_CHATBOT_TEXT_DOMAIN); ?></div>
                    </div>
                </td>
            </tr>
    <?php 
        endforeach;
    }
    ?>
</tbody>
    </table>
</div>
    </div>
    
    <div id="tab-style" class="tab-content" style="display:none;">
        <form method="post">
            <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION, NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD ); ?>
            <table class="form-table">
               <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Header background color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_header_bg_color" value="<?php echo esc_attr($newcodebyte_chatbot_header_bg_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                 <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Header text color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_header_text_color" value="<?php echo esc_attr($newcodebyte_chatbot_header_text_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Chatbox background color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_chatbox_bg_color" value="<?php echo esc_attr($newcodebyte_chatbot_chatbox_bg_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'User message background color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_user_message_bg_color" value="<?php echo esc_attr($newcodebyte_chatbot_user_message_bg_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'User message text color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_user_message_text_color" value="<?php echo esc_attr($newcodebyte_chatbot_user_message_text_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Bot message background color', 'chatbot-ai-free-models' ); ?></th>
                     <td><input type="text" name="chatbot_bot_message_bg_color" value="<?php echo esc_attr($newcodebyte_chatbot_bot_message_bg_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                  <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Bot message text color', 'chatbot-ai-free-models' ); ?></th>
                     <td><input type="text" name="chatbot_bot_message_text_color" value="<?php echo esc_attr($newcodebyte_chatbot_bot_message_text_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Send button background color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_send_button_bg_color" value="<?php echo esc_attr($newcodebyte_chatbot_send_button_bg_color); ?>" class="chatbot-color-picker"></td>
                </tr>
                 <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Send button text color', 'chatbot-ai-free-models' ); ?></th>
                    <td><input type="text" name="chatbot_send_button_text_color" value="<?php echo esc_attr($newcodebyte_chatbot_send_button_text_color); ?>" class="chatbot-color-picker"></td>
                </tr>

                 <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Chat Window Height', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                    <input type="number" name="chatbot_window_height" min="300" max="1000" step="10" 
                    value="<?php echo esc_attr(get_option('newcodebyte_chatbot_window_height', '600')); ?>" class="small-text" /> px
                    <p class="description"><?php esc_html_e( 'Set the height of the chat window on desktop. Default: 600px. (Min: 300, Max: 1000)', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Chatbot Position', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <select name="chatbot_position" id="chatbot_position">
                            <option value="right" <?php selected( get_option( 'newcodebyte_chatbot_position', 'right' ), 'right' ); ?>>
                                <?php esc_html_e( 'Bottom Right', 'chatbot-ai-free-models' ); ?>
                            </option>
                            <option value="left" <?php selected( get_option( 'newcodebyte_chatbot_position', 'right' ), 'left' ); ?>>
                                <?php esc_html_e( 'Bottom Left', 'chatbot-ai-free-models' ); ?>
                            </option>
                        </select>
                        <p class="description"><?php esc_html_e( 'Choose which corner of the screen the chatbot button should appear in.', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>                              
            </table>
           <input type="submit" name="newcodebyte_chatbot_save_settings_tab_style" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>
    </div>

    <div id="tab-images" class="tab-content" style="display:none;">
        <form method="post" enctype="multipart/form-data">
        <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION, NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'User Avatar', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <img src="<?php echo esc_url( $newcodebyte_chatbot_user_avatar_url, array( 'http', 'https' ) ); ?>" 
                                 alt="<?php echo esc_attr_e( 'User Avatar Preview', 'chatbot-ai-free-models' ); ?>" 
                                 style="max-width: 40px; max-height: 40px; border-radius: 50%; margin-right: 10px;" 
                                 id="chatbot_user_avatar_preview">
                            <button type="button" 
                                    class="button chatbot-upload-button" 
                                    data-target="chatbot_user_avatar_url"><?php esc_html_e( 'Upload Image', 'chatbot-ai-free-models' ); ?></button>
                        </div>
                        <input type="hidden" name="chatbot_user_avatar_url" value="<?php echo esc_url($newcodebyte_chatbot_user_avatar_url); ?>">
                        <p class="description"><?php esc_html_e( 'Accepted formats: JPG, PNG, GIF', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Bot Avatar', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <img src="<?php echo esc_url( $newcodebyte_chatbot_bot_avatar_url, array( 'http', 'https' ) ); ?>" 
                                 alt="<?php echo esc_attr_e( 'Bot Avatar Preview', 'chatbot-ai-free-models' ); ?>" 
                                 style="max-width: 40px; max-height: 40px; border-radius: 50%; margin-right: 10px;" 
                                 id="chatbot_bot_avatar_preview">
                            <button type="button" 
                                    class="button chatbot-upload-button" 
                                    data-target="chatbot_bot_avatar_url"><?php esc_html_e( 'Upload Image', 'chatbot-ai-free-models' ); ?></button>
                        </div>
                        <input type="hidden" name="chatbot_bot_avatar_url" value="<?php echo esc_url($newcodebyte_chatbot_bot_avatar_url); ?>">
                        <p class="description"><?php esc_html_e( 'Accepted formats: JPG, PNG, GIF', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Chat Open Icon', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <img src="<?php echo esc_url($newcodebyte_chatbot_icon_open_url, array( 'http', 'https' ) ); ?>" 
                                 alt="<?php echo esc_attr_e( 'Chat Open Icon Preview', 'chatbot-ai-free-models' ); ?>" 
                                 style="max-width: 40px; max-height: 40px; border-radius: 50%; margin-right: 10px;" 
                                 id="chatbot_icon_open_preview">
                            <button type="button" 
                                    class="button chatbot-upload-button" 
                                    data-target="chatbot_icon_open_url"><?php esc_html_e( 'Upload Image', 'chatbot-ai-free-models' ); ?></button>
                        </div>
                        <input type="hidden" name="chatbot_icon_open_url" value="<?php echo esc_url($newcodebyte_chatbot_icon_open_url); ?>">
                        <p class="description"><?php esc_html_e( 'Accepted formats: JPG, PNG, GIF', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Chat Closed Icon', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <img src="<?php echo esc_url($newcodebyte_chatbot_icon_closed_url, array( 'http', 'https' ) ); ?>" 
                                 alt="<?php echo esc_attr_e( 'Chat Closed Icon Preview', 'chatbot-ai-free-models' ); ?>" 
                                 style="max-width: 40px; max-height: 40px; border-radius: 50%; margin-right: 10px;" 
                                 id="chatbot_icon_closed_preview">
                            <button type="button" 
                                    class="button chatbot-upload-button" 
                                    data-target="chatbot_icon_closed_url"><?php esc_html_e( 'Upload Image', 'chatbot-ai-free-models' ); ?></button>
                        </div>
                        <input type="hidden" name="chatbot_icon_closed_url" value="<?php echo esc_url($newcodebyte_chatbot_icon_closed_url); ?>">
                        <p class="description"><?php esc_html_e( 'Accepted formats: JPG, PNG, GIF', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
            </table>
            <input type="submit" name="newcodebyte_chatbot_save_settings_tab_images" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>
    </div>

    <div id="tab-sounds" class="tab-content" style="display:none;">
        <form method="post">
            <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_ACTION, NEWCODEBYTE_CHATBOT_SETTINGS_NONCE_FIELD ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php esc_html_e( 'Notification Sound', 'chatbot-ai-free-models' ); ?></th>
                    <td>
                        <div style="display: flex; align-items: center;">
                            <audio id="chatbot_notification_sound_preview" src="<?php echo esc_url($newcodebyte_chatbot_notification_sound_url); ?>" controls style="max-width: 200px; margin-right: 10px; display: <?php echo empty($newcodebyte_chatbot_notification_sound_url) ? 'none' : 'block'; ?>;"></audio>
                            <button type="button" class="button chatbot-upload-button" data-target="chatbot_notification_sound_url"><?php esc_html_e( 'Upload Sound', 'chatbot-ai-free-models' ); ?></button>
                        </div>
                        <input type="hidden" name="chatbot_notification_sound_url" value="<?php echo esc_url($newcodebyte_chatbot_notification_sound_url); ?>">
                        <?php if (!empty($newcodebyte_chatbot_notification_sound_url)): ?>
                            <p class="description">
                                <?php esc_html_e( 'Current sound file:', 'chatbot-ai-free-models' ); ?> 
                                <strong><?php echo esc_html(basename($newcodebyte_chatbot_notification_sound_url)); ?></strong>
                            </p>
                        <?php endif; ?>
                        <p class="description"><?php esc_html_e( 'Upload a custom sound for new notifications (MP3, WAV, or OGG format). If no sound is uploaded, the default sound will be used.', 'chatbot-ai-free-models' ); ?></p>
                    </td>
                </tr>
            </table>
            <input type="submit" name="newcodebyte_chatbot_save_settings_tab_sounds" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>
    </div>

    <div id="tab-guide" class="tab-content" style="display:none;">
        <h3><?php esc_html_e( 'Chatbot AI Free Models - Guide', 'chatbot-ai-free-models' ); ?></h3>
        <p><?php esc_html_e( 'Thank you for installing Chatbot AI Free Models! This guide will help you configure the plugin and get the most out of it.', 'chatbot-ai-free-models' ); ?></p>
        <b><?php esc_html_e( 'Basic Configuration', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'Get an API Key: This plugin uses the OpenRouter API. Get your free API key at', 'chatbot-ai-free-models' ); ?> <a href="https://openrouter.ai/sign-up?redirect_url=https%3A%2F%2Fopenrouter.ai%2Fsettings%2Fkeys" target="_blank">OpenRouter.ai</a>. <?php esc_html_e('OpenRouter offers access to over 300 models, including ChatGPT, Claude, DeepSeek, Gemini, and many others, also in free versions such as Llama, DeepSeek, Qwen, Gemini, and many more. All with a single API key, allowing you to use a wide range of models at competitive prices, without complications!', 'chatbot-ai-free-models'); ?><br />
        <?php esc_html_e( 'Enter your API Key: Go to the "Settings" tab and enter your OpenRouter API key in the "API Key" field.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Choose a Model: Select an AI model from the "Model" dropdown. Free models have the suffix ":free" at the end of their name. You can also use paid models for better performance. Note that all models are accessed THROUGH OpenRouter, regardless of the original provider.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Provide Context: In the "Information for responses" field, enter information about your website or business.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Set the bot\'s behavior: In the "Behavior type" field, enter instructions about the bot\'s behavior.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Save Settings: Click "Save settings". Remember to refresh your website (Ctrl+F5 (Windows) or Cmd+Shift+R on Mac)) after saving, otherwise the changes may not be displayed correctly due to caching.', 'chatbot-ai-free-models' ); ?><br /><br />
        <b><?php esc_html_e( 'Customization', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'You can customize the appearance of the chatbot in the "Style" and "Images" tabs.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Style: Change the colors of the header, chatbox, messages, and send button.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Images: Change the avatars for the user and bot, and the icons for the chat button.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Sounds: In the tab "Sounds", you can change the default sound when opening the chatbot window to one of your choice; an MP3 audio file is recommended.', 'chatbot-ai-free-models' ); ?><br /><br />
        <b><?php esc_html_e( 'Troubleshooting', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'Changes not appearing? After making changes, press Ctrl+F5 (or Cmd+Shift+R on Mac) to hard refresh your browser cache.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Bot not responding? Check your API key and make sure it\'s valid. Also, check the OpenRouter status page to see if there are any known issues.', 'chatbot-ai-free-models' ); ?><br /><br />
        <b><?php esc_html_e( 'Managing Messages', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'You can view and export the messages in the "Messages" tab.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'View: See all chat messages.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Export: Export the messages in various formats (TXT, CSV, MD, HTML).', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Delete: Delete all chat messages.', 'chatbot-ai-free-models' ); ?><br /><br />
        <b><?php esc_html_e( 'Saving messages', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'You can enable or disable saving messages in the "Messages" tab.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'If enabled, all chat messages and IP will be saved in the database. If disabled, no chat messages will be saved.', 'chatbot-ai-free-models' ); ?><br />
        <?php esc_html_e( 'Important: If you enable message saving, be sure to update your privacy policy to reflect this data collection practice.', 'chatbot-ai-free-models' ); ?><br /><br />
        <b><?php esc_html_e( 'Enabling "Powered by NewCodeByte"', 'chatbot-ai-free-models' ); ?></b><br />
        <?php esc_html_e( 'Enabling "Powered by NewCodeByte" helps me support the development of this free plugin. If you enjoy Chatbot AI Free Models, please consider enabling it!', 'chatbot-ai-free-models' ); ?><br />
        <?php
        printf(
            esc_html__( 'If you\'d prefer not to display the "Powered by NewCodeByte" link, you can support me with a donation on Buy Me a Coffee via %s.', 'chatbot-ai-free-models' ),
            '<a href="' . esc_url( 'https://www.buymeacoffee.com/codebytewp' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Buy Me a Coffee', 'chatbot-ai-free-models' ) . '</a>'
        );
        esc_html_e( 'All donations are greatly appreciated and will help me continue to improve and maintain this plugin.', 'chatbot-ai-free-models' ); ?>

        <form method="post">
            <?php wp_nonce_field( NEWCODEBYTE_CHATBOT_GUIDE_NONCE_ACTION, NEWCODEBYTE_CHATBOT_GUIDE_NONCE_FIELD ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">
                        <div style="min-width: 250px;">
                            <?php esc_html_e( 'Show "Powered by NewCodeByte"?', 'chatbot-ai-free-models' ); ?>
                        </div>
                    </th>
                    <td>
                        <label>
                            <input type="hidden" name="chatbot_show_powered_by" value="0">
                            <input type="checkbox" name="chatbot_show_powered_by" value="1" <?php checked($newcodebyte_chatbot_show_powered_by, '1'); ?> />
                            <?php esc_html_e( 'Yes, show the link to support the plugin.', 'chatbot-ai-free-models' ); ?>
                        </label>
                    </td>
                </tr>
            </table>
            <input type="submit" name="newcodebyte_chatbot_save_settings_tab_guide" class="button-primary" value="<?php esc_attr_e( 'Save settings', 'chatbot-ai-free-models' ); ?>">
        </form>
    </div>
<!-- Contenitore tab plugins-->
<div id="tab-more-plugins" class="tab-content" style="display:none;">      
<div class="newcodebyte-plugins-grid">
    <div class="plugin-card">
        <img class="plugin-icon-img" src="https://ps.w.org/chatbot-ai-free-models/assets/icon-256x256.png" alt="Chatbot AI Icon">
        <div class="plugin-info">
            <h3>Chatbot AI Free Models</h3>
            <p><?php esc_html_e('Boost visitor engagement with a powerful AI Chatbot for WordPress. Automatically greet users with proactive messages, capture leads with an optional pre-chat form, and provide instant 24/7 customer support. Access GPT, Claude, Llama, and over 70 free models with a single, easy-to-use API key.', 'chatbot-ai-free-models'); ?></p>
            <div class="plugin-links">
                Link: <a href="https://wordpress.org/plugins/chatbot-ai-free-models/" target="_blank">WordPress.org</a>
            </div>
        </div>
    </div>
    <div class="plugin-card">
        <img class="plugin-icon-img" src="https://ps.w.org/smart-external-links-manager/assets/icon-256x256.png" alt="Smart Links Icon">
        <div class="plugin-info">
            <h3>Smart External Links Manager</h3>
            <p><?php esc_html_e('The complete manager for external links. Opens in new tabs, handles dynamic content (AJAX, infinite scroll), adds custom icons & CSS classes. Full control of rel attributes (nofollow, noopener, noreferrer, sponsored). Secure and XHTML Strict compliant. The professional choice for modern sites.', 'chatbot-ai-free-models'); ?></p>
            <div class="plugin-links">
                Link: <a href="https://wordpress.org/plugins/smart-external-links-manager/" target="_blank">WordPress.org</a>
            </div>
        </div>
    </div>
    <div class="plugin-card">
        <img class="plugin-icon-img" src="https://ps.w.org/advanced-redirect-manager/assets/icon-256x256.gif" alt="Smart Links Icon">
        <div class="plugin-info">
            <h3>Advanced Redirect Manager</h3>
            <p><?php esc_html_e('Your all-in-one suite for total link control and site maintenance. Manage 301/302 redirects with powerful, easy-to-use wildcard rules. Actively monitors 404 errors with a live log, letting you create fixes instantly. Our proactive Link Scanner finds and helps eliminate broken links across your entire website. The professional choice for SEO health.', 'chatbot-ai-free-models'); ?></p>
            <div class="plugin-links">
                Link: <a href="https://wordpress.org/plugins/advanced-redirect-manager/" target="_blank">WordPress.org</a>
            </div>
        </div>
    </div>        

</div>
</div><!-- Chiusura del contenitore -->
        
</div>