# mxchat-basic/1.0.10/includes/class-mxchat-admin.php

MxChat – AI Chatbot &amp; Content Generation for WordPress, version 1.0.10. 1,771 lines.

- Page: https://pluginprobe.com/plugins/mxchat-basic/1.0.10/code/includes/class-mxchat-admin.php
- Raw: https://pluginprobe.com/plugins/mxchat-basic/1.0.10/raw/includes/class-mxchat-admin.php
- Modified: 2024-09-19T00:52:48+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/mxchat-basic/1.0.10/code/includes/class-mxchat-admin.php#L10-L20`.

```php
<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class MxChat_Admin {
    private $options;
    private $chat_count;
    private $is_activated;

    public function __construct() {
        $this->options = get_option('mxchat_options');
        $this->chat_count = get_option('mxchat_chat_count', 0);
        $this->is_activated = $this->is_license_active();

        // Initialize default options if they are not set
        if (!$this->options) {
            $this->initialize_default_options();
        }

        // Add admin menu and initialize settings
        add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
        add_action('admin_init', array($this, 'mxchat_page_init'));
        add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
        add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
        add_action('admin_post_mxchat_submit_content', array($this, 'mxchat_handle_content_submission'));
        add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
        add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
        add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
        add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
        add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
        add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
        add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
        add_action('wp_ajax_mxchat_activate_license', array($this, 'mxchat_handle_activate_license'));
        add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));

    }

    // Method to check if the license is active
    private function is_license_active() {
        $license_status = get_option('mxchat_license_status', 'inactive');
        return $license_status === 'active';
    }

    // Initialize default options
    private function initialize_default_options() {
        $default_options = array(
            'api_key' => '',
            'system_prompt_instructions' => '[EXAMPLE INSTRUCTIONS] You are an AI Chatbot assistant for this website. The primary subject you should focus on is [insert proper subject here]. Your main goal is to assist visitors with questions related to this specific topic. Here are some key things to keep in mind:
            - Your name is [Chatbot Name]. Always introduce yourself as this name when appropriate.
            - Stay focused on topics related to [insert proper subject here]. If a visitor asks about an unrelated topic, politely redirect the conversation to how you can assist them with this subject. If there is an exception topic (e.g., "parking") that you should assist with, you may do so if instructed.
            - When appropriate, highlight the benefits of [insert proper subject here]. Offer to guide visitors to relevant pages or provide them with more information.
            - If a visitor asks for a purchase link or further information, provide them with this link: [Insert Purchase Link Here]. Always ensure that the link is relevant and directly related to the website\'s offerings.
            - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
            - If you reference specific content, provide a hyperlink to the relevant page using hypertext. Avoid including links that do not directly relate to the content or answer the visitor\'s query.
            - Provide answers based on the knowledge available to you. If you do not have an answer to a specific question, let the visitor know that you don’t have the information and suggest where they might find it or offer to help with something else.',
            'model' => 'gpt-3.5-turbo',
            'rate_limit' => '100',
            'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
            'top_bar_title' => 'MxChat',
            'intro_message' => 'Hello! How can I assist you today?',
            'append_to_body' => 'on',
            'close_button_color' => '#fff',
            'chatbot_bg_color' => '#fff',
            'user_message_bg_color' => '#fff',
            'user_message_font_color' => '#212121',
            'bot_message_bg_color' => '#212121',
            'bot_message_font_color' => '#fff',
            'top_bar_bg_color' => '#212121',
            'send_button_font_color' => '#212121',
            'chat_input_font_color' => '#212121',
            'chatbot_background_color' => '#212121',
            'icon_color' => '#fff',
            'enable_woocommerce_integration' => '0',
            'enable_woocommerce_order_access' => '0',
            'link_target_toggle' => 'on', 
        );


        // Merge existing options with defaults
        $existing_options = get_option('mxchat_options', array());
        $merged_options = wp_parse_args($existing_options, $default_options);

        // Update the options if they have changed
        if ($existing_options !== $merged_options) {
            update_option('mxchat_options', $merged_options);
        }

        // Update the $this->options property
        $this->options = $merged_options;
    }

    public function mxchat_add_plugin_page() {
        // Main menu page
        add_menu_page(
            'MxChat Settings',
            'MxChat',
            'manage_options',
            'mxchat-max',
            array($this, 'mxchat_create_admin_page'),
            'dashicons-testimonial',
            6
        );

        // Submenu page for Knowledge
        add_submenu_page(
            'mxchat-max',
            'Prompts',
            'Knowledge',
            'manage_options',
            'mxchat-prompts',
            array($this, 'mxchat_create_prompts_page')
        );

        // Submenu page for Chat Transcripts
        add_submenu_page(
            'mxchat-max',  // Corrected parent slug to match the main menu
            'Chat Transcripts',
            'Transcripts',
            'manage_options',
            'mxchat-transcripts',
            array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
        );

        // Submenu page for Activation Key
        add_submenu_page(
            'mxchat-max',
            'Pro Upgrade',
            'Pro Upgrade',
            'manage_options',
            'mxchat-activation',
            array($this, 'mxchat_create_activation_page')
        );
    }


public function mxchat_handle_content_submission() {
    // Check if the form was submitted and the user has sufficient permissions
    if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
        return;
    }

    // Verify the nonce field for security
    $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
    if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
        wp_die('Nonce verification failed.');
    }

    // Sanitize the content input
    $article_content = sanitize_textarea_field($_POST['article_content']);

    // Generate the embedding vector for the content
    $embedding_vector = $this->mxchat_generate_embedding($article_content);

    global $wpdb;
    $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';

    // Check if the 'source_url' column exists in the table and add it if it doesn't
    if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
        // Use wpdb::query and a prepared statement to avoid SQL injection
        $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
    }

    if (is_array($embedding_vector)) {
        // Serialize the embedding vector before storing it
        $embedding_vector_serialized = serialize($embedding_vector);

        // Insert the content and embedding vector into the database, using a prepared statement
        $inserted = $wpdb->insert(
            $table_name,
            array(
                'article_content' => $article_content,
                'embedding_vector' => $embedding_vector_serialized,
                'source_url'       => '', // Empty string as a placeholder for now, or pass a valid URL if applicable
            ),
            array(
                '%s', // Format for article_content (string)
                '%s', // Format for embedding_vector (serialized string)
                '%s', // Format for source_url (string)
            )
        );

        if ($inserted === false) {
            error_log('Error inserting content: ' . $wpdb->last_error);
            set_transient('mxchat_admin_notice', 'Error inserting content into the database. Please try again.', 30);
        } else {
            set_transient('mxchat_admin_notice', 'Content successfully submitted!', 30);
        }
    } else {
        error_log('Embedding generation failed for article content: ' . $article_content);
        set_transient('mxchat_admin_notice', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
    }

    // Redirect after setting the transient
    wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
    exit;
}

public function mxchat_display_admin_notice() {
    // Get the message from the transient
    $message = get_transient('mxchat_admin_notice');

    if ($message) {
        echo '<div class="notice notice-error is-dismissible">';
        echo '<p>' . esc_html($message) . '</p>';
        echo '</div>';

        // Delete the transient after displaying the message
        delete_transient('mxchat_admin_notice');
    }
}


    public function mxchat_handle_delete_prompt() {
        // Sanitize and validate nonce using wp_unslash and sanitize_text_field
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
            wp_die('Nonce verification failed.');
        }

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_die('You do not have sufficient permissions to delete prompts.');
        }

        // Sanitize and validate the 'id' parameter
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if ($id <= 0) {
            wp_die('Invalid prompt ID.');
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';

        // Clear relevant cache before deletion
        $cache_key = 'prompt_' . $id;
        wp_cache_delete($cache_key, 'mxchat_prompts');

        // Delete the record using a prepared statement
        $deleted = $wpdb->delete($table_name, array('id' => $id), array('%d'));

        if ($deleted !== false) {
            // Optionally, clear a general cache if you have one
            wp_cache_delete('all_prompts', 'mxchat_prompts');
        }

        // Redirect to the prompts page with a success message
        $redirect_url = add_query_arg(array(
            'page' => 'mxchat-prompts',
            'deleted' => 'true'
        ), admin_url('admin.php'));

        wp_safe_redirect($redirect_url);
        exit;
    }


public function mxchat_create_admin_page() {
    ?>
    <div class="wrap mxchat-admin">
        <?php if (!$this->is_activated): ?>
        <div class="mxchat-pro-banner">
            <p>
                Want even more features such as a fully customizable theme, WooCommerce integration, dedicated support, and much more?
                <a href="https://mxchat.ai/" target="_blank">Upgrade to MxChat Pro today and get a special launch lifetime license for only $49.97!</a>
            </p>
        </div>
        <?php endif; ?>
        <h2 class="admin-title">Mx<span class="admin-emphasis">Chat</span></h2>
        <h2 class="nav-tab-wrapper">
            <a href="#chatbot" class="nav-tab nav-tab-active" data-tab="chatbot">Chatbot</a>
            <a href="#embed" class="nav-tab" data-tab="embed">Embed</a>
            <a href="#theme" class="nav-tab" data-tab="theme">Theme</a>
            <a href="#general" class="nav-tab" data-tab="general">General</a>
        </h2>
        <form method="post" action="options.php">
            <?php settings_fields('mxchat_option_group'); ?>
            <div id="chatbot" class="tab-content active">
                <?php do_settings_sections('mxchat-chatbot'); ?>
            </div>
            <div id="embed" class="tab-content">
                <?php do_settings_sections('mxchat-embed'); ?>
            </div>
            <div id="theme" class="tab-content">
                <?php do_settings_sections('mxchat-theme'); ?>
            </div>
            <div id="general" class="tab-content">
                <?php do_settings_sections('mxchat-general'); ?>
                <div class="mxchat-general-notes">
                    <h3>Important Notes</h3>
                    <p>
                        You can add the chatbot to your site using the <code>[mxchat_chatbot floating="yes"]</code> or <code>[mxchat_chatbot floating="no"]</code> shortcode. Additionally, you can automatically append the chatbot to your site’s body element from the settings page.
                    </p>
                    <p>
                        Please note that you must have an OpenAI API key to use the chatbot. You can obtain an API key from the <a href="https://platform.openai.com/signup" target="_blank">OpenAI website</a>. It's easy to sign up, and you'll need to add credits to your account before using the chatbot. Generally, as little as $5 in credits is sufficient to get started.
                    </p>
                </div>
            </div>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}


        public function mxchat_create_transcripts_page() {
            ?>
            <div class="wrap mxchat-admin">
                <h2><?php esc_html_e('Chat Transcripts', 'mxchat'); ?></h2>
                <form id="mxchat-delete-form" method="post">
                    <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
                    <div class="mxchat-controls">
                        <label for="mxchat-select-all-transcripts" class="mxchat-select-all-label">
                            <input type="checkbox" id="mxchat-select-all-transcripts" /> <?php esc_html_e('Select All', 'mxchat'); ?>
                        </label>
                        <input type="submit" value="<?php esc_attr_e('Delete Selected', 'mxchat'); ?>" class="button button-primary delete-chats-button" />
                    </div>
                    <div id="mxchat-transcripts">
                        <!-- Transcripts will be loaded here -->
                    </div>
                </form>
            </div>
            <?php
        }




    public function mxchat_create_prompts_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';

        // Verify the nonce before processing the request
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';

        if (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce')) {
            // Sanitize input data
            $search_query = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';
            $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
        } else {
            $search_query = '';
            $current_page = 1;
        }

        $per_page = 10;

        // Create cache keys
        $cache_key_total = 'total_prompts_' . md5($search_query);
        $cache_key_prompts = 'prompts_' . md5($search_query . '_' . $current_page);

        // Retrieve total number of prompts from cache or database
        $total_prompts = wp_cache_get($cache_key_total, 'mxchat_prompts');
        if ($total_prompts === false) {
            if (!empty($search_query)) {
                $total_prompts = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(*) FROM {$table_name} WHERE article_content LIKE %s",
                        '%' . $wpdb->esc_like($search_query) . '%'
                    )
                );
            } else {
                $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
            }
            wp_cache_set($cache_key_total, $total_prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
        }

        $total_pages = ceil($total_prompts / $per_page);
        $offset = ($current_page - 1) * $per_page;

        // Retrieve prompts from cache or database
        $prompts = wp_cache_get($cache_key_prompts, 'mxchat_prompts');
        if ($prompts === false) {
            if (!empty($search_query)) {
                $prompts = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$table_name} WHERE article_content LIKE %s ORDER BY timestamp DESC LIMIT %d OFFSET %d",
                        '%' . $wpdb->esc_like($search_query) . '%',
                        $per_page,
                        $offset
                    )
                );
            } else {
                $prompts = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$table_name} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
                        $per_page,
                        $offset
                    )
                );
            }
            wp_cache_set($cache_key_prompts, $prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
        }

        ?>

        <div class="wrap mxchat-admin">
            <div class="mxchat-grid-container">

                <!-- Submit Content -->
                <div class="mxchat-grid-item full-width">
                    <h2>Submit Content</h2>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
                        <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
                        <div class="mxchat-form-group">
                            <label for="article_content">Article Content:</label>
                            <textarea name="article_content" id="article_content" required></textarea>
                            <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
                        </div>
                    </form>
                </div>

                <!-- Submit Sitemap -->
                <div class="mxchat-grid-item">
                    <h2>Submit Sitemap</h2>
                    <form id="mxchat-sitemap-form" method="post" class="mxchat-sitemap-form" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_sitemap')); ?>">
                        <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
                        <div class="mxchat-search-group">
                            <input type="url" name="sitemap_url" id="sitemap_url" placeholder="Sitemap URL" required />
                            <input type="submit" name="submit_sitemap" value="Submit Sitemap" class="button button-primary" />
                        </div>
                    </form>
                    <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"></div>
                    <div id="mxchat-loading-text" style="display: none; margin-top: 10px; color: #333;">Loading sitemap content into database, please wait...</div>
                </div>

                <!-- Search Knowledge -->
                <div class="mxchat-grid-item">
                    <h2>Search Knowledge</h2>
                    <form method="get" id="knowledge-search">
                        <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
                        <input type="hidden" name="page" value="mxchat-prompts" />
                        <div class="mxchat-search-group">
                            <input type="text" name="search" placeholder="Search Knowledge" value="<?php echo esc_attr($search_query); ?>" />
                            <input type="submit" value="Search" class="button button-primary" />
                        </div>
                    </form>
                </div>
            </div>

            <!-- Table below the forms -->
            <div class="tablenav">
                <div class="tablenav-pages">
                    <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
                    <?php
                    $page_links = paginate_links(array(
                        'base'      => add_query_arg('paged', '%#%', admin_url('admin.php?page=mxchat-prompts')),
                        'format'    => '',
                        'prev_text' => __('&laquo; Previous'),
                        'next_text' => __('Next &raquo;'),
                        'total'     => $total_pages,
                        'current'   => $current_page,
                        'add_args'  => array(
                            'search' => $search_query,
                            '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')
                        ),
                    ));

                    if ($page_links) {
                        echo '<div class="tablenav-pages">' . wp_kses_post($page_links) . '</div>';
                    }
                    ?>
                </div>
            </div>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Article Content</th>
                        <th>URL</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($prompts) {
                        foreach ($prompts as $prompt) {
                            ?>
                            <tr>
                                <td><?php echo esc_html($prompt->id); ?></td>
                                <td class="mxchat_article_content_dashboard"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></td>
                                <td class="mxchat_article_url_dashboard">
                                    <?php if (!empty($prompt->source_url)): ?>
                                        <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_prompt&id=' . esc_attr($prompt->id) . '&_wpnonce=' . wp_create_nonce('mxchat_delete_prompt_nonce'))); ?>">Delete</a>
                                </td>
                            </tr>
                            <?php
                        }
                    } else {
                        ?>
                        <tr>
                            <td colspan="4">No prompts found.</td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>

        <?php
    }

    public function mxchat_generate_embedding($text) {
        $options = get_option('mxchat_options');
        $api_key = $options['api_key'] ?? 'default_api_key';

        $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
            'body'    => wp_json_encode(array(
                'model' => 'text-embedding-ada-002',
                'input' => $text
            )),
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json'
            ),
        ));

        if (is_wp_error($response)) {
            return null;
        }

        $response_data = json_decode(wp_remote_retrieve_body($response), true);
        return $response_data['data'][0]['embedding'] ?? null;
    }

    public function mxchat_delete_chat_history() {
        if (!current_user_can('manage_options')) {
            echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
            wp_die();
        }

        check_ajax_referer('mxchat_delete_chat_history', 'security');

        global $wpdb;
        $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';

        if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
            foreach ($_POST['delete_session_ids'] as $session_id) {
                $session_id_sanitized = sanitize_text_field($session_id);

                // Clear relevant cache before deletion
                $cache_key = 'chat_session_' . $session_id_sanitized;
                wp_cache_delete($cache_key, 'mxchat_chat_sessions');

                // Perform the deletion
                $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
            }

            // Optionally, clear a general cache if you have one
            wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');

            echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
        } else {
            echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
        }

        wp_die();
    }



public function mxchat_fetch_chat_history() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';

    // Check if the current user has sufficient permissions
    if (!current_user_can('manage_options')) {
        echo esc_html__('You do not have sufficient permissions to view this page.', 'mxchat');
        wp_die();
    }

    // Fetch chat transcripts from the database, ordered by timestamp
    $chat_transcripts = $wpdb->get_results(
        $wpdb->prepare("SELECT * FROM {$table_name} ORDER BY timestamp ASC")
    );

    // If no transcripts are available, display a message
    if (empty($chat_transcripts)) {
        echo esc_html__('No chat history available.', 'mxchat');
        wp_die();
    }

    ob_start();
    $current_session_id = '';

    foreach ($chat_transcripts as $transcript) {
        // Start a new session block if session ID changes
        if ($current_session_id !== $transcript->session_id) {
            if ($current_session_id !== '') {
                echo '</div>'; // Close the previous session block
            }
            $current_session_id = sanitize_text_field($transcript->session_id);
            echo '<div class="chat-session">';
            echo '<h4><input type="checkbox" name="delete_session_ids[]" value="' . esc_attr($transcript->session_id) . '"> ' . esc_html__('Session ID:', 'mxchat') . ' ' . esc_html($current_session_id) . '</h4>';
        }

        // Format the timestamp for display
        $formatted_timestamp = date_i18n('F j, Y g:i a', strtotime($transcript->timestamp));

        // Determine the role to display (user identifier or email for users, bot for the AI)
        $role = $transcript->role;
        if ($role === 'user') {
            // Sanitize email if available
            if (!empty($transcript->user_email)) {
                $role = sanitize_email($transcript->user_email);
            } else {
                // Sanitize user identifier, anonymize if it's an IP address
                $user_identifier = sanitize_text_field($transcript->user_identifier);
                
                // Check if the user identifier is an IP address and anonymize it
                if (filter_var($user_identifier, FILTER_VALIDATE_IP)) {
                    $role = preg_replace('/\.\d+$/', '.xxx', $user_identifier); // Mask the last octet
                } else {
                    $role = $user_identifier; // If it's not an IP, just display the identifier
                }
            }
        }

        // Output the chat message
        echo '<div class="chat-message">';
        echo '<strong>' . esc_html($role) . ' (' . esc_html($formatted_timestamp) . '):</strong> ';
        echo wp_kses_post($transcript->message);
        echo '</div>';
    }

    // Close the final session block
    echo '</div>';

    $output = ob_get_clean();

    echo $output;
    wp_die();
}


public function mxchat_create_activation_page() {
    $license_status = get_option('mxchat_license_status', 'inactive');
    $license_error = get_option('mxchat_license_error', '');

    ?>
    <div class="wrap mxchat-admin">
        <h2>MxChat Pro: Activation</h2>
        <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
            <div class="error notice">
                <p><?php echo esc_html($license_error); ?></p>
            </div>
        <?php endif; ?>
        <form id="mxchat-activation-form">
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Email Address</th>
                    <td>
                        <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" />
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Activation Key</th>
                    <td>
                        <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" />
                    </td>
                </tr>
            </table>
            <?php if ($license_status !== 'active'): ?>
                <?php submit_button('Activate License', 'primary', 'activate_license'); ?>
            <?php else: ?>
                <h3>MxChat Pro</h3>
            <?php endif; ?>
        </form>
        <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
    </div>
    <?php
}



public function mxchat_page_init() {
    // Register settings
    register_setting(
        'mxchat_option_group',
        'mxchat_options',
        array($this, 'mxchat_sanitize')
    );

    // Chatbot Settings Section
    add_settings_section(
        'mxchat_chatbot_section',
        'Chatbot Settings',
        null,
        'mxchat-chatbot'
    );

    // Registering fields for the Chatbot Settings section
    add_settings_field(
        'api_key',
        'API Key',
        array($this, 'api_key_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'system_prompt_instructions',
        'AI Instructions',
        array($this, 'system_prompt_instructions_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'model',
        'Model',
        array($this, 'mxchat_model_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'top_bar_title',
        'Top Bar Title',
        array($this, 'mxchat_top_bar_title_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'intro_message',
        'Introductory Message',
        array($this, 'mxchat_intro_message_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'rate_limit',
        'Rate Limit',
        array($this, 'mxchat_rate_limit_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'rate_limit_message',
        'Rate Limit Message',
        array($this, 'mxchat_rate_limit_message_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    add_settings_field(
        'pre_chat_message',
        'Pre-Chat Message',
        array($this, 'mxchat_pre_chat_message_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

        add_settings_field(
        'append_to_body',
        'Append Chat Widget to Body',
        array($this, 'mxchat_append_to_body_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );
    
        add_settings_field(
        'privacy_toggle',
        'Toggle Privacy Notice',
        array($this, 'mxchat_privacy_toggle_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );
    
    add_settings_field(
        'link_target_toggle',
        'Open Links in a New Tab',
        array($this, 'mxchat_link_target_toggle_callback'),
        'mxchat-chatbot',
        'mxchat_chatbot_section'
    );

    // Embed Settings Section
    add_settings_section(
        'mxchat_embed_section',
        'Embed Settings',
        null,
        'mxchat-embed'
    );

    add_settings_field(
        'enable_woocommerce_integration',
        'Automatically Embed Products',
        array($this, 'mxchat_enable_woocommerce_integration_callback'),
        'mxchat-embed',
        'mxchat_embed_section'
    );
    
    add_settings_field(
        'enable_woocommerce_order_access',
        'Order History Access',
        array($this, 'mxchat_enable_woocommerce_order_access_callback'),
        'mxchat-embed',
        'mxchat_embed_section'
    );

    add_settings_field(
        'woocommerce_consumer_key',
        'WooCommerce Consumer Key',
        array($this, 'mxchat_woocommerce_consumer_key_callback'),
        'mxchat-embed',
        'mxchat_embed_section'
    );

    add_settings_field(
        'woocommerce_consumer_secret',
        'WooCommerce Consumer Secret',
        array($this, 'mxchat_woocommerce_consumer_secret_callback'),
        'mxchat-embed',
        'mxchat_embed_section'
    );

    // Theme Settings Section
    add_settings_section(
        'mxchat_theme_section',
        'Theme Settings',
        null,
        'mxchat-theme'
    );

    add_settings_field(
        'close_button_color',
        'Close Button & Title Color',
        array($this, 'mxchat_close_button_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'chatbot_bg_color',
        'Chatbot Background Color',
        array($this, 'mxchat_chatbot_bg_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'user_message_bg_color',
        'User Message Background Color',
        array($this, 'mxchat_user_message_bg_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'user_message_font_color',
        'User Message Font Color',
        array($this, 'mxchat_user_message_font_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'bot_message_bg_color',
        'Bot Message Background Color',
        array($this, 'mxchat_bot_message_bg_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'bot_message_font_color',
        'Bot Message Font Color',
        array($this, 'mxchat_bot_message_font_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'top_bar_bg_color',
        'Top Bar Background Color',
        array($this, 'mxchat_top_bar_bg_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'send_button_font_color',
        'Send Button Color',
        array($this, 'mxchat_send_button_font_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'chat_input_font_color',
        'Chat Input Font Color',
        array($this, 'mxchat_chat_input_font_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'chatbot_background_color',
        'Floating Widget Background Color',
        array($this, 'mxchat_chatbot_background_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    add_settings_field(
        'icon_color',
        'Chatbot Icon Color',
        array($this, 'mxchat_icon_color_callback'),
        'mxchat-theme',
        'mxchat_theme_section'
    );

    // General Settings Section
    add_settings_section(
        'mxchat_general_section',
        'General Information',
        null,
        'mxchat-general'
    );


}




    public function mxchat_handle_activate_license() {
        check_ajax_referer('mxchat_activate_license_nonce', 'security');

        $license_key = isset($_POST['key']) ? sanitize_text_field($_POST['key']) : '';
        $customer_email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';

        if (empty($license_key) || empty($customer_email)) {
            wp_send_json_error('Email or License Key is missing');
        }

        $product_id = 'MxChatPRO';

        $response = wp_remote_get("http://mxchat.ai/?wc-api=software-api&request=activation&email={$customer_email}&license_key={$license_key}&product_id={$product_id}");

        if (is_wp_error($response)) {
            wp_send_json_error('Activation failed due to a server error');
        }

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

        if ($data && isset($data->activated) && $data->activated) {
            update_option('mxchat_license_status', 'active');
            wp_send_json_success();
        } else {
            $error_message = isset($data->error) ? $data->error : 'Activation failed';
            update_option('mxchat_license_status', 'inactive');
            update_option('mxchat_license_error', $error_message);
            wp_send_json_error($error_message);
        }
    }


public function mxchat_rate_limit_callback() {
    $rate_limits = array('5', '10', '15', '20', '100');
    $selected_rate_limit = isset($this->options['rate_limit']) ? $this->options['rate_limit'] : '100';

    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    echo '<select id="rate_limit" name="mxchat_options[rate_limit]" ' . $disabled . '>';
    foreach ($rate_limits as $limit) {
        echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
    }
    echo '</select>';

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}

public function mxchat_rate_limit_message_callback() {
    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    printf(
        '<textarea id="rate_limit_message" name="mxchat_options[rate_limit_message]" rows="3" cols="50" %s>%s</textarea>',
        esc_attr($disabled),
        isset($this->options['rate_limit_message']) ? esc_textarea($this->options['rate_limit_message']) : 'Rate limit exceeded. Please try again later.'
    );

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}


public function mxchat_enable_woocommerce_integration_callback() {
    $checked = isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1' ? 'checked' : '';
    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    echo '<label class="toggle-switch">';
    echo '<input type="checkbox" id="enable_woocommerce_integration" name="mxchat_options[enable_woocommerce_integration]" value="1" ' . $checked . ' ' . $disabled . '>';
    echo '<span class="slider"></span>';
    echo '</label>';

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}


public function mxchat_enable_woocommerce_order_access_callback() {
    $checked = isset($this->options['enable_woocommerce_order_access']) && $this->options['enable_woocommerce_order_access'] === '1' ? 'checked' : '';
    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    echo '<label class="toggle-switch">';
    echo '<input type="checkbox" id="enable_woocommerce_order_access" name="mxchat_options[enable_woocommerce_order_access]" value="1" ' . $checked . ' ' . $disabled . '>';
    echo '<span class="slider"></span>';
    echo '</label>';

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}


    private function mxchat_add_option_field($id, $title, $callback = '') {
        add_settings_field(
            $id,
            $title,
            $callback ? array($this, $callback) : array($this, $id . '_callback'),
            'mxchat-max',
            'mxchat_setting_section_id',
            $id === 'model' ? ['label_for' => 'model'] : []
        );
    }
    
            
        public function api_key_callback() {
            $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
            echo '<input type="password" id="api_key" name="mxchat_options[api_key]" value="' . $apiKey . '" class="regular-text" />';
            echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
        }



public function mxchat_woocommerce_consumer_key_callback() {
    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    printf(
        '<input type="text" id="woocommerce_consumer_key" name="mxchat_options[woocommerce_consumer_key]" value="%s" class="regular-text" %s />',
        isset($this->options['woocommerce_consumer_key']) ? esc_attr($this->options['woocommerce_consumer_key']) : '',
        $disabled
    );

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}

public function mxchat_woocommerce_consumer_secret_callback() {
    $disabled = $this->is_activated ? '' : 'disabled';
    $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';

    echo '<div class="' . esc_attr($class) . '">';
    printf(
        '<input type="password" id="woocommerce_consumer_secret" name="mxchat_options[woocommerce_consumer_secret]" value="%s" class="regular-text" %s />',
        isset($this->options['woocommerce_consumer_secret']) ? esc_attr($this->options['woocommerce_consumer_secret']) : '',
        $disabled
    );
    echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
}



    public function mxchat_pre_chat_message_callback() {
        printf(
            '<textarea id="pre_chat_message" name="mxchat_options[pre_chat_message]" rows="5" cols="50">%s</textarea>',
            isset($this->options['pre_chat_message']) ? esc_textarea($this->options['pre_chat_message']) : ''
        );
    }

    // Callback for AI Instructions textarea
    public function system_prompt_instructions_callback() {
        printf(
            '<textarea id="system_prompt_instructions" name="mxchat_options[system_prompt_instructions]" rows="5" cols="50">%s</textarea>',
            isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''
        );
    }

    public function mxchat_model_callback() {
        $models = array(
            'gpt-4o' => 'gpt-4o',
            'gpt-4o-mini' => 'gpt-4o-mini',
            'gpt-4-turbo' => 'gpt-4-turbo',
            'gpt-4' => 'gpt-4',
            'gpt-3.5-turbo' => 'gpt-3.5-turbo',
        );

        $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';

        echo '<select id="model" name="mxchat_options[model]">';
        foreach ($models as $model_value => $model_label) {
            echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
        }
        echo '</select>';
    }

    public function mxchat_top_bar_title_callback() {
        printf(
            '<input type="text" id="top_bar_title" name="mxchat_options[top_bar_title]" value="%s" />',
            isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : ''
        );
    }

    public function mxchat_intro_message_callback() {
        printf(
            '<textarea id="intro_message" name="mxchat_options[intro_message]" rows="5" cols="50">%s</textarea>',
            isset($this->options['intro_message']) ? esc_textarea($this->options['intro_message']) : 'Hello! How can I assist you today?'
        );
    }





    public function mxchat_close_button_color_callback() {
    $disabled = $this->is_activated ? '' : 'disabled';

    echo '<div class="pro-feature-wrapper">';
    printf(
        '<input type="text" id="close_button_color" name="mxchat_options[close_button_color]" value="%s" class="my-color-field" data-default-color="#4a4a4a" %s />',
        isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '',
        esc_attr($disabled)
    );

    if (!$this->is_activated) {
        echo '<div class="pro-feature-overlay">';
        echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
        echo '</div>';
    }

    echo '</div>';
    }

    public function mxchat_chatbot_bg_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="chatbot_bg_color" name="mxchat_options[chatbot_bg_color]" value="%s" class="my-color-field" data-default-color="#f9f9f9" %s />',
            isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_user_message_bg_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="user_message_bg_color" name="mxchat_options[user_message_bg_color]" value="%s" class="my-color-field" data-default-color="#0078d7" %s />',
            isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_user_message_font_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="user_message_font_color" name="mxchat_options[user_message_font_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
            isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_bot_message_bg_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="bot_message_bg_color" name="mxchat_options[bot_message_bg_color]" value="%s" class="my-color-field" data-default-color="#e1e1e1" %s />',
            isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_bot_message_font_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="bot_message_font_color" name="mxchat_options[bot_message_font_color]" value="%s" class="my-color-field" data-default-color="#333333" %s />',
            isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_top_bar_bg_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="top_bar_bg_color" name="mxchat_options[top_bar_bg_color]" value="%s" class="my-color-field" data-default-color="#00b294" %s />',
            isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_send_button_font_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="send_button_font_color" name="mxchat_options[send_button_font_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
            isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_chatbot_background_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="chatbot_background_color" name="mxchat_options[chatbot_background_color]" value="%s" class="my-color-field" data-default-color="#000000" %s />',
            isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_icon_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="icon_color" name="mxchat_options[icon_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
            isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }

    public function mxchat_chat_input_font_color_callback() {
        $disabled = $this->is_activated ? '' : 'disabled';

        echo '<div class="pro-feature-wrapper">';
        printf(
            '<input type="text" id="chat_input_font_color" name="mxchat_options[chat_input_font_color]" value="%s" class="my-color-field" data-default-color="#555555" %s />',
            isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '',
            esc_attr($disabled)
        );

        if (!$this->is_activated) {
            echo '<div class="pro-feature-overlay">';
            echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
            echo '</div>';
        }

        echo '</div>';
    }


public function mxchat_append_to_body_callback() {
    $append_to_body_checked = isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on' ? 'checked' : '';
    echo '<label class="toggle-switch">';
    printf(
        '<input type="checkbox" id="append_to_body" name="mxchat_options[append_to_body]" %s />',
        esc_attr($append_to_body_checked)
    );
    echo '<span class="slider"></span>';
    echo '</label>';
    echo '<p class="description">Enable to append the chat widget directly to the body element or use shortcode: [mxchat_chatbot floating="yes"]</p>';
}


public function mxchat_privacy_toggle_callback() {
    // Check if the privacy toggle is enabled
    $privacy_toggle_checked = isset($this->options['privacy_toggle']) && $this->options['privacy_toggle'] === 'on' ? 'checked' : '';

    // Retrieve the stored privacy URL if it exists
    $privacy_url = isset($this->options['privacy_url']) ? esc_url($this->options['privacy_url']) : '';

    // Output the toggle switch
    echo '<label class="toggle-switch">';
    printf(
        '<input type="checkbox" id="privacy_toggle" name="mxchat_options[privacy_toggle]" %s />',
        esc_attr($privacy_toggle_checked)
    );
    echo '<span class="slider"></span>';
    echo '</label>';
    echo '<p class="description">Enable this option to display a privacy policy link below the chat widget.</p>';

    // Output the URL input field
    printf(
        '<input type="text" id="privacy_url" name="mxchat_options[privacy_url]" value="%s" placeholder="https://example.com/privacy-policy" class="regular-text" />',
        esc_attr($privacy_url)
    );
    echo '<p class="description">Enter the URL to your privacy policy page.</p>';
}

public function mxchat_link_target_toggle_callback() {
    // Check if the toggle is enabled in the options
    $link_target_toggle = isset($this->options['link_target_toggle']) && $this->options['link_target_toggle'] === 'on' ? 'checked' : '';

    // Output the toggle switch
    echo '<label class="toggle-switch">';
    printf(
        '<input type="checkbox" id="link_target_toggle" name="mxchat_options[link_target_toggle]" %s />',
        esc_attr($link_target_toggle)
    );
    echo '<span class="slider"></span>';
    echo '</label>';
    echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
}




    public function mxchat_enqueue_admin_assets() {
        wp_enqueue_style('wp-color-picker');

        // Get the plugin version or file modification time for cache busting
        $plugin_version = '1.0.10'; // Replace this with your plugin's version

        // File paths
        $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
        $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
        $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
        $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';

        // Check if files exist and get modification times
        $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
        $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
        $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
        $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
    
        // Enqueue scripts and styles with corrected paths
        wp_enqueue_script(
            'mxchat-color-picker',
            plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
            array('wp-color-picker'),
            $color_picker_version,
            true
        );

        wp_enqueue_script(
            'mxchat-embedding-check',
            plugin_dir_url(__FILE__) . '../js/embedding-check.js',
            array(),
            $embedding_check_version,
            true
        );

        wp_enqueue_script(
            'mxchat-transcripts-js',
            plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
            array('jquery'),
            $transcripts_js_version,
            true
        );

        wp_enqueue_script(
            'mxchat-admin-js',
            plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
            array('jquery'),
            $plugin_version,
            true
        );

        wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('mxchat_activate_license_nonce'),
        ));

        wp_enqueue_style(
            'mxchat-admin-css',
            plugin_dir_url(__FILE__) . '../css/admin-style.css',
            array(),
            $admin_css_version
        );

        // Use wp_json_encode for localizing script
        wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'link_target' => $link_target, 
            'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
            'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
            'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
            'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
            'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
            'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
            'close_button_color' => $this->options['close_button_color'] ?? '#fff',
            'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
            'icon_color' => $this->options['icon_color'] ?? '#fff',
            'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121'
        ));
    }

    public function mxchat_sanitize($input) {
        $new_input = array();

        if (isset($input['api_key'])) {
            $new_input['api_key'] = sanitize_text_field($input['api_key']);
        }

        if (isset($input['enable_woocommerce_integration'])) {
            $new_input['enable_woocommerce_integration'] = isset($input['enable_woocommerce_integration']) && $input['enable_woocommerce_integration'] === '1' ? '1' : '0';

        }
        
        if (isset($input['privacy_toggle'])) {
        $new_input['privacy_toggle'] = $input['privacy_toggle'];
        }
        
        // Handle link target toggle - set to 'off' if not checked
        $new_input['link_target_toggle'] = isset($input['link_target_toggle']) ? 'on' : 'off';

        
        if (isset($input['privacy_url'])) {
            // Sanitize the URL
            $new_input['privacy_url'] = esc_url_raw($input['privacy_url']);
        }
        
        if (isset($input['enable_woocommerce_order_access'])) {
            $new_input['enable_woocommerce_order_access'] = isset($input['enable_woocommerce_order_access']) && $input['enable_woocommerce_order_access'] === '1' ? '1' : '0';

        }

        if (isset($input['system_prompt_instructions'])) {
            $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
        }

        if (isset($input['mxchat_pro_email'])) {
            $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
        }

        if (isset($input['mxchat_activation_key'])) {
            $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
        }

        if (isset($input['append_to_body'])) {
            $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
        }

        if (isset($input['top_bar_title'])) {
            $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
        }

        if (isset($input['intro_message'])) {
            $new_input['intro_message'] = sanitize_text_field($input['intro_message']);
        }

        if (isset($input['rate_limit_message'])) {
            $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
        }


        if (isset($input['pre_chat_message'])) {
            $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
        }

        if (isset($input['model'])) {
            $allowed_models = array(
                'gpt-4o',
                'gpt-4o-mini',
                'gpt-4-turbo',
                'gpt-4',
                'gpt-3.5-turbo',
            );
            if (in_array($input['model'], $allowed_models)) {
                $new_input['model'] = sanitize_text_field($input['model']);
            }
        }

        // Sanitize new pro features
        if (isset($input['close_button_color'])) {
            $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
        }

        if (isset($input['chatbot_bg_color'])) {
            $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
        }

        if (isset($input['woocommerce_consumer_key'])) {
            $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
        }

        if (isset($input['woocommerce_consumer_secret'])) {
            $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
        }

        if (isset($input['user_message_bg_color'])) {
            $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
        }

        if (isset($input['user_message_font_color'])) {
            $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
        }

        if (isset($input['bot_message_bg_color'])) {
            $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
        }

        if (isset($input['bot_message_font_color'])) {
            $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
        }

        if (isset($input['top_bar_bg_color'])) {
            $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
        }

        if (isset($input['send_button_font_color'])) {
            $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
        }

        if (isset($input['chatbot_background_color'])) {
            $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
        }

        if (isset($input['icon_color'])) {
            $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
        }

        if (isset($input['chat_input_font_color'])) {
            $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
        }

        return $new_input;
    }


    // Method to append the chatbot to the body
    public function mxchat_append_chatbot_to_body() {
        $options = get_option('mxchat_options');
        if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
            echo do_shortcode('[mxchat_chatbot floating="yes"]');
        }
    }



private function mxchat_extract_main_content($html) {
    $dom = new DOMDocument;
    libxml_use_internal_errors(true); // Suppress HTML parsing errors
    @$dom->loadHTML($html);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);

    // Simplified selectors focusing on common content areas
    $selectors = [
        '//article',
        '//*[@id="content"]',
        '//*[@class="entry-content"]',
        '//main',
    ];

    foreach ($selectors as $selector) {
        $nodes = $xpath->query($selector);
        if ($nodes->length > 0) {
            $content = '';
            foreach ($nodes as $node) {
                $content .= $dom->saveHTML($node);
            }
            return $content;
        }
    }

    // Fallback: Return the entire body content if no specific selector matches
    $body = $dom->getElementsByTagName('body');
    return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
}

public function mxchat_handle_sitemap_submission() {
    if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
        return;
    }

    check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');

    $sitemap_url = esc_url_raw($_POST['sitemap_url']);

    $response = wp_remote_get($sitemap_url);
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        set_transient('mxchat_admin_notice', 'Failed to fetch the sitemap. Please check the URL and try again.', 30);
        wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
        exit;
    }

    $sitemap_content = wp_remote_retrieve_body($response);

    $xml = simplexml_load_string($sitemap_content);
    if ($xml === false) {
        set_transient('mxchat_admin_notice', 'Invalid sitemap XML. Please provide a valid sitemap.', 30);
        wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
        exit;
    }

    $embedding_success = true; // Flag to track if all embeddings are successful

    foreach ($xml->url as $url_element) {
        $page_url = (string)$url_element->loc;

        $page_response = wp_remote_get($page_url);
        if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
            continue;
        }

        $page_html = wp_remote_retrieve_body($page_response);
        $page_content = $this->mxchat_extract_main_content($page_html);
        $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);

        if (!empty($sanitized_content)) {
            $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
            if (is_array($embedding_vector)) {
                MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $this->options['api_key']);
            } else {
                $embedding_success = false; // Set flag to false if any embedding fails
            }
        }
    }

    if ($embedding_success) {
        set_transient('mxchat_admin_notice', 'Sitemap content successfully submitted!', 30);
    } else {
        set_transient('mxchat_admin_notice', 'Some content failed to embed. Please check your API key and try again.', 30);
    }

    wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
    exit;
}



private function mxchat_sanitize_content_for_api($content) {
    // Remove script, style tags, and HTML comments
    $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
    $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
    $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);

    // Remove all HTML tags and decode HTML entities
    $content = wp_strip_all_tags($content);
    $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);

    // Trim and normalize whitespace
    $content = trim(preg_replace('/\s+/', ' ', $content));

    return $content;
}


}
?>

```
