PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.4
MxChat – AI Chatbot & Content Generation for WordPress v1.4
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-admin.php +1926 -9982 3.2.191.4 View file →
@@ -6,31 +6,13 @@
6 6 class MxChat_Admin {
7 7 private $options;
8 8 private $chat_count;
9 9 private $is_activated;
10 - private $knowledge_manager;
11 10
12 - /**
13 - * Get whether the license is activated
14 - * @return bool
15 - */
16 - public function is_activated() {
17 - return $this->is_activated;
18 - }
19 -
20 - /**
21 - * Get plugin options
22 - * @return array
23 - */
24 - public function get_options() {
25 - return $this->options;
26 - }
27 -
28 - public function __construct($knowledge_manager = null) {
11 + public function __construct() {
29 12 $this->options = get_option('mxchat_options');
30 13 $this->chat_count = get_option('mxchat_chat_count', 0);
31 14 $this->is_activated = $this->is_license_active();
32 - $this->knowledge_manager = $knowledge_manager;
33 15
34 16 // Initialize default options if they are not set
35 17 if (!$this->options) {
36 18 $this->initialize_default_options();
@@ -37,407 +19,78 @@
37 19 }
38 20
39 21 // Add admin menu and initialize settings
40 22 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
41 - // Pro & Extensions registers at priority 30 so it always lands last in
42 - // the sidebar — below API Access (priority 20) and below any other
43 - // submenu that hooks at default priority 10.
44 - add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
45 - // Onboarding visibility — runs LAST so it can remove the submenu after every
46 - // other add_submenu_page() call. The page stays reachable by direct URL.
47 - add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999);
48 23 add_action('admin_init', array($this, 'mxchat_page_init'));
49 - add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
50 24 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
51 - // Add body class for the Onboarding wizard (plan-905439) so the
52 - // chrome-surgery CSS in admin-onboarding-wizard.css can scope its
53 - // WP-sidebar collapse to this page only.
54 - add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class'));
55 25 add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
26 + add_action('admin_post_mxchat_submit_content', array($this, 'mxchat_handle_content_submission'));
56 27 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
57 28 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
58 29 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
59 - add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
30 + add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
60 31 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
61 32 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
62 33 add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
34 + add_action('wp_ajax_mxchat_activate_license', array($this, 'mxchat_handle_activate_license'));
63 35 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
36 + // Add the AJAX handler for logged-in users
37 + add_action('wp_ajax_mxchat_save_inline_prompt', array($this, 'mxchat_save_inline_prompt'));
64 38 add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
65 - add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
66 - add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
67 - add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
68 - add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
69 39
70 - // Leads tab (inside Transcripts)
71 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
72 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
73 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
74 40
75 - add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
76 - add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
77 - add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
78 - add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
79 - // Self-heal: the cleanup event is otherwise only scheduled at activation or
80 - // when the retention setting CHANGES — if it is ever lost (deactivate cycle,
81 - // cron-option wipe, DB restore) nothing re-registers it and retention goes
82 - // silently inert while the UI still says it is on (plan-bc08a6).
83 - add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled'));
84 -
85 - add_action('admin_init', array($this, 'register_pinecone_settings'));
86 - add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
87 -
88 - add_action('admin_notices', array($this, 'display_admin_notices'));
89 -
90 - add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
91 - add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
92 - add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
93 -
94 - // wp_ajax_mxchat_save_selected_bot is registered (and handled) in
95 - // admin/class-ajax-handler.php — a duplicate registration here pointed
96 - // at a method this class never defined, a load-order-dependent fatal
97 - // waiting to fire (plan 52bcad).
98 - add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
99 - add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
100 -
101 - // Actions page AJAX handlers
102 - add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
103 - add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
104 - add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
105 - add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
106 - add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
107 - add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
108 - add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
109 - add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
110 - add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
111 - add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
112 -
113 - // Slack test connection
114 - add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
115 -
116 - // Translation handlers
117 - add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
118 - add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
119 -
120 - // 3.2.3: Embedding model switch protection
121 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
122 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
123 - add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax'));
124 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
125 - add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice'));
126 41 }
127 42
128 - /**
129 - * Nudge admins to configure a Telegram webhook secret (plan-0c17b5).
130 - *
131 - * Shown only when a Telegram bot token is configured (integration active)
132 - * AND no webhook secret is set. Without a secret the webhook falls back to a
133 - * Telegram source-IP check — safer than the old fail-open, but a real secret
134 - * is the recommended protection. Dismissible; does not block anything.
135 - */
136 - public function mxchat_telegram_secret_notice() {
137 - if (!current_user_can('manage_options')) {
138 - return;
139 - }
140 - $options = get_option('mxchat_options', array());
141 - $has_token = !empty($options['telegram_bot_token']);
142 - $has_secret = !empty($options['telegram_webhook_secret']);
143 - if (!$has_token || $has_secret) {
144 - return;
145 - }
146 - if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') {
147 - return;
148 - }
149 - $settings_url = admin_url('admin.php?page=mxchat-max');
150 - ?>
151 - <div class="notice notice-warning is-dismissible mxchat-telegram-secret-notice">
152 - <p><strong><?php esc_html_e('MxChat: Telegram webhook is running without a secret token', 'mxchat'); ?></strong></p>
153 - <p>
154 - <?php esc_html_e('Your Telegram integration is active but no webhook secret is configured. Requests are currently verified only by origin IP. For full protection, set a webhook secret token in the Telegram settings and re-register your webhook.', 'mxchat'); ?>
155 - </p>
156 - <p>
157 - <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
158 - </p>
159 - </div>
160 - <script>
161 - (function(){
162 - var n = document.querySelector('.mxchat-telegram-secret-notice');
163 - if (!n) return;
164 - n.addEventListener('click', function(e){
165 - if (e.target && e.target.classList.contains('notice-dismiss')) {
166 - var d = new FormData();
167 - d.append('action', 'mxchat_dismiss_telegram_secret_notice');
168 - d.append('nonce', '<?php echo esc_js(wp_create_nonce('mxchat_dismiss_telegram_secret')); ?>');
169 - fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', { method: 'POST', body: d, credentials: 'same-origin' });
170 - }
171 - });
172 - })();
173 - </script>
174 - <?php
43 + // Method to check if the license is active
44 + private function is_license_active() {
45 + $license_status = get_option('mxchat_license_status', 'inactive');
46 + return $license_status === 'active';
175 47 }
176 48
177 - /**
178 - * AJAX: persist dismissal of the Telegram-secret admin notice (plan-0c17b5).
179 - */
180 - public function mxchat_dismiss_telegram_secret_notice_ajax() {
181 - if (!current_user_can('manage_options')
182 - || !check_ajax_referer('mxchat_dismiss_telegram_secret', 'nonce', false)) {
183 - wp_send_json_error();
184 - }
185 - update_option('mxchat_dismissed_telegram_secret_notice', '1', 'no');
186 - wp_send_json_success();
187 - }
188 -
189 - /**
190 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
191 - * switch. Pure option comparison — no counts, no DB queries beyond the
192 - * cached options. The dialog is shown whenever the user has previously
193 - * embedded with a different model than the one they're switching to.
194 - */
195 - public function mxchat_check_embedding_switch_ajax() {
196 - check_ajax_referer('mxchat_admin_nonce', 'security');
197 - if (!current_user_can('manage_options')) {
198 - wp_send_json_error(__('Unauthorized', 'mxchat'));
199 - }
200 -
201 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
202 - $options = get_option('mxchat_options', array());
203 - if (isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
204 - // The standard dropdown is inert while custom embeddings are on —
205 - // whatever value it posts, the next embed uses the custom identity.
206 - $new_model = MxChat_Utils::get_selected_embedding_model($options);
207 - }
208 - $active_model = MxChat_Utils::get_active_embedding_model();
209 -
210 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
211 -
212 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
213 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
214 -
215 - wp_send_json_success(array(
216 - 'is_mismatch' => $is_mismatch,
217 - 'active_model' => $active_model,
218 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
219 - 'new_model' => $new_model,
220 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
221 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
222 - 'active_dims' => $active_dims,
223 - 'new_dims' => $new_dims,
224 - ));
225 - }
226 -
227 - /**
228 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
229 - * pair so the banner reappears on the next switch event.
230 - */
231 - public function mxchat_dismiss_embedding_mismatch_ajax() {
232 - check_ajax_referer('mxchat_admin_nonce', 'security');
233 - if (!current_user_can('manage_options')) {
234 - wp_send_json_error(__('Unauthorized', 'mxchat'));
235 - }
236 -
237 - $options = get_option('mxchat_options', array());
238 - $selected = MxChat_Utils::get_selected_embedding_model($options);
239 - $active = MxChat_Utils::get_active_embedding_model();
240 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
241 - wp_send_json_success();
242 - }
243 -
244 - /**
245 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
246 - * (last used to actually embed something) differs from the currently
247 - * selected model. Pure option comparison — no DB queries on every page
248 - * load. The banner auto-clears once both match again, i.e. after a delete
249 - * + re-embed cycle.
250 - */
251 - public function mxchat_embedding_mismatch_notice() {
252 - if (!current_user_can('manage_options')) {
253 - return;
254 - }
255 -
256 - $options = get_option('mxchat_options', array());
257 - $selected = MxChat_Utils::get_selected_embedding_model($options);
258 - $active = MxChat_Utils::get_active_embedding_model();
259 -
260 - if (empty($active) || empty($selected) || $active === $selected) {
261 - return;
262 - }
263 -
264 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
265 - if ($dismissed === $active . '|' . $selected) {
266 - return;
267 - }
268 -
269 - $active_label = MxChat_Utils::embedding_model_label($active);
270 - $selected_label = MxChat_Utils::embedding_model_label($selected);
271 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
272 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
273 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
274 -
275 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
276 - $actions_url = admin_url('admin.php?page=mxchat-actions');
277 -
278 - ?>
279 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
280 - data-active="<?php echo esc_attr($active); ?>"
281 - data-selected="<?php echo esc_attr($selected); ?>">
282 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
283 - <p>
284 - <?php
285 - printf(
286 - /* translators: 1: previously-used model name, 2: currently-selected model name */
287 - esc_html__('Your knowledge base and actions were embedded with %1$s, but %2$s is now selected. Similarity matching will return inaccurate or empty results until you delete all existing embeddings and re-embed your content with the new model.', 'mxchat'),
288 - '<code>' . esc_html($active_label) . '</code>',
289 - '<code>' . esc_html($selected_label) . '</code>'
290 - );
291 - ?>
292 - </p>
293 - <?php if ($dims_differ) : ?>
294 - <p>
295 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
296 - <?php
297 - printf(
298 - /* translators: 1: old dim count, 2: new dim count */
299 - esc_html__('Existing vectors are %1$d-dimensional but the new model produces %2$d-dimensional vectors. If you use Pinecone, your index will reject queries entirely until re-embedded.', 'mxchat'),
300 - (int) $active_dims,
301 - (int) $selected_dims
302 - );
303 - ?>
304 - </p>
305 - <?php endif; ?>
306 - <p>
307 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
308 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
309 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
310 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
311 - </p>
312 - </div>
313 - <script>
314 - (function($){
315 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
316 - $.post(ajaxurl, {
317 - action: 'mxchat_dismiss_embedding_mismatch',
318 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
319 - });
320 - });
321 - })(jQuery);
322 - </script>
323 - <?php
324 - }
325 -
326 -private function is_license_active() {
327 - $license_status = get_option('mxchat_license_status', 'inactive');
328 - return ($license_status === 'active');
329 -}
330 -
49 + // Initialize default options
331 50 private function initialize_default_options() {
332 51 $default_options = array(
333 52 'api_key' => '',
334 53 'xai_api_key' => '',
335 54 'claude_api_key' => '',
336 - 'deepseek_api_key' => '',
337 - 'voyage_api_key' => '',
338 - 'gemini_api_key' => '',
339 - 'enable_streaming_toggle' => 'off',
340 - 'enable_web_search' => 'off',
341 - 'embedding_model' => 'text-embedding-ada-002',
342 - 'system_prompt_instructions' => 'You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
55 + '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:
56 + - Your name is [Chatbot Name]. Always introduce yourself as this name when appropriate.
57 + - 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.
58 + - When appropriate, highlight the benefits of [insert proper subject here]. Offer to guide visitors to relevant pages or provide them with more information.
59 + - 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.
60 + - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
61 + - 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.
62 + - 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.',
63 + 'model' => 'gpt-3.5-turbo',
64 + 'rate_limit' => '100',
65 + 'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
66 + 'top_bar_title' => 'MxChat',
67 + 'intro_message' => 'Hello! How can I assist you today?',
68 + 'input_copy' => 'How can I assist?',
69 + 'append_to_body' => 'off',
70 + 'close_button_color' => '#fff',
71 + 'chatbot_bg_color' => '#fff',
72 + 'user_message_bg_color' => '#fff',
73 + 'user_message_font_color' => '#212121',
74 + 'bot_message_bg_color' => '#212121',
75 + 'bot_message_font_color' => '#fff',
76 + 'top_bar_bg_color' => '#212121',
77 + 'send_button_font_color' => '#212121',
78 + 'chat_input_font_color' => '#212121',
79 + 'chatbot_background_color' => '#212121',
80 + 'icon_color' => '#fff',
81 + 'enable_woocommerce_integration' => '0',
82 + 'link_target_toggle' => 'off',
83 + 'pre_chat_message' => 'Hey there! Ask me anything!',
343 84
344 - # Response Style - CRITICALLY IMPORTANT
345 - - MAXIMUM LENGTH: 1-3 short sentences per response
346 - - Ultra-concise: Get straight to the answer with no filler
347 - - No introductions like "Sure!" or "I\'d be happy to help"
348 - - No phrases like "based on my knowledge" or "according to information"
349 - - No explanatory text before giving the answer
350 - - No summaries or repetition
351 - - Hyperlink all URLs
352 - - Respond in user\'s language
353 - - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
354 -
355 - # Knowledge Base Requirements - PREVENT HALLUCINATIONS
356 - - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
357 - - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
358 - - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
359 - - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
360 - - Better to admit insufficient information than provide inaccurate answers',
361 - 'model' => esc_html__('gpt-5.6-sol', 'mxchat'),
362 - 'rate_limit_logged_out' => esc_html__('100', 'mxchat'),
363 - 'role_rate_limits' => array(),
364 - 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
365 - 'enable_email_block' => '',
366 - 'email_blocker_header_content' => __("<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>", 'mxchat'),
367 - 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
368 - 'enable_name_field' => 'off', // NEW
369 - 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
370 - 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
371 - 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
372 - 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
373 - 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
374 - 'append_to_body' => esc_html__('off', 'mxchat'),
375 - 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
376 - 'post_type_visibility_list' => array(), // Array of post type slugs
377 - 'contextual_awareness_toggle' => 'off',
378 - 'citation_links_toggle' => 'on',
379 - 'satisfaction_rating_enabled' => 'off',
380 - 'satisfaction_rating_idle_seconds' => 60,
381 - 'satisfaction_rating_question' => '',
382 - 'satisfaction_rating_thanks' => '',
383 - 'satisfaction_rating_placeholder' => '',
384 - 'satisfaction_rating_saved' => '',
385 - 'close_button_color' => esc_html__('#fff', 'mxchat'),
386 - 'chatbot_bg_color' => esc_html__('#fff', 'mxchat'),
387 - 'user_message_bg_color' => esc_html__('#fff', 'mxchat'),
388 - 'user_message_font_color' => esc_html__('#212121', 'mxchat'),
389 - 'bot_message_bg_color' => esc_html__('#212121', 'mxchat'),
390 - 'bot_message_font_color' => esc_html__('#fff', 'mxchat'),
391 - 'top_bar_bg_color' => esc_html__('#212121', 'mxchat'),
392 - 'send_button_font_color' => esc_html__('#212121', 'mxchat'),
393 - 'chat_input_font_color' => esc_html__('#212121', 'mxchat'),
394 - 'chatbot_background_color' => esc_html__('#212121', 'mxchat'),
395 - 'icon_color' => esc_html__('#fff', 'mxchat'),
396 - 'enable_woocommerce_integration' => esc_html__('0', 'mxchat'),
397 - 'link_target_toggle' => esc_html__('off', 'mxchat'),
398 - 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
399 -
400 85 // New fields for Loops Integration
401 86 'loops_api_key' => '',
402 87 'loops_mailing_list' => '',
403 - 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
404 - 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
88 + 'triggered_phrase_response' => 'Would you like to join our mailing list? Please provide your email below.',
89 + 'email_capture_response' => 'Thank you for providing your email! You\'ve been added to our list.',
405 90 'popular_question_1' => '',
406 91 'popular_question_2' => '',
407 92 'popular_question_3' => '',
408 - 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
409 - 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
410 - 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
411 - 'pdf_max_pages' => 69,
412 - 'show_pdf_upload_button' => 'on',
413 - 'show_word_upload_button' => 'on',
414 -
415 - // Live Agent Integration (Slack)
416 - 'live_agent_webhook_url' => '',
417 - 'live_agent_secret_key' => '',
418 - 'live_agent_bot_token' => '',
419 - 'live_agent_message_bg_color' => esc_html__('#ffffff', 'mxchat'),
420 - 'live_agent_message_font_color' => esc_html__('#333333', 'mxchat'),
421 -
422 - // Telegram Integration
423 - 'telegram_status' => 'off',
424 - 'telegram_bot_token' => '',
425 - 'telegram_group_id' => '',
426 - 'telegram_webhook_secret' => '',
427 - 'telegram_notification_message' => __("I've notified a support agent. Please allow a moment for them to respond. If you'd like to continue with AI, just type \"Switch to AI\" at any time.", 'mxchat'),
428 - 'telegram_away_message' => __("I just checked, and it looks like our support team isn't personally available at the moment. If you'd like, you can leave your email address, and they'll get back to you as soon as possible. In the meantime, you can keep chatting with me — just let me know how I can help!", 'mxchat'),
429 -
430 - 'chat_toolbar_toggle' => esc_html__('off', 'mxchat'),
431 - 'mode_indicator_bg_color' => esc_html__('#767676', 'mxchat'),
432 - 'mode_indicator_font_color' => esc_html__('#ffffff', 'mxchat'),
433 - 'toolbar_icon_color' => esc_html__('#212121', 'mxchat'),
434 -
435 - // Optimization settings
436 - 'script_loading_strategy' => 'default',
437 -
438 - // Debug settings
439 - 'debug_mode' => 'off',
440 93 );
441 94
442 95
443 96 // Merge existing options with defaults
@@ -448,687 +101,134 @@
448 101 if ($existing_options !== $merged_options) {
449 102 update_option('mxchat_options', $merged_options);
450 103 }
451 104
452 - // Add default limits for each role
453 - $roles = wp_roles()->get_names();
454 - foreach ($roles as $role_id => $role_name) {
455 - $default_options['role_rate_limits'][$role_id] = esc_html__('100', 'mxchat');
456 - }
457 -
458 - return $default_options;
459 -
460 105 // Update the $this->options property
461 106 $this->options = $merged_options;
462 107 }
463 108
464 -public function mxchat_add_plugin_page() {
465 - // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file).
466 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
467 109
468 - // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu
469 - // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now
470 - // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding).
471 - add_menu_page(
472 - esc_html__('MxChat', 'mxchat'),
473 - esc_html__('MxChat', 'mxchat'),
474 - 'manage_options',
475 - 'mxchat-max',
476 - array($this, 'mxchat_create_dashboard_page'),
477 - 'dashicons-testimonial',
478 - 6
479 - );
480 110
481 - // Onboarding submenu — first child under MxChat (plan-d14e89).
482 - // First registration uses menu_slug === parent slug 'mxchat-max' →
483 - // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the
484 - // first child shows as "Onboarding" instead of a redundant pair.
485 - add_submenu_page(
486 - 'mxchat-max',
487 - esc_html__('MxChat Onboarding', 'mxchat'),
488 - esc_html__('Onboarding', 'mxchat'),
489 - 'manage_options',
490 - 'mxchat-max',
491 - array($this, 'mxchat_create_dashboard_page')
492 - );
493 - // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link
494 - // + legacy redirects still target this slug). Parent === null keeps it
495 - // out of the menu while remaining accessible by URL.
496 - add_submenu_page(
497 - null,
498 - esc_html__('MxChat Onboarding', 'mxchat'),
499 - esc_html__('Onboarding', 'mxchat'),
500 - 'manage_options',
501 - 'mxchat-onboarding',
502 - array($this, 'mxchat_create_dashboard_page')
503 - );
111 + public function mxchat_add_plugin_page() {
112 + // Main menu page
113 + add_menu_page(
114 + 'MxChat Settings',
115 + 'MxChat',
116 + 'manage_options',
117 + 'mxchat-max',
118 + array($this, 'mxchat_create_admin_page'),
119 + 'dashicons-testimonial',
120 + 6
121 + );
504 122
505 - // Settings submenu — same callback as before, just at a new slug.
506 - add_submenu_page(
507 - 'mxchat-max',
508 - esc_html__('MxChat Settings', 'mxchat'),
509 - esc_html__('Settings', 'mxchat'),
510 - 'manage_options',
511 - 'mxchat-settings',
512 - array($this, 'mxchat_create_admin_page')
513 - );
123 + // Submenu page for Knowledge
124 + add_submenu_page(
125 + 'mxchat-max',
126 + 'Prompts',
127 + 'Knowledge',
128 + 'manage_options',
129 + 'mxchat-prompts',
130 + array($this, 'mxchat_create_prompts_page')
131 + );
514 132
515 - // Submenu page for Knowledge
516 - add_submenu_page(
517 - 'mxchat-max',
518 - esc_html__('Prompts', 'mxchat'),
519 - esc_html__('Knowledge', 'mxchat'),
520 - 'manage_options',
521 - 'mxchat-prompts',
522 - array($this, 'mxchat_create_prompts_page')
523 - );
133 + // Submenu page for Chat Transcripts
134 + add_submenu_page(
135 + 'mxchat-max', // Corrected parent slug to match the main menu
136 + 'Chat Transcripts',
137 + 'Transcripts',
138 + 'manage_options',
139 + 'mxchat-transcripts',
140 + array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
141 + );
524 142
143 + // Submenu page for Intents
525 144 add_submenu_page(
526 - 'mxchat-max',
527 - esc_html__('Chat Transcripts', 'mxchat'),
528 - esc_html__('Transcripts', 'mxchat'),
529 - 'manage_options',
530 - 'mxchat-transcripts',
531 - array($this, 'mxchat_create_transcripts_page')
145 + 'mxchat-max', // Parent slug
146 + 'MxChat Intents', // Page title
147 + 'Intents', // Menu title
148 + 'manage_options', // Capability
149 + 'mxchat-intents', // Menu slug
150 + array($this, 'mxchat_intents_page_html') // Callback function
532 151 );
533 152
534 - add_submenu_page(
535 - 'mxchat-max',
536 - esc_html__('MxChat Actions', 'mxchat'),
537 - esc_html__('Actions', 'mxchat'),
538 - 'manage_options',
539 - 'mxchat-actions',
540 - array($this, 'mxchat_actions_page_html')
541 - );
153 + // Submenu page for Activation Key
154 + add_submenu_page(
155 + 'mxchat-max',
156 + 'Pro Upgrade',
157 + 'Pro Upgrade',
158 + 'manage_options',
159 + 'mxchat-activation',
160 + array($this, 'mxchat_create_activation_page')
161 + );
542 162
543 - // Content Generator page
544 - add_submenu_page(
545 - 'mxchat-max',
546 - esc_html__('Content', 'mxchat'),
547 - esc_html__('Content', 'mxchat'),
548 - 'manage_options',
549 - 'mxchat-content',
550 - array($this, 'mxchat_create_content_page')
551 - );
552 163
553 164 }
554 165
555 -/**
556 - * Register the Pro & Extensions submenu on a later admin_menu priority so it
557 - * always renders as the bottom-most item in the MxChat sidebar — below
558 - * configuration pages like API Access (priority 20).
559 - */
560 -public function mxchat_add_pro_extensions_page() {
561 - add_submenu_page(
562 - 'mxchat-max',
563 - esc_html__('Pro & Extensions', 'mxchat'),
564 - esc_html__('Pro & Extensions', 'mxchat'),
565 - 'manage_options',
566 - 'mxchat-activation',
567 - array($this, 'mxchat_create_activation_page')
568 - );
569 -}
570 166
571 -public function mxchat_create_addons_page() {
572 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
573 - $addons_page = new MxChat_Addons();
574 - $addons_page->render_page();
575 -}
576 -
577 -/**
578 - * Render the Content Generator admin page
579 - */
580 -public function mxchat_create_content_page() {
581 - require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
582 - // The Editor Assistant toggle on the Settings tab renders through
583 - // mxchat_render_field_wrapper(), which lives in admin-settings-page.php
584 - // (plan-f7df40 relocation) — load it the same way the settings page does.
585 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
586 - mxchat_render_content_page($this);
587 -}
588 -
589 -/**
590 - * Test actual streaming functionality in the WordPress environment
591 - */
592 -public function mxchat_handle_test_streaming_actual() {
593 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
594 -
595 - // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler
596 - // reads the site's provider keys and spends them on an outbound call, so it
597 - // is billable abuse for any logged-in user who obtained the nonce.
598 - if (!current_user_can('manage_options')) {
599 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
600 - }
601 -
602 - // Check if headers have already been sent
603 - if (headers_sent()) {
604 - wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
167 +public function mxchat_handle_content_submission() {
168 + // Check if the form was submitted and the user has sufficient permissions
169 + if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
605 170 return;
606 171 }
607 172
608 - // Check for required functions
609 - if (!function_exists('curl_init')) {
610 - wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
611 - return;
173 + // Verify the nonce field for security
174 + $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
175 + if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
176 + wp_die('Nonce verification failed.');
612 177 }
613 178
614 - // Get user's selected model and API key
615 - $options = get_option('mxchat_options', []);
616 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
179 + // Sanitize the content input
180 + $article_content = sanitize_textarea_field($_POST['article_content']);
617 181
618 - // Get the provider from the model
619 - $model_parts = explode('-', $selected_model);
620 - $provider = strtolower($model_parts[0]);
182 + // Sanitize the URL input (optional URL)
183 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : ''; // Default to empty if not provided
621 184
622 - // Get the appropriate API key
623 - $api_key = '';
624 - switch ($provider) {
625 - case 'gpt':
626 - case 'o1':
627 - $api_key = $options['api_key'] ?? '';
628 - break;
629 - case 'claude':
630 - $api_key = $options['claude_api_key'] ?? '';
631 - break;
632 - case 'grok':
633 - $api_key = $options['xai_api_key'] ?? '';
634 - break;
635 - case 'deepseek':
636 - $api_key = $options['deepseek_api_key'] ?? '';
637 - break;
638 - case 'gemini':
639 - $api_key = $options['gemini_api_key'] ?? '';
640 - break;
641 - default:
642 - // Default to OpenAI for unknown models
643 - $api_key = $options['api_key'] ?? '';
644 - $provider = 'gpt';
645 - break;
646 - }
185 + // Generate the embedding vector for the content
186 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
647 187
648 - if (empty($api_key)) {
649 - wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
650 - return;
651 - }
188 + global $wpdb;
189 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
652 190
653 - // Test streaming with the selected model and provider
654 - try {
655 - $this->perform_streaming_test($provider, $selected_model, $api_key);
656 - } catch (Exception $e) {
657 - wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
191 + // Check if the 'source_url' column exists in the table and add it if it doesn't
192 + if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
193 + // Use wpdb::query and a prepared statement to avoid SQL injection
194 + $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
658 195 }
659 -}
660 196
661 -/**
662 - * Perform the actual streaming test
663 - */
664 -private function perform_streaming_test($provider, $model, $api_key) {
665 - // Set streaming headers
666 - header('Content-Type: text/event-stream');
667 - header('Cache-Control: no-cache');
668 - header('X-Accel-Buffering: no'); // Disable nginx buffering
197 + if (is_array($embedding_vector)) {
198 + // Serialize the embedding vector before storing it
199 + $embedding_vector_serialized = serialize($embedding_vector);
669 200
670 - // Prepare test message
671 - $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
672 -
673 - // Configure API request based on provider
674 - $url = '';
675 - $headers = [];
676 - $body = [];
677 -
678 - switch ($provider) {
679 - case 'gpt':
680 - case 'o1':
681 - $url = 'https://api.openai.com/v1/chat/completions';
682 - $headers = [
683 - 'Content-Type: application/json',
684 - 'Authorization: Bearer ' . $api_key
685 - ];
686 - $body = [
687 - 'model' => $model,
688 - 'messages' => [['role' => 'user', 'content' => $test_message]],
689 - 'max_tokens' => 50,
690 - 'temperature' => 0.3,
691 - 'stream' => true
692 - ];
693 - break;
694 -
695 - case 'claude':
696 - $url = 'https://api.anthropic.com/v1/messages';
697 - $headers = [
698 - 'Content-Type: application/json',
699 - 'x-api-key: ' . $api_key,
700 - 'anthropic-version: 2023-06-01'
701 - ];
702 - $body = [
703 - 'model' => $model,
704 - 'messages' => [['role' => 'user', 'content' => $test_message]],
705 - 'max_tokens' => 50,
706 - 'temperature' => 0.3,
707 - 'stream' => true
708 - ];
709 - // Claude flagships from Opus 4.7 onward reject the temperature
710 - // param outright (400). Reuse the catalog's decision — this path
711 - // previously sent temperature unconditionally, so the streaming
712 - // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5.
713 - if (class_exists('MxChat_Model_Catalog')
714 - && method_exists('MxChat_Model_Catalog', 'supports_temperature')
715 - && !MxChat_Model_Catalog::supports_temperature($model)) {
716 - unset($body['temperature']);
717 - }
718 - break;
719 -
720 - case 'grok':
721 - $url = 'https://api.x.ai/v1/chat/completions';
722 - $headers = [
723 - 'Content-Type: application/json',
724 - 'Authorization: Bearer ' . $api_key
725 - ];
726 - $body = [
727 - 'model' => $model,
728 - 'messages' => [['role' => 'user', 'content' => $test_message]],
729 - 'max_tokens' => 50,
730 - 'temperature' => 0.3,
731 - 'stream' => true
732 - ];
733 - break;
734 -
735 - case 'deepseek':
736 - $url = 'https://api.deepseek.com/v1/chat/completions';
737 - $headers = [
738 - 'Content-Type: application/json',
739 - 'Authorization: Bearer ' . $api_key
740 - ];
741 - $body = [
742 - 'model' => $model,
743 - 'messages' => [['role' => 'user', 'content' => $test_message]],
744 - 'max_tokens' => 50,
745 - 'temperature' => 0.3,
746 - 'stream' => true,
747 - // DeepSeek V4 defaults to thinking mode ON — reasoning would
748 - // consume the 50-token test budget and return no visible text.
749 - 'thinking' => ['type' => 'disabled']
750 - ];
751 - break;
752 -
753 - default:
754 - echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
755 - flush();
756 - return;
757 - }
758 -
759 - // Initialize cURL
760 - $ch = curl_init();
761 - curl_setopt($ch, CURLOPT_URL, $url);
762 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
763 - curl_setopt($ch, CURLOPT_POST, true);
764 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
765 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
766 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
767 - curl_setopt($ch, CURLOPT_TIMEOUT, 30);
768 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
769 - return $this->process_streaming_test_data($data, $provider);
770 - });
771 -
772 - // Send initial test message
773 - echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
774 - flush();
775 -
776 - $result = curl_exec($ch);
777 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
778 - $curl_error = curl_error($ch);
779 - curl_close($ch);
780 -
781 - if ($curl_error) {
782 - echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
783 - flush();
784 - return;
785 - }
786 -
787 - if ($http_code !== 200) {
788 - echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
789 - flush();
790 - return;
791 - }
792 -
793 - // Send completion signal
794 - echo "data: [DONE]\n\n";
795 - flush();
796 -}
797 -
798 -/**
799 - * Process streaming data for the test
800 - */
801 -private function process_streaming_test_data($data, $provider) {
802 - static $chunk_count = 0;
803 -
804 - $lines = explode("\n", $data);
805 -
806 - foreach ($lines as $line) {
807 - if (trim($line) === '') {
808 - continue;
809 - }
810 -
811 - // Handle different provider formats
812 - if ($provider === 'claude') {
813 - // Claude uses event: and data: format
814 - if (strpos($line, 'data: ') === 0) {
815 - $json_str = substr($line, 6);
816 - $json = json_decode($json_str, true);
817 -
818 - if (isset($json['type']) && $json['type'] === 'content_block_delta') {
819 - if (isset($json['delta']['text'])) {
820 - $chunk_count++;
821 - echo "data: " . json_encode([
822 - 'content' => $json['delta']['text'],
823 - 'test_chunk' => $chunk_count
824 - ]) . "\n\n";
825 - flush();
826 - }
827 - }
828 - }
829 - } else {
830 - // OpenAI, X.AI, DeepSeek format
831 - if (strpos($line, 'data: ') === 0) {
832 - $json_str = substr($line, 6);
833 -
834 - if ($json_str === '[DONE]') {
835 - // Don't echo [DONE] here, let the main function handle it
836 - continue;
837 - }
838 -
839 - $json = json_decode($json_str, true);
840 - if (isset($json['choices'][0]['delta']['content'])) {
841 - $chunk_count++;
842 - echo "data: " . json_encode([
843 - 'content' => $json['choices'][0]['delta']['content'],
844 - 'test_chunk' => $chunk_count
845 - ]) . "\n\n";
846 - flush();
847 - }
848 - }
849 - }
850 - }
851 -
852 - return strlen($data);
853 -}
854 -
855 -/**
856 - * Updated version of your existing test method (keep this as a fallback)
857 - */
858 -public function mxchat_handle_test_streaming() {
859 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
860 -
861 - // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but
862 - // fail here so the alias never becomes a bypass if that call is refactored.
863 - if (!current_user_can('manage_options')) {
864 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
865 - }
866 -
867 - // Use the actual streaming test instead
868 - $this->mxchat_handle_test_streaming_actual();
869 -}
870 -
871 -
872 -public function register_pinecone_settings() {
873 - register_setting(
874 - 'mxchat_pinecone_addon_options',
875 - 'mxchat_pinecone_addon_options',
876 - array(
877 - 'type' => 'array',
878 - 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
879 - 'default' => array(
880 - 'mxchat_use_pinecone' => '0',
881 - 'mxchat_pinecone_api_key' => '',
882 - 'mxchat_pinecone_host' => '',
883 - 'mxchat_pinecone_index' => '',
884 - 'mxchat_pinecone_environment' => ''
885 - )
886 - )
887 - );
888 -}
889 -
890 -public function sanitize_pinecone_settings($input) {
891 - $sanitized = array();
892 -
893 - $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
894 - $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
895 - $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
896 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
897 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
898 -
899 - // Remove https:// from host if present
900 - $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
901 -
902 - return $sanitized;
903 -}
904 -
905 -public function register_openai_vectorstore_settings() {
906 - register_setting(
907 - 'mxchat_openai_vectorstore_options',
908 - 'mxchat_openai_vectorstore_options',
909 - array(
910 - 'type' => 'array',
911 - 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
912 - 'default' => array(
913 - 'mxchat_use_openai_vectorstore' => '0',
914 - 'mxchat_vectorstore_ids' => '',
915 - 'mxchat_vectorstore_max_results' => 5
916 - )
917 - )
918 - );
919 -}
920 -
921 -public function sanitize_openai_vectorstore_settings($input) {
922 - $sanitized = array();
923 -
924 - $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
925 - $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
926 - $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
927 -
928 - // Ensure max results is within reasonable range
929 - if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
930 - $sanitized['mxchat_vectorstore_max_results'] = 1;
931 - }
932 - if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
933 - $sanitized['mxchat_vectorstore_max_results'] = 20;
934 - }
935 -
936 - return $sanitized;
937 -}
938 -
939 -/**
940 - * AJAX handler to test OpenAI Vector Store connection
941 - */
942 -public function mxchat_test_vectorstore_connection() {
943 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
944 -
945 - if (!current_user_can('manage_options')) {
946 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
947 - return;
948 - }
949 -
950 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
951 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
952 - $mxchat_options = get_option('mxchat_options', array());
953 - $api_key = $mxchat_options['api_key'] ?? '';
954 -
955 - if (empty($api_key)) {
956 - wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
957 - return;
958 - }
959 -
960 - if (empty($vectorstore_ids)) {
961 - wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
962 - return;
963 - }
964 -
965 - // Get the first Vector Store ID for testing
966 - $ids_array = array_map('trim', explode(',', $vectorstore_ids));
967 - $test_id = $ids_array[0];
968 -
969 - // Test by retrieving the Vector Store info
970 - $response = wp_remote_get(
971 - 'https://api.openai.com/v1/vector_stores/' . $test_id,
972 - array(
973 - 'headers' => array(
974 - 'Authorization' => 'Bearer ' . $api_key,
975 - 'Content-Type' => 'application/json',
976 - 'OpenAI-Beta' => 'assistants=v2'
201 + // Insert the content, embedding vector, and source URL into the database, using a prepared statement
202 + $inserted = $wpdb->insert(
203 + $table_name,
204 + array(
205 + 'article_content' => $article_content,
206 + 'embedding_vector' => $embedding_vector_serialized,
207 + 'source_url' => $article_url, // Insert the URL, empty string if not provided
977 208 ),
978 - 'timeout' => 30
979 - )
980 - );
981 -
982 - if (is_wp_error($response)) {
983 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
984 - return;
985 - }
986 -
987 - $status_code = wp_remote_retrieve_response_code($response);
988 - $body = json_decode(wp_remote_retrieve_body($response), true);
989 -
990 - if ($status_code === 200 && isset($body['id'])) {
991 - $file_count = $body['file_counts']['completed'] ?? 0;
992 - $name = $body['name'] ?? $test_id;
993 - wp_send_json_success(array(
994 - 'message' => sprintf(
995 - __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
996 - esc_html($name),
997 - $file_count
209 + array(
210 + '%s', // Format for article_content (string)
211 + '%s', // Format for embedding_vector (serialized string)
212 + '%s', // Format for source_url (string)
998 213 )
999 - ));
1000 - } elseif ($status_code === 404) {
1001 - wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
1002 - } elseif ($status_code === 401) {
1003 - wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
1004 - } else {
1005 - $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
1006 - wp_send_json_error(array('message' => $error_message));
1007 - }
1008 -}
1009 -
1010 -/**
1011 - * AJAX handler to test Slack connection and validate scopes
1012 - */
1013 -public function mxchat_test_slack_connection() {
1014 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
1015 -
1016 - if (!current_user_can('manage_options')) {
1017 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1018 - return;
1019 - }
1020 -
1021 - $bot_token = $this->options['live_agent_bot_token'] ?? '';
1022 -
1023 - if (empty($bot_token)) {
1024 - wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
1025 - return;
1026 - }
1027 -
1028 - // Test 1: Validate bot token with auth.test
1029 - $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
1030 - 'headers' => array(
1031 - 'Authorization' => 'Bearer ' . $bot_token,
1032 - 'Content-Type' => 'application/json'
1033 - ),
1034 - 'timeout' => 15
1035 - ));
1036 -
1037 - if (is_wp_error($auth_response)) {
1038 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
1039 - return;
1040 - }
1041 -
1042 - $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
1043 -
1044 - if (!isset($auth_body['ok']) || !$auth_body['ok']) {
1045 - $error = $auth_body['error'] ?? 'unknown_error';
1046 - $error_messages = array(
1047 - 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
1048 - 'not_authed' => __('No authentication token provided.', 'mxchat'),
1049 - 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
1050 - 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
1051 214 );
1052 - $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
1053 - wp_send_json_error(array('message' => $message));
1054 - return;
1055 - }
1056 215
1057 - $team_name = $auth_body['team'] ?? 'Unknown Workspace';
1058 - $bot_name = $auth_body['user'] ?? 'Unknown Bot';
216 + if ($inserted === false) {
217 + //error_log('Error inserting content: ' . $wpdb->last_error);
218 + set_transient('mxchat_admin_notice_error', 'Error inserting content into the database. Please try again.', 30);
219 + } else {
220 + set_transient('mxchat_admin_notice_success', 'Content successfully submitted!', 30);
221 + }
1059 222
1060 - // Test 2: Check if we can list channels (tests channels:read scope)
1061 - $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
1062 - 'headers' => array(
1063 - 'Authorization' => 'Bearer ' . $bot_token,
1064 - 'Content-Type' => 'application/json'
1065 - ),
1066 - 'body' => json_encode(array('limit' => 1)),
1067 - 'timeout' => 15
1068 - ));
1069 -
1070 - $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
1071 - $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
1072 -
1073 - // Test 3: Check if we can create channels (tests channels:manage scope)
1074 - // We'll just check the error message without actually creating
1075 - $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
1076 - 'headers' => array(
1077 - 'Authorization' => 'Bearer ' . $bot_token,
1078 - 'Content-Type' => 'application/json'
1079 - ),
1080 - 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
1081 - 'timeout' => 15
1082 - ));
1083 -
1084 - $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
1085 -
1086 - // If channel was created, delete it immediately
1087 - if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
1088 - wp_remote_post('https://slack.com/api/conversations.archive', array(
1089 - 'headers' => array(
1090 - 'Authorization' => 'Bearer ' . $bot_token,
1091 - 'Content-Type' => 'application/json'
1092 - ),
1093 - 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
1094 - 'timeout' => 15
1095 - ));
1096 - $can_create_channels = true;
1097 223 } else {
1098 - $create_error = $create_body['error'] ?? '';
1099 - // name_taken means we have permission but channel exists
1100 - $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
1101 -
1102 - // Check for missing scope errors
1103 - if ($create_error === 'missing_scope') {
1104 - $can_create_channels = false;
1105 - }
224 + //error_log('Embedding generation failed for article content: ' . $article_content);
225 + set_transient('mxchat_admin_notice_error', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
1106 226 }
1107 227
1108 - // Build result message
1109 - $results = array();
1110 - $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
1111 - $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
1112 - $results[] = '';
1113 - $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
1114 - $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
1115 -
1116 - $missing_scopes = array();
1117 - if (!$can_read_channels) $missing_scopes[] = 'channels:read';
1118 - if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
1119 -
1120 - if (!empty($missing_scopes)) {
1121 - wp_send_json_error(array(
1122 - 'message' => implode("\n", $results),
1123 - 'missing_scopes' => $missing_scopes,
1124 - 'partial' => true
1125 - ));
1126 - } else {
1127 - wp_send_json_success(array(
1128 - 'message' => implode("\n", $results)
1129 - ));
1130 - }
228 + // Redirect after setting the transient
229 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
230 + exit;
1131 231 }
1132 232
1133 233 public function mxchat_display_admin_notice() {
1134 234 // Success notice
@@ -1135,9 +235,9 @@
1135 235 if ($message = get_transient('mxchat_admin_notice_success')) {
1136 236 ?>
1137 237 <div class="notice notice-success is-dismissible">
1138 238 <p><?php echo esc_html($message); ?></p>
1139 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
239 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1140 240 </div>
1141 241 <?php
1142 242 delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1143 243 }
@@ -1146,9 +246,9 @@
1146 246 if ($message = get_transient('mxchat_admin_notice_error')) {
1147 247 ?>
1148 248 <div class="notice notice-error is-dismissible">
1149 249 <p><?php echo esc_html($message); ?></p>
1150 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
250 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1151 251 </div>
1152 252 <?php
1153 253 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1154 254 }
@@ -1153,5077 +253,1019 @@
1153 253 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1154 254 }
1155 255 }
1156 256
1157 -public function show_live_agent_disabled_banner() {
1158 - $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1159 257
1160 - if ($show_disabled_notice) {
1161 - ?>
1162 - <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1163 - <div class="mxchat-pro-notification">
1164 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1165 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1166 - <line x1="18" y1="6" x2="6" y2="18"></line>
1167 - <line x1="6" y1="6" x2="18" y2="18"></line>
1168 - </svg>
1169 - </button>
1170 - <div class="mxchat-live-agent-content">
1171 - <h3>🔧 Live Agent Integration Updated!</h3>
1172 - <p>We've temporarily disabled your Live Agent integration due to recent enhancements that have made it much better! You can easily turn it back on by going to <strong>Settings &rarr; Integrations &rarr; Toolbar</strong> and reviewing the new configuration options.</p>
1173 - </div>
1174 - </div>
1175 - </div>
1176 - <?php
1177 - }
1178 -}
1179 -/**
1180 - * Render the Onboarding page. Delegates to the procedural renderer in
1181 - * includes/admin-onboarding-page.php. Wired to both `?page=mxchat-max`
1182 - * (legacy top-level URL) and `?page=mxchat-onboarding` (the canonical
1183 - * Onboarding submenu).
1184 - *
1185 - * When the user has dismissed onboarding and lands on `mxchat-max` (the
1186 - * legacy URL, since the Onboarding submenu has been removed), redirect to
1187 - * Settings instead — the page is "graduated" and we shouldn't dump them
1188 - * back onto it. They can still navigate here directly via the unhide link.
1189 - */
1190 -public function mxchat_create_dashboard_page() {
1191 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
1192 258
1193 - $current = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1194 - if ($current === 'mxchat-max' && function_exists('mxchat_onboarding_is_dismissed') && mxchat_onboarding_is_dismissed()) {
1195 - wp_safe_redirect(admin_url('admin.php?page=mxchat-settings'));
1196 - exit;
1197 - }
1198 259
1199 - if (function_exists('mxchat_render_onboarding_page')) {
1200 - mxchat_render_onboarding_page();
1201 - return;
1202 - }
1203 - // Defensive: if the include failed to load, fall back to the old Settings page
1204 - // so the top-level menu never lands on an empty screen.
1205 - $this->mxchat_create_admin_page();
1206 -}
1207 260
1208 -/**
1209 - * Hide the Onboarding submenu when the user has dismissed it (either
1210 - * manually or via auto-graduation). The page itself remains routable so
1211 - * the Settings "Show MxChat Onboarding again" link can navigate back to it.
1212 - */
1213 -public function mxchat_apply_onboarding_visibility() {
1214 - if (!function_exists('mxchat_onboarding_is_dismissed')) {
1215 - return;
1216 - }
1217 - if (mxchat_onboarding_is_dismissed()) {
1218 - // The first MxChat child is the same-slug-as-parent registration
1219 - // (slug 'mxchat-max', labelled "Onboarding") added in plan-d14e89.
1220 - // Remove it so the menu opens straight to Settings after dismiss.
1221 - remove_submenu_page('mxchat-max', 'mxchat-max');
1222 - }
1223 -}
1224 -
1225 261 public function mxchat_create_admin_page() {
1226 - $this->add_live_agent_nonce();
1227 - $this->add_theme_migration_nonce();
1228 -
1229 - // Include and render the new sidebar-based settings page
1230 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1231 - mxchat_render_settings_page($this);
1232 -}
1233 -
1234 -public function dismiss_live_agent_notice() {
1235 - // Add debugging
1236 - //error_log('dismiss_live_agent_notice called');
1237 - //error_log('POST data: ' . print_r($_POST, true));
1238 -
1239 - // Verify nonce
1240 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1241 - //error_log('Nonce verification failed');
1242 - wp_die('Security check failed');
1243 - }
1244 -
1245 - // Remove the notice flag
1246 - $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1247 - //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
1248 -
1249 - wp_send_json_success();
1250 -}
1251 -public function add_live_agent_nonce() {
1252 - if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1253 - // Make sure your admin script is enqueued and localize the data
1254 - wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1255 - 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1256 - 'ajaxurl' => admin_url('admin-ajax.php')
1257 - ));
1258 - }
1259 -}
1260 -
1261 -/**
1262 - * Show theme migration notice for Pro users with AI-generated themes
1263 - * Only shown once - dismissible and stored in options
1264 - */
1265 -public function show_theme_migration_banner() {
1266 - // Only show if Pro is activated
1267 - if (!$this->is_activated) {
1268 - return;
1269 - }
1270 -
1271 - // Check if notice should be shown
1272 - $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1273 -
1274 - if ($show_notice) {
1275 - ?>
1276 - <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1277 - <div class="mxchat-pro-notification">
1278 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1279 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1280 - <line x1="18" y1="6" x2="6" y2="18"></line>
1281 - <line x1="6" y1="6" x2="18" y2="18"></line>
1282 - </svg>
1283 - </button>
1284 - <div class="mxchat-theme-migration-content">
1285 - <h3>🎨 AI Theme Migration Required</h3>
1286 - <p>If you're using an AI-generated chatbot theme, you'll need to migrate it to match the new CSS structure. Go to <strong>Theme Settings</strong>, select your theme from the sidebar, and click the <strong>Migrate</strong> button.</p>
1287 - </div>
262 + ?>
263 + <div class="wrap mxchat-admin">
264 + <?php if (!$this->is_activated): ?>
265 + <div class="mxchat-pro-banner">
266 + <p>
267 + Limited-time offer: Get a lifetime MxChat Pro license for just $49.97 until 01.01.25! After that, it switches to an annual license at $99.97/year. Purchase now and be grandfathered into the lifetime deal!
268 + <a href="https://mxchat.ai/" target="_blank">Upgrade to MxChat Pro today!</a>
269 + </p>
270 + </div>
271 + <?php endif; ?>
272 + <h2 class="admin-title">Mx<span class="admin-emphasis">Chat</span></h2>
273 + <h2 class="mxchat-nav-tab-wrapper">
274 + <a href="#chatbot" class="mxchat-nav-tab mxchat-nav-tab-active" data-tab="chatbot">Chatbot</a>
275 + <a href="#embed" class="mxchat-nav-tab" data-tab="embed">Integrations</a>
276 + <a href="#theme" class="mxchat-nav-tab" data-tab="theme">Theme</a>
277 + <a href="#general" class="mxchat-nav-tab" data-tab="general">FAQ</a>
278 + </h2>
279 + <form method="post" action="options.php">
280 + <?php settings_fields('mxchat_option_group'); ?>
281 + <div id="chatbot" class="mxchat-tab-content active">
282 + <?php do_settings_sections('mxchat-chatbot'); ?>
1288 283 </div>
1289 - </div>
1290 - <?php
1291 - }
1292 -}
1293 284
1294 -/**
1295 - * Dismiss theme migration notice via AJAX
1296 - */
1297 -public function dismiss_theme_migration_notice() {
1298 - // Verify nonce
1299 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1300 - wp_die('Security check failed');
1301 - }
1302 285
1303 - // Remove the notice flag
1304 - delete_option('mxchat_show_theme_migration_notice');
1305 286
1306 - wp_send_json_success();
1307 -}
287 +<div id="embed" class="mxchat-tab-content">
288 + <div class="mxchat-settings-section">
289 + <h2>WooCommerce Settings</h2>
290 + <table class="form-table">
291 + <?php do_settings_fields('mxchat-embed', 'mxchat_woocommerce_section'); ?>
292 + </table>
293 + </div>
1308 294
1309 -/**
1310 - * Add nonce for theme migration notice dismiss
1311 - */
1312 -public function add_theme_migration_nonce() {
1313 - if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1314 - wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1315 - 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1316 - 'ajaxurl' => admin_url('admin-ajax.php')
1317 - ));
1318 - }
1319 -}
295 + <div class="section-divider"></div> <!-- Divider -->
1320 296
1321 -public function mxchat_create_transcripts_page() {
1322 - global $wpdb;
1323 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
297 + <div class="mxchat-settings-section">
298 + <h2>Loops Settings</h2>
299 + <table class="form-table">
300 + <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
301 + </table>
302 + </div>
1324 303
1325 - // Get basic stats
1326 - $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1327 - $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
1328 304
1329 - // Count unique users with detailed breakdown
1330 - $total_users = $wpdb->get_var("
1331 - SELECT COUNT(DISTINCT
1332 - CASE
1333 - WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1334 - WHEN user_id != 0 THEN CONCAT('user_', user_id)
1335 - WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1336 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1337 - AND user_identifier NOT LIKE 'Language Learner'
1338 - AND user_identifier NOT LIKE 'Casual Browser'
1339 - AND user_identifier NOT LIKE 'Policy Enforcer'
1340 - AND user_identifier NOT LIKE 'Researcher'
1341 - AND user_identifier NOT LIKE 'Loyalty Member'
1342 - AND user_identifier NOT LIKE 'Gift Buyer'
1343 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1344 - THEN user_identifier
1345 - ELSE session_id
1346 - END
1347 - )
1348 - FROM $table_name
1349 - WHERE role != 'assistant'
1350 - ");
305 + <div class="section-divider"></div> <!-- Divider -->
1351 306
1352 - // Get user type breakdown
1353 - $registered_users = $wpdb->get_var("
1354 - SELECT COUNT(DISTINCT user_email)
1355 - FROM $table_name
1356 - WHERE user_email != '' AND user_email IS NOT NULL
1357 - ");
307 + <!-- Brave Search Settings Section -->
308 + <div class="mxchat-settings-section">
309 + <h2>Brave Search Settings</h2>
310 + <table class="form-table">
311 + <?php do_settings_fields('mxchat-embed', 'mxchat_brave_section'); ?>
312 + </table>
313 + </div>
314 +</div>
1358 315
1359 - $guest_users = $wpdb->get_var("
1360 - SELECT COUNT(DISTINCT user_identifier)
1361 - FROM $table_name
1362 - WHERE (user_email = '' OR user_email IS NULL)
1363 - AND role != 'assistant'
1364 - AND user_identifier NOT LIKE 'Tech-Savvy User'
1365 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1366 - AND user_identifier NOT LIKE 'Language Learner'
1367 - AND user_identifier NOT LIKE 'Casual Browser'
1368 - AND user_identifier NOT LIKE 'Policy Enforcer'
1369 - AND user_identifier NOT LIKE 'Researcher'
1370 - AND user_identifier NOT LIKE 'Loyalty Member'
1371 - AND user_identifier NOT LIKE 'Gift Buyer'
1372 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1373 - ");
1374 316
1375 - // Get agent test messages count
1376 - $agent_tests = $wpdb->get_var("
1377 - SELECT COUNT(DISTINCT session_id)
1378 - FROM $table_name
1379 - WHERE user_identifier IN (
1380 - 'Tech-Savvy User',
1381 - 'Detail-Oriented User',
1382 - 'Language Learner',
1383 - 'Casual Browser',
1384 - 'Policy Enforcer',
1385 - 'Researcher',
1386 - 'Loyalty Member',
1387 - 'Gift Buyer',
1388 - 'Parent or Caregiver'
1389 - )
1390 - ");
1391 - // Get activity metrics
1392 - $today_chats = $wpdb->get_var("
1393 - SELECT COUNT(DISTINCT session_id)
1394 - FROM $table_name
1395 - WHERE DATE(timestamp) = CURDATE()
1396 - ");
1397 -
1398 - $week_chats = $wpdb->get_var("
1399 - SELECT COUNT(DISTINCT session_id)
1400 - FROM $table_name
1401 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1402 - ");
1403 -
1404 - $month_chats = $wpdb->get_var("
1405 - SELECT COUNT(DISTINCT session_id)
1406 - FROM $table_name
1407 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1408 - ");
1409 -
1410 - // Get daily chat data for last 7 days
1411 - $daily_stats = $wpdb->get_results("
1412 - SELECT
1413 - DATE(timestamp) as date,
1414 - COUNT(DISTINCT session_id) as chats,
1415 - COUNT(*) as messages
1416 - FROM $table_name
1417 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1418 - GROUP BY DATE(timestamp)
1419 - ORDER BY date ASC
1420 - ");
1421 -
1422 - // Get average messages per chat
1423 - $avg_messages = $wpdb->get_var("
1424 - SELECT AVG(message_count)
1425 - FROM (
1426 - SELECT session_id, COUNT(*) as message_count
1427 - FROM $table_name
1428 - GROUP BY session_id
1429 - ) as chat_counts
1430 - ");
1431 - $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1432 -
1433 - // Get busiest hour
1434 - $busiest_hour = $wpdb->get_row("
1435 - SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1436 - FROM $table_name
1437 - GROUP BY HOUR(timestamp)
1438 - ORDER BY chat_count DESC
1439 - LIMIT 1
1440 - ");
1441 -
1442 - // Prepare chart data
1443 - $chart_labels = array();
1444 - $chart_chats = array();
1445 - $chart_messages = array();
1446 -
1447 - // Fill last 7 days with data
1448 - for ($i = 6; $i >= 0; $i--) {
1449 - $date = date('Y-m-d', strtotime("-$i days"));
1450 - $day_name = date('D', strtotime("-$i days"));
1451 - $chart_labels[] = $day_name;
1452 -
1453 - $found = false;
1454 - foreach ($daily_stats as $stat) {
1455 - if ($stat->date === $date) {
1456 - $chart_chats[] = (int)$stat->chats;
1457 - $chart_messages[] = (int)$stat->messages;
1458 - $found = true;
1459 - break;
1460 - }
1461 - }
1462 - if (!$found) {
1463 - $chart_chats[] = 0;
1464 - $chart_messages[] = 0;
1465 - }
1466 - }
1467 317
1468 - // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1469 - $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
1470 318
1471 - // Prepare page data for the template
1472 - $page_data = array(
1473 - 'total_chats' => $total_chats,
1474 - 'total_messages' => $total_messages,
1475 - 'total_users' => $total_users,
1476 - 'registered_users' => $registered_users,
1477 - 'guest_users' => $guest_users,
1478 - 'agent_tests' => $agent_tests,
1479 - 'today_chats' => $today_chats,
1480 - 'week_chats' => $week_chats,
1481 - 'month_chats' => $month_chats,
1482 - 'avg_messages' => $avg_messages,
1483 - 'busiest_hour' => $busiest_hour,
1484 - 'chart_labels' => $chart_labels,
1485 - 'chart_chats' => $chart_chats,
1486 - 'chart_messages' => $chart_messages,
1487 - 'satisfaction_stats' => $satisfaction_stats,
1488 - );
1489 319
1490 - // Include and render the new template
1491 - require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1492 - mxchat_render_transcripts_page($this, $page_data);
1493 -}
320 + <div id="theme" class="mxchat-tab-content">
321 + <?php do_settings_sections('mxchat-theme'); ?>
322 + </div>
323 + <div id="general" class="mxchat-tab-content">
324 + <?php do_settings_sections('mxchat-general'); ?>
325 +<p>If you’re having trouble with setup or getting the responses you need, we encourage you to review our <a href="https://mxchat.ai/documentation/" target="_blank" rel="noopener noreferrer">documentation</a>.</p>
1494 326
1495 -/**
1496 - * Per-bot satisfaction rating rollup over the last $days days. Used by the
1497 - * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1498 - *
1499 - * @param int $days Window in days.
1500 - * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1501 - */
1502 -public function get_satisfaction_rating_stats($days = 30) {
1503 - global $wpdb;
1504 - $table = $wpdb->prefix . 'mxchat_session_ratings';
1505 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1506 - return array();
1507 - }
1508 - $days = max(1, (int) $days);
1509 - $rows = $wpdb->get_results($wpdb->prepare(
1510 - "SELECT bot_id,
1511 - COUNT(*) AS total,
1512 - SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1513 - SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1514 - FROM {$table}
1515 - WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1516 - GROUP BY bot_id
1517 - ORDER BY total DESC",
1518 - $days
1519 - ));
1520 - $out = array();
1521 - foreach ((array) $rows as $row) {
1522 - $total = (int) $row->total;
1523 - $positive = (int) $row->positive;
1524 - $negative = (int) $row->negative;
1525 - $out[] = array(
1526 - 'bot_id' => $row->bot_id ?: 'default',
1527 - 'total' => $total,
1528 - 'positive' => $positive,
1529 - 'negative' => $negative,
1530 - 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1531 - 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1532 - );
1533 - }
1534 - return $out;
1535 -}
1536 -
1537 -/**
1538 - * Get chart data for transcripts page
1539 - * Used by both page render and script localization
1540 - *
1541 - * @return array Chart data with labels, chats, and messages arrays
1542 - */
1543 -private function get_transcripts_chart_data() {
1544 - global $wpdb;
1545 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1546 -
1547 - // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1548 - $daily_stats = $wpdb->get_results("
1549 - SELECT
1550 - DATE(timestamp) as date,
1551 - COUNT(DISTINCT session_id) as chats,
1552 - COUNT(*) as messages
1553 - FROM $table_name
1554 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1555 - GROUP BY DATE(timestamp)
1556 - ORDER BY date ASC
1557 - ");
1558 -
1559 - // Prepare chart data
1560 - $chart_labels = array();
1561 - $chart_chats = array();
1562 - $chart_messages = array();
1563 -
1564 - // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1565 - for ($i = 6; $i >= 0; $i--) {
1566 - $date = date('Y-m-d', strtotime("-$i days"));
1567 - $day_name = date('D', strtotime("-$i days"));
1568 - $chart_labels[] = $day_name;
1569 -
1570 - $found = false;
1571 - if ($daily_stats) {
1572 - foreach ($daily_stats as $stat) {
1573 - if ($stat->date === $date) {
1574 - $chart_chats[] = (int)$stat->chats;
1575 - $chart_messages[] = (int)$stat->messages;
1576 - $found = true;
1577 - break;
1578 - }
1579 - }
1580 - }
1581 - if (!$found) {
1582 - $chart_chats[] = 0;
1583 - $chart_messages[] = 0;
1584 - }
1585 - }
1586 -
1587 - return array(
1588 - 'labels' => $chart_labels,
1589 - 'chats' => $chart_chats,
1590 - 'messages' => $chart_messages
1591 - );
1592 -}
1593 -
1594 -public function mxchat_transcripts_notification_section_callback() {
1595 - echo '<p>' . esc_html__('Configure email notifications for new chat transcripts. You will receive an email notification when a new chat session begins.', 'mxchat') . '</p>';
1596 -}
1597 -public function mxchat_enable_notifications_callback() {
1598 - $options = get_option('mxchat_transcripts_options', array());
1599 - $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1600 - ?>
1601 - <label for="mxchat_enable_notifications">
1602 - <input type="checkbox" id="mxchat_enable_notifications"
1603 - name="mxchat_transcripts_options[mxchat_enable_notifications]"
1604 - value="1" <?php checked(1, $enabled); ?>>
1605 - <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1606 - </label>
1607 - <p class="description">
1608 - <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
327 +<div class="faq-item">
328 + <h3>How does the Claude API integration work?</h3>
329 + <p>
330 + The Claude API, provided by Anthropic, allows for intelligent, context-aware chatbot responses in MxChat. To use it, you will need both an OpenAI API key and a Claude API key. This is necessary because the system utilizes OpenAI for vector embedding in the Retrieval-Augmented Generation (RAG) process, as Claude does not currently offer an embedding API.
1609 331 </p>
1610 - <?php
1611 -}
1612 -public function mxchat_notification_email_callback() {
1613 - $options = get_option('mxchat_transcripts_options', array());
1614 - $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1615 - ?>
1616 - <?php /* type="text", not "email": the browser rejects a comma-separated list outright (plan 2f131a). Validation is server-side in MxChat_Utils. */ ?>
1617 - <input type="text" id="mxchat_notification_email"
1618 - name="mxchat_transcripts_options[mxchat_notification_email]"
1619 - value="<?php echo esc_attr($email); ?>"
1620 - class="regular-text">
1621 - <p class="description">
1622 - <?php printf(esc_html__('Enter the email address where notifications should be sent. Separate up to %d addresses with commas. Defaults to the admin email address.', 'mxchat'), (int) MxChat_Utils::NOTIFICATION_EMAIL_MAX); ?>
332 + <p>
333 + When using the Claude API, your custom content is sent to Claude for generating responses, while the embeddings are processed through OpenAI. This ensures your chatbot provides accurate and engaging responses while maintaining knowledge relevant to your website.
1623 334 </p>
1624 - <?php
1625 -}
335 + <p>
336 + You can obtain your Claude API key by signing up on the <a href="https://www.anthropic.com/api" target="_blank" rel="noopener">Anthropic API page</a>.
337 + </p>
338 +</div>
1626 339
1627 -public function mxchat_auto_delete_transcripts_callback() {
1628 - $options = get_option('mxchat_transcripts_options', array());
1629 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1630 - ?>
1631 - <select id="mxchat_auto_delete_transcripts"
1632 - name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1633 - <option value="never" <?php selected($interval, 'never'); ?>>
1634 - <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1635 - </option>
1636 - <option value="1week" <?php selected($interval, '1week'); ?>>
1637 - <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1638 - </option>
1639 - <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1640 - <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1641 - </option>
1642 - <option value="1month" <?php selected($interval, '1month'); ?>>
1643 - <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1644 - </option>
1645 - </select>
1646 - <p class="description">
1647 - <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
340 +<div class="faq-item">
341 + <h3>How does the X.AI API integration work?</h3>
342 + <p>
343 + The X.AI API, released on 10.21.24, is currently in beta. To use it, you will need both an OpenAI API key and an X.AI API key. This is because OpenAI handles vector embeddings in the Retrieval-Augmented Generation (RAG) process, as X.AI does not yet provide an embedding API.
1648 344 </p>
1649 - <?php
1650 -}
345 + <p>
346 + Custom content is sent to the X.AI API for generating responses, while OpenAI processes the embeddings. This allows the chatbot to provide advanced responses while maintaining context from your website. You can get your X.AI API key from the <a href="https://docs.x.ai/docs" target="_blank" rel="noopener">X.AI API documentation</a>.
347 + </p>
348 +</div>
1651 349
1652 -/**
1653 - * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1654 - * and deletes transcripts older than the given number of days. Set to 0 to fall
1655 - * back to the dropdown (or "Never" if the dropdown is also Never).
1656 - *
1657 - * Devs can override the final day count via the `mxchat_transcript_retention_days`
1658 - * filter — runs in `cleanup_old_transcripts()` after this option is read.
1659 - *
1660 - * (plan-mxchat-20260509-9b80b1)
1661 - */
1662 -public function mxchat_retention_days_callback() {
1663 - $options = get_option('mxchat_transcripts_options', array());
1664 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1665 - ?>
1666 - <input type="number"
1667 - id="mxchat_retention_days"
1668 - name="mxchat_transcripts_options[mxchat_retention_days]"
1669 - value="<?php echo esc_attr($days); ?>"
1670 - min="0"
1671 - max="3650"
1672 - step="1"
1673 - style="width: 90px;" />
1674 - <p class="description">
1675 - <?php esc_html_e('Number of days to retain transcripts. When set to a value greater than 0, this overrides the dropdown above. Set to 0 to use the dropdown. Maximum 3650 (10 years). A daily wp-cron task removes anything older, cascading to translations and click-tracking rows.', 'mxchat'); ?>
1676 - <br>
1677 - <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1678 - <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
350 +<div class="faq-item">
351 + <h3>Do I need an OpenAI API key to use the chatbot?</h3>
352 + <p>
353 + Yes, you will need an OpenAI API key to power the chatbot. You can obtain an API key by signing up on the <a href="https://platform.openai.com/signup" target="_blank" rel="noopener">OpenAI platform</a>. After signing up, you must add credits to your account—typically, $5 in credits is sufficient to get started.
1679 354 </p>
1680 - <?php
1681 -}
1682 -
1683 -public function mxchat_auto_email_transcript_callback() {
1684 - $options = get_option('mxchat_transcripts_options', array());
1685 - $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1686 - $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1687 - $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1688 - ?>
1689 - <label>
1690 - <input type="checkbox"
1691 - id="mxchat_auto_email_transcript_enabled"
1692 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1693 - value="1"
1694 - <?php checked($enabled, 1); ?>>
1695 - <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1696 - </label>
1697 - <br><br>
1698 - <label for="mxchat_auto_email_transcript_delay">
1699 - <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1700 - </label>
1701 - <select id="mxchat_auto_email_transcript_delay"
1702 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1703 - <option value="15" <?php selected($delay, '15'); ?>>
1704 - <?php esc_html_e('15 minutes', 'mxchat'); ?>
1705 - </option>
1706 - <option value="30" <?php selected($delay, '30'); ?>>
1707 - <?php esc_html_e('30 minutes', 'mxchat'); ?>
1708 - </option>
1709 - <option value="60" <?php selected($delay, '60'); ?>>
1710 - <?php esc_html_e('1 hour', 'mxchat'); ?>
1711 - </option>
1712 - </select>
1713 - <br><br>
1714 - <label>
1715 - <input type="checkbox"
1716 - id="mxchat_auto_email_transcript_require_contact"
1717 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1718 - value="1"
1719 - <?php checked($require_contact, 1); ?>>
1720 - <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1721 - </label>
1722 - <p class="description">
1723 - <?php esc_html_e('Automatically email the full transcript as a .txt file after the specified time has passed since the last user message. The scheduled email will be cancelled if a new message is received.', 'mxchat'); ?>
1724 - <br>
1725 - <?php esc_html_e('When "Only send if visitor provided contact info" is enabled, transcripts will only be emailed if the visitor shared an email address or phone number (including WhatsApp) in the chat.', 'mxchat'); ?>
355 + <p>
356 + Once you have your API key, simply enter it in the chatbot's settings to enable functionality. The chatbot relies on OpenAI’s models for generating responses, so having sufficient credits in your OpenAI account is essential for smooth operation.
1726 357 </p>
1727 - <?php
1728 -}
358 +</div>
1729 359
360 + <div class="faq-item">
361 + <h3>How do I add the chatbot to my site?</h3>
362 + <p>
363 + You can add the chatbot using the shortcode <code>[mxchat_chatbot floating="yes"]</code> or <code>[mxchat_chatbot floating="no"]</code>. For initial testing and styling, it's best to use the shortcode on a draft or non-public page. Once you’re ready to go live, enable the “Append Chat Widget to Body” option in the settings for site-wide integration (recommended) or add shortcode to the footer.
364 + </p>
365 + </div>
1730 366
367 + <div class="faq-item">
368 + <h3>How does the chatbot use my content to generate responses?</h3>
369 + <p>
370 + The chatbot uses AI and vector embeddings to connect users with relevant information. When you submit content, it converts it into a mathematical format. When a user asks a question, the bot matches it to your stored content and generates a response based on relevance. For example, submitting "Our phone number is 910-123-4567" allows the bot to retrieve this information when asked about contact details. To ensure related information is provided together, submit it in one entry.
371 + </p>
372 + </div>
1731 373
1732 -public function sanitize_transcripts_options($input) {
1733 - $sanitized = array();
374 + <div class="faq-item">
375 + <h3>Why does the chatbot sometimes make up links or information?</h3>
376 + <p>
377 + Occasionally, the chatbot may generate inaccurate links or information, known as "hallucinations." To minimize this, you can add system instructions to guide its behavior. For example, include an instruction like: "Only provide links you directly have access to or retrieve from the knowledge base. Do not make up links or information that you do not have direct access to." This helps the bot stay aligned with your content.
378 + </p>
379 + </div>
1734 380
1735 - $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
381 + <div class="faq-item">
382 + <h3>How do intents work in MxChat?</h3>
383 + <p>
384 + Intents allow MxChat to recognize user requests and trigger specific actions, such as capturing emails or displaying product information. This helps provide a more interactive and responsive experience. For a detailed explanation of each intent, please refer to our <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">Intents Documentation</a>.
385 + </p>
386 + </div>
1736 387
1737 - if (isset($input['mxchat_notification_email'])) {
1738 - // Same list rule as the Transcripts autosave path (plan 2f131a). These two
1739 - // paths disagreeing is how the original bug survived: this one DID call
1740 - // is_email(), but on sanitize_email()'s output — which is valid even when
1741 - // the input was two addresses mashed into one. See MxChat_Utils.
1742 - $parsed = MxChat_Utils::parse_notification_emails($input['mxchat_notification_email']);
1743 - if ($parsed['error'] !== '') {
1744 - add_settings_error(
1745 - 'mxchat_transcripts_options',
1746 - 'invalid_email',
1747 - $parsed['error'],
1748 - 'error'
1749 - );
1750 - // Keep whatever was already stored. Do NOT fall back to admin_email:
1751 - // that fallback belongs to a genuinely EMPTY field, and using it here
1752 - // would quietly redirect notifications away from the address on screen.
1753 - $existing = get_option('mxchat_transcripts_options', array());
1754 - if (is_array($existing) && isset($existing['mxchat_notification_email'])) {
1755 - $sanitized['mxchat_notification_email'] = $existing['mxchat_notification_email'];
1756 - }
1757 - } else {
1758 - $sanitized['mxchat_notification_email'] = implode(', ', $parsed['emails']);
1759 - }
1760 - }
1761 388
1762 - // Sanitize auto-delete setting
1763 - $valid_intervals = array('never', '1week', '2weeks', '1month');
1764 - if (isset($input['mxchat_auto_delete_transcripts'])) {
1765 - $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1766 - ? $input['mxchat_auto_delete_transcripts']
1767 - : 'never';
1768 - } else {
1769 - $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1770 - }
389 + <div class="faq-item">
390 + <h3>How does the Complianz integration work?</h3>
391 + <p>
392 + The Pro version offers direct integration with the Complianz GDPR plugin, making it easy to stay compliant with GDPR. If Complianz is enabled on your website, users must accept consent before the chatbot widget appears. The chatbot will only display once the user has accepted, ensuring compliance with data privacy regulations.
393 + </p>
394 + </div>
1771 395
1772 - // Sanitize custom retention-days override (plan-9b80b1).
1773 - if (isset($input['mxchat_retention_days'])) {
1774 - $days = (int) $input['mxchat_retention_days'];
1775 - $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1776 - } else {
1777 - $sanitized['mxchat_retention_days'] = 0;
1778 - }
396 + <div class="faq-item">
397 + <h3>How does the WooCommerce integration work?</h3>
398 + <p>
399 + With WooCommerce integration, the chatbot automatically embeds new products and updates existing ones. For already-published products, you can click update or submit the product sitemap. The “Order History Access” setting allows the bot to access users' order history (requires login) and assist with order inquiries. To enable the “Add to Cart” feature, add this system instruction: “After discussing a product, ask if the user wants to add it to their cart. The user must say 'Add to cart' exactly.” Currently, this feature supports English only, with more languages coming soon.
400 + </p>
401 + </div>
1779 402
1780 - // Get old values to check if auto-delete or retention-days changed.
1781 - $old_options = get_option('mxchat_transcripts_options');
1782 - $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1783 - $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
403 + <div class="faq-item">
404 + <h3>Why isn't my chatbot responding as expected?</h3>
405 + <p>
406 + AI chatbots can sometimes behave in unexpected ways, especially if you're new to configuring AI for specific tasks. We're committed to helping you get the most out of your chatbot experience. While we’re working on comprehensive guides and video tutorials, our team is here to assist you directly. If your chatbot isn't delivering the responses you need, please don’t hesitate to <a href="https://mxchat.ai/contact/" target="_blank" rel="noopener noreferrer">contact us</a> for personalized support.
407 + </p>
408 + <p>
409 + We’re dedicated to your success and ready to guide you in aligning the AI's behavior to meet your goals.
410 + </p>
411 + </div>
1784 412
1785 - // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1786 - // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1787 - // reason to keep the daily cron registered.
1788 - $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1789 - $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1790 - if ($interval_changed || $retention_changed) {
1791 - $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1792 - $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1793 - }
413 + <div class="faq-item">
414 + <h3>What is Loops, and how do I get an API key?</h3>
415 + <p>
416 + Loops is a powerful SaaS email service that helps you automate and enhance your email marketing campaigns, making it easy to reach and engage with your audience. To integrate Loops with MxChat, you’ll need an API key from Loops. You can obtain this key by logging into your Loops account and navigating to the API settings. Visit the <a href="https://loops.so" target="_blank" rel="noopener noreferrer">Loops website</a> to get started or to sign up for an account.
417 + </p>
418 + </div>
1794 419
1795 - // Sanitize auto-email transcript settings
1796 - $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
1797 420
1798 - $valid_delays = array('15', '30', '60');
1799 - if (isset($input['mxchat_auto_email_transcript_delay'])) {
1800 - $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1801 - ? $input['mxchat_auto_email_transcript_delay']
1802 - : '30';
1803 - } else {
1804 - $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1805 - }
1806 -
1807 - // Sanitize require contact info setting
1808 - $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1809 -
1810 - return $sanitized;
421 + </div>
422 + <?php submit_button(); ?>
423 + </form>
424 + </div>
425 + <?php
1811 426 }
1812 427
1813 -/**
1814 - * Schedule or unschedule the transcript cleanup cron job
1815 - */
1816 -public function schedule_transcript_cleanup($interval) {
1817 - // Clear any existing scheduled event
1818 - $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1819 - if ($timestamp) {
1820 - wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1821 - }
1822 428
1823 - // Schedule new event whenever retention is active. "active" is the canonical
1824 - // value passed by sanitize_transcripts_options when either the dropdown != never
1825 - // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1826 - // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1827 - if ($interval !== 'never') {
1828 - // Schedule to run daily at 3 AM
1829 - $next_run = strtotime('tomorrow 3:00 AM');
1830 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1831 - }
1832 -}
429 + public function mxchat_create_transcripts_page() {
430 + ?>
431 + <div class="wrap mxchat-admin">
432 + <h2><?php esc_html_e('Chat Transcripts', 'mxchat'); ?></h2>
433 + <form id="mxchat-delete-form" method="post">
434 + <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
435 + <div class="mxchat-controls">
436 + <label for="mxchat-select-all-transcripts" class="mxchat-select-all-label">
437 + <input type="checkbox" id="mxchat-select-all-transcripts" /> <?php esc_html_e('Select All', 'mxchat'); ?>
438 + </label>
439 + <input type="submit" value="<?php esc_attr_e('Delete Selected', 'mxchat'); ?>" class="button delete-chats-button" />
440 + </div>
441 + <div id="mxchat-transcripts">
442 + <!-- Transcripts will be loaded here -->
443 + </div>
444 + </form>
445 + </div>
446 + <?php
447 + }
1833 448
1834 -/**
1835 - * Self-heal guard: keep the cleanup cron in sync with the retention setting.
1836 - *
1837 - * Runs on admin_init. Cost when nothing is wrong: one get_option() (cached) and
1838 - * one wp_next_scheduled() (reads the cached cron option) — no writes. It only
1839 - * schedules when retention is active but the event is missing, and only
1840 - * unschedules when retention is off but the event survived. Both directions
1841 - * reuse schedule_transcript_cleanup() so there is exactly one scheduling path.
1842 - * Legacy dropdown values (1week/2weeks/1month) count as active, matching the
1843 - * helper's own semantics. Deliberately not gated on DISABLE_WP_CRON: scheduling
1844 - * writes the cron option regardless of how cron is executed, so a server-side
1845 - * cron runner still picks the event up.
1846 - */
1847 -public function ensure_transcript_cleanup_scheduled() {
1848 - $options = get_option('mxchat_transcripts_options', array());
1849 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1850 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1851 - $active = ($interval !== 'never') || ($days > 0);
1852 - $scheduled = (bool) wp_next_scheduled('mxchat_cleanup_old_transcripts');
1853 449
1854 - if ($active && !$scheduled) {
1855 - $this->schedule_transcript_cleanup('active');
1856 - } elseif (!$active && $scheduled) {
1857 - $this->schedule_transcript_cleanup('never');
1858 - }
1859 -}
1860 450
1861 -/**
1862 - * Delete old transcripts based on the configured interval
1863 - */
1864 -public function cleanup_old_transcripts() {
1865 - $options = get_option('mxchat_transcripts_options', array());
1866 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1867 - $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1868 451
1869 - // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
1870 - $days = 0;
1871 - if ($custom_days > 0) {
1872 - $days = $custom_days;
1873 - } else {
1874 - switch ($interval) {
1875 - case '1week': $days = 7; break;
1876 - case '2weeks': $days = 14; break;
1877 - case '1month': $days = 30; break;
1878 - case 'never':
1879 - default:
1880 - $days = 0;
1881 - }
1882 - }
1883 -
1884 - // Devs can override the final day count programmatically.
1885 - $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
1886 -
1887 - if ($days <= 0) {
1888 - return; // Retention disabled — bail.
1889 - }
1890 -
452 +public function mxchat_create_prompts_page() {
1891 453 global $wpdb;
1892 - $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1893 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1894 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
454 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1895 455
1896 - // Defensive: if the main table doesn't exist (fresh-ish install), bail.
1897 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
1898 - return;
456 + // Display success message if all prompts were deleted
457 + if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
458 + echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p></div>';
1899 459 }
1900 460
1901 - $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
461 + // Set up pagination and search query
462 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
463 + $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
464 + $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
465 + $per_page = 10;
466 + $offset = ($current_page - 1) * $per_page;
1902 467
1903 - // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
1904 - // the cron will pick up where it left off on the next tick (within hours).
1905 - $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
468 + // Retrieve total number of prompts
469 + $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
470 + $total_pages = ceil($total_prompts / $per_page);
1906 471
1907 - $sessions_to_delete = $wpdb->get_col(
472 + // Retrieve prompts from the database
473 + $prompts = $wpdb->get_results(
1908 474 $wpdb->prepare(
1909 - "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
1910 - $cutoff_date,
1911 - $batch_cap
475 + "SELECT * FROM {$table_name} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
476 + $per_page,
477 + $offset
1912 478 )
1913 479 );
1914 480
1915 - if (empty($sessions_to_delete)) {
1916 - return;
1917 - }
481 + ?>
1918 482
1919 - $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
483 + <div class="wrap mxchat-admin">
484 + <div class="mxchat-grid-container">
485 + <!-- Submit Content Form -->
486 + <div class="mxchat-grid-item full-width">
487 + <h2>Submit Content</h2>
488 + <form id="mxchat-content-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
489 + <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
490 + <div class="mxchat-form-group">
491 + <label for="article_content">Article Content:</label>
492 + <textarea name="article_content" id="article_content" required></textarea>
493 + </div>
494 + <div class="mxchat-form-group">
495 + <label for="article_url">Article URL (Optional):</label>
496 + <input type="url" name="article_url" id="article_url" placeholder="Enter related URL for the content">
497 + </div>
498 + <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
499 + </form>
500 + <div id="mxchat-content-loading" class="mxchat-content-spinner" style="display: none;"></div>
501 + <div id="mxchat-content-loading-text" class="mxchat-loading-text">Submitting content, please wait...</div>
502 + </div>
1920 503
1921 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1922 - // $placeholders is a server-built list of literal "%s" tokens.
1923 - $deleted_transcripts = (int) $wpdb->query(
1924 - $wpdb->prepare(
1925 - "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
1926 - $sessions_to_delete
1927 - )
1928 - );
1929 504
1930 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
1931 - $wpdb->query(
1932 - $wpdb->prepare(
1933 - "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
1934 - $sessions_to_delete
1935 - )
1936 - );
1937 - }
505 + <!-- Submit Sitemap Form -->
506 + <div class="mxchat-grid-item">
507 + <h2>Submit Sitemap or Page URL</h2>
508 + <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')); ?>">
509 + <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
510 + <div class="mxchat-search-group">
511 + <input type="url" name="sitemap_url" id="sitemap_url" placeholder="Sitemap or URL" required />
512 + <input type="submit" name="submit_sitemap" value="Submit" class="button button-primary" />
513 + </div>
514 + </form>
515 + <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"></div>
516 + <div id="mxchat-loading-text">Loading sitemap content into database, please wait...</div>
1938 517
1939 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
1940 - $wpdb->query(
1941 - $wpdb->prepare(
1942 - "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
1943 - $sessions_to_delete
1944 - )
1945 - );
1946 - }
1947 - // phpcs:enable
518 + </div>
1948 519
1949 - update_option('mxchat_retention_last_swept_at', time(), false);
1950 - update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
1951 -}
520 + <!-- Search Knowledge Form -->
521 + <div class="mxchat-grid-item">
522 + <h2>Search Knowledge</h2>
523 + <form method="get" id="knowledge-search">
524 + <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
525 + <input type="hidden" name="page" value="mxchat-prompts" />
526 + <div class="mxchat-search-group">
527 + <input type="text" name="search" placeholder="Search Knowledge" value="<?php echo esc_attr($search_query); ?>" />
528 + <input type="submit" value="Search" class="button button-primary" />
529 + </div>
530 + </form>
531 + </div>
532 + </div>
1952 533
1953 -public function export_chat_transcripts() {
1954 - if (!current_user_can('manage_options')) {
1955 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1956 - }
534 + <!-- Table navigation with Delete All Button -->
535 + <div class="tablenav">
536 + <div class="tablenav-pages">
537 + <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
1957 538
1958 - check_ajax_referer('mxchat_export_transcripts', 'security');
539 + <!-- Delete All Prompts Button -->
540 + <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_all_prompts')); ?>" style="display: inline;" onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete all prompts? This action cannot be undone.', 'mxchat'); ?>');">
541 + <?php wp_nonce_field('mxchat_delete_all_prompts_action', 'mxchat_delete_all_prompts_nonce'); ?>
542 + <input type="submit" name="delete_all_prompts" value="<?php esc_attr_e('Delete All Knowledge', 'mxchat'); ?>" class="button mxchat-delete-all" />
543 + </form>
1959 544
1960 - global $wpdb;
1961 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
545 + <?php
546 + // Display pagination links
547 + $page_links = paginate_links(array(
548 + 'base' => add_query_arg('paged', '%#%', admin_url('admin.php?page=mxchat-prompts')),
549 + 'format' => '',
550 + 'prev_text' => __('&laquo; Previous'),
551 + 'next_text' => __('Next &raquo;'),
552 + 'total' => $total_pages,
553 + 'current' => $current_page,
554 + 'add_args' => array(
555 + 'search' => $search_query,
556 + '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')
557 + ),
558 + ));
1962 559
1963 - // Get all transcripts ordered by session and timestamp
1964 - $results = $wpdb->get_results(
1965 - "SELECT session_id, user_email, user_identifier, role, message, timestamp
1966 - FROM {$table_name}
1967 - ORDER BY session_id, timestamp ASC"
1968 - );
560 + if ($page_links) {
561 + echo '<div class="tablenav-pages">' . wp_kses_post($page_links) . '</div>';
562 + }
563 + ?>
564 + </div>
565 + </div>
1969 566
1970 - if (empty($results)) {
1971 - wp_send_json_error(array('message' => 'No transcripts found.'));
1972 - wp_die();
1973 - }
567 + <!-- Prompts Table -->
568 + <table class="mxchat-table">
569 + <thead>
570 + <tr>
571 + <th>ID</th>
572 + <th>Article Content</th>
573 + <th>URL</th>
574 + <th>Actions</th>
575 + </tr>
576 + </thead>
577 + <tbody>
578 + <?php if ($prompts) : ?>
579 + <?php foreach ($prompts as $prompt) : ?>
580 + <tr id="prompt-<?php echo esc_attr($prompt->id); ?>">
581 + <td><?php echo esc_html($prompt->id); ?></td>
582 + <td class="mxchat_article_content_dashboard">
583 + <span class="content-view"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></span>
584 + <textarea class="content-edit" style="display:none;"><?php echo esc_textarea($prompt->article_content); ?></textarea>
585 + </td>
586 + <td class="mxchat_article_url_dashboard">
587 + <span class="url-view">
588 + <?php if (!empty($prompt->source_url)) : ?>
589 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
590 + <?php else : ?>
591 + N/A
592 + <?php endif; ?>
593 + </span>
594 + <input type="url" class="url-edit" value="<?php echo esc_attr($prompt->source_url); ?>" style="display:none;" />
595 + </td>
596 + <td>
597 + <button class="button edit-button" data-id="<?php echo esc_attr($prompt->id); ?>">Edit</button>
598 + <button class="button save-button" data-id="<?php echo esc_attr($prompt->id); ?>" style="display:none;">Save</button>
599 + <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'))); ?>" class="button delete-button">Delete</a>
600 + </td>
601 + </tr>
602 + <?php endforeach; ?>
603 + <?php else : ?>
604 + <tr>
605 + <td colspan="4"><?php esc_html_e('No prompts found.', 'mxchat'); ?></td>
606 + </tr>
607 + <?php endif; ?>
608 + </tbody>
609 + </table>
610 + </div>
611 + <?php
612 +}
1974 613
1975 - // Set headers for CSV download
1976 - header('Content-Type: text/csv');
1977 - header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
1978 - header('Pragma: no-cache');
1979 - header('Expires: 0');
1980 -
1981 - // Create output stream
1982 - $output = fopen('php://output', 'w');
1983 -
1984 - // Add UTF-8 BOM for proper Excel encoding
1985 - fputs($output, "\xEF\xBB\xBF");
1986 -
1987 - // Add CSV headers
1988 - fputcsv($output, array(
1989 - 'Session ID',
1990 - 'Email',
1991 - 'User Identifier',
1992 - 'Role',
1993 - 'Message',
1994 - 'Timestamp'
1995 - ));
1996 -
1997 - // Add data rows
1998 - foreach ($results as $row) {
1999 - fputcsv($output, array(
2000 - $row->session_id,
2001 - $row->user_email,
2002 - $row->user_identifier,
2003 - $row->role,
2004 - $row->message,
2005 - $row->timestamp
2006 - ));
614 +// Delete All Prompts
615 +public function mxchat_handle_delete_all_prompts() {
616 + // Verify nonce
617 + if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
618 + wp_die(__('Nonce verification failed.', 'mxchat'));
2007 619 }
2008 620
2009 - fclose($output);
2010 - wp_die();
2011 -}
2012 -
2013 -// ============================================================================
2014 -// Leads tab (inside Transcripts)
2015 -//
2016 -// Leads are derived from existing data — no dedicated table. Primary source:
2017 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
2018 -// source: the mxchat_sessions table's visitor_email/visitor_name columns
2019 -// (plus any unmigrated legacy `mxchat_email_{sid}` wp_options rows) for
2020 -// "orphan" leads who submitted the pre-chat form but never chatted.
2021 -// ============================================================================
2022 -
2023 -/**
2024 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
2025 - */
2026 -public function mxchat_fetch_leads() {
621 + // Check permissions
2027 622 if (!current_user_can('manage_options')) {
2028 - wp_send_json_error(['message' => 'Insufficient permissions']);
2029 - wp_die();
623 + wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
2030 624 }
2031 625
2032 626 global $wpdb;
2033 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
627 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2034 628
2035 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
2036 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
2037 - $offset = ($page - 1) * $per_page;
2038 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
2039 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
2040 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
2041 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
2042 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
2043 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
629 + // Delete all prompts from the table
630 + $wpdb->query("DELETE FROM {$table_name}");
2044 631
2045 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
2046 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
632 + // Clear relevant cache
633 + wp_cache_delete('all_prompts', 'mxchat_prompts');
2047 634
2048 - // Base WHERE for transcripts leads.
2049 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
2050 - $where_params = [];
635 + // Redirect back with a success message
636 + $redirect_url = add_query_arg(array(
637 + 'page' => 'mxchat-prompts',
638 + 'all_deleted' => 'true'
639 + ), admin_url('admin.php'));
2051 640
2052 - if ($date_cutoff) {
2053 - $where_clauses[] = 'timestamp >= %s';
2054 - $where_params[] = $date_cutoff;
2055 - }
2056 - if ($page_filter && $has_page_url_column) {
2057 - $where_clauses[] = 'originating_page_url = %s';
2058 - $where_params[] = $page_filter;
2059 - }
2060 - if ($search !== '') {
2061 - $like = '%' . $wpdb->esc_like($search) . '%';
2062 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
2063 - $where_params[] = $like;
2064 - $where_params[] = $like;
2065 - }
2066 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
641 + wp_safe_redirect($redirect_url);
642 + exit;
643 +}
2067 644
2068 - // Aggregate query grouped by email.
2069 - $select_sql = $has_page_url_column
2070 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2071 - COUNT(DISTINCT session_id) AS conversation_count"
2072 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2073 - COUNT(DISTINCT session_id) AS conversation_count";
2074 -
2075 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
2076 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
2077 -
2078 - $transcripts_sql = $wpdb->prepare(
2079 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
2080 - array_merge($where_params, [$per_page, $offset])
2081 - );
2082 - $transcript_rows = $wpdb->get_results($transcripts_sql);
2083 -
2084 - // Count of unique transcript-based leads under the same filters.
2085 - $count_sql = $wpdb->prepare(
2086 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
2087 - $where_params
2088 - );
2089 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
2090 -
2091 - // Hydrate each row: name, latest_session_id, top page.
2092 - $leads = [];
2093 - foreach ($transcript_rows as $row) {
2094 - $detail = $has_page_url_column
2095 - ? $wpdb->get_row($wpdb->prepare(
2096 - "SELECT session_id, user_name, originating_page_url, originating_page_title
2097 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2098 - $row->user_email
2099 - ))
2100 - : $wpdb->get_row($wpdb->prepare(
2101 - "SELECT session_id, user_name FROM {$table}
2102 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2103 - $row->user_email
2104 - ));
2105 -
2106 - $leads[] = [
2107 - 'email' => $row->user_email,
2108 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2109 - 'conversation_count' => (int) $row->conversation_count,
2110 - 'last_seen' => $row->last_seen,
2111 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
2112 - 'first_seen' => $row->first_seen,
2113 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
2114 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2115 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
2116 - 'is_orphan' => false,
2117 - 'status' => 'active',
2118 - ];
645 +// Single Prompt Deletion
646 +public function mxchat_handle_delete_prompt() {
647 + // Sanitize and validate nonce
648 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
649 + if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
650 + wp_die('Nonce verification failed.');
2119 651 }
2120 652
2121 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
2122 - // status filter below. Deduplication priority when the same email appears in multiple
2123 - // sources: transcripts > chat_deleted > orphan.
2124 - $transcripts_emails_seen = array_flip(array_map(
2125 - function ($r) { return strtolower($r['email']); },
2126 - $leads
2127 - ));
2128 -
2129 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
2130 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
2131 - $chat_deleted_leads_all = [];
2132 - if ($status === 'all' || $status === 'chat_deleted') {
2133 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
2134 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
2135 - $chat_deleted_leads_all = array_values(array_filter(
2136 - $chat_deleted_leads_all,
2137 - function ($row) use ($transcripts_emails_seen) {
2138 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2139 - }
2140 - ));
2141 - foreach ($chat_deleted_leads_all as $row) {
2142 - $transcripts_emails_seen[strtolower($row['email'])] = true;
2143 - }
2144 - }
2145 -
2146 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
2147 - // when a date filter is active.
2148 - $orphan_leads_all = [];
2149 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
2150 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
2151 - $orphan_leads_all = array_values(array_filter(
2152 - $orphan_leads_all,
2153 - function ($row) use ($transcripts_emails_seen) {
2154 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2155 - }
2156 - ));
2157 - }
2158 -
2159 - // Apply status filter to the transcripts-derived list.
2160 - if ($status === 'orphan' || $status === 'chat_deleted') {
2161 - $leads = [];
2162 - $transcripts_lead_count = 0;
2163 - }
2164 -
2165 - // Stitch the current page from the three buckets in priority order.
2166 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
2167 - $remaining_slots = $per_page - count($leads);
2168 -
2169 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
2170 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
2171 - if ($start < count($chat_deleted_leads_all)) {
2172 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
2173 - $remaining_slots = $per_page - count($leads);
2174 - }
2175 - }
2176 -
2177 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
2178 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
2179 - $start = max(0, ($page - 1) * $per_page - $before);
2180 - if ($start < count($orphan_leads_all)) {
2181 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
2182 - }
2183 - }
2184 -
2185 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
2186 -
2187 - // Stats strip: always computed over full dataset, unaffected by filters.
2188 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
2189 -
2190 - // Top pages: top 5 by distinct emails captured.
2191 - $top_pages = [];
2192 - if ($has_page_url_column) {
2193 - $top_pages_rows = $wpdb->get_results(
2194 - "SELECT originating_page_url AS url,
2195 - MAX(originating_page_title) AS title,
2196 - COUNT(DISTINCT user_email) AS lead_count
2197 - FROM {$table}
2198 - WHERE user_email IS NOT NULL AND user_email != ''
2199 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
2200 - GROUP BY originating_page_url
2201 - ORDER BY lead_count DESC, url ASC
2202 - LIMIT 5"
2203 - );
2204 - foreach ($top_pages_rows as $p) {
2205 - $top_pages[] = [
2206 - 'url' => $p->url,
2207 - 'title' => $p->title ?: $p->url,
2208 - 'lead_count' => (int) $p->lead_count,
2209 - ];
2210 - }
2211 - }
2212 -
2213 - wp_send_json([
2214 - 'success' => true,
2215 - 'leads' => $leads,
2216 - 'page' => $page,
2217 - 'per_page' => $per_page,
2218 - 'total_count' => $total_count,
2219 - 'total_pages' => $total_pages,
2220 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
2221 - 'showing_end' => min($offset + $per_page, $total_count),
2222 - 'stats' => $stats,
2223 - 'top_pages' => $top_pages,
2224 - ]);
2225 - wp_die();
2226 -}
2227 -
2228 -/**
2229 - * Delete one or more leads by email. Removes every transcripts row for that
2230 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2231 - * mxchat_history_{sid}) and any orphan option entries matching the email.
2232 - */
2233 -public function mxchat_delete_leads() {
653 + // Check permissions
2234 654 if (!current_user_can('manage_options')) {
2235 - wp_send_json_error(['message' => 'Insufficient permissions']);
2236 - wp_die();
655 + wp_die('You do not have sufficient permissions to delete prompts.');
2237 656 }
2238 - check_ajax_referer('mxchat_delete_leads', 'security');
2239 657
2240 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2241 - $emails = [];
2242 - foreach ($emails_raw as $e) {
2243 - $clean = sanitize_email((string) $e);
2244 - if ($clean) {
2245 - $emails[] = $clean;
2246 - }
658 + // Validate and sanitize ID parameter
659 + $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
660 + if ($id <= 0) {
661 + wp_die('Invalid prompt ID.');
2247 662 }
2248 - if (empty($emails)) {
2249 - wp_send_json_error(['message' => 'No emails provided']);
2250 - wp_die();
2251 - }
2252 663
2253 - $summary = self::mxchat_wipe_leads_by_email($emails);
2254 -
2255 - wp_send_json([
2256 - 'success' => true,
2257 - 'deleted_leads' => count($emails),
2258 - 'deleted_sessions' => $summary['deleted_sessions'],
2259 - 'deleted_rows' => $summary['deleted_rows'],
2260 - ]);
2261 - wp_die();
2262 -}
2263 -
2264 -/**
2265 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2266 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2267 - *
2268 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2269 - * Input emails must already be sanitized with sanitize_email().
2270 - */
2271 -private static function mxchat_wipe_leads_by_email(array $emails) {
2272 664 global $wpdb;
2273 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2274 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2275 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
665 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2276 666
2277 - $deleted_sessions = 0;
2278 - $deleted_rows = 0;
2279 - $emails_lc = array_map('strtolower', $emails);
667 + // Clear cache and delete prompt
668 + wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
669 + $wpdb->delete($table_name, array('id' => $id), array('%d'));
2280 670
2281 - foreach ($emails as $email) {
2282 - $session_ids = $wpdb->get_col($wpdb->prepare(
2283 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2284 - $email
2285 - ));
2286 -
2287 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2288 - if ($rows_removed !== false) {
2289 - $deleted_rows += (int) $rows_removed;
2290 - }
2291 -
2292 - foreach ($session_ids as $sid) {
2293 - $deleted_sessions++;
2294 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2295 - delete_option('mxchat_history_' . $sid);
2296 - delete_option('mxchat_email_' . $sid);
2297 - delete_option('mxchat_name_' . $sid);
2298 - delete_option('mxchat_agent_name_' . $sid);
2299 - delete_option('mxchat_lead_del_email_' . $sid);
2300 - delete_option('mxchat_lead_del_name_' . $sid);
2301 - delete_option('mxchat_lead_del_ts_' . $sid);
2302 - if (class_exists('MxChat_Session_Store')) {
2303 - MxChat_Session_Store::delete_session($sid); // b64b77
2304 - }
2305 - if ($has_translations) {
2306 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2307 - }
2308 - }
2309 - }
2310 -
2311 - // Table-side twin of the option sweep below (5658f2): orphan pre-chat
2312 - // captures now live in the sessions table's identity columns.
2313 - if (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'find_by_email')) {
2314 - foreach ($emails as $email) {
2315 - foreach (MxChat_Session_Store::find_by_email($email) as $sid) {
2316 - MxChat_Session_Store::delete_session($sid);
2317 - }
2318 - }
2319 - }
2320 -
2321 - // Clean up any lingering option entries (unmigrated orphan pre-chat captures +
2322 - // chat_deleted preservations) whose stored value matches one of the emails being wiped.
2323 - $lingering = $wpdb->get_results(
2324 - "SELECT option_name, option_value FROM {$wpdb->options}
2325 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2326 - );
2327 - foreach ($lingering as $opt) {
2328 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2329 - continue;
2330 - }
2331 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2332 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2333 - delete_option('mxchat_lead_del_email_' . $sid);
2334 - delete_option('mxchat_lead_del_name_' . $sid);
2335 - delete_option('mxchat_lead_del_ts_' . $sid);
2336 - } else {
2337 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2338 - delete_option('mxchat_email_' . $sid);
2339 - delete_option('mxchat_name_' . $sid);
2340 - }
2341 - }
2342 -
2343 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2344 -
2345 - return [
2346 - 'deleted_sessions' => $deleted_sessions,
2347 - 'deleted_rows' => $deleted_rows,
2348 - ];
671 + wp_safe_redirect(add_query_arg(array('page' => 'mxchat-prompts', 'deleted' => 'true'), admin_url('admin.php')));
672 + exit;
2349 673 }
2350 674
2351 -/**
2352 - * Stream a leads CSV. scope=all exports every lead under current filters is not
2353 - * supported to keep semantics simple; caller either exports all leads or a
2354 - * specific set of selected emails.
2355 - */
2356 -public function mxchat_export_leads() {
2357 - if (!current_user_can('manage_options')) {
2358 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2359 - }
2360 - check_ajax_referer('mxchat_export_leads', 'security');
2361 675
2362 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2363 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2364 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2365 676
2366 - $emails_in_clean = [];
2367 - foreach ($emails_in as $e) {
2368 - $clean = sanitize_email((string) $e);
2369 - if ($clean) {
2370 - $emails_in_clean[] = $clean;
2371 - }
2372 - }
2373 677
2374 - global $wpdb;
2375 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2376 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
678 + public function mxchat_generate_embedding($text) {
679 + $options = get_option('mxchat_options');
680 + $api_key = $options['api_key'] ?? 'default_api_key';
2377 681
2378 - // Collect leads from transcripts.
2379 - $transcripts_sql = "SELECT user_email AS email,
2380 - MAX(timestamp) AS last_seen,
2381 - COUNT(DISTINCT session_id) AS conversation_count
2382 - FROM {$table}
2383 - WHERE user_email IS NOT NULL AND user_email != ''";
2384 - $params = [];
2385 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2386 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2387 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2388 - $params = $emails_in_clean;
2389 - }
2390 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
2391 -
2392 - $rows = !empty($params)
2393 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2394 - : $wpdb->get_results($transcripts_sql);
2395 -
2396 - // Hydrate each row with name + top page.
2397 - $export_rows = [];
2398 - foreach ($rows as $row) {
2399 - $detail = $has_page_url_column
2400 - ? $wpdb->get_row($wpdb->prepare(
2401 - "SELECT user_name, originating_page_url FROM {$table}
2402 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2403 - $row->email
2404 - ))
2405 - : $wpdb->get_row($wpdb->prepare(
2406 - "SELECT user_name FROM {$table}
2407 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2408 - $row->email
2409 - ));
2410 - $export_rows[] = [
2411 - 'email' => $row->email,
2412 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2413 - 'conversation_count' => (int) $row->conversation_count,
2414 - 'last_seen' => $row->last_seen,
2415 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2416 - ];
2417 - }
2418 -
2419 - // Include orphan + chat_deleted leads when exporting all.
2420 - if ($scope === 'all') {
2421 - $transcripts_emails_lc = array_flip(array_map(
2422 - function ($r) { return strtolower($r['email']); },
2423 - $export_rows
682 + $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
683 + 'body' => wp_json_encode(array(
684 + 'model' => 'text-embedding-ada-002',
685 + 'input' => $text
686 + )),
687 + 'headers' => array(
688 + 'Authorization' => 'Bearer ' . $api_key,
689 + 'Content-Type' => 'application/json'
690 + ),
2424 691 ));
2425 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2426 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2427 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2428 - $export_rows[] = [
2429 - 'email' => $cd['email'],
2430 - 'name' => $cd['name'],
2431 - 'conversation_count' => 0,
2432 - 'last_seen' => $cd['last_seen'],
2433 - 'top_page_url' => '',
2434 - ];
2435 - }
2436 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2437 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2438 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2439 - $export_rows[] = [
2440 - 'email' => $orphan['email'],
2441 - 'name' => $orphan['name'],
2442 - 'conversation_count' => 0,
2443 - 'last_seen' => '',
2444 - 'top_page_url' => '',
2445 - ];
2446 - }
2447 - }
2448 692
2449 - if (empty($export_rows)) {
2450 - wp_send_json_error(['message' => 'No leads to export.']);
2451 - wp_die();
2452 - }
2453 -
2454 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2455 - header('Content-Type: text/csv');
2456 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2457 - header('Pragma: no-cache');
2458 - header('Expires: 0');
2459 -
2460 - $output = fopen('php://output', 'w');
2461 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2462 -
2463 - if ($fields_mode === 'email_only') {
2464 - fputcsv($output, ['Email']);
2465 - foreach ($export_rows as $r) {
2466 - fputcsv($output, [$r['email']]);
693 + if (is_wp_error($response)) {
694 + return null;
2467 695 }
2468 - } else {
2469 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page']);
2470 - foreach ($export_rows as $r) {
2471 - fputcsv($output, [
2472 - $r['email'],
2473 - $r['name'],
2474 - $r['conversation_count'],
2475 - $r['last_seen'],
2476 - $r['top_page_url'],
2477 - ]);
2478 - }
2479 - }
2480 696
2481 - fclose($output);
2482 - wp_die();
2483 -}
2484 -
2485 -/**
2486 - * Stats strip payload (independent of filters).
2487 - */
2488 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2489 - global $wpdb;
2490 -
2491 - $total_transcripts_emails = (int) $wpdb->get_var(
2492 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2493 - WHERE user_email IS NOT NULL AND user_email != ''"
2494 - );
2495 -
2496 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2497 - "SELECT COUNT(*) FROM (
2498 - SELECT user_email FROM {$table}
2499 - WHERE user_email IS NOT NULL AND user_email != ''
2500 - GROUP BY user_email
2501 - HAVING MIN(timestamp) >= %s
2502 - ) AS new_leads",
2503 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2504 - ));
2505 -
2506 - $total_convos = (int) $wpdb->get_var(
2507 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2508 - WHERE user_email IS NOT NULL AND user_email != ''"
2509 - );
2510 -
2511 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2512 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
2513 -
2514 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2515 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2516 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2517 -
2518 - $avg = $total_transcripts_emails > 0
2519 - ? round($total_convos / $total_transcripts_emails, 1)
2520 - : 0;
2521 -
2522 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2523 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2524 - // inflate this number.
2525 - $orphan_pct = $total_leads > 0
2526 - ? (int) round(($orphan_count / $total_leads) * 100)
2527 - : 0;
2528 -
2529 - return [
2530 - 'total_leads' => $total_leads,
2531 - 'new_this_week' => $new_this_week,
2532 - 'avg_convos' => $avg,
2533 - 'orphan_pct' => $orphan_pct,
2534 - 'orphan_count' => $orphan_count,
2535 - 'chat_deleted_count' => $chat_deleted_count,
2536 - ];
2537 -}
2538 -
2539 -/**
2540 - * Collect leads who had a conversation that an admin later deleted (preserved via
2541 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2542 - * original last-seen timestamp so they still sort and filter sensibly.
2543 - *
2544 - * @param string $search Optional email/name substring filter.
2545 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2546 - * @return array
2547 - */
2548 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2549 - global $wpdb;
2550 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2551 -
2552 - $rows = $wpdb->get_results(
2553 - "SELECT option_name, option_value FROM {$wpdb->options}
2554 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2555 - );
2556 - if (empty($rows)) {
2557 - return [];
697 + $response_data = json_decode(wp_remote_retrieve_body($response), true);
698 + return $response_data['data'][0]['embedding'] ?? null;
2558 699 }
2559 700
2560 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2561 - // they've come back and chatted, so they're active leads again.
2562 - $emails_in_transcripts = array_map(
2563 - 'strtolower',
2564 - (array) $wpdb->get_col(
2565 - "SELECT DISTINCT user_email FROM {$table}
2566 - WHERE user_email IS NOT NULL AND user_email != ''"
2567 - )
2568 - );
2569 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2570 -
2571 - $needle = strtolower(trim((string) $search));
2572 - $by_email = [];
2573 -
2574 - foreach ($rows as $opt) {
2575 - $email = sanitize_email(trim((string) $opt->option_value));
2576 - if (!$email) {
2577 - continue;
701 + public function mxchat_delete_chat_history() {
702 + if (!current_user_can('manage_options')) {
703 + echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
704 + wp_die();
2578 705 }
2579 - if (isset($emails_in_transcripts[strtolower($email)])) {
2580 - continue;
2581 - }
2582 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2583 - if (!$sid) {
2584 - continue;
2585 - }
2586 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2587 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2588 706
2589 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2590 - continue;
2591 - }
2592 - if ($needle !== '') {
2593 - $hay = strtolower($email . ' ' . $name);
2594 - if (strpos($hay, $needle) === false) {
2595 - continue;
2596 - }
2597 - }
707 + check_ajax_referer('mxchat_delete_chat_history', 'security');
2598 708
2599 - $key = strtolower($email);
2600 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2601 - $by_email[$key] = [
2602 - 'email' => $email,
2603 - 'name' => $name,
2604 - 'conversation_count' => 0,
2605 - 'last_seen' => $ts,
2606 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2607 - 'first_seen' => $ts,
2608 - 'latest_session_id' => '',
2609 - 'top_page_url' => '',
2610 - 'top_page_title' => '',
2611 - 'is_orphan' => false,
2612 - 'status' => 'chat_deleted',
2613 - ];
2614 - }
2615 - }
709 + global $wpdb;
710 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2616 711
2617 - // Newest chat_deleted first.
2618 - usort($by_email, function ($a, $b) {
2619 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2620 - });
2621 - return array_values($by_email);
2622 -}
712 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
713 + foreach ($_POST['delete_session_ids'] as $session_id) {
714 + $session_id_sanitized = sanitize_text_field($session_id);
2623 715
2624 -/**
2625 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2626 - */
2627 -private static function mxchat_count_chat_deleted_leads() {
2628 - global $wpdb;
2629 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
716 + // Clear relevant cache before deletion
717 + $cache_key = 'chat_session_' . $session_id_sanitized;
718 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
2630 719
2631 - $emails = $wpdb->get_col(
2632 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2633 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2634 - );
2635 - if (empty($emails)) {
2636 - return 0;
2637 - }
2638 -
2639 - $transcripts_emails = array_map(
2640 - 'strtolower',
2641 - (array) $wpdb->get_col(
2642 - "SELECT DISTINCT user_email FROM {$table}
2643 - WHERE user_email IS NOT NULL AND user_email != ''"
2644 - )
2645 - );
2646 - $transcripts_emails = array_flip($transcripts_emails);
2647 -
2648 - $count = 0;
2649 - $seen = [];
2650 - foreach ($emails as $raw) {
2651 - $email = strtolower(trim((string) $raw));
2652 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2653 - continue;
2654 - }
2655 - $seen[$email] = true;
2656 - $count++;
2657 - }
2658 - return $count;
2659 -}
2660 -
2661 -/**
2662 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2663 - * Returned rows have no conversation_count, no timestamp.
2664 - *
2665 - * @param string $search Optional email/name substring filter.
2666 - * @return array
2667 - */
2668 -private static function mxchat_collect_orphan_leads($search = '') {
2669 - global $wpdb;
2670 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2671 -
2672 - // Primary source since 5658f2: the sessions table's identity columns.
2673 - // The legacy option scan stays for installs still mid-migration.
2674 - $store_rows = (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'identity_rows'))
2675 - ? MxChat_Session_Store::identity_rows()
2676 - : [];
2677 -
2678 - $option_rows = $wpdb->get_results(
2679 - "SELECT option_name, option_value FROM {$wpdb->options}
2680 - WHERE option_name LIKE 'mxchat_email_%'"
2681 - );
2682 - if (empty($option_rows) && empty($store_rows)) {
2683 - return [];
2684 - }
2685 -
2686 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2687 - $session_ids_with_rows = $wpdb->get_col(
2688 - "SELECT DISTINCT session_id FROM {$table}
2689 - WHERE user_email IS NOT NULL AND user_email != ''"
2690 - );
2691 - $session_ids_with_rows = array_flip($session_ids_with_rows);
2692 -
2693 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2694 - $emails_in_transcripts = array_map(
2695 - 'strtolower',
2696 - (array) $wpdb->get_col(
2697 - "SELECT DISTINCT user_email FROM {$table}
2698 - WHERE user_email IS NOT NULL AND user_email != ''"
2699 - )
2700 - );
2701 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2702 -
2703 - $orphans_by_email = [];
2704 - $needle = strtolower(trim((string) $search));
2705 -
2706 - // Normalize both sources into [sid, email, name] candidates. Table rows
2707 - // first — a session can only live in one home, and dedup-by-email below
2708 - // handles any overlap either way.
2709 - $candidates = [];
2710 - foreach ($store_rows as $row) {
2711 - $candidates[] = [
2712 - 'sid' => (string) $row['session_id'],
2713 - 'email' => (string) $row['visitor_email'],
2714 - 'name' => is_string($row['visitor_name'] ?? null) ? $row['visitor_name'] : '',
2715 - ];
2716 - }
2717 - foreach ($option_rows as $opt) {
2718 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2719 - $name_option = $sid ? get_option('mxchat_name_' . $sid, '') : '';
2720 - $candidates[] = [
2721 - 'sid' => (string) $sid,
2722 - 'email' => (string) $opt->option_value,
2723 - 'name' => is_string($name_option) ? $name_option : '',
2724 - ];
2725 - }
2726 -
2727 - foreach ($candidates as $cand) {
2728 - $email = sanitize_email(trim($cand['email']));
2729 - if (!$email) {
2730 - continue;
2731 - }
2732 - $sid = $cand['sid'];
2733 - if (!$sid) {
2734 - continue;
2735 - }
2736 - // Exclude leads who have any transcripts rows (they appear in the main list).
2737 - if (isset($emails_in_transcripts[strtolower($email)])) {
2738 - continue;
2739 - }
2740 - if (isset($session_ids_with_rows[$sid])) {
2741 - continue;
2742 - }
2743 -
2744 - $name = trim($cand['name']);
2745 -
2746 - if ($needle !== '') {
2747 - $hay = strtolower($email . ' ' . $name);
2748 - if (strpos($hay, $needle) === false) {
2749 - continue;
720 + // Perform the deletion
721 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
2750 722 }
2751 - }
2752 723
2753 - $key = strtolower($email);
2754 - if (!isset($orphans_by_email[$key])) {
2755 - $orphans_by_email[$key] = [
2756 - 'email' => $email,
2757 - 'name' => $name,
2758 - 'conversation_count' => 0,
2759 - 'last_seen' => '',
2760 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2761 - 'first_seen' => '',
2762 - 'latest_session_id' => '',
2763 - 'top_page_url' => '',
2764 - 'top_page_title' => '',
2765 - 'is_orphan' => true,
2766 - 'status' => 'orphan',
2767 - ];
2768 - }
2769 - }
724 + // Optionally, clear a general cache if you have one
725 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2770 726
2771 - return array_values($orphans_by_email);
2772 -}
2773 -
2774 -/**
2775 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2776 - */
2777 -private static function mxchat_leads_date_cutoff($date_range) {
2778 - switch ($date_range) {
2779 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2780 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2781 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2782 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2783 - case 'all':
2784 - default: return '';
2785 - }
2786 -}
2787 -
2788 -/**
2789 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2790 - */
2791 -private static function mxchat_leads_format_relative($timestamp) {
2792 - if (!$timestamp) {
2793 - return '';
2794 - }
2795 - $ts = strtotime($timestamp . ' UTC');
2796 - if (!$ts) {
2797 - return '';
2798 - }
2799 - $diff = time() - $ts;
2800 - if ($diff < 60) return __('just now', 'mxchat');
2801 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2802 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2803 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2804 - return wp_date('M j', $ts);
2805 -}
2806 -
2807 -/**
2808 - * Handle translation of chat messages via AJAX
2809 - */
2810 -public function mxchat_translate_messages() {
2811 - if (!current_user_can('manage_options')) {
2812 - wp_send_json_error(['error' => 'Insufficient permissions']);
2813 - wp_die();
2814 - }
2815 -
2816 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2817 - $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
2818 - $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
2819 - $messages = json_decode($messages_json, true);
2820 -
2821 - if (empty($session_id)) {
2822 - wp_send_json_error(['error' => 'No session ID provided']);
2823 - wp_die();
2824 - }
2825 -
2826 - if (empty($messages) || !is_array($messages)) {
2827 - wp_send_json_error(['error' => 'No messages to translate']);
2828 - wp_die();
2829 - }
2830 -
2831 - // Language names for prompting
2832 - $languages = [
2833 - 'en' => 'English',
2834 - 'es' => 'Spanish',
2835 - 'fr' => 'French',
2836 - 'de' => 'German',
2837 - 'it' => 'Italian',
2838 - 'pt' => 'Portuguese',
2839 - 'nl' => 'Dutch',
2840 - 'ru' => 'Russian',
2841 - 'zh' => 'Chinese',
2842 - 'ja' => 'Japanese',
2843 - 'ko' => 'Korean',
2844 - 'ar' => 'Arabic',
2845 - 'hi' => 'Hindi',
2846 - 'tr' => 'Turkish',
2847 - 'pl' => 'Polish',
2848 - 'vi' => 'Vietnamese',
2849 - 'th' => 'Thai',
2850 - 'id' => 'Indonesian',
2851 - 'sv' => 'Swedish',
2852 - 'da' => 'Danish'
2853 - ];
2854 -
2855 - $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
2856 -
2857 - // Build combined text for translation (numbered for parsing)
2858 - $numbered_messages = [];
2859 - foreach ($messages as $i => $msg) {
2860 - $content = isset($msg['content']) ? trim($msg['content']) : '';
2861 - if (!empty($content)) {
2862 - $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
727 + echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
728 + } else {
729 + echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
2863 730 }
2864 - }
2865 731
2866 - if (empty($numbered_messages)) {
2867 - wp_send_json_error(['error' => 'No valid messages to translate']);
2868 732 wp_die();
2869 733 }
2870 734
2871 - $combined_text = implode("\n\n", $numbered_messages);
2872 735
2873 - // Prepare the translation prompt
2874 - $system_prompt = "You are a translator. Translate the following messages to {$target_lang_name}. Keep the [MSG#] and [/MSG#] tags exactly as they are - only translate the content between them. Maintain the original formatting, line breaks, and any HTML tags. Return ONLY the translated messages with the tags, no explanations.";
736 +public function mxchat_save_inline_prompt() {
737 + // Check for nonce security
738 + check_ajax_referer('mxchat_save_inline_nonce');
2875 739
2876 - // Get user's selected model and determine provider
2877 - $options = get_option('mxchat_options', []);
2878 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
2879 -
2880 - // Check if using OpenRouter
2881 - if ($selected_model === 'openrouter') {
2882 - $provider = 'openrouter';
2883 - $selected_model = $options['openrouter_selected_model'] ?? '';
2884 - $api_key = $options['openrouter_api_key'] ?? '';
2885 -
2886 - if (empty($selected_model)) {
2887 - wp_send_json_error(['error' => 'No OpenRouter model selected']);
2888 - wp_die();
2889 - }
2890 - } else {
2891 - // Determine provider from model name
2892 - $model_parts = explode('-', $selected_model);
2893 - $provider = strtolower($model_parts[0]);
2894 -
2895 - // Get the appropriate API key based on provider
2896 - $api_key = '';
2897 - switch ($provider) {
2898 - case 'gpt':
2899 - case 'o1':
2900 - $api_key = $options['api_key'] ?? '';
2901 - break;
2902 - case 'claude':
2903 - $api_key = $options['claude_api_key'] ?? '';
2904 - break;
2905 - case 'grok':
2906 - $api_key = $options['xai_api_key'] ?? '';
2907 - break;
2908 - case 'deepseek':
2909 - $api_key = $options['deepseek_api_key'] ?? '';
2910 - break;
2911 - case 'gemini':
2912 - $api_key = $options['gemini_api_key'] ?? '';
2913 - break;
2914 - default:
2915 - // Default to OpenAI
2916 - $api_key = $options['api_key'] ?? '';
2917 - $provider = 'gpt';
2918 - break;
2919 - }
2920 - }
2921 -
2922 - if (empty($api_key)) {
2923 - wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
2924 - wp_die();
2925 - }
2926 -
2927 - // Make API request based on provider
2928 - $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
2929 -
2930 - if (is_wp_error($response)) {
2931 - wp_send_json_error(['error' => $response->get_error_message()]);
2932 - wp_die();
2933 - }
2934 -
2935 - // Parse the response to extract translated messages
2936 - $translations = [];
2937 - foreach ($messages as $msg) {
2938 - $index = $msg['index'];
2939 - $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
2940 - if (preg_match($pattern, $response, $matches)) {
2941 - $translations[] = [
2942 - 'index' => $index,
2943 - 'translated' => trim($matches[1])
2944 - ];
2945 - }
2946 - }
2947 -
2948 - // Save translations to database
2949 - if (!empty($translations)) {
2950 - $this->save_transcript_translation($session_id, $target_lang, $translations);
2951 - }
2952 -
2953 - wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
2954 - wp_die();
2955 -}
2956 -
2957 -/**
2958 - * Save transcript translation to database
2959 - */
2960 -private function save_transcript_translation($session_id, $language_code, $translations) {
2961 - global $wpdb;
2962 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
2963 -
2964 - // Check if table exists, create if not
2965 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
2966 - mxchat_create_translations_table();
2967 - }
2968 -
2969 - $now = current_time('mysql');
2970 - $translations_json = wp_json_encode($translations);
2971 -
2972 - // Use REPLACE to insert or update
2973 - $wpdb->query($wpdb->prepare(
2974 - "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
2975 - VALUES (%s, %s, %s, %s, %s)",
2976 - $session_id,
2977 - $language_code,
2978 - $translations_json,
2979 - $now,
2980 - $now
2981 - ));
2982 -}
2983 -
2984 -/**
2985 - * Get saved translation for a session
2986 - */
2987 -public function mxchat_get_transcript_translation() {
740 + // Verify permissions
2988 741 if (!current_user_can('manage_options')) {
2989 - wp_send_json_error(['error' => 'Insufficient permissions']);
2990 - wp_die();
742 + wp_send_json_error('Permission denied.');
743 + return;
2991 744 }
2992 745
2993 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2994 -
2995 - if (empty($session_id)) {
2996 - wp_send_json_error(['error' => 'No session ID provided']);
2997 - wp_die();
2998 - }
2999 -
3000 746 global $wpdb;
3001 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
747 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3002 748
3003 - // Check if table exists
3004 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3005 - wp_send_json(['success' => true, 'has_translation' => false]);
3006 - wp_die();
3007 - }
749 + // Validate and sanitize input data
750 + $prompt_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
751 + $article_content = isset($_POST['article_content']) ? sanitize_textarea_field($_POST['article_content']) : '';
752 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : '';
3008 753
3009 - // Get the most recent translation for this session
3010 - $result = $wpdb->get_row($wpdb->prepare(
3011 - "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
3012 - $session_id
3013 - ));
754 + if ($prompt_id > 0 && !empty($article_content)) {
755 + // Re-generate the embedding vector for the updated content
756 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
3014 757
3015 - if ($result) {
3016 - $translations = json_decode($result->translations, true);
3017 - wp_send_json([
3018 - 'success' => true,
3019 - 'has_translation' => true,
3020 - 'language' => $result->language_code,
3021 - 'translations' => $translations
3022 - ]);
3023 - } else {
3024 - wp_send_json(['success' => true, 'has_translation' => false]);
3025 - }
3026 - wp_die();
3027 -}
758 + if (is_array($embedding_vector)) {
759 + // Serialize the embedding vector before storing it
760 + $embedding_vector_serialized = serialize($embedding_vector);
3028 761
3029 -/**
3030 - * Translate text using the user's selected provider and model
3031 - */
3032 -private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
3033 - switch ($provider) {
3034 - case 'claude':
3035 - return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
3036 - case 'grok':
3037 - return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
3038 - case 'deepseek':
3039 - return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
3040 - case 'gemini':
3041 - return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
3042 - case 'openrouter':
3043 - return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
3044 - case 'gpt':
3045 - case 'o1':
3046 - default:
3047 - return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
3048 - }
3049 -}
3050 -
3051 -/**
3052 - * Translate text using OpenAI API
3053 - */
3054 -private function translate_with_openai($api_key, $model, $system_prompt, $text) {
3055 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
3056 - 'timeout' => 60,
3057 - 'headers' => [
3058 - 'Authorization' => 'Bearer ' . $api_key,
3059 - 'Content-Type' => 'application/json'
3060 - ],
3061 - 'body' => wp_json_encode([
3062 - 'model' => $model,
3063 - 'messages' => [
3064 - ['role' => 'system', 'content' => $system_prompt],
3065 - ['role' => 'user', 'content' => $text]
3066 - ],
3067 - 'temperature' => 0.3
3068 - ])
3069 - ]);
3070 -
3071 - if (is_wp_error($response)) {
3072 - return $response;
3073 - }
3074 -
3075 - $body = json_decode(wp_remote_retrieve_body($response), true);
3076 -
3077 - if (isset($body['error'])) {
3078 - return new WP_Error('api_error', $body['error']['message']);
3079 - }
3080 -
3081 - if (isset($body['choices'][0]['message']['content'])) {
3082 - return $body['choices'][0]['message']['content'];
3083 - }
3084 -
3085 - return new WP_Error('api_error', 'Invalid API response');
3086 -}
3087 -
3088 -/**
3089 - * Translate text using Claude API
3090 - */
3091 -private function translate_with_claude($api_key, $model, $system_prompt, $text) {
3092 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3093 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3094 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3095 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3096 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
3097 - 'timeout' => 60,
3098 - 'headers' => [
3099 - 'x-api-key' => $api_key,
3100 - 'anthropic-version' => '2023-06-01',
3101 - 'Content-Type' => 'application/json'
3102 - ],
3103 - 'body' => wp_json_encode([
3104 - 'model' => $model,
3105 - 'max_tokens' => 4096,
3106 - // Prompt-cache breakpoint (plan 1ff43b): the translate instruction
3107 - // repeats across every message in a batch, so cache reads bill at
3108 - // 0.1x. Below the model's minimum prefix it silently no-ops.
3109 - 'system' => trim((string) $system_prompt) === '' ? $system_prompt : [
3110 - ['type' => 'text', 'text' => $system_prompt, 'cache_control' => ['type' => 'ephemeral']]
3111 - ],
3112 - 'messages' => [
3113 - ['role' => 'user', 'content' => $text]
3114 - ]
3115 - ])
3116 - ]);
3117 -
3118 - if (is_wp_error($response)) {
3119 - return $response;
3120 - }
3121 -
3122 - $body = json_decode(wp_remote_retrieve_body($response), true);
3123 -
3124 - if (isset($body['error'])) {
3125 - return new WP_Error('api_error', $body['error']['message']);
3126 - }
3127 -
3128 - if (isset($body['content'][0]['text'])) {
3129 - return $body['content'][0]['text'];
3130 - }
3131 -
3132 - return new WP_Error('api_error', 'Invalid API response');
3133 -}
3134 -
3135 -/**
3136 - * Translate text using xAI (Grok) API
3137 - */
3138 -private function translate_with_xai($api_key, $model, $system_prompt, $text) {
3139 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
3140 - 'timeout' => 60,
3141 - 'headers' => [
3142 - 'Authorization' => 'Bearer ' . $api_key,
3143 - 'Content-Type' => 'application/json'
3144 - ],
3145 - 'body' => wp_json_encode([
3146 - 'model' => $model,
3147 - 'messages' => [
3148 - ['role' => 'system', 'content' => $system_prompt],
3149 - ['role' => 'user', 'content' => $text]
3150 - ],
3151 - 'temperature' => 0.3
3152 - ])
3153 - ]);
3154 -
3155 - if (is_wp_error($response)) {
3156 - return $response;
3157 - }
3158 -
3159 - $body = json_decode(wp_remote_retrieve_body($response), true);
3160 -
3161 - if (isset($body['error'])) {
3162 - return new WP_Error('api_error', $body['error']['message']);
3163 - }
3164 -
3165 - if (isset($body['choices'][0]['message']['content'])) {
3166 - return $body['choices'][0]['message']['content'];
3167 - }
3168 -
3169 - return new WP_Error('api_error', 'Invalid API response');
3170 -}
3171 -
3172 -/**
3173 - * Translate text using DeepSeek API
3174 - */
3175 -private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
3176 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
3177 - 'timeout' => 60,
3178 - 'headers' => [
3179 - 'Authorization' => 'Bearer ' . $api_key,
3180 - 'Content-Type' => 'application/json'
3181 - ],
3182 - 'body' => wp_json_encode([
3183 - 'model' => $model,
3184 - 'messages' => [
3185 - ['role' => 'system', 'content' => $system_prompt],
3186 - ['role' => 'user', 'content' => $text]
3187 - ],
3188 - 'temperature' => 0.3,
3189 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
3190 - // slow responses); translation wants non-thinking.
3191 - 'thinking' => ['type' => 'disabled']
3192 - ])
3193 - ]);
3194 -
3195 - if (is_wp_error($response)) {
3196 - return $response;
3197 - }
3198 -
3199 - $body = json_decode(wp_remote_retrieve_body($response), true);
3200 -
3201 - if (isset($body['error'])) {
3202 - return new WP_Error('api_error', $body['error']['message']);
3203 - }
3204 -
3205 - if (isset($body['choices'][0]['message']['content'])) {
3206 - return $body['choices'][0]['message']['content'];
3207 - }
3208 -
3209 - return new WP_Error('api_error', 'Invalid API response');
3210 -}
3211 -
3212 -/**
3213 - * Translate text using Google Gemini API
3214 - */
3215 -private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
3216 - if ($model === 'gemini-3-pro-preview') {
3217 - $model = 'gemini-3.1-pro-preview';
3218 - }
3219 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
3220 -
3221 - $response = wp_remote_post($url, [
3222 - 'timeout' => 60,
3223 - 'headers' => [
3224 - 'Content-Type' => 'application/json'
3225 - ],
3226 - 'body' => wp_json_encode([
3227 - 'contents' => [
3228 - [
3229 - 'parts' => [
3230 - ['text' => $system_prompt . "\n\n" . $text]
3231 - ]
3232 - ]
3233 - ],
3234 - 'generationConfig' => [
3235 - 'temperature' => 0.3
3236 - ]
3237 - ])
3238 - ]);
3239 -
3240 - if (is_wp_error($response)) {
3241 - return $response;
3242 - }
3243 -
3244 - $body = json_decode(wp_remote_retrieve_body($response), true);
3245 -
3246 - if (isset($body['error'])) {
3247 - return new WP_Error('api_error', $body['error']['message']);
3248 - }
3249 -
3250 - if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
3251 - return $body['candidates'][0]['content']['parts'][0]['text'];
3252 - }
3253 -
3254 - return new WP_Error('api_error', 'Invalid API response');
3255 -}
3256 -
3257 -/**
3258 - * Translate text using OpenRouter API
3259 - */
3260 -private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
3261 - $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
3262 - 'timeout' => 60,
3263 - 'headers' => [
3264 - 'Authorization' => 'Bearer ' . $api_key,
3265 - 'Content-Type' => 'application/json',
3266 - 'HTTP-Referer' => home_url(),
3267 - 'X-Title' => 'MxChat Translation'
3268 - ],
3269 - 'body' => wp_json_encode([
3270 - 'model' => $model,
3271 - 'messages' => [
3272 - ['role' => 'system', 'content' => $system_prompt],
3273 - ['role' => 'user', 'content' => $text]
3274 - ],
3275 - 'temperature' => 0.3
3276 - ])
3277 - ]);
3278 -
3279 - if (is_wp_error($response)) {
3280 - return $response;
3281 - }
3282 -
3283 - $body = json_decode(wp_remote_retrieve_body($response), true);
3284 -
3285 - if (isset($body['error'])) {
3286 - return new WP_Error('api_error', $body['error']['message']);
3287 - }
3288 -
3289 - if (isset($body['choices'][0]['message']['content'])) {
3290 - return $body['choices'][0]['message']['content'];
3291 - }
3292 -
3293 - return new WP_Error('api_error', 'Invalid API response');
3294 -}
3295 -
3296 -public function mxchat_fetch_chat_history() {
3297 - global $wpdb;
3298 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3299 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3300 -
3301 - if (!current_user_can('manage_options')) {
3302 - wp_send_json_error(['message' => 'Insufficient permissions']);
3303 - wp_die();
3304 - }
3305 -
3306 - $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3307 - $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3308 - $offset = ($page - 1) * $per_page;
3309 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3310 - $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3311 - $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3312 - if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3313 - $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3314 - $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3315 - $ratings_join = '';
3316 - $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3317 - if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3318 - // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3319 - $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3320 - $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3321 - }
3322 -
3323 - // Build search condition
3324 - $search_condition = '';
3325 - $search_params = [];
3326 - if (!empty($search)) {
3327 - $search_condition = "WHERE (
3328 - session_id LIKE %s
3329 - OR user_email LIKE %s
3330 - OR user_name LIKE %s
3331 - OR user_identifier LIKE %s
3332 - OR message LIKE %s
3333 - )";
3334 - $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3335 - }
3336 -
3337 - // Get total count
3338 - $count_query = !empty($search)
3339 - ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3340 - : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3341 - $total_sessions = (int) $wpdb->get_var($count_query);
3342 -
3343 - // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3344 - // and order by rating value (NULLs last) with recency as tiebreaker.
3345 - if ($ratings_join) {
3346 - $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3347 - } else {
3348 - $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3349 - }
3350 - $session_query = !empty($search)
3351 - ? $wpdb->prepare(
3352 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3353 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3354 - array_merge($search_params, [$per_page, $offset])
3355 - )
3356 - : $wpdb->prepare(
3357 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3358 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3359 - $per_page, $offset
3360 - );
3361 - $session_ids = $wpdb->get_col($session_query);
3362 -
3363 - $total_pages = ceil($total_sessions / $per_page);
3364 -
3365 - if (empty($session_ids)) {
3366 - wp_send_json([
3367 - 'success' => true,
3368 - 'sessions' => [],
3369 - 'page' => $page,
3370 - 'total_pages' => 0,
3371 - 'total_sessions' => 0,
3372 - 'showing_start' => 0,
3373 - 'showing_end' => 0
3374 - ]);
3375 - wp_die();
3376 - }
3377 -
3378 - // Check for optional columns/tables
3379 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3380 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3381 -
3382 - // Batch-fetch session ratings for this page (plan-a5b006).
3383 - $ratings_map = array();
3384 - if ($rating_table_exists && !empty($session_ids)) {
3385 - $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3386 - $rating_rows = $wpdb->get_results($wpdb->prepare(
3387 - "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3388 - $session_ids
3389 - ));
3390 - foreach ($rating_rows as $row) {
3391 - $ratings_map[$row->session_id] = array(
3392 - 'value' => (int) $row->rating_value,
3393 - 'feedback' => (string) $row->rating_feedback,
762 + // Update the prompt in the database
763 + $updated = $wpdb->update(
764 + $table_name,
765 + array(
766 + 'article_content' => $article_content,
767 + 'embedding_vector' => $embedding_vector_serialized,
768 + 'source_url' => $article_url,
769 + ),
770 + array('id' => $prompt_id),
771 + array('%s', '%s', '%s'),
772 + array('%d')
3394 773 );
3395 - }
3396 - }
3397 774
3398 - // Build session list data
3399 - $sessions = [];
3400 - foreach ($session_ids as $session_id) {
3401 - // Get session metadata
3402 - $session_data = $originating_columns_exist
3403 - ? $wpdb->get_row($wpdb->prepare(
3404 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3405 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3406 - $session_id
3407 - ))
3408 - : $wpdb->get_row($wpdb->prepare(
3409 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3410 - WHERE session_id = %s LIMIT 1",
3411 - $session_id
3412 - ));
3413 -
3414 - // Get message count and latest timestamp
3415 - $message_stats = $wpdb->get_row($wpdb->prepare(
3416 - "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3417 - $session_id
3418 - ));
3419 -
3420 - // Get first user message as preview
3421 - $first_user_msg = $wpdb->get_var($wpdb->prepare(
3422 - "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3423 - $session_id
3424 - ));
3425 - $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3426 -
3427 - // Build display name
3428 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3429 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3430 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3431 -
3432 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3433 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3434 -
3435 - // Format time - show relative for recent, date for older
3436 - $timestamp = strtotime($message_stats->latest . ' UTC');
3437 - $now = time();
3438 - $diff = $now - $timestamp;
3439 - if ($diff < 3600) {
3440 - $time_display = floor($diff / 60) . 'm ago';
3441 - } elseif ($diff < 86400) {
3442 - $time_display = floor($diff / 3600) . 'h ago';
3443 - } elseif ($diff < 604800) {
3444 - $time_display = floor($diff / 86400) . 'd ago';
775 + if ($updated !== false) {
776 + wp_send_json_success();
777 + } else {
778 + wp_send_json_error('Database update failed.');
779 + }
3445 780 } else {
3446 - $time_display = wp_date('M j', $timestamp);
781 + wp_send_json_error('Embedding generation failed.');
3447 782 }
3448 -
3449 - // Get initials for avatar
3450 - $initials = strtoupper(substr($display_name, 0, 2));
3451 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3452 - $parts = explode(' ', $display_name);
3453 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3454 - }
3455 -
3456 - $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3457 - $rating_value = $rating_entry ? $rating_entry['value'] : null;
3458 - $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3459 -
3460 - $sessions[] = [
3461 - 'session_id' => $session_id,
3462 - 'display_name' => $display_name,
3463 - 'display_sub' => $display_sub,
3464 - 'initials' => $initials,
3465 - 'preview' => $preview,
3466 - 'message_count' => (int) $message_stats->count,
3467 - 'time_display' => $time_display,
3468 - 'timestamp' => $message_stats->latest,
3469 - 'rating_value' => $rating_value,
3470 - 'rating_feedback' => $rating_feedback,
3471 - ];
783 + } else {
784 + wp_send_json_error('Invalid data.');
3472 785 }
786 +}
3473 787
3474 - wp_send_json([
3475 - 'success' => true,
3476 - 'sessions' => $sessions,
3477 - 'page' => $page,
3478 - 'total_pages' => $total_pages,
3479 - 'total_sessions' => $total_sessions,
3480 - 'showing_start' => $offset + 1,
3481 - 'showing_end' => min($offset + $per_page, $total_sessions)
3482 - ]);
3483 - wp_die();
3484 -}
3485 788
3486 -/**
3487 - * Fetch single conversation details for split-panel view
3488 - */
3489 -public function mxchat_fetch_conversation() {
789 +public function mxchat_fetch_chat_history() {
3490 790 global $wpdb;
3491 791 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3492 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3493 792
793 + // Check if the current user has sufficient permissions
3494 794 if (!current_user_can('manage_options')) {
3495 - wp_send_json_error(['message' => 'Insufficient permissions']);
795 + echo esc_html__('You do not have sufficient permissions to view this page.', 'mxchat');
3496 796 wp_die();
3497 797 }
3498 798
3499 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3500 - if (empty($session_id)) {
3501 - wp_send_json_error(['message' => 'No session ID provided']);
3502 - wp_die();
3503 - }
799 + // Fetch chat transcripts from the database, ordered by timestamp
800 + $chat_transcripts = $wpdb->get_results(
801 + $wpdb->prepare("SELECT * FROM {$table_name} ORDER BY timestamp ASC")
802 + );
3504 803
3505 - // Check for optional columns/tables
3506 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3507 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3508 -
3509 - // Get session metadata
3510 - $session_data = $originating_columns_exist
3511 - ? $wpdb->get_row($wpdb->prepare(
3512 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3513 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3514 - $session_id
3515 - ))
3516 - : $wpdb->get_row($wpdb->prepare(
3517 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3518 - WHERE session_id = %s LIMIT 1",
3519 - $session_id
3520 - ));
3521 -
3522 - if (!$session_data) {
3523 - wp_send_json_error(['message' => 'Session not found']);
804 + // If no transcripts are available, display a message
805 + if (empty($chat_transcripts)) {
806 + echo esc_html__('No chat history available.', 'mxchat');
3524 807 wp_die();
3525 808 }
3526 809
3527 - // Get clicked URLs
3528 - $clicked_urls = [];
3529 - if ($url_table_exists) {
3530 - $url_clicks = $wpdb->get_results($wpdb->prepare(
3531 - "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3532 - WHERE session_id = %s ORDER BY click_timestamp ASC",
3533 - $session_id
3534 - ));
3535 - foreach ($url_clicks as $click) {
3536 - $clicked_urls[] = $click->clicked_url;
3537 - }
3538 - }
810 + ob_start();
811 + $current_session_id = '';
3539 812
3540 - // Get all messages
3541 - $messages = $wpdb->get_results($wpdb->prepare(
3542 - "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3543 - $session_id
3544 - ));
3545 -
3546 - // Build user info
3547 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3548 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3549 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3550 -
3551 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3552 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3553 -
3554 - // Get initials
3555 - $initials = strtoupper(substr($display_name, 0, 2));
3556 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3557 - $parts = explode(' ', $display_name);
3558 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3559 - }
3560 -
3561 - // Page info
3562 - $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3563 - $page_title = '';
3564 - if ($page_url) {
3565 - $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3566 - }
3567 -
3568 - // Format messages for output
3569 - $formatted_messages = [];
3570 - foreach ($messages as $msg) {
3571 - $is_user = ($msg->role === 'user');
3572 - // Live-agent replies (Slack/Telegram handoff) persist with role 'agent'.
3573 - // Kept OUT of $is_bot so the RAG Sources link below stays bot-only.
3574 - $is_agent = ($msg->role === 'agent');
3575 - $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3576 -
3577 - $content = wp_kses(
3578 - stripslashes($msg->message),
3579 - [
3580 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3581 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3582 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3583 - 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3584 - 'img' => ['src' => [], 'alt' => [], 'class' => []],
3585 - 'h3' => ['class' => []],
3586 - 'h4' => ['class' => []],
3587 - 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
3588 - 'select' => ['class' => [], 'data-attribute' => []],
3589 - 'option' => ['value' => []],
3590 - 'span' => ['class' => []],
3591 - 'del' => [], 'ins' => [],
3592 - ]
3593 - );
3594 - $formatted_content = $this->format_transcript_message($content);
3595 -
3596 - $has_rag = $is_bot && !empty($msg->rag_context);
3597 -
3598 - $formatted_messages[] = [
3599 - 'id' => $msg->id,
3600 - 'role' => $msg->role,
3601 - 'is_user' => $is_user,
3602 - 'is_agent' => $is_agent,
3603 - 'is_bot' => $is_bot,
3604 - 'content' => $formatted_content,
3605 - 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
3606 - 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
3607 - 'has_rag' => $has_rag
3608 - ];
3609 - }
3610 -
3611 - // First message timestamp for "started" display
3612 - $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
3613 -
3614 - // Pull rating_feedback for this session (if any) so the details drawer can show it.
3615 - $rating_feedback = '';
3616 - $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
3617 - if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
3618 - $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
3619 - "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
3620 - $session_id
3621 - ));
3622 - }
3623 -
3624 - wp_send_json([
3625 - 'success' => true,
3626 - 'session_id' => $session_id,
3627 - 'user' => [
3628 - 'name' => $display_name,
3629 - 'sub' => $display_sub,
3630 - 'initials' => $initials,
3631 - 'email' => $user_email,
3632 - 'identifier' => $user_identifier
3633 - ],
3634 - 'page' => [
3635 - 'url' => $page_url,
3636 - 'title' => $page_title
3637 - ],
3638 - 'clicked_urls' => $clicked_urls,
3639 - 'messages' => $formatted_messages,
3640 - 'message_count' => count($messages),
3641 - 'started' => $started,
3642 - 'rating_feedback' => $rating_feedback
3643 - ]);
3644 - wp_die();
3645 -}
3646 -
3647 -
3648 -/**
3649 - * ALTERNATIVE: Simpler helper method using string replacement
3650 - */
3651 -private function highlight_clicked_links($message_content, $clicked_urls) {
3652 - if (empty($clicked_urls)) {
3653 - return wp_kses(
3654 - $message_content,
3655 - [
3656 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3657 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3658 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3659 - ]
3660 - );
3661 - }
3662 -
3663 - // First apply standard sanitization
3664 - $message_content = wp_kses(
3665 - $message_content,
3666 - [
3667 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3668 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3669 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3670 - ]
3671 - );
3672 -
3673 - // Process each clicked URL
3674 - foreach ($clicked_urls as $clicked_url) {
3675 - // Try multiple patterns to catch different link formats
3676 - $patterns = [
3677 - // Standard link format
3678 - '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
3679 - // Link with trailing slash
3680 - '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
3681 - // Encoded entities version
3682 - '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
3683 - ];
3684 -
3685 - foreach ($patterns as $pattern) {
3686 - if (preg_match($pattern, $message_content)) {
3687 - $message_content = preg_replace_callback(
3688 - $pattern,
3689 - function($matches) {
3690 - $full_match = $matches[0];
3691 - $attributes = $matches[1];
3692 -
3693 - // Check if it already has the class
3694 - if (strpos($full_match, 'mxchat-clicked-link') !== false) {
3695 - return $full_match;
3696 - }
3697 -
3698 - // Check if class attribute exists
3699 - if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
3700 - // Add to existing class
3701 - $new_attributes = preg_replace(
3702 - '/class=["\']([^"\']*)["\']/',
3703 - 'class="$1 mxchat-clicked-link"',
3704 - $attributes
3705 - );
3706 - } else {
3707 - // Add new class attribute
3708 - $new_attributes = $attributes . ' class="mxchat-clicked-link"';
3709 - }
3710 -
3711 - // Add title if not present
3712 - if (strpos($new_attributes, 'title=') === false) {
3713 - $new_attributes .= ' title="User clicked this link"';
3714 - }
3715 -
3716 - return '<a' . $new_attributes . '>';
3717 - },
3718 - $message_content
3719 - );
3720 -
3721 - // If we found and replaced, break out of the patterns loop
3722 - break;
813 + foreach ($chat_transcripts as $transcript) {
814 + // Start a new session block if session ID changes
815 + if ($current_session_id !== $transcript->session_id) {
816 + if ($current_session_id !== '') {
817 + echo '</div>'; // Close the previous session block
3723 818 }
819 + $current_session_id = sanitize_text_field($transcript->session_id);
820 + echo '<div class="chat-session">';
821 + 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>';
3724 822 }
3725 - }
3726 823
3727 - return $message_content;
3728 -}
824 + // Format the timestamp for display
825 + $formatted_timestamp = date_i18n('F j, Y g:i a', strtotime($transcript->timestamp));
3729 826
3730 -public function mxchat_create_prompts_page() {
3731 - //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
827 + // Determine the role to display (user identifier or email for users, bot for the AI)
828 + $role = $transcript->role;
829 + if ($role === 'user') {
830 + // Sanitize email if available
831 + if (!empty($transcript->user_email)) {
832 + $role = sanitize_email($transcript->user_email);
833 + } else {
834 + // Sanitize user identifier, anonymize if it's an IP address
835 + $user_identifier = sanitize_text_field($transcript->user_identifier);
3732 836
3733 - global $wpdb;
3734 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3735 -
3736 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3737 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
3738 -
3739 - // Display success message if all prompts were deleted
3740 - if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
3741 - echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button></div>';
3742 - }
3743 -
3744 - // Set up pagination, search query, and content type filter
3745 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
3746 - $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
3747 - $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
3748 - $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
3749 - $per_page = 25;
3750 -
3751 - //error_log('DEBUG: Search query: ' . $search_query);
3752 - //error_log('DEBUG: Content type filter: ' . $content_type_filter);
3753 - //error_log('DEBUG: Current page: ' . $current_page);
3754 - //error_log('DEBUG: Per page: ' . $per_page);
3755 -
3756 - // ================================
3757 - // MULTI-BOT CONFIGURATION
3758 - // ================================
3759 -
3760 - // Check for multi-bot and set up bot selection
3761 - if (class_exists('MxChat_Multi_Bot_Manager')) {
3762 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
3763 - $available_bots = $multi_bot_manager->get_available_bots();
3764 -
3765 - // Get saved bot selection (user-specific first, then site-wide default)
3766 - $user_id = get_current_user_id();
3767 - $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
3768 - if (empty($saved_bot_id)) {
3769 - $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
3770 - }
3771 -
3772 - // Allow URL override but default to saved selection
3773 - $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
3774 - $multibot_active = true;
3775 - } else {
3776 - $current_bot_id = 'default';
3777 - $multibot_active = false;
3778 - }
3779 -
3780 - // ================================
3781 - // DATA SOURCE CONFIGURATION
3782 - // ================================
3783 -
3784 - // Get bot-specific Pinecone settings
3785 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
3786 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3787 - $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
3788 -
3789 - // Get OpenAI Vector Store settings
3790 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
3791 - $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
3792 -
3793 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3794 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
3795 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
3796 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
3797 -
3798 - if ($use_pinecone && !empty($pinecone_api_key)) {
3799 - //error_log('DEBUG: Using PINECONE data source with bot-specific config');
3800 - // PINECONE DATA SOURCE
3801 - $data_source = 'pinecone';
3802 -
3803 - // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
3804 - // UPDATED 2.5.6: Added content_type_filter parameter
3805 - $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
3806 -
3807 - // TEMPORARY DEBUG - Add this right after the fetch call
3808 - //error_log('=== DEBUG: Bot switching issue ===');
3809 - //error_log('Current bot ID: ' . $current_bot_id);
3810 - //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3811 - //error_log('Records returned: ' . count($records['data'] ?? []));
3812 - //error_log('Total records: ' . ($records['total'] ?? 0));
3813 -
3814 - // Check first few records to see their bot_id
3815 - if (!empty($records['data'])) {
3816 - foreach (array_slice($records['data'], 0, 3) as $i => $record) {
3817 - $record_bot_id = $record->bot_id ?? 'NOT_SET';
3818 - //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
3819 - }
3820 - }
3821 - //error_log('=== END DEBUG ===');
3822 -
3823 - $total_records = $records['total'] ?? 0;
3824 - $prompts = $records['data'] ?? array();
3825 - $total_in_database = $records['total_in_database'] ?? 0;
3826 - $showing_recent_only = $records['showing_recent_only'] ?? false;
3827 -
3828 - $total_pages = ceil($total_records / $per_page);
3829 -
3830 - } else {
3831 - //error_log('DEBUG: Using WORDPRESS DB data source');
3832 - // WORDPRESS DB DATA SOURCE (your existing logic)
3833 - $data_source = 'wordpress';
3834 -
3835 - // Initialize these variables for WordPress DB
3836 - $total_in_database = 0;
3837 - $showing_recent_only = false;
3838 -
3839 - $offset = ($current_page - 1) * $per_page;
3840 -
3841 - // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
3842 - $where_clauses = array();
3843 - $where_values = array();
3844 -
3845 - if ($search_query) {
3846 - $where_clauses[] = "article_content LIKE %s";
3847 - $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
3848 - }
3849 -
3850 - if ($content_type_filter) {
3851 - $where_clauses[] = "content_type = %s";
3852 - $where_values[] = $content_type_filter;
3853 - }
3854 -
3855 - $sql_where = "";
3856 - if (!empty($where_clauses)) {
3857 - $sql_where = "WHERE " . implode(" AND ", $where_clauses);
3858 - }
3859 -
3860 - // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
3861 - // This ensures pagination shows X entries per page, not X chunks
3862 - // Entries with empty source_url are counted individually
3863 - if (!empty($where_values)) {
3864 - // Count unique source_urls + count of rows with empty source_url
3865 - $count_query = $wpdb->prepare(
3866 - "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
3867 - (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
3868 - array_merge($where_values, $where_values)
3869 - );
3870 - } else {
3871 - $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
3872 - (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
3873 - }
3874 - $total_records = $wpdb->get_var($count_query);
3875 - $total_pages = ceil($total_records / $per_page);
3876 -
3877 - // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
3878 - // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
3879 - if (!empty($where_values)) {
3880 - $urls_query = $wpdb->prepare(
3881 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
3882 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3883 - array_merge($where_values, array($per_page, $offset))
3884 - );
3885 - } else {
3886 - $urls_query = $wpdb->prepare(
3887 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
3888 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3889 - $per_page, $offset
3890 - );
3891 - }
3892 - $page_urls = $wpdb->get_results($urls_query);
3893 -
3894 - // Step 2: Fetch all rows for these source_urls
3895 - $prompts = array();
3896 - if (!empty($page_urls)) {
3897 - // Build URL order map to preserve newest-first ordering from step 1
3898 - $url_order_map = array();
3899 - $url_list = array();
3900 - $has_empty_url = false;
3901 - $order_index = 0;
3902 - foreach ($page_urls as $url_row) {
3903 - if (empty($url_row->source_url)) {
3904 - $has_empty_url = true;
3905 - $url_order_map['__empty__'] = $order_index++;
837 + // Check if the user identifier is an IP address and anonymize it
838 + if (filter_var($user_identifier, FILTER_VALIDATE_IP)) {
839 + $role = preg_replace('/\.\d+$/', '.xxx', $user_identifier); // Mask the last octet
3906 840 } else {
3907 - $url_list[] = $url_row->source_url;
3908 - $url_order_map[$url_row->source_url] = $order_index++;
841 + $role = $user_identifier; // If it's not an IP, just display the identifier
3909 842 }
3910 843 }
3911 -
3912 - // Build query to fetch all rows for these URLs
3913 - $url_conditions = array();
3914 - $url_values = array();
3915 -
3916 - if (!empty($url_list)) {
3917 - $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
3918 - $url_conditions[] = "source_url IN ($placeholders)";
3919 - $url_values = array_merge($url_values, $url_list);
3920 - }
3921 -
3922 - if ($has_empty_url) {
3923 - $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
3924 - }
3925 -
3926 - if (!empty($url_conditions)) {
3927 - $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
3928 -
3929 - // Add original filters back
3930 - if (!empty($where_clauses)) {
3931 - $url_where .= " AND " . implode(" AND ", $where_clauses);
3932 - $url_values = array_merge($url_values, $where_values);
3933 - }
3934 -
3935 - if (!empty($url_values)) {
3936 - $prompts_query = $wpdb->prepare(
3937 - "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
3938 - $url_values
3939 - );
3940 - } else {
3941 - $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
3942 - }
3943 -
3944 - $prompts = $wpdb->get_results($prompts_query);
3945 -
3946 - // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
3947 - usort($prompts, function($a, $b) use ($url_order_map) {
3948 - $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
3949 - $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
3950 - $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
3951 - $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
3952 -
3953 - // First sort by URL order (newest URLs first)
3954 - if ($order_a !== $order_b) {
3955 - return $order_a - $order_b;
3956 - }
3957 -
3958 - // Within same URL, sort by timestamp DESC (newest chunks first)
3959 - return strtotime($b->timestamp) - strtotime($a->timestamp);
3960 - });
3961 - }
3962 844 }
3963 - }
3964 845
3965 - // ================================
3966 - // PAGINATION GENERATION
3967 - // ================================
3968 -
3969 - // Generate pagination links
3970 - if ($total_pages > 1) {
3971 - // Build a clean base URL with only necessary parameters
3972 - $pagination_args = array('page' => 'mxchat-prompts');
3973 -
3974 - // Preserve bot_id parameter if multi-bot is active
3975 - if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
3976 - $pagination_args['bot_id'] = $current_bot_id;
3977 - }
3978 -
3979 - // Preserve search query and nonce if present
3980 - if ($search_query) {
3981 - $pagination_args['search'] = $search_query;
3982 - if (!empty($nonce)) {
3983 - $pagination_args['_wpnonce'] = $nonce;
3984 - }
3985 - }
3986 -
3987 - // Preserve content type filter if present
3988 - if ($content_type_filter) {
3989 - $pagination_args['content_type'] = $content_type_filter;
3990 - }
3991 -
3992 - // Build clean base URL
3993 - $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
3994 -
3995 - $page_links = paginate_links(array(
3996 - 'base' => $base_url . '%_%',
3997 - 'format' => '&paged=%#%',
3998 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
3999 - 'next_text' => __('Next &raquo;', 'mxchat'),
4000 - 'total' => $total_pages,
4001 - 'current' => $current_page,
4002 - 'type' => 'plain',
4003 - ));
4004 - } else {
4005 - $page_links = '';
846 + // Output the chat message
847 + echo '<div class="chat-message">';
848 + echo '<strong>' . esc_html($role) . ' (' . esc_html($formatted_timestamp) . '):</strong> ';
849 + echo wp_kses_post($transcript->message);
850 + echo '</div>';
4006 851 }
4007 852
4008 - // ================================
4009 - // PROCESSING STATUS RETRIEVAL
4010 - // ================================
853 + // Close the final session block
854 + echo '</div>';
4011 855
4012 - // Retrieve processing statuses using queue-based method
4013 - $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
4014 - $pdf_status = $processing_statuses['pdf_status'];
4015 - $sitemap_status = $processing_statuses['sitemap_status'];
4016 - $is_processing = $processing_statuses['is_processing'];
856 + $output = ob_get_clean();
4017 857
4018 - //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
4019 -
4020 - // ================================
4021 - // RENDER PAGE WITH NEW SIDEBAR LAYOUT
4022 - // ================================
4023 -
4024 - // Include the new knowledge page template
4025 - require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
4026 -
4027 - // Package all page data for the render function
4028 - $page_data = array(
4029 - 'prompts' => $prompts,
4030 - 'total_records' => $total_records,
4031 - 'total_pages' => $total_pages,
4032 - 'current_page' => $current_page,
4033 - 'per_page' => $per_page,
4034 - 'page_links' => $page_links,
4035 - 'search_query' => $search_query,
4036 - 'content_type_filter' => $content_type_filter,
4037 - 'data_source' => $data_source,
4038 - 'use_pinecone' => $use_pinecone,
4039 - 'use_vectorstore' => $use_vectorstore,
4040 - 'multibot_active' => $multibot_active,
4041 - 'current_bot_id' => $current_bot_id,
4042 - 'pdf_status' => $pdf_status,
4043 - 'sitemap_status' => $sitemap_status,
4044 - 'is_processing' => $is_processing,
4045 - 'total_in_database' => $total_in_database ?? 0,
4046 - 'showing_recent_only' => $showing_recent_only ?? false,
4047 - );
4048 -
4049 - // Render the new sidebar-based page
4050 - mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
4051 -}
4052 -
4053 -/**
4054 - * Get bot-specific Pinecone configuration
4055 - * Used in the knowledge retrieval functions
4056 - */
4057 -private function get_bot_pinecone_config($bot_id = 'default') {
4058 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
4059 -
4060 - // If default bot or multi-bot add-on not active, use default Pinecone config
4061 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
4062 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
4063 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
4064 - $config = array(
4065 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
4066 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
4067 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
4068 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
4069 - );
4070 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
4071 - return $config;
4072 - }
4073 -
4074 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
4075 -
4076 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
4077 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
4078 -
4079 - if (!empty($bot_pinecone_config)) {
4080 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
4081 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
4082 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
4083 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
4084 - } else {
4085 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
4086 - }
4087 -
4088 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
4089 -}
4090 -
4091 -public function mxchat_delete_chat_history() {
4092 - if (!current_user_can('manage_options')) {
4093 - echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4094 - wp_die();
4095 - }
4096 - check_ajax_referer('mxchat_delete_chat_history', 'security');
4097 -
4098 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
4099 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
4100 - wp_die();
4101 - }
4102 -
4103 - global $wpdb;
4104 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4105 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
4106 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
4107 -
4108 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
4109 - // across the whole table). Default false: the chat rows go away but the lead is
4110 - // preserved as a separate "chat deleted" lead in the Leads tab.
4111 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
4112 -
4113 - $deleted_count = 0;
4114 - $preserved_as_deleted_leads = 0;
4115 - $emails_to_fully_wipe = [];
4116 -
4117 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
4118 - $session_id_sanitized = MxChat_Utils::sanitize_session_id($session_id);
4119 - if ($session_id_sanitized === '') {
4120 - continue;
4121 - }
4122 -
4123 - // Capture the lead info attached to this session *before* we delete the rows.
4124 - $lead_row = $wpdb->get_row($wpdb->prepare(
4125 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
4126 - FROM {$table_name}
4127 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
4128 - GROUP BY user_email, user_name
4129 - ORDER BY last_ts DESC LIMIT 1",
4130 - $session_id_sanitized
4131 - ));
4132 -
4133 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
4134 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
4135 -
4136 - if ($has_translations) {
4137 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
4138 - }
4139 -
4140 - delete_option('mxchat_history_' . $session_id_sanitized);
4141 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
4142 - if (class_exists('MxChat_Session_Store')) {
4143 - MxChat_Session_Store::delete_session($session_id_sanitized); // b64b77
4144 - }
4145 -
4146 - if ($lead_row && !empty($lead_row->user_email)) {
4147 - if ($also_delete_lead) {
4148 - // Full-wipe requested — queue the email so that all their sessions and
4149 - // related options get swept below. Also clear this session's pre-chat
4150 - // capture options (they're no longer meaningful).
4151 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
4152 - delete_option('mxchat_email_' . $session_id_sanitized);
4153 - delete_option('mxchat_name_' . $session_id_sanitized);
4154 - } else {
4155 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
4156 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
4157 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
4158 - if (!empty($lead_row->user_name)) {
4159 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
4160 - }
4161 - if (!empty($lead_row->last_ts)) {
4162 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
4163 - }
4164 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
4165 - delete_option('mxchat_email_' . $session_id_sanitized);
4166 - delete_option('mxchat_name_' . $session_id_sanitized);
4167 - $preserved_as_deleted_leads++;
4168 - }
4169 - } else {
4170 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
4171 - delete_option('mxchat_email_' . $session_id_sanitized);
4172 - delete_option('mxchat_name_' . $session_id_sanitized);
4173 - }
4174 -
4175 - $deleted_count++;
4176 - }
4177 -
4178 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
4179 - // chat_deleted preservation) for each affected email. Reuses the same internal
4180 - // helper as the Leads-tab Delete button for consistency.
4181 - if (!empty($emails_to_fully_wipe)) {
4182 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
4183 - }
4184 -
4185 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
4186 -
4187 - echo wp_json_encode([
4188 - 'success' => sprintf(
4189 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
4190 - $deleted_count
4191 - ),
4192 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
4193 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
4194 - ]);
858 + echo $output;
4195 859 wp_die();
4196 860 }
4197 861
4198 -/**
4199 - * Format transcript message content with markdown processing
4200 - * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
4201 - */
4202 -private function format_transcript_message($text) {
4203 - if (empty($text)) {
4204 - return '';
4205 - }
4206 862
4207 - // Normalize line endings and clean up excessive whitespace
4208 - $text = str_replace("\r\n", "\n", $text);
4209 - $text = str_replace("\r", "\n", $text);
863 +public function mxchat_create_activation_page() {
864 + $license_status = get_option('mxchat_license_status', 'inactive');
865 + $license_error = get_option('mxchat_license_error', '');
866 + ?>
867 + <div class="wrap mxchat-admin">
868 + <h2>MxChat Pro: Activation</h2>
869 + <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
870 + <div class="error notice">
871 + <p><?php echo esc_html($license_error); ?></p>
872 + </div>
873 + <?php endif; ?>
4210 874
4211 - // Clean up existing <br> tags that may have been saved (legacy data)
4212 - // Convert <br>, <br/>, <br /> back to newlines for consistent processing
4213 - $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
875 + <form id="mxchat-activation-form" style="<?php echo $license_status === 'active' ? 'display: none;' : ''; ?>">
876 + <table class="form-table">
877 + <tr valign="top">
878 + <th scope="row">Email Address</th>
879 + <td>
880 + <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" required />
881 + </td>
882 + </tr>
883 + <tr valign="top">
884 + <th scope="row">Activation Key</th>
885 + <td>
886 + <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" required />
887 + </td>
888 + </tr>
889 + </table>
890 + <?php if ($license_status !== 'active'): ?>
891 + <button type="submit" id="activate_license_button" class="button button-primary"><?php esc_html_e('Activate License', 'mxchat'); ?></button>
892 + <div id="mxchat-activation-spinner" class="mxchat-activation-spinner" style="display: none;"></div>
893 + <?php endif; ?>
894 + </form>
4214 895
4215 - // Collapse 3+ consecutive newlines to just 2 (paragraph break)
4216 - $text = preg_replace('/\n{3,}/', "\n\n", $text);
4217 -
4218 - // Process markdown headers (# Header)
4219 - $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
4220 - $level = strlen($matches[1]);
4221 - $content = esc_html(trim($matches[2]));
4222 - return "<h{$level}>{$content}</h{$level}>";
4223 - }, $text);
4224 -
4225 - // Process code blocks with triple backticks
4226 - $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
4227 - $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
4228 - $code = esc_html($matches[2]);
4229 - return "<pre><code{$language}>{$code}</code></pre>";
4230 - }, $text);
4231 -
4232 - // Process inline code with single backticks
4233 - $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
4234 -
4235 - // Process bold text **text** or __text__
4236 - $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
4237 - $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
4238 -
4239 - // Process italic text *text* or _text_ (but not if part of URL)
4240 - $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
4241 - $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
4242 -
4243 - // Process markdown links [text](url)
4244 - $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
4245 - $link_text = esc_html($matches[1]);
4246 - $url = esc_url($matches[2]);
4247 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
4248 - }, $text);
4249 -
4250 - // Process citation-style brackets [URL]
4251 - $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
4252 - $url = esc_url($matches[1]);
4253 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
4254 - }, $text);
4255 -
4256 - // Process standalone URLs (not already in links or img src)
4257 - $text = preg_replace_callback(
4258 - '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
4259 - function($matches) {
4260 - $url = esc_url($matches[1]);
4261 - // Truncate display URL if too long
4262 - $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
4263 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
4264 - },
4265 - $text
4266 - );
4267 -
4268 - // Process mailto links
4269 - $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
4270 - $link_text = esc_html($matches[1]);
4271 - $mailto = esc_url($matches[2]);
4272 - return "<a href=\"{$mailto}\">{$link_text}</a>";
4273 - }, $text);
4274 -
4275 - // Convert paragraphs: split by double newlines, wrap in <p> tags
4276 - // This creates proper paragraph structure instead of excessive <br> tags
4277 - $paragraphs = preg_split('/\n\n+/', $text);
4278 -
4279 - // Filter out empty paragraphs but preserve content like "0"
4280 - $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
4281 - return $p !== '';
4282 - }));
4283 -
4284 - if (empty($paragraphs)) {
4285 - // No content after filtering
4286 - return '';
4287 - } elseif (count($paragraphs) > 1) {
4288 - // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
4289 - $formatted_paragraphs = array_map(function($p) {
4290 - return nl2br($p);
4291 - }, $paragraphs);
4292 - $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4293 - } else {
4294 - // Single paragraph - just convert newlines to <br>
4295 - $text = nl2br($paragraphs[0]);
4296 - }
4297 -
4298 - return $text;
896 + <!-- License Status Display -->
897 + <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
898 + </div>
899 + <?php
4299 900 }
4300 901
4301 -/**
4302 - * AJAX handler to fetch RAG context for a specific message
4303 - * Used by the transcript viewer to show retrieved documents
4304 - */
4305 -public function mxchat_get_rag_context() {
4306 - // Check permissions
4307 - if (!current_user_can('manage_options')) {
4308 - wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4309 - wp_die();
4310 - }
4311 902
4312 - // Validate message ID
4313 - if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4314 - wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4315 - wp_die();
4316 - }
4317 903
4318 - $message_id = absint($_POST['message_id']);
4319 -
4320 - global $wpdb;
4321 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4322 -
4323 - // Fetch the RAG context for this message
4324 - $result = $wpdb->get_row($wpdb->prepare(
4325 - "SELECT rag_context FROM {$table_name} WHERE id = %d",
4326 - $message_id
4327 - ));
4328 -
4329 - if (!$result || empty($result->rag_context)) {
4330 - wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4331 - wp_die();
4332 - }
4333 -
4334 - // Decode the JSON data
4335 - $rag_context = json_decode($result->rag_context, true);
4336 -
4337 - if (json_last_error() !== JSON_ERROR_NONE) {
4338 - wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4339 - wp_die();
4340 - }
4341 -
4342 - wp_send_json_success($rag_context);
4343 - wp_die();
4344 -}
4345 -
4346 -public function display_admin_notices() {
4347 - // Check if we're on a MXChat admin page
4348 - $screen = get_current_screen();
4349 - if (!$screen || strpos($screen->base, 'mxchat') === false) {
904 +public function mxchat_intents_page_html() {
905 + if ( ! current_user_can( 'manage_options' ) ) {
4350 906 return;
4351 907 }
4352 908
4353 - $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4354 -
4355 - // Check for error notices
4356 - $error_notice = get_transient('mxchat_admin_notice_error');
4357 - if ($error_notice) {
4358 - echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4359 - delete_transient('mxchat_admin_notice_error');
909 + // Handle form submissions
910 + if ( isset( $_POST['mxchat_add_intent'] ) && check_admin_referer( 'mxchat_add_intent_nonce' ) ) {
911 + $this->mxchat_handle_add_intent();
912 + } elseif ( isset( $_POST['mxchat_delete_intent'] ) && check_admin_referer( 'mxchat_delete_intent_nonce' ) ) {
913 + $this->mxchat_handle_delete_intent();
914 + } elseif ( isset( $_POST['mxchat_update_intent_threshold'] ) && check_admin_referer( 'mxchat_update_intent_threshold_nonce' ) ) {
915 + $this->mxchat_handle_update_intent_threshold();
4360 916 }
4361 917
4362 - // Check for success notices
4363 - $success_notice = get_transient('mxchat_admin_notice_success');
4364 - if ($success_notice) {
4365 - echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4366 - delete_transient('mxchat_admin_notice_success');
4367 - }
4368 -
4369 - // Check for info notices
4370 - $info_notice = get_transient('mxchat_admin_notice_info');
4371 - if ($info_notice) {
4372 - echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4373 - delete_transient('mxchat_admin_notice_info');
4374 - }
4375 -}
4376 -
4377 -
4378 -public function mxchat_create_activation_page() {
4379 - // Include the new Pro & Extensions page template
4380 - require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
4381 -
4382 - // Get addons configuration from the MxChat_Addons class
4383 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4384 - $addons_instance = new MxChat_Addons();
4385 - $addons_config = $addons_instance->get_addons_config();
4386 -
4387 - // Render the consolidated Pro & Extensions page
4388 - mxchat_render_pro_page($this, $addons_config);
4389 -}
4390 -
4391 -/**
4392 - * Check if current activation is linked to a domain
4393 - * This checks YOUR website's database, not the user's local database
4394 - */
4395 -public function is_current_activation_linked($domain) {
4396 - $license_key = get_option('mxchat_activation_key');
4397 - $email = get_option('mxchat_pro_email');
4398 -
4399 - if (empty($license_key) || empty($email)) {
4400 - return false;
4401 - }
4402 -
4403 - // Check with YOUR website's API
4404 - $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4405 - 'body' => array(
4406 - 'license_key' => $license_key,
4407 - 'email' => $email,
4408 - 'domain' => $domain
4409 - ),
4410 - 'timeout' => 10,
4411 - 'sslverify' => false
4412 - ));
4413 -
4414 - if (is_wp_error($response)) {
4415 - return false;
4416 - }
4417 -
4418 - $body = json_decode(wp_remote_retrieve_body($response), true);
4419 - return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
4420 -}
4421 -
4422 -
4423 -public function mxchat_actions_page_html() {
4424 - if (!current_user_can('manage_options')) {
4425 - return;
4426 - }
4427 -
918 + // Fetch existing intents with pagination and filtering
4428 919 global $wpdb;
4429 920 $table_name = $wpdb->prefix . 'mxchat_intents';
921 + $page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
922 + $per_page = 20;
923 + $offset = ( $page - 1 ) * $per_page;
4430 924
4431 - // Get stats for dashboard
4432 - $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4433 - $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4434 - $disabled_actions = $total_actions - $enabled_actions;
925 + // Build the WHERE clause based on filters
926 + $where = '1=1';
927 + $search_term = isset( $_GET['s'] ) ? trim( $_GET['s'] ) : '';
928 + $callback_filter = isset( $_GET['callback_filter'] ) ? sanitize_text_field( $_GET['callback_filter'] ) : '';
4435 929
4436 - // Get unique action types count
4437 - $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
4438 -
4439 - // Get action type distribution
4440 - $type_distribution_raw = $wpdb->get_results("SELECT callback_function, COUNT(*) as count FROM $table_name GROUP BY callback_function ORDER BY count DESC LIMIT 10");
4441 - $available_callbacks = $this->mxchat_get_available_callbacks();
4442 - $callback_groups = $this->mxchat_get_available_callbacks(true, true);
4443 -
4444 - $action_type_distribution = array();
4445 - foreach ($type_distribution_raw as $row) {
4446 - $label = isset($available_callbacks[$row->callback_function]['label'])
4447 - ? $available_callbacks[$row->callback_function]['label']
4448 - : $row->callback_function;
4449 - $action_type_distribution[$label] = $row->count;
930 + if ( $search_term ) {
931 + $search_term_like = '%' . $wpdb->esc_like( $search_term ) . '%';
932 + $where .= $wpdb->prepare( ' AND (intent_label LIKE %s OR phrases LIKE %s)', $search_term_like, $search_term_like );
4450 933 }
4451 934
4452 - // Native function-calling (AI Tools) data — plan-mxchat-20260617-a41dee.
4453 - // The AI Tools checklist reads from MxChat_Tool_Registry, the SAME single
4454 - // source the chat-time function-calling loop reads, so the two never drift.
4455 - if (!class_exists('MxChat_Tool_Registry')) {
4456 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-tool-registry.php';
935 + if ( $callback_filter ) {
936 + $where .= $wpdb->prepare( ' AND callback_function = %s', $callback_filter );
4457 937 }
4458 - if (!class_exists('MxChat_Model_Catalog')) {
4459 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
4460 - }
4461 - $fc_options = get_option('mxchat_options', array());
4462 - $fc_current_model = isset($fc_options['model']) ? $fc_options['model'] : 'gpt-5.6-sol';
4463 - $fc_model_capable = class_exists('MxChat_Model_Catalog')
4464 - ? MxChat_Model_Catalog::supports_tools($fc_current_model) : true;
4465 - $active_tab = (isset($_GET['tab']) && $_GET['tab'] === 'ai-tools') ? 'ai-tools' : 'dashboard';
4466 938
4467 - // Enrich each AI Tool with the dashicon its callback already uses on the
4468 - // Trigger Phrases "Choose what it does" grid, so the AI Tools cards/modal
4469 - // share the same iconography (plan 8bbf98 part 4). View-layer only — the
4470 - // registry's model-facing data is untouched. Default admin-generic.
4471 - $fc_tools = MxChat_Tool_Registry::available_tools();
4472 - foreach ($fc_tools as &$fc_tool_ref) {
4473 - $fc_cb_ref = $fc_tool_ref['callback'];
4474 - $fc_tool_ref['icon'] = isset($available_callbacks[$fc_cb_ref]['icon'])
4475 - ? $available_callbacks[$fc_cb_ref]['icon']
4476 - : 'admin-generic';
4477 - }
4478 - unset($fc_tool_ref);
939 + // Get total count for pagination
940 + $total_intents = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name WHERE $where" );
941 + $total_pages = ceil( $total_intents / $per_page );
4479 942
4480 - // Count of ACTIVE tools — drives the AI Tools sidebar nav badge, mirroring
4481 - // $total_actions for Trigger Phrases. A tool in the list = active (plan
4482 - // d450a7), so the badge shows the same number the list pane shows (plan 5f7409).
4483 - $total_tools = count(array_filter($fc_tools, function ($t) {
4484 - return !empty($t['enabled']);
4485 - }));
943 + // Fetch intents with pagination and filters
944 + $intents = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE $where LIMIT %d OFFSET %d", $per_page, $offset ) );
4486 945
4487 - // Brave-key dependency check (plan 183856): Web Search + Image Search run on
4488 - // the Brave Search API. If either is enabled as a tool but no brave_api_key is
4489 - // configured, surface a graceful "key not set" notice so the admin isn't met
4490 - // with a silently no-firing tool.
4491 - $fc_brave_missing = false;
4492 - $brave_key = isset($fc_options['brave_api_key']) ? trim($fc_options['brave_api_key']) : '';
4493 - if ($brave_key === '') {
4494 - foreach ($fc_tools as $fc_t) {
4495 - if (!empty($fc_t['enabled']) && isset($fc_t['requires_key']) && $fc_t['requires_key'] === 'brave_api_key') {
4496 - $fc_brave_missing = true;
4497 - break;
4498 - }
4499 - }
4500 - }
946 + // Get available callback functions with 'pro_only' flag
947 + $available_callbacks = $this->mxchat_get_available_callbacks();
948 + ?>
4501 949
4502 - // Prepare page data
4503 - $page_data = array(
4504 - 'total_actions' => $total_actions,
4505 - 'enabled_actions' => $enabled_actions,
4506 - 'disabled_actions' => $disabled_actions,
4507 - 'action_types_count' => $action_types_count,
4508 - 'action_type_distribution' => $action_type_distribution,
4509 - 'available_callbacks' => $available_callbacks,
4510 - 'callback_groups' => $callback_groups,
4511 - // AI Tools section
4512 - 'active_tab' => $active_tab,
4513 - 'fc_enabled' => MxChat_Tool_Registry::is_enabled(),
4514 - 'total_tools' => $total_tools,
4515 - 'fc_tools' => $fc_tools,
4516 - 'fc_current_model' => $fc_current_model,
4517 - 'fc_model_capable' => $fc_model_capable,
4518 - 'fc_brave_missing' => $fc_brave_missing,
4519 - 'fc_saved' => isset($_GET['mxchat_fc_saved']),
4520 - );
4521 -
4522 - // Include and render the new template
4523 - require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4524 - mxchat_render_actions_page($this, $page_data);
4525 -}
4526 -
4527 -/**
4528 - * LEGACY HTML - Preserved below for reference, to be removed in future update
4529 - */
4530 -function mxchat_actions_page_legacy_html() {
4531 - // This function is deprecated and no longer used
4532 - // The new template is in includes/admin-actions-page.php
4533 - ?>
4534 - <div class="wrap mxchat-wrapper">
4535 - <!-- Hero Section -->
4536 - <div class="mxchat-hero">
4537 - <h1 class="mxchat-main-title">
4538 - <span class="mxchat-gradient-text">Actions</span> Manager
4539 - </h1>
4540 - <p class="mxchat-hero-subtitle">
4541 - <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
950 + <div class="wrap mxchat-admin">
951 + <form method="post">
952 + <?php wp_nonce_field( 'mxchat_add_intent_nonce' ); ?>
953 + <h2><?php esc_html_e( 'Add New Intent', 'mxchat' ); ?></h2>
954 + <p class="description">
955 + <?php esc_html_e( 'We highly encourage users to quickly read our ', 'mxchat' ); ?>
956 + <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">
957 + <?php esc_html_e( 'documentation', 'mxchat' ); ?>
958 + </a>
959 + <?php esc_html_e( ' to better understand intents. Some intents require setup in the Integration tab.', 'mxchat' ); ?>
4542 960 </p>
4543 - </div>
4544 961
4545 - <!-- Actions Header with Search and Filter -->
4546 - <div class="mxchat-actions-header">
4547 - <div class="mxchat-actions-filters">
4548 - <form method="get" class="mxchat-search-form">
4549 - <input type="hidden" name="page" value="mxchat-actions">
4550 - <div class="mxchat-search-group">
4551 - <span class="dashicons dashicons-search"></span>
4552 - <input type="text" name="s" class="mxchat-search-input"
4553 - placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
4554 - value="<?php echo esc_attr($search_term); ?>">
4555 - </div>
4556 - <select name="callback_filter" class="mxchat-action-filter">
4557 - <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
4558 - <?php foreach ($available_callbacks as $function => $callback_data) :
4559 - $label = $callback_data['label']; ?>
4560 - <option value="<?php echo esc_attr($function); ?>"
4561 - <?php selected($callback_filter, $function); ?>>
4562 - <?php echo esc_html($label); ?>
4563 - </option>
4564 - <?php endforeach; ?>
4565 - </select>
4566 - <button type="submit" class="mxchat-button-secondary">
4567 - <?php esc_html_e('Filter', 'mxchat'); ?>
4568 - </button>
4569 - </form>
962 + <div class="mxchat-form-group">
963 + <label for="intent_label"><?php esc_html_e( 'Intent Label', 'mxchat' ); ?></label>
964 + <input name="intent_label" type="text" id="intent_label" class="regular-text" required>
4570 965 </div>
4571 - <div class="mxchat-actions-controls">
4572 - <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
4573 - <span class="dashicons dashicons-plus-alt"></span>
4574 - <?php esc_html_e('Add New Action', 'mxchat'); ?>
4575 - </button>
966 + <div class="mxchat-form-group">
967 + <label for="phrases"><?php esc_html_e( 'Phrases (comma-separated)', 'mxchat' ); ?></label>
968 + <textarea name="phrases" id="phrases" rows="5" class="large-text" required></textarea>
4576 969 </div>
4577 - </div>
4578 -
4579 - <!-- Actions Grid Layout - All actions in a single grid -->
4580 - <div class="mxchat-actions-grid">
4581 - <div class="mxchat-cards-container">
4582 - <?php if (!empty($actions)) : ?>
4583 - <?php foreach ($actions as $action) :
4584 - $callback_function = $action->callback_function;
4585 - $callback_label = isset($available_callbacks[$callback_function]['label'])
4586 - ? $available_callbacks[$callback_function]['label']
4587 - : $callback_function;
4588 - $threshold_value = isset($action->similarity_threshold)
4589 - ? round($action->similarity_threshold * 100)
4590 - : 85;
4591 -
4592 - // Check if this is a form action
4593 - $is_form_action = strpos($action->intent_label, 'Form ') === 0;
4594 -
4595 - // Get action status (enabled/disabled) - default to true if column doesn't exist
4596 - $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
4597 -
4598 - // Get enabled bots for display
4599 - $enabled_bots = [];
4600 - if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
4601 - $enabled_bots = json_decode($action->enabled_bots, true);
4602 - if (!is_array($enabled_bots)) {
4603 - $enabled_bots = ['default'];
4604 - }
4605 - } else {
4606 - $enabled_bots = ['default']; // Backward compatibility
4607 - }
4608 - ?>
4609 - <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
4610 - <div class="mxchat-card-header">
4611 - <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
4612 - <div class="mxchat-card-toggle">
4613 - <label class="mxchat-switch">
4614 - <input type="checkbox" class="mxchat-action-toggle"
4615 - data-action-id="<?php echo esc_attr($action->id); ?>"
4616 - <?php checked($is_enabled); ?>>
4617 - <span class="mxchat-slider round"></span>
4618 - </label>
4619 - </div>
4620 - </div>
4621 -
4622 - <div class="mxchat-card-body">
4623 - <div class="mxchat-card-description">
4624 - <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
4625 - <?php echo esc_html($callback_label); ?>
4626 - </div>
4627 -
4628 - <div class="mxchat-card-phrases">
4629 - <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
4630 - <div class="mxchat-phrases-preview">
4631 - <?php
4632 - // Check if the helper function exists, otherwise use a simple substring
4633 - if (method_exists($this, 'get_trimmed_phrases')) {
4634 - echo esc_html($this->get_trimmed_phrases($action->phrases));
4635 - } else {
4636 - echo esc_html(strlen($action->phrases) > 100 ?
4637 - substr($action->phrases, 0, 97) . '...' :
4638 - $action->phrases);
4639 - }
4640 - ?>
4641 - </div>
4642 - </div>
4643 -
4644 - <div class="mxchat-threshold-control">
4645 - <div class="mxchat-threshold-label">
4646 - <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
4647 - <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
4648 - </div>
4649 - </div>
4650 -
4651 - <!-- Bot Availability Display (Read-only) -->
4652 - <div class="mxchat-card-bots">
4653 - <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
4654 - <div class="mxchat-bot-badges">
4655 - <?php
4656 - foreach ($enabled_bots as $bot_id) {
4657 - if ($bot_id === 'default') {
4658 - echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
4659 - } else {
4660 - // Try to get bot name from multi-bot manager
4661 - if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
4662 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4663 - $available_bots = $multi_bot_manager->get_available_bots();
4664 - $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
4665 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
4666 - } else {
4667 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
4668 - }
4669 - }
4670 - }
4671 - ?>
4672 - </div>
4673 - </div>
4674 - </div>
4675 -
4676 - <div class="mxchat-card-footer">
4677 - <?php
4678 - // Check if it's a form action
4679 - $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
4680 -
4681 - // Check if it's a recommendation flow action
4682 - $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
4683 -
4684 - if ($is_form_action) {
4685 - $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
4686 - ?>
4687 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
4688 - class="mxchat-button-primary">
4689 - <span class="dashicons dashicons-feedback"></span>
4690 - <?php esc_html_e('Edit Form', 'mxchat'); ?>
4691 - </a>
4692 - <?php } elseif ($is_flow_action) {
4693 - ?>
4694 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
4695 - class="mxchat-button-primary">
4696 - <span class="dashicons dashicons-list-view"></span>
4697 - <?php esc_html_e('Manage Flows', 'mxchat'); ?>
4698 - </a>
4699 - <?php } else { ?>
4700 - <button type="button"
4701 - class="mxchat-button-secondary mxchat-edit-button"
4702 - data-action-id="<?php echo esc_attr($action->id); ?>"
4703 - data-phrases="<?php echo esc_attr($action->phrases); ?>"
4704 - data-label="<?php echo esc_attr($action->intent_label); ?>"
4705 - data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
4706 - data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
4707 - data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
4708 - <span class="dashicons dashicons-edit"></span>
4709 - <?php esc_html_e('Edit', 'mxchat'); ?>
4710 - </button>
4711 - <form method="post"
4712 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
4713 - class="mxchat-delete-form"
4714 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
4715 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
4716 - <input type="hidden" name="action" value="mxchat_delete_intent">
4717 - <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
4718 - <button type="submit" class="mxchat-button-text mxchat-delete-button">
4719 - <span class="dashicons dashicons-trash"></span>
4720 - <?php esc_html_e('Delete', 'mxchat'); ?>
4721 - </button>
4722 - </form>
4723 - <?php } ?>
4724 - </div>
4725 - </div>
970 + <div class="mxchat-form-group">
971 + <label for="callback_function"><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></label>
972 + <select name="callback_function" id="callback_function" required>
973 + <option value=""><?php esc_html_e( 'Select a Callback', 'mxchat' ); ?></option>
974 + <?php foreach ( $available_callbacks as $function => $callback_data ) : ?>
975 + <?php
976 + $label = $callback_data['label'];
977 + $pro_only = $callback_data['pro_only'];
978 + $disabled = ( ! $this->is_activated && $pro_only ) ? 'disabled' : '';
979 + $label_suffix = ( ! $this->is_activated && $pro_only ) ? ' (Pro Only)' : '';
980 + ?>
981 + <option value="<?php echo esc_attr( $function ); ?>" <?php echo $disabled; ?>>
982 + <?php echo esc_html( $label . $label_suffix ); ?>
983 + </option>
4726 984 <?php endforeach; ?>
4727 - <?php else : ?>
4728 - <!-- If no actions found -->
4729 - <div class="mxchat-no-actions">
4730 - <div class="mxchat-empty-state">
4731 - <span class="dashicons dashicons-format-chat"></span>
4732 - <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4733 - <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4734 - <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4735 - <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4736 - </button>
4737 - </div>
4738 - </div>
4739 - <?php endif; ?>
985 + </select>
4740 986 </div>
4741 - </div>
987 + <button type="submit" name="mxchat_add_intent" class="button button-primary submit-content-button">
988 + <?php esc_html_e( 'Add Intent', 'mxchat' ); ?>
989 + </button>
990 + </form>
4742 991
4743 - <?php if ($total_pages > 1) : ?>
4744 - <div class="mxchat-pagination">
4745 - <?php
4746 - echo paginate_links(array(
4747 - 'base' => add_query_arg('paged', '%#%'),
4748 - 'format' => '',
4749 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4750 - 'next_text' => __('Next &raquo;', 'mxchat'),
4751 - 'total' => $total_pages,
4752 - 'current' => $page
4753 - ));
4754 - ?>
4755 - </div>
4756 - <?php endif; ?>
992 + <div id="mxchat-intent-loading" class="mxchat-intent-spinner" style="display: none;"></div>
993 + <div id="mxchat-intent-loading-text" class="mxchat-loading-text">Saving intent, please wait...</div>
4757 994
4758 -<!-- Add/Edit Action Modal with Step-Based Approach -->
4759 -<!-- Complete Modal HTML with Defined Groups Variable -->
4760 -<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
4761 - <div class="mxchat-modal-content">
4762 - <span class="mxchat-modal-close">&times;</span>
4763 -
4764 - <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4765 - <!-- Dynamic nonce field -->
4766 - <div id="action-nonce-container">
4767 - <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
995 + <!-- Filter Form -->
996 + <form method="get" action="">
997 + <input type="hidden" name="page" value="mxchat-intents">
998 + <div class="mxchat-search-group">
999 + <input type="text" name="s" id="mxchat-intent-search" placeholder="<?php esc_attr_e( 'Search Intents', 'mxchat' ); ?>" value="<?php echo esc_attr( $search_term ); ?>">
1000 + <select name="callback_filter" id="mxchat-callback-filter">
1001 + <option value=""><?php esc_html_e( 'All Callbacks', 'mxchat' ); ?></option>
1002 + <?php foreach ( $available_callbacks as $function => $callback_data ) : ?>
1003 + <?php $label = $callback_data['label']; ?>
1004 + <option value="<?php echo esc_attr( $function ); ?>" <?php selected( $callback_filter, $function ); ?>><?php echo esc_html( $label ); ?></option>
1005 + <?php endforeach; ?>
1006 + </select>
1007 + <button type="submit" class="button"><?php esc_html_e( 'Filter', 'mxchat' ); ?></button>
4768 1008 </div>
4769 - <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4770 - <input type="hidden" name="intent_id" id="edit_action_id" value="">
4771 - <input type="hidden" name="callback_function" id="callback_function" value="">
1009 + </form>
4772 1010
4773 - <!-- Step 1: Action Type Selection -->
4774 - <div id="mxchat-action-step-1" class="mxchat-action-step active">
4775 - <div class="mxchat-step-indicator">
4776 - <div class="mxchat-step-number">1</div>
4777 - <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4778 - </div>
4779 -
4780 - <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4781 - <div class="mxchat-action-type-search">
4782 - <span class="dashicons dashicons-search"></span>
4783 - <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4784 - </div>
4785 -
4786 - <?php
4787 - // Get the callbacks - IMPORTANT: Define the $groups variable here
4788 - $groups = $this->mxchat_get_available_callbacks(true, true);
4789 - ?>
4790 -
4791 - <div class="mxchat-action-type-categories">
4792 - <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
1011 + <!-- Intents Table -->
1012 + <table class="wp-list-table mxchat-intents-table widefat fixed striped">
1013 + <thead>
1014 + <tr>
1015 + <th><?php esc_html_e( 'Intent Label', 'mxchat' ); ?></th>
1016 + <th><?php esc_html_e( 'Phrases', 'mxchat' ); ?></th>
1017 + <th><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></th>
1018 + <th><?php esc_html_e( 'Similarity Threshold', 'mxchat' ); ?></th>
1019 + <th><?php esc_html_e( 'Actions', 'mxchat' ); ?></th>
1020 + </tr>
1021 + </thead>
1022 + <tbody>
1023 + <?php if ( $intents ) : ?>
1024 + <?php foreach ( $intents as $intent ) : ?>
4793 1025 <?php
4794 - // Get unique categories from the defined groups
4795 - foreach ($groups as $group_label => $group_callbacks) :
4796 - $category_slug = sanitize_title($group_label);
1026 + $callback_function = $intent->callback_function;
1027 + $callback_label = isset( $available_callbacks[ $callback_function ]['label'] ) ? $available_callbacks[ $callback_function ]['label'] : $callback_function;
1028 + $threshold_value = isset( $intent->similarity_threshold ) ? round( $intent->similarity_threshold * 100 ) : 85;
4797 1029 ?>
4798 - <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4799 - <?php endforeach; ?>
4800 - </div>
4801 -
4802 - <div class="mxchat-action-types-grid">
4803 - <?php
4804 - // Generate action cards from available callbacks
4805 - foreach ($groups as $group_label => $group_callbacks) :
4806 - $category_slug = sanitize_title($group_label);
4807 -
4808 - foreach ($group_callbacks as $function => $data) :
4809 - $label = $data['label'];
4810 - $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4811 - $description = isset($data['description']) ? $data['description'] : '';
4812 - $is_addon = isset($data['addon']) && $data['addon'] !== false;
4813 - $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4814 - $is_installed = isset($data['installed']) ? $data['installed'] : true;
4815 - $is_promo = !empty($data['addon_promo']) && !$is_installed;
4816 -
4817 - // Determine card status and styling
4818 - $card_class = 'mxchat-action-type-card';
4819 - $icon_class = 'mxchat-action-type-icon';
4820 - $status_badge = '';
4821 -
4822 - if ($is_promo) {
4823 - // Promotional card — not selectable, just informational
4824 - $card_class .= ' not-installed mxchat-promo-card';
4825 - $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4826 - } elseif ($is_addon && !$is_installed) {
4827 - // Add-on not installed
4828 - $card_class .= ' not-installed';
4829 - $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4830 - }
4831 -
4832 - // Default description if none provided
4833 - if (empty($description)) {
4834 - $description = sprintf(
4835 - esc_html__('Use the %s action in your chatbot', 'mxchat'),
4836 - $label
4837 - );
4838 - }
4839 - ?>
4840 - <div class="<?php echo esc_attr($card_class); ?>"
4841 - data-category="<?php echo esc_attr($category_slug); ?>"
4842 - <?php if (!$is_promo) : ?>
4843 - data-value="<?php echo esc_attr($function); ?>"
4844 - data-label="<?php echo esc_attr($label); ?>"
4845 - <?php endif; ?>
4846 - data-pro="false"
4847 - data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4848 - data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
4849 - <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
4850 - <div class="<?php echo esc_attr($icon_class); ?>">
4851 - <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4852 - </div>
4853 - <div class="mxchat-action-type-info">
4854 - <h4><?php echo esc_html($label); ?></h4>
4855 - <p><?php echo esc_html($description); ?></p>
4856 - <?php if (!empty($status_badge)) : ?>
4857 - <?php echo $status_badge; ?>
4858 - <?php endif; ?>
4859 -
4860 - <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
4861 - <div class="mxchat-addon-info">
4862 - <?php echo esc_html(sprintf(
4863 - __('Requires %s', 'mxchat'),
4864 - $addon_name
4865 - )); ?>
4866 - — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
4867 - </div>
4868 - <?php endif; ?>
4869 - </div>
4870 - </div>
4871 - <?php endforeach;
4872 - endforeach; ?>
4873 - </div>
4874 - </div>
4875 -
4876 - <div class="mxchat-modal-actions">
4877 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4878 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4879 - </button>
4880 - </div>
4881 - </div>
4882 -
4883 - <!-- Step 2: Action Configuration -->
4884 - <div id="mxchat-action-step-2" class="mxchat-action-step">
4885 - <div class="mxchat-step-indicator">
4886 - <div class="mxchat-step-number">2</div>
4887 - <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4888 - </div>
4889 -
4890 - <div class="mxchat-selected-action">
4891 - <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
4892 - <span class="dashicons dashicons-arrow-left-alt"></span>
4893 - <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
4894 - </button>
4895 - <div class="mxchat-selected-action-info">
4896 - <div id="selected-action-icon" class="mxchat-action-type-icon">
4897 - <span class="dashicons dashicons-admin-generic"></span>
4898 - </div>
4899 - <div class="mxchat-selected-action-details">
4900 - <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
4901 - <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
4902 - </div>
4903 - </div>
4904 - </div>
4905 -
4906 - <div class="mxchat-form-group">
4907 - <label for="intent_label">
4908 - <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
4909 - </label>
4910 - <input name="intent_label" type="text" id="intent_label" required
4911 - class="mxchat-intent-input"
4912 - placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
4913 - </div>
4914 -
4915 - <div class="mxchat-form-group">
4916 - <label for="phrases">
4917 - <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
4918 - </label>
4919 - <textarea name="phrases" id="action_phrases" rows="5" required
4920 - class="mxchat-intent-textarea"
4921 - placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
4922 - </div>
4923 -
4924 - <div class="mxchat-form-group">
4925 - <label for="similarity_threshold">
4926 - <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
4927 - <span class="mxchat-threshold-value-display">85%</span>
4928 - </label>
4929 - <div class="mxchat-slider-group modal-slider">
4930 - <input type="range"
4931 - name="similarity_threshold"
4932 - id="similarity_threshold"
4933 - min="10"
4934 - max="95"
4935 - value="85"
4936 - class="mxchat-intent-slider"
4937 - oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
4938 - </div>
4939 - <div class="mxchat-threshold-hint">
4940 - <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
4941 - </div>
4942 - </div>
4943 -
4944 - <!-- Bot Selection Section -->
4945 - <div class="mxchat-form-group">
4946 - <label for="enabled_bots">
4947 - <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
4948 - </label>
4949 - <div class="mxchat-bot-selector">
4950 - <div class="mxchat-bot-option">
4951 - <label class="mxchat-checkbox-label">
4952 - <input type="checkbox"
4953 - name="enabled_bots[]"
4954 - value="default"
4955 - id="bot_default"
4956 - checked="checked">
4957 - <span class="mxchat-checkmark"></span>
4958 - <?php esc_html_e('Default Bot', 'mxchat'); ?>
4959 - </label>
4960 - </div>
4961 -
4962 - <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
4963 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4964 - $available_bots = $multi_bot_manager->get_available_bots();
4965 -
4966 - foreach ($available_bots as $bot_id => $bot_name) :
4967 - if ($bot_id === 'default') continue; // Skip default, already shown above
4968 - ?>
4969 - <div class="mxchat-bot-option">
4970 - <label class="mxchat-checkbox-label">
4971 - <input type="checkbox"
4972 - name="enabled_bots[]"
4973 - value="<?php echo esc_attr($bot_id); ?>"
4974 - id="bot_<?php echo esc_attr($bot_id); ?>">
4975 - <span class="mxchat-checkmark"></span>
4976 - <?php echo esc_html($bot_name); ?>
4977 - </label>
4978 - </div>
4979 - <?php
4980 - endforeach;
4981 - endif; ?>
4982 - </div>
4983 - </div>
4984 -
4985 - <div class="mxchat-modal-actions">
4986 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4987 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4988 - </button>
4989 - <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
4990 - <?php esc_html_e('Save Action', 'mxchat'); ?>
4991 - </button>
4992 - </div>
4993 - </div>
4994 - </form>
1030 + <tr>
1031 + <td><?php echo esc_html( $intent->intent_label ); ?></td>
1032 + <td><?php echo esc_html( $intent->phrases ); ?></td>
1033 + <td><?php echo esc_html( $callback_label ); ?></td>
1034 + <!-- Similarity Threshold Column -->
1035 + <td>
1036 + <form method="post">
1037 + <?php wp_nonce_field( 'mxchat_update_intent_threshold_nonce' ); ?>
1038 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
1039 + <input type="range" name="intent_threshold" id="intent_threshold_<?php echo esc_attr( $intent->id ); ?>" min="70" max="95" value="<?php echo esc_attr( $threshold_value ); ?>" oninput="document.getElementById('threshold_output_<?php echo esc_attr( $intent->id ); ?>').value = this.value + '%'">
1040 + <output id="threshold_output_<?php echo esc_attr( $intent->id ); ?>"><?php echo esc_html( $threshold_value ); ?>%</output>
1041 + </td>
1042 + <!-- Actions Column -->
1043 + <td>
1044 + <!-- Save Button -->
1045 + <button type="submit" name="mxchat_update_intent_threshold" class="button button-primary mxchat-save-button">
1046 + <?php esc_html_e( 'Save', 'mxchat' ); ?>
1047 + </button>
1048 + </form>
1049 + <!-- Delete Form -->
1050 + <form method="post" onsubmit="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this intent?', 'mxchat' ); ?>');">
1051 + <?php wp_nonce_field( 'mxchat_delete_intent_nonce' ); ?>
1052 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
1053 + <button type="submit" name="mxchat_delete_intent" class="button mxchat-delete-all">
1054 + <?php esc_html_e( 'Delete', 'mxchat' ); ?>
1055 + </button>
1056 + </form>
1057 + </td>
1058 + </tr>
1059 + <?php endforeach; ?>
1060 + <?php else : ?>
1061 + <tr>
1062 + <td colspan="5"><?php esc_html_e( 'No intents found.', 'mxchat' ); ?></td>
1063 + </tr>
1064 + <?php endif; ?>
1065 + </tbody>
1066 + </table>
4995 1067 </div>
4996 -</div>
4997 -
4998 -<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
4999 - <div class="mxchat-action-loading-spinner"></div>
5000 - <div class="mxchat-action-loading-text">
5001 - <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
5002 - </div>
5003 -</div>
5004 - </div><!-- .mxchat-wrapper -->
5005 1068 <?php
5006 1069 }
5007 -private function get_trimmed_phrases($phrases, $max_length = 100) {
5008 - if (strlen($phrases) <= $max_length) {
5009 - return $phrases;
5010 - }
5011 1070
5012 - $trimmed = substr($phrases, 0, $max_length);
5013 - $last_comma = strrpos($trimmed, ',');
5014 1071
5015 - if ($last_comma !== false) {
5016 - $trimmed = substr($trimmed, 0, $last_comma);
1072 +
1073 +public function mxchat_handle_update_intent_threshold() {
1074 + if (!current_user_can('manage_options')) {
1075 + return;
5017 1076 }
5018 1077
5019 - return $trimmed . '...';
5020 -}
5021 -public function mxchat_add_enabled_column_to_intents() {
5022 - global $wpdb;
5023 - $table_name = $wpdb->prefix . 'mxchat_intents';
1078 + check_admin_referer('mxchat_update_intent_threshold_nonce');
5024 1079
5025 - // Check if the column already exists
5026 - $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
1080 + if (isset($_POST['intent_id']) && isset($_POST['intent_threshold'])) {
1081 + $intent_id = intval($_POST['intent_id']);
1082 + $threshold_percentage = intval($_POST['intent_threshold']);
5027 1083
5028 - if (empty($columns)) {
5029 - // Add the column with default value of 1 (enabled)
5030 - $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
5031 - }
5032 -}
1084 + // Ensure the percentage is between 30 and 95
1085 + $threshold_percentage = max(70, min(95, $threshold_percentage));
5033 1086
5034 -public function mxchat_handle_delete_intent() {
5035 - if ( ! current_user_can( 'manage_options' ) ) {
5036 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
5037 - }
1087 + // Convert percentage to decimal
1088 + $similarity_threshold = $threshold_percentage / 100;
5038 1089
5039 - check_admin_referer('mxchat_delete_intent_nonce');
5040 -
5041 - if (isset($_POST['intent_id'])) {
1090 + // Update the intent's threshold in the database
5042 1091 global $wpdb;
5043 1092 $table_name = $wpdb->prefix . 'mxchat_intents';
5044 - $intent_id = intval($_POST['intent_id']);
1093 + $updated = $wpdb->update(
1094 + $table_name,
1095 + array('similarity_threshold' => $similarity_threshold),
1096 + array('id' => $intent_id),
1097 + array('%f'),
1098 + array('%d')
1099 + );
5045 1100
5046 - $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5047 - }
5048 -
5049 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5050 - exit;
5051 -}
5052 -public function mxchat_handle_edit_intent() {
5053 - // Security checks (nonce and permissions)
5054 - if (!current_user_can('manage_options')) {
5055 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5056 - }
5057 - check_admin_referer('mxchat_edit_intent');
5058 -
5059 - // Get POST data
5060 - $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
5061 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5062 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5063 - $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
5064 - $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
5065 -
5066 - // Handle enabled_bots
5067 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5068 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5069 -
5070 - // Ensure default is always included for backward compatibility
5071 - if (!in_array('default', $enabled_bots)) {
5072 - $enabled_bots[] = 'default';
5073 - }
5074 -
5075 - $enabled_bots_json = json_encode($enabled_bots);
5076 -
5077 - // Validate inputs
5078 - if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
5079 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5080 - return;
5081 - }
5082 -
5083 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5084 - if (empty($phrases_array)) {
5085 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5086 - return;
5087 - }
5088 -
5089 - // Generate embeddings with improved error handling
5090 - $vectors = [];
5091 - $failed_phrases = [];
5092 -
5093 - foreach ($phrases_array as $phrase) {
5094 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5095 - if (is_array($embedding_vector)) {
5096 - $vectors[] = $embedding_vector;
1101 + if ($updated === false) {
1102 + wp_die(esc_html__('Error updating intent threshold.', 'mxchat'));
5097 1103 } else {
5098 - $failed_phrases[] = $phrase;
1104 + // Redirect to avoid resubmission
1105 + wp_safe_redirect($_SERVER['REQUEST_URI']);
1106 + exit;
5099 1107 }
1108 + } else {
1109 + wp_die(esc_html__('Invalid input. Please try again.', 'mxchat'));
5100 1110 }
1111 +}
5101 1112
5102 - if (!empty($failed_phrases)) {
5103 - $this->handle_embedding_error(
5104 - sprintf(
5105 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5106 - implode(', ', $failed_phrases)
5107 - )
5108 - );
5109 - return;
5110 - }
5111 1113
5112 - if (empty($vectors)) {
5113 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
1114 +public function mxchat_handle_add_intent() {
1115 + if (!current_user_can('manage_options')) {
5114 1116 return;
5115 1117 }
5116 1118
5117 - $combined_vector = $this->mxchat_average_vectors($vectors);
5118 - $serialized_vector = maybe_serialize($combined_vector);
1119 + check_admin_referer('mxchat_add_intent_nonce');
5119 1120
5120 - // Update the database
5121 1121 global $wpdb;
5122 1122 $table_name = $wpdb->prefix . 'mxchat_intents';
5123 1123
5124 - $result = $wpdb->update(
5125 - $table_name,
5126 - array(
5127 - 'intent_label' => $intent_label,
5128 - 'phrases' => implode(', ', $phrases_array),
5129 - 'embedding_vector' => $serialized_vector,
5130 - 'similarity_threshold' => $similarity_threshold,
5131 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
5132 - ),
5133 - array('id' => $intent_id),
5134 - array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
5135 - array('%d') // Where format: integer
5136 - );
5137 -
5138 - if (false === $result) {
5139 - $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
5140 - return;
5141 - }
5142 -
5143 - // Set success message and redirect
5144 - set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
5145 -
5146 - $redirect_url = add_query_arg(
5147 - array(
5148 - 'page' => 'mxchat-actions'
5149 - ),
5150 - admin_url('admin.php')
5151 - );
5152 - wp_safe_redirect($redirect_url);
5153 - exit;
5154 -}
5155 -public function mxchat_handle_add_intent() {
5156 - if (!current_user_can('manage_options')) {
5157 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5158 - }
5159 - check_admin_referer('mxchat_add_intent_nonce');
5160 - global $wpdb;
5161 - $table_name = $wpdb->prefix . 'mxchat_intents';
5162 -
5163 - // Sanitize and get form data
1124 + // Get the form input
5164 1125 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5165 1126 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5166 1127 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5167 -
5168 - // Get similarity threshold from form (convert percentage to decimal)
5169 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5170 -
5171 - // Handle enabled_bots
5172 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5173 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5174 -
5175 - // Ensure default is always included for backward compatibility with existing actions
5176 - if (!in_array('default', $enabled_bots)) {
5177 - $enabled_bots[] = 'default';
5178 - }
5179 -
5180 - $enabled_bots_json = json_encode($enabled_bots);
5181 -
5182 - // Validate required fields
1128 + $default_threshold = 0.85;
1129 +
5183 1130 if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
5184 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5185 - return;
1131 + wp_die(esc_html__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5186 1132 }
5187 -
1133 +
1134 + // Get available callback functions
1135 + $available_callbacks = $this->mxchat_get_available_callbacks();
1136 +
5188 1137 // Validate callback function
5189 - $available_callbacks = $this->mxchat_get_available_callbacks();
5190 1138 if (!array_key_exists($callback_function, $available_callbacks)) {
5191 - $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
5192 - return;
1139 + wp_die(esc_html__('Invalid callback function selected.', 'mxchat'));
5193 1140 }
5194 -
5195 - // Check if this is an add-on promotional placeholder (not a real action)
5196 - if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
5197 - $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
5198 - $this->handle_embedding_error(sprintf(
5199 - __('This action requires the %s to be installed and activated.', 'mxchat'),
5200 - $addon_name
5201 - ));
5202 - return;
1141 +
1142 + // Check if the callback is Pro-only and the user is not activated
1143 + $is_pro_only = $available_callbacks[$callback_function]['pro_only'];
1144 + if ($is_pro_only && !$this->is_activated) {
1145 + wp_die(esc_html__('This callback function is available in the Pro version only.', 'mxchat'));
5203 1146 }
5204 -
5205 - // Process phrases
1147 +
1148 + // Split and sanitize phrases
5206 1149 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
1150 +
5207 1151 if (empty($phrases_array)) {
5208 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5209 - return;
1152 + wp_die(esc_html__('Please enter at least one valid phrase.', 'mxchat'));
5210 1153 }
5211 -
5212 - // Generate embeddings with improved error handling
1154 +
1155 + // Generate and collect embeddings for each phrase
5213 1156 $vectors = [];
5214 - $failed_phrases = [];
5215 1157 foreach ($phrases_array as $phrase) {
5216 1158 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5217 1159 if (is_array($embedding_vector)) {
5218 1160 $vectors[] = $embedding_vector;
5219 1161 } else {
5220 - $failed_phrases[] = $phrase;
1162 + wp_die(esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase));
5221 1163 }
5222 1164 }
5223 -
5224 - // Check for embedding failures
5225 - if (!empty($failed_phrases)) {
5226 - $this->handle_embedding_error(
5227 - sprintf(
5228 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5229 - implode(', ', $failed_phrases)
5230 - )
5231 - );
5232 - return;
5233 - }
5234 -
5235 - if (empty($vectors)) {
5236 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5237 - return;
5238 - }
5239 -
5240 - // Create combined vector and insert into database
5241 - $combined_vector = $this->mxchat_average_vectors($vectors);
5242 - $serialized_vector = maybe_serialize($combined_vector);
5243 -
5244 - $result = $wpdb->insert($table_name, [
5245 - 'intent_label' => $intent_label,
5246 - 'phrases' => implode(', ', $phrases_array),
5247 - 'embedding_vector' => $serialized_vector,
5248 - 'callback_function' => $callback_function,
5249 - 'similarity_threshold' => $similarity_threshold,
5250 - 'enabled_bots' => $enabled_bots_json, // NEW field
5251 - ]);
5252 -
5253 - if ($result === false) {
5254 - $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
5255 - return;
5256 - }
5257 -
5258 - // Set success message and redirect
5259 - set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
5260 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5261 - exit;
5262 -}
5263 1165
1166 + // Average the vectors to create a single embedding vector for the intent
1167 + if (!empty($vectors)) {
1168 + $combined_vector = $this->mxchat_average_vectors($vectors);
1169 + $serialized_vector = maybe_serialize($combined_vector);
5264 1170
1171 + // Insert the combined vector as a single entry for the intent
1172 + $result = $wpdb->insert($table_name, [
1173 + 'intent_label' => $intent_label,
1174 + 'phrases' => implode(', ', $phrases_array),
1175 + 'embedding_vector' => $serialized_vector,
1176 + 'callback_function' => $callback_function,
1177 + 'similarity_threshold' => $default_threshold,
1178 + ]);
5265 1179
5266 -
5267 -private function handle_embedding_error($message, $redirect = true) {
5268 - // Store the error message in the existing transient
5269 - set_transient('mxchat_admin_notice_error', $message, 60);
5270 -
5271 - if ($redirect) {
5272 - // Redirect back to the actions page
5273 - $redirect_url = add_query_arg(
5274 - array(
5275 - 'page' => 'mxchat-actions'
5276 - ),
5277 - admin_url('admin.php')
5278 - );
5279 - wp_safe_redirect($redirect_url);
5280 - exit;
5281 - }
5282 -}
5283 -
5284 -/**
5285 - * AJAX handler to fetch actions list for the new split-panel UI
5286 - */
5287 -public function mxchat_fetch_actions_list() {
5288 - check_ajax_referer('mxchat_actions_nonce', 'security');
5289 -
5290 - if (!current_user_can('manage_options')) {
5291 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5292 - }
5293 -
5294 - global $wpdb;
5295 - $table_name = $wpdb->prefix . 'mxchat_intents';
5296 -
5297 - $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
5298 - $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
5299 - $offset = ($page - 1) * $per_page;
5300 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
5301 - $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
5302 - $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
5303 -
5304 - // Build WHERE clause
5305 - $where = '1=1';
5306 - $params = array();
5307 -
5308 - if ($search) {
5309 - $search_like = '%' . $wpdb->esc_like($search) . '%';
5310 - $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
5311 - $params[] = $search_like;
5312 - $params[] = $search_like;
5313 - }
5314 -
5315 - if ($callback_filter) {
5316 - $where .= ' AND callback_function = %s';
5317 - $params[] = $callback_filter;
5318 - }
5319 -
5320 - // Get total count
5321 - $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
5322 - if (!empty($params)) {
5323 - $count_query = $wpdb->prepare($count_query, $params);
5324 - }
5325 - $total_actions = $wpdb->get_var($count_query);
5326 -
5327 - // Get actions
5328 - $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
5329 - $all_params = array_merge($params, array($per_page, $offset));
5330 - $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
5331 -
5332 - // Get available callbacks for labels/icons
5333 - $available_callbacks = $this->mxchat_get_available_callbacks();
5334 -
5335 - // Prefetch individual phrase counts for all fetched actions
5336 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5337 - $phrase_counts = array();
5338 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5339 - $action_ids = wp_list_pluck($actions, 'id');
5340 - if (!empty($action_ids)) {
5341 - $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5342 - $count_results = $wpdb->get_results($wpdb->prepare(
5343 - "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
5344 - $action_ids
5345 - ));
5346 - foreach ($count_results as $row) {
5347 - $phrase_counts[$row->intent_id] = intval($row->cnt);
5348 - }
5349 - }
5350 - }
5351 -
5352 - // Format actions for response
5353 - $formatted_actions = array();
5354 - foreach ($actions as $action) {
5355 - $callback_data = isset($available_callbacks[$action->callback_function])
5356 - ? $available_callbacks[$action->callback_function]
5357 - : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5358 -
5359 - $enabled_bots = json_decode($action->enabled_bots, true);
5360 - if (!is_array($enabled_bots)) {
5361 - $enabled_bots = array('default');
5362 - }
5363 -
5364 - $formatted_actions[] = array(
5365 - 'id' => intval($action->id),
5366 - 'label' => $action->intent_label,
5367 - 'phrases' => $action->phrases,
5368 - 'callback_function' => $action->callback_function,
5369 - 'callback_label' => $callback_data['label'],
5370 - 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5371 - 'threshold' => round($action->similarity_threshold * 100),
5372 - 'enabled' => (bool) $action->enabled,
5373 - 'enabled_bots' => $enabled_bots,
5374 - 'has_legacy_vector' => !empty($action->embedding_vector),
5375 - 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5376 - );
5377 - }
5378 -
5379 - $total_pages = ceil($total_actions / $per_page);
5380 - $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5381 - $showing_end = min($offset + $per_page, $total_actions);
5382 -
5383 - wp_send_json_success(array(
5384 - 'actions' => $formatted_actions,
5385 - 'page' => $page,
5386 - 'per_page' => $per_page,
5387 - 'total_actions' => intval($total_actions),
5388 - 'total_pages' => $total_pages,
5389 - 'showing_start' => $showing_start,
5390 - 'showing_end' => $showing_end,
5391 - ));
5392 -}
5393 -
5394 -/**
5395 - * AJAX handler to toggle action enabled status
5396 - */
5397 -public function mxchat_toggle_action_status() {
5398 - check_ajax_referer('mxchat_actions_nonce', 'security');
5399 -
5400 - if (!current_user_can('manage_options')) {
5401 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5402 - }
5403 -
5404 - $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5405 - $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
5406 -
5407 - if (!$action_id) {
5408 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5409 - }
5410 -
5411 - global $wpdb;
5412 - $table_name = $wpdb->prefix . 'mxchat_intents';
5413 -
5414 - $result = $wpdb->update(
5415 - $table_name,
5416 - array('enabled' => $enabled ? 1 : 0),
5417 - array('id' => $action_id),
5418 - array('%d'),
5419 - array('%d')
5420 - );
5421 -
5422 - if ($result === false) {
5423 - wp_send_json_error(__('Failed to update action status', 'mxchat'));
5424 - }
5425 -
5426 - wp_send_json_success(array('enabled' => (bool) $enabled));
5427 -}
5428 -
5429 -/**
5430 - * AJAX handler to bulk delete actions
5431 - */
5432 -public function mxchat_bulk_delete_actions() {
5433 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5434 -
5435 - if (!current_user_can('manage_options')) {
5436 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5437 - }
5438 -
5439 - $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5440 -
5441 - if (empty($action_ids)) {
5442 - wp_send_json_error(__('No actions selected', 'mxchat'));
5443 - }
5444 -
5445 - global $wpdb;
5446 - $table_name = $wpdb->prefix . 'mxchat_intents';
5447 -
5448 - $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5449 - $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5450 - $result = $wpdb->query($query);
5451 -
5452 - if ($result === false) {
5453 - wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5454 - }
5455 -
5456 - // Also delete individual phrases for these intents
5457 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5458 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5459 - $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5460 - }
5461 -
5462 - wp_send_json_success(array('deleted' => $result));
5463 -}
5464 -
5465 -/**
5466 - * AJAX handler to add a new intent/action
5467 - */
5468 -public function mxchat_add_intent_ajax() {
5469 - check_ajax_referer('mxchat_add_intent_nonce', 'security');
5470 -
5471 - if (!current_user_can('manage_options')) {
5472 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5473 - }
5474 -
5475 - global $wpdb;
5476 - $table_name = $wpdb->prefix . 'mxchat_intents';
5477 -
5478 - // Sanitize input
5479 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5480 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5481 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5482 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5483 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5484 -
5485 - // Validate
5486 - // Check if using new individual phrases mode or legacy mode
5487 - $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5488 - $use_individual = !empty($individual_phrases);
5489 -
5490 - // Validate required fields (phrases not required when using individual mode)
5491 - if (empty($intent_label) || empty($callback_function)) {
5492 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5493 - }
5494 - if (!$use_individual && empty($phrases_input)) {
5495 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5496 - }
5497 -
5498 - // Ensure default bot is included
5499 - if (!in_array('default', $enabled_bots)) {
5500 - $enabled_bots[] = 'default';
5501 - }
5502 - $enabled_bots_json = json_encode($enabled_bots);
5503 -
5504 - if ($use_individual) {
5505 - // New mode: individual phrases each get their own vector
5506 - // Insert the intent row with empty legacy fields
5507 - $result = $wpdb->insert(
5508 - $table_name,
5509 - array(
5510 - 'intent_label' => $intent_label,
5511 - 'phrases' => '',
5512 - 'embedding_vector' => '',
5513 - 'similarity_threshold' => $similarity_threshold,
5514 - 'callback_function' => $callback_function,
5515 - 'enabled' => 1,
5516 - 'enabled_bots' => $enabled_bots_json,
5517 - )
5518 - );
5519 -
5520 1180 if ($result === false) {
5521 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
1181 + wp_die(esc_html__('Database error: ', 'mxchat') . esc_html($wpdb->last_error));
5522 1182 }
5523 1183
5524 - $intent_id = $wpdb->insert_id;
5525 -
5526 - // Insert each phrase individually with its own embedding
5527 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5528 - $failed_phrases = array();
5529 - foreach ($individual_phrases as $phrase) {
5530 - $phrase = trim($phrase);
5531 - if (empty($phrase)) continue;
5532 -
5533 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5534 - if (is_wp_error($embedding_vector)) {
5535 - $failed_phrases[] = $phrase;
5536 - continue;
5537 - }
5538 -
5539 - $wpdb->insert(
5540 - $phrases_table,
5541 - array(
5542 - 'intent_id' => $intent_id,
5543 - 'phrase' => $phrase,
5544 - 'embedding_vector' => maybe_serialize($embedding_vector),
5545 - )
5546 - );
5547 - }
5548 -
5549 - $response = array('id' => $intent_id);
5550 - if (!empty($failed_phrases)) {
5551 - $response['failed_phrases'] = $failed_phrases;
5552 - }
5553 - wp_send_json_success($response);
5554 -
1184 + // Redirect to avoid resubmission
1185 + wp_safe_redirect($_SERVER['REQUEST_URI']);
1186 + exit;
5555 1187 } else {
5556 - // Legacy mode: combine all phrases into one embedding (backwards compatible)
5557 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5558 - if (empty($phrases_array)) {
5559 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5560 - }
5561 -
5562 - // Generate embedding (combine phrases into single string for embedding)
5563 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5564 - if (is_wp_error($embedding_vector)) {
5565 - // Fallback: store without embedding
5566 - $serialized_vector = null;
5567 - } else {
5568 - $serialized_vector = maybe_serialize($embedding_vector);
5569 - }
5570 -
5571 - // Insert
5572 - $result = $wpdb->insert(
5573 - $table_name,
5574 - array(
5575 - 'intent_label' => $intent_label,
5576 - 'phrases' => implode(', ', $phrases_array),
5577 - 'embedding_vector' => $serialized_vector,
5578 - 'similarity_threshold' => $similarity_threshold,
5579 - 'callback_function' => $callback_function,
5580 - 'enabled' => 1,
5581 - 'enabled_bots' => $enabled_bots_json,
5582 - )
5583 - );
5584 -
5585 - if ($result === false) {
5586 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5587 - }
5588 -
5589 - wp_send_json_success(array('id' => $wpdb->insert_id));
1188 + wp_die(esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5590 1189 }
5591 1190 }
5592 1191
5593 -/**
5594 - * AJAX handler to edit an existing intent/action
5595 - */
5596 -public function mxchat_edit_intent_ajax() {
5597 - check_ajax_referer('mxchat_edit_intent', 'security');
5598 1192
5599 - if (!current_user_can('manage_options')) {
5600 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5601 - }
5602 1193
5603 - global $wpdb;
5604 - $table_name = $wpdb->prefix . 'mxchat_intents';
5605 1194
5606 - // Sanitize input
5607 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5608 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5609 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5610 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5611 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5612 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5613 1195
5614 - // Validate
5615 - if (!$intent_id || empty($intent_label)) {
5616 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5617 - }
1196 +private function mxchat_get_available_callbacks() {
1197 + return [
1198 + 'mxchat_handle_email_capture' => [
1199 + 'label' => 'Email Capture',
1200 + 'pro_only' => false,
1201 + ],
1202 + 'mxchat_handle_product_inquiry' => [
1203 + 'label' => 'Show Product Card',
1204 + 'pro_only' => true,
1205 + ],
1206 + 'mxchat_handle_order_history' => [
1207 + 'label' => 'Order History',
1208 + 'pro_only' => true,
1209 + ],
1210 + 'mxchat_generate_image' => [
1211 + 'label' => 'Generate Image',
1212 + 'pro_only' => true,
1213 + ],
1214 + 'mxchat_handle_search_request' => [
1215 + 'label' => 'Brave Web Search',
1216 + 'pro_only' => false,
1217 + ],
1218 + 'mxchat_handle_image_search_request' => [
1219 + 'label' => 'Brave Image Search',
1220 + 'pro_only' => false,
1221 + ],
1222 + 'mxchat_handle_add_to_cart_intent' => [
1223 + 'label' => 'Add to Cart',
1224 + 'pro_only' => true,
1225 + ],
1226 + 'mxchat_handle_checkout_intent' => [
1227 + 'label' => 'Proceed to Checkout',
1228 + 'pro_only' => true,
1229 + ],
1230 + ];
1231 +}
5618 1232
5619 - // Check if phrases are managed individually (empty phrases_input means individual mode)
5620 - $uses_individual_phrases = empty($phrases_input);
5621 1233
5622 - if ($uses_individual_phrases) {
5623 - // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
5624 - $update_data = array(
5625 - 'intent_label' => $intent_label,
5626 - 'similarity_threshold' => $similarity_threshold,
5627 - 'callback_function' => $callback_function,
5628 - 'enabled_bots' => json_encode($enabled_bots),
5629 - );
5630 - } else {
5631 - // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
5632 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5633 - if (empty($phrases_array)) {
5634 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5635 - }
1234 +private function mxchat_average_vectors($vectors) {
1235 + $vector_length = count($vectors[0]);
1236 + $sum_vector = array_fill(0, $vector_length, 0);
5636 1237
5637 - // Generate new embedding (combine phrases into single string for embedding)
5638 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5639 - if (is_wp_error($embedding_vector)) {
5640 - // Keep existing embedding
5641 - $update_data = array(
5642 - 'intent_label' => $intent_label,
5643 - 'phrases' => implode(', ', $phrases_array),
5644 - 'similarity_threshold' => $similarity_threshold,
5645 - 'callback_function' => $callback_function,
5646 - 'enabled_bots' => json_encode($enabled_bots),
5647 - );
5648 - } else {
5649 - $serialized_vector = maybe_serialize($embedding_vector);
5650 - $update_data = array(
5651 - 'intent_label' => $intent_label,
5652 - 'phrases' => implode(', ', $phrases_array),
5653 - 'embedding_vector' => $serialized_vector,
5654 - 'similarity_threshold' => $similarity_threshold,
5655 - 'callback_function' => $callback_function,
5656 - 'enabled_bots' => json_encode($enabled_bots),
5657 - );
1238 + foreach ($vectors as $vector) {
1239 + for ($i = 0; $i < $vector_length; $i++) {
1240 + $sum_vector[$i] += $vector[$i];
5658 1241 }
5659 1242 }
5660 1243
5661 - // Ensure default bot is included
5662 - if (!in_array('default', $enabled_bots)) {
5663 - $enabled_bots[] = 'default';
1244 + // Divide each component by the number of vectors to get the average
1245 + $num_vectors = count($vectors);
1246 + for ($i = 0; $i < $vector_length; $i++) {
1247 + $sum_vector[$i] /= $num_vectors;
5664 1248 }
5665 - $update_data['enabled_bots'] = json_encode($enabled_bots);
5666 1249
5667 - $result = $wpdb->update(
5668 - $table_name,
5669 - $update_data,
5670 - array('id' => $intent_id),
5671 - null,
5672 - array('%d')
5673 - );
5674 -
5675 - if ($result === false) {
5676 - wp_send_json_error(__('Failed to update action.', 'mxchat'));
5677 - }
5678 -
5679 - wp_send_json_success(array('updated' => true));
1250 + return $sum_vector;
5680 1251 }
5681 1252
5682 -/**
5683 - * AJAX handler to delete a single intent/action
5684 - */
5685 -public function mxchat_delete_intent_ajax() {
5686 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
1253 +public function mxchat_handle_delete_intent() {
1254 + check_admin_referer('mxchat_delete_intent_nonce');
5687 1255
5688 - if (!current_user_can('manage_options')) {
5689 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5690 - }
1256 + if (isset($_POST['intent_id'])) {
1257 + global $wpdb;
1258 + $table_name = $wpdb->prefix . 'mxchat_intents';
1259 + $intent_id = intval($_POST['intent_id']);
5691 1260
5692 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5693 -
5694 - if (!$intent_id) {
5695 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
1261 + // Delete the intent from the database
1262 + $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5696 1263 }
5697 -
5698 - global $wpdb;
5699 - $table_name = $wpdb->prefix . 'mxchat_intents';
5700 -
5701 - $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
5702 -
5703 - if ($result === false) {
5704 - wp_send_json_error(__('Failed to delete action', 'mxchat'));
5705 - }
5706 -
5707 - // Also delete individual phrases for this intent
5708 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5709 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5710 - $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
5711 - }
5712 -
5713 - wp_send_json_success(array('deleted' => true));
5714 1264 }
5715 1265
5716 -/**
5717 - * AJAX handler to add a single phrase with its own embedding to an intent
5718 - */
5719 -public function mxchat_add_phrase_ajax() {
5720 - check_ajax_referer('mxchat_add_phrase_nonce', 'security');
5721 -
5722 - if (!current_user_can('manage_options')) {
5723 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5724 - }
5725 -
5726 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5727 - $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
5728 -
5729 - if (!$intent_id || empty($phrase)) {
5730 - wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
5731 - }
5732 -
5733 - // Verify the intent exists
5734 - global $wpdb;
5735 - $intents_table = $wpdb->prefix . 'mxchat_intents';
5736 - $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
5737 - if (!$intent) {
5738 - wp_send_json_error(__('Action not found.', 'mxchat'));
5739 - }
5740 -
5741 - // Generate embedding for this single phrase
5742 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5743 - if (is_wp_error($embedding_vector)) {
5744 - wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
5745 - }
5746 -
5747 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5748 - $result = $wpdb->insert(
5749 - $phrases_table,
5750 - array(
5751 - 'intent_id' => $intent_id,
5752 - 'phrase' => $phrase,
5753 - 'embedding_vector' => maybe_serialize($embedding_vector),
5754 - )
5755 - );
5756 -
5757 - if ($result === false) {
5758 - wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
5759 - }
5760 -
5761 - wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
5762 -}
5763 -
5764 -/**
5765 - * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
5766 - */
5767 -public function mxchat_delete_phrase_ajax() {
5768 - check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
5769 -
5770 - if (!current_user_can('manage_options')) {
5771 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5772 - }
5773 -
5774 - $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
5775 - if (!$phrase_id) {
5776 - wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
5777 - }
5778 -
5779 - global $wpdb;
5780 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5781 - $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
5782 -
5783 - if ($result === false) {
5784 - wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
5785 - }
5786 -
5787 - wp_send_json_success(array('deleted' => true));
5788 -}
5789 -
5790 -/**
5791 - * AJAX handler to fetch individual phrases for an intent
5792 - */
5793 -public function mxchat_get_phrases_ajax() {
5794 - check_ajax_referer('mxchat_get_phrases_nonce', 'security');
5795 -
5796 - if (!current_user_can('manage_options')) {
5797 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5798 - }
5799 -
5800 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5801 - if (!$intent_id) {
5802 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5803 - }
5804 -
5805 - global $wpdb;
5806 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5807 -
5808 - $phrases = array();
5809 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5810 - $phrases = $wpdb->get_results($wpdb->prepare(
5811 - "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
5812 - $intent_id
5813 - ));
5814 - }
5815 -
5816 - wp_send_json_success(array('phrases' => $phrases));
5817 -}
5818 -
5819 -/**
5820 - * AJAX handler to clear legacy phrases and embedding from the main intents table
5821 - */
5822 -public function mxchat_delete_legacy_phrases_ajax() {
5823 - check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
5824 -
5825 - if (!current_user_can('manage_options')) {
5826 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5827 - }
5828 -
5829 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5830 - if (!$intent_id) {
5831 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5832 - }
5833 -
5834 - global $wpdb;
5835 - $table_name = $wpdb->prefix . 'mxchat_intents';
5836 -
5837 - $result = $wpdb->update(
5838 - $table_name,
5839 - array('phrases' => '', 'embedding_vector' => ''),
5840 - array('id' => $intent_id),
5841 - array('%s', '%s'),
5842 - array('%d')
5843 - );
5844 -
5845 - if ($result === false) {
5846 - wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
5847 - }
5848 -
5849 - wp_send_json_success(array('cleared' => true));
5850 -}
5851 -
5852 -/**
5853 - * Enhanced get_available_callbacks function with form action exclusion
5854 - *
5855 - * @param bool $grouped Whether to return callbacks grouped by category
5856 - * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
5857 - * @return array Callbacks data with icons, descriptions and availability status
5858 - */
5859 -private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
5860 - // Load WordPress plugin functions if needed
5861 - if (!function_exists('get_plugins')) {
5862 - require_once ABSPATH . 'wp-admin/includes/plugin.php';
5863 - }
5864 -
5865 - // Get active plugins
5866 - $active_plugins = get_option('active_plugins', array());
5867 -
5868 - // Functions to exclude from the action selector only if Pro is activated
5869 - // If user doesn't have Pro, show these so they can see what they're missing
5870 - $excluded_when_pro_active_functions = array(
5871 - 'mxchat_handle_form_collection' // Forms add-on action
5872 - );
5873 -
5874 - // Always excluded functions (regardless of Pro status)
5875 - $always_excluded_functions = array();
5876 -
5877 - // Combine exclusion lists based on Pro activation status
5878 - $excluded_functions = $always_excluded_functions;
5879 - if ($this->is_activated) {
5880 - // Only exclude add-on managed functions if Pro is active
5881 - $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
5882 - }
5883 -
5884 - // Define add-on plugin files and their corresponding action functions
5885 - $addon_plugins = array(
5886 - 'mxchat-woo/mxchat-woo.php' => array(
5887 - 'functions' => array(
5888 - 'mxchat_handle_product_recommendations',
5889 - 'mxchat_handle_order_history',
5890 - 'mxchat_show_product_card',
5891 - 'mxchat_add_to_cart',
5892 - 'mxchat_checkout_redirect',
5893 - 'mxchat_handle_featured_products'
5894 - ),
5895 - 'name' => __('WooCommerce Add-on', 'mxchat'),
5896 - 'pro_required' => true
5897 - ),
5898 - 'mxchat-perplexity/mxchat-perplexity.php' => array(
5899 - 'functions' => array('mxchat_perplexity_research'),
5900 - 'name' => __('Perplexity Add-on', 'mxchat'),
5901 - 'pro_required' => true
5902 - ),
5903 - 'mxchat-forms/mxchat-forms.php' => array(
5904 - 'functions' => array('mxchat_handle_form_collection'),
5905 - 'name' => __('Forms Add-on', 'mxchat'),
5906 - 'pro_required' => true
5907 - ),
5908 - // Add other add-ons and their functions here
5909 - );
5910 -
5911 - // Get the functions that are provided by active add-ons
5912 - $addon_provided_functions = array();
5913 - $addon_function_mapping = array(); // Maps functions to their add-on info
5914 -
5915 - // Check which add-ons are active
5916 - foreach ($addon_plugins as $plugin_file => $addon_info) {
5917 - $is_active = in_array($plugin_file, $active_plugins);
5918 -
5919 - // For each function in this addon
5920 - foreach ($addon_info['functions'] as $function) {
5921 - // Consider a function installed only if:
5922 - // 1. The add-on is active AND
5923 - // 2. Either it doesn't require Pro OR Pro is activated
5924 - $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
5925 -
5926 - // If the add-on is installed, mark this function as provided by an add-on
5927 - if ($is_installed) {
5928 - $addon_provided_functions[] = $function;
5929 - }
5930 -
5931 - // Store addon info for this function regardless of installation status
5932 - $addon_function_mapping[$function] = array(
5933 - 'addon' => basename(dirname($plugin_file)),
5934 - 'addon_name' => $addon_info['name'],
5935 - 'pro_required' => $addon_info['pro_required'],
5936 - 'is_active' => $is_active,
5937 - 'is_installed' => $is_installed
5938 - );
5939 - }
5940 - }
5941 -
5942 - // Core callbacks - always available in the base plugin
5943 - $core_callbacks = array(
5944 - 'mxchat_handle_email_capture' => array(
5945 - 'label' => __('Loops Email Capture', 'mxchat'),
5946 - 'pro_only' => false,
5947 - 'group' => __('Customer Engagement', 'mxchat'),
5948 - 'icon' => 'email-alt',
5949 - 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
5950 - 'addon' => false, // Not from an add-on
5951 - 'installed' => true // Always installed with base plugin
5952 - ),
5953 - 'mxchat_handle_search_request' => array(
5954 - 'label' => __('Brave Web Search', 'mxchat'),
5955 - 'pro_only' => false,
5956 - 'group' => __('Search Features', 'mxchat'),
5957 - 'icon' => 'search',
5958 - 'description' => __('Let users search the web directly from the chat (requires a Brave Search API key)', 'mxchat'),
5959 - 'addon' => false,
5960 - 'installed' => true
5961 - ),
5962 - 'mxchat_handle_image_search_request' => array(
5963 - 'label' => __('Brave Image Search', 'mxchat'),
5964 - 'pro_only' => false,
5965 - 'group' => __('Search Features', 'mxchat'),
5966 - 'icon' => 'format-image',
5967 - 'description' => __('Search and display images in the chat conversation (requires a Brave Search API key)', 'mxchat'),
5968 - 'addon' => false,
5969 - 'installed' => true
5970 - ),
5971 - // Pro core features - check is_activated property
5972 - 'mxchat_generate_image' => array(
5973 - 'label' => __('Generate Image (OpenAI)', 'mxchat'),
5974 - 'pro_only' => false,
5975 - 'group' => __('Other Features', 'mxchat'),
5976 - 'icon' => 'art',
5977 - 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
5978 - 'addon' => false,
5979 - 'installed' => true
5980 - ),
5981 - 'mxchat_generate_gemini_image' => array(
5982 - 'label' => __('Generate Image (Gemini)', 'mxchat'),
5983 - 'pro_only' => false,
5984 - 'group' => __('Other Features', 'mxchat'),
5985 - 'icon' => 'art',
5986 - 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
5987 - 'addon' => false,
5988 - 'installed' => true
5989 - ),
5990 - 'mxchat_handle_pdf_discussion' => array(
5991 - 'label' => __('Chat with PDF', 'mxchat'),
5992 - 'pro_only' => false,
5993 - 'group' => __('Other Features', 'mxchat'),
5994 - 'icon' => 'media-document',
5995 - 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
5996 - 'addon' => false,
5997 - 'installed' => true
5998 - ),
5999 - 'mxchat_live_agent_handover' => array(
6000 - 'label' => __('Slack Live Agent', 'mxchat'),
6001 - 'pro_only' => false,
6002 - 'group' => __('Customer Engagement', 'mxchat'),
6003 - 'icon' => 'admin-users',
6004 - 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
6005 - 'addon' => false,
6006 - 'installed' => true
6007 - ),
6008 - 'mxchat_telegram_live_agent_handover' => array(
6009 - 'label' => __('Telegram Live Agent', 'mxchat'),
6010 - 'pro_only' => false,
6011 - 'group' => __('Customer Engagement', 'mxchat'),
6012 - 'icon' => 'format-chat',
6013 - 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
6014 - 'addon' => false,
6015 - 'installed' => true
6016 - ),
6017 - 'mxchat_handle_switch_to_chatbot_intent' => array(
6018 - 'label' => __('Back to Chatbot', 'mxchat'),
6019 - 'pro_only' => false,
6020 - 'group' => __('Customer Engagement', 'mxchat'),
6021 - 'icon' => 'backup',
6022 - 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
6023 - 'addon' => false,
6024 - 'installed' => true
6025 - ),
6026 - );
6027 -
6028 - // Add-on callbacks with placeholders - only include if the add-on is NOT active
6029 - // These are promotional/informational only — not selectable as real actions
6030 - $addon_callbacks = array(
6031 - // WooCommerce Add-on
6032 - 'mxchat_handle_product_recommendations' => array(
6033 - 'label' => __('Product Recommendations', 'mxchat'),
6034 - 'pro_only' => false,
6035 - 'addon_promo' => true,
6036 - 'group' => __('WooCommerce Features', 'mxchat'),
6037 - 'icon' => 'cart',
6038 - 'description' => __('Suggest products based on customer preferences', 'mxchat'),
6039 - ),
6040 - 'mxchat_handle_order_history' => array(
6041 - 'label' => __('Order History', 'mxchat'),
6042 - 'pro_only' => false,
6043 - 'addon_promo' => true,
6044 - 'group' => __('WooCommerce Features', 'mxchat'),
6045 - 'icon' => 'clipboard',
6046 - 'description' => __('Allow customers to check their order status', 'mxchat'),
6047 - ),
6048 - 'mxchat_show_product_card' => array(
6049 - 'label' => __('Show Product Card', 'mxchat'),
6050 - 'pro_only' => false,
6051 - 'addon_promo' => true,
6052 - 'group' => __('WooCommerce Features', 'mxchat'),
6053 - 'icon' => 'products',
6054 - 'description' => __('Display product information in the chat', 'mxchat'),
6055 - ),
6056 - 'mxchat_add_to_cart' => array(
6057 - 'label' => __('Add to Cart', 'mxchat'),
6058 - 'pro_only' => false,
6059 - 'addon_promo' => true,
6060 - 'group' => __('WooCommerce Features', 'mxchat'),
6061 - 'icon' => 'plus-alt',
6062 - 'description' => __('Add products to cart directly from chat', 'mxchat'),
6063 - ),
6064 - 'mxchat_checkout_redirect' => array(
6065 - 'label' => __('Proceed to Checkout', 'mxchat'),
6066 - 'pro_only' => false,
6067 - 'addon_promo' => true,
6068 - 'group' => __('WooCommerce Features', 'mxchat'),
6069 - 'icon' => 'arrow-right-alt',
6070 - 'description' => __('Redirect customer to checkout page', 'mxchat'),
6071 - ),
6072 - 'mxchat_handle_featured_products' => array(
6073 - 'label' => __('Featured Products Showcase', 'mxchat'),
6074 - 'pro_only' => false,
6075 - 'addon_promo' => true,
6076 - 'group' => __('WooCommerce Features', 'mxchat'),
6077 - 'icon' => 'star-filled',
6078 - 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
6079 - ),
6080 -
6081 - // Perplexity Add-on
6082 - 'mxchat_perplexity_research' => array(
6083 - 'label' => __('Perplexity Research', 'mxchat'),
6084 - 'pro_only' => false,
6085 - 'addon_promo' => true,
6086 - 'group' => __('Search Features', 'mxchat'),
6087 - 'icon' => 'book-alt',
6088 - 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
6089 - ),
6090 -
6091 - // Forms Add-on
6092 - 'mxchat_handle_form_collection' => array(
6093 - 'label' => __('Form Collection', 'mxchat'),
6094 - 'pro_only' => false,
6095 - 'addon_promo' => true,
6096 - 'group' => __('Form Features', 'mxchat'),
6097 - 'icon' => 'feedback',
6098 - 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
6099 - ),
6100 - );
6101 -
6102 - // Enhance add-on callbacks with installation status and addon info
6103 - foreach ($addon_callbacks as $function => $data) {
6104 - if (isset($addon_function_mapping[$function])) {
6105 - $addon_info = $addon_function_mapping[$function];
6106 -
6107 - $addon_callbacks[$function]['addon'] = $addon_info['addon'];
6108 - $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6109 - $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
6110 -
6111 - // Set pro_only based on add-on configuration
6112 - $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6113 - } else {
6114 - $addon_callbacks[$function]['addon'] = 'unknown';
6115 - $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
6116 - $addon_callbacks[$function]['installed'] = false;
6117 - }
6118 - }
6119 -
6120 - // Initialize callbacks with core features
6121 - $callbacks = $core_callbacks;
6122 -
6123 - // Get callbacks from active add-ons
6124 - $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
6125 -
6126 - // Add placeholder callbacks only for add-ons that aren't active
6127 - if ($include_all) {
6128 - foreach ($addon_callbacks as $function => $data) {
6129 - // Skip placeholders for functions provided by active add-ons
6130 - if (in_array($function, $addon_provided_functions)) {
6131 - continue;
6132 - }
6133 -
6134 - // Skip excluded functions
6135 - if (in_array($function, $excluded_functions)) {
6136 - continue;
6137 - }
6138 -
6139 - // Add the placeholder
6140 - $callbacks[$function] = $data;
6141 - }
6142 - }
6143 -
6144 - // Add callbacks from active add-ons (will override placeholders)
6145 - foreach ($active_addon_callbacks as $function => $data) {
6146 - // Skip excluded functions
6147 - if (in_array($function, $excluded_functions)) {
6148 - continue;
6149 - }
6150 -
6151 - // Always include callbacks from add-ons
6152 - $callbacks[$function] = $data;
6153 -
6154 - // Ensure they have the proper add-on info
6155 - if (isset($addon_function_mapping[$function])) {
6156 - $addon_info = $addon_function_mapping[$function];
6157 - $callbacks[$function]['addon'] = $addon_info['addon'];
6158 - $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6159 - $callbacks[$function]['installed'] = $addon_info['is_installed'];
6160 - $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6161 - }
6162 - }
6163 -
6164 - // Just before returning callbacks, sort them to prioritize free features
6165 - if (!$grouped) {
6166 - // Create temporary arrays for sorting
6167 - $free_callbacks = array();
6168 - $pro_callbacks = array();
6169 -
6170 - // Split callbacks into free and pro
6171 - foreach ($callbacks as $key => $data) {
6172 - if (isset($data['pro_only']) && $data['pro_only']) {
6173 - $pro_callbacks[$key] = $data;
6174 - } else {
6175 - $free_callbacks[$key] = $data;
6176 - }
6177 - }
6178 -
6179 - // Merge with free callbacks first
6180 - $callbacks = array_merge($free_callbacks, $pro_callbacks);
6181 - }
6182 -
6183 - // Return grouped structure if requested
6184 - if ($grouped) {
6185 - $grouped_callbacks = array();
6186 - foreach ($callbacks as $key => $data) {
6187 - $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
6188 -
6189 - // Ensure we carry forward all the new fields in grouped mode
6190 - $callback_data = array(
6191 - 'label' => $data['label'],
6192 - 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
6193 - 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
6194 - 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
6195 - 'addon' => isset($data['addon']) ? $data['addon'] : false,
6196 - 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
6197 - 'installed' => isset($data['installed']) ? $data['installed'] : true
6198 - );
6199 -
6200 - $grouped_callbacks[$group_label][$key] = $callback_data;
6201 - }
6202 -
6203 - // Sort within each group to prioritize free features
6204 - foreach ($grouped_callbacks as $group => $items) {
6205 - $free_items = array();
6206 - $pro_items = array();
6207 -
6208 - foreach ($items as $key => $data) {
6209 - if (isset($data['pro_only']) && $data['pro_only']) {
6210 - $pro_items[$key] = $data;
6211 - } else {
6212 - $free_items[$key] = $data;
6213 - }
6214 - }
6215 -
6216 - $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
6217 - }
6218 -
6219 - return $grouped_callbacks;
6220 - }
6221 -
6222 - return $callbacks;
6223 -}
6224 -
6225 1266 public function mxchat_page_init() {
1267 + // Register settings
6226 1268 register_setting(
6227 1269 'mxchat_option_group',
6228 1270 'mxchat_options',
6229 1271 array($this, 'mxchat_sanitize')
@@ -6228,207 +1270,53 @@
6228 1270 'mxchat_options',
6229 1271 array($this, 'mxchat_sanitize')
6230 1272 );
6231 1273
6232 - register_setting(
6233 - 'mxchat_option_group',
6234 - 'mxchat_similarity_threshold',
6235 - array(
6236 - 'type' => 'number',
6237 - 'sanitize_callback' => function($value) {
6238 - $value = absint($value);
6239 - return min(max($value, 20), 95);
6240 - },
6241 - 'default' => 80,
6242 - )
6243 - );
6244 -
6245 1274 // Chatbot Settings Section
6246 1275 add_settings_section(
6247 1276 'mxchat_chatbot_section',
6248 - esc_html__('Chatbot Settings', 'mxchat'),
1277 + 'Chatbot Settings',
6249 1278 null,
6250 1279 'mxchat-chatbot'
6251 1280 );
6252 1281
6253 - // API Keys Settings Section
6254 - add_settings_section(
6255 - 'mxchat_api_keys_section',
6256 - esc_html__('API Keys', 'mxchat'),
6257 - array($this, 'mxchat_api_keys_section_callback'),
6258 - 'mxchat-api-keys'
6259 - );
6260 -
6261 - // OpenAI API Key
1282 + // Registering fields for the Chatbot Settings section
6262 1283 add_settings_field(
6263 1284 'api_key',
6264 - esc_html__('OpenAI API Key', 'mxchat'),
1285 + 'OpenAI API Key',
6265 1286 array($this, 'api_key_callback'),
6266 - 'mxchat-api-keys',
6267 - 'mxchat_api_keys_section'
1287 + 'mxchat-chatbot',
1288 + 'mxchat_chatbot_section'
6268 1289 );
6269 1290
6270 - // X.AI API Key
6271 1291 add_settings_field(
6272 - 'xai_api_key',
6273 - esc_html__('X.AI API Key', 'mxchat'),
6274 - array($this, 'xai_api_key_callback'),
6275 - 'mxchat-api-keys',
6276 - 'mxchat_api_keys_section'
1292 + 'xai_api_key',
1293 + 'X.AI API Key',
1294 + array($this, 'xai_api_key_callback'),
1295 + 'mxchat-chatbot',
1296 + 'mxchat_chatbot_section'
6277 1297 );
6278 1298
6279 - // Claude API Key
6280 1299 add_settings_field(
6281 1300 'claude_api_key',
6282 - esc_html__('Claude API Key', 'mxchat'),
1301 + 'Claude API Key',
6283 1302 array($this, 'claude_api_key_callback'),
6284 - 'mxchat-api-keys',
6285 - 'mxchat_api_keys_section'
6286 - );
6287 -
6288 - // DeepSeek API Key
6289 - add_settings_field(
6290 - 'deepseek_api_key',
6291 - esc_html__('DeepSeek API Key', 'mxchat'),
6292 - array($this, 'deepseek_api_key_callback'),
6293 - 'mxchat-api-keys',
6294 - 'mxchat_api_keys_section'
6295 - );
6296 -
6297 - // Google Gemini API Key
6298 - add_settings_field(
6299 - 'gemini_api_key',
6300 - esc_html__('Google Gemini API Key', 'mxchat'),
6301 - array($this, 'gemini_api_key_callback'),
6302 - 'mxchat-api-keys',
6303 - 'mxchat_api_keys_section'
6304 - );
6305 -
6306 - // Voyage AI API Key
6307 - add_settings_field(
6308 - 'voyage_api_key',
6309 - esc_html__('Voyage AI API Key', 'mxchat'),
6310 - array($this, 'voyage_api_key_callback'),
6311 - 'mxchat-api-keys',
6312 - 'mxchat_api_keys_section'
6313 - );
6314 -
6315 - // OpenRouter API Key
6316 - add_settings_field(
6317 - 'openrouter_api_key',
6318 - esc_html__('OpenRouter API Key', 'mxchat'),
6319 - array($this, 'openrouter_api_key_callback'),
6320 - 'mxchat-api-keys',
6321 - 'mxchat_api_keys_section'
6322 - );
6323 -
6324 - // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6325 - add_settings_field(
6326 - 'custom_provider',
6327 - esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
6328 - array($this, 'custom_provider_callback'),
6329 - 'mxchat-api-keys',
6330 - 'mxchat_api_keys_section'
6331 - );
6332 -
6333 - // Loops API Key
6334 - add_settings_field(
6335 - 'loops_api_key',
6336 - esc_html__('Loops API Key', 'mxchat'),
6337 - array($this, 'mxchat_loops_api_key_callback'),
6338 - 'mxchat-api-keys',
6339 - 'mxchat_api_keys_section'
6340 - );
6341 -
6342 - // Brave Search API Key
6343 - add_settings_field(
6344 - 'brave_api_key',
6345 - __('Brave API Key', 'mxchat'),
6346 - array($this, 'mxchat_brave_api_key_callback'),
6347 - 'mxchat-api-keys',
6348 - 'mxchat_api_keys_section'
6349 - );
6350 -
6351 - // Similarity Threshold Slider
6352 - add_settings_field(
6353 - 'similarity_threshold', // Field ID
6354 - esc_html__('Similarity Threshold', 'mxchat'), // Field title
6355 - array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6356 - 'mxchat-chatbot', // Page
6357 - 'mxchat_chatbot_section' // Section
6358 - );
6359 -
6360 - // RAG Sources Limit Slider
6361 - add_settings_field(
6362 - 'rag_sources_limit', // Field ID
6363 - esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6364 - array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6365 - 'mxchat-chatbot', // Page
6366 - 'mxchat_chatbot_section' // Section
6367 - );
6368 -
6369 - // RAG Chunks Limit Slider
6370 - add_settings_field(
6371 - 'rag_chunks_limit', // Field ID
6372 - esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6373 - array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6374 - 'mxchat-chatbot', // Page
6375 - 'mxchat_chatbot_section' // Section
6376 - );
6377 -
6378 - add_settings_field(
6379 - 'append_to_body',
6380 - esc_html__('Auto-Display Chatbot', 'mxchat'),
6381 - array($this, 'mxchat_append_to_body_callback'),
6382 1303 'mxchat-chatbot',
6383 1304 'mxchat_chatbot_section'
6384 1305 );
6385 1306
6386 - add_settings_field(
6387 - 'contextual_awareness_toggle',
6388 - esc_html__('Contextual Awareness', 'mxchat'),
6389 - array($this, 'mxchat_contextual_awareness_callback'),
6390 - 'mxchat-chatbot',
6391 - 'mxchat_chatbot_section'
6392 - );
6393 1307
6394 1308 add_settings_field(
6395 - 'citation_links_toggle',
6396 - esc_html__('Citation Links', 'mxchat'),
6397 - array($this, 'mxchat_citation_links_toggle_callback'),
1309 + 'system_prompt_instructions',
1310 + 'AI Instructions',
1311 + array($this, 'system_prompt_instructions_callback'),
6398 1312 'mxchat-chatbot',
6399 1313 'mxchat_chatbot_section'
6400 1314 );
6401 1315
6402 - // Satisfaction rating toggle (plan-a5b006).
6403 1316 add_settings_field(
6404 - 'satisfaction_rating_enabled',
6405 - esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6406 - array($this, 'mxchat_satisfaction_rating_toggle_callback'),
6407 - 'mxchat-chatbot',
6408 - 'mxchat_chatbot_section'
6409 - );
6410 -
6411 - // Satisfaction rating customization (plan-141a12, plan-29caac):
6412 - // the 5 customization fields are now inline-rendered inside
6413 - // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6414 -
6415 - add_settings_field(
6416 - 'enable_streaming_toggle',
6417 - esc_html__('Enable Streaming', 'mxchat'),
6418 - array($this, 'enable_streaming_toggle_callback'),
6419 - 'mxchat-chatbot',
6420 - 'mxchat_chatbot_section', // Same section as your working toggle
6421 - array(
6422 - 'class' => 'mxchat-setting-row streaming-setting',
6423 - 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6424 - )
6425 - );
6426 -
6427 -
6428 - add_settings_field(
6429 1317 'model',
6430 - esc_html__('Chat Model', 'mxchat'),
1318 + 'Model',
6431 1319 array($this, 'mxchat_model_callback'),
6432 1320 'mxchat-chatbot',
6433 1321 'mxchat_chatbot_section'
6434 1322 );
@@ -6433,27 +1321,10 @@
6433 1321 'mxchat_chatbot_section'
6434 1322 );
6435 1323
6436 1324 add_settings_field(
6437 - 'embedding_model',
6438 - esc_html__('Embedding Model', 'mxchat'),
6439 - array($this, 'embedding_model_callback'),
6440 - 'mxchat-chatbot',
6441 - 'mxchat_chatbot_section'
6442 - );
6443 -
6444 - add_settings_field(
6445 - 'system_prompt_instructions',
6446 - esc_html__('AI Instructions (Behavior)', 'mxchat'),
6447 - array($this, 'system_prompt_instructions_callback'),
6448 - 'mxchat-chatbot',
6449 - 'mxchat_chatbot_section'
6450 - );
6451 -
6452 -
6453 - add_settings_field(
6454 1325 'top_bar_title',
6455 - esc_html__('Top Bar Title', 'mxchat'),
1326 + 'Top Bar Title',
6456 1327 array($this, 'mxchat_top_bar_title_callback'),
6457 1328 'mxchat-chatbot',
6458 1329 'mxchat_chatbot_section'
6459 1330 );
@@ -6458,82 +1329,58 @@
6458 1329 'mxchat_chatbot_section'
6459 1330 );
6460 1331
6461 1332 add_settings_field(
6462 - 'ai_agent_text',
6463 - esc_html__('AI Agent Text', 'mxchat'),
6464 - array($this, 'mxchat_ai_agent_text_callback'),
1333 + 'intro_message',
1334 + 'Introductory Message',
1335 + array($this, 'mxchat_intro_message_callback'),
6465 1336 'mxchat-chatbot',
6466 1337 'mxchat_chatbot_section'
6467 1338 );
6468 1339
6469 1340 add_settings_field(
6470 - 'enable_email_block',
6471 - esc_html__('Require Email To Chat', 'mxchat'),
6472 - array($this, 'enable_email_block_callback'),
1341 + 'input_copy',
1342 + 'Input Copy',
1343 + array($this, 'mxchat_input_copy_callback'),
6473 1344 'mxchat-chatbot',
6474 1345 'mxchat_chatbot_section'
6475 1346 );
6476 1347
6477 1348 add_settings_field(
6478 - 'email_blocker_header_content',
6479 - esc_html__('Require Email Chat Content', 'mxchat'),
6480 - array($this, 'email_blocker_header_content_callback'),
1349 + 'rate_limit',
1350 + 'Rate Limit',
1351 + array($this, 'mxchat_rate_limit_callback'),
6481 1352 'mxchat-chatbot',
6482 1353 'mxchat_chatbot_section'
6483 1354 );
6484 1355
6485 1356 add_settings_field(
6486 - 'email_blocker_button_text',
6487 - esc_html__('Require Email Chat Button Text', 'mxchat'),
6488 - [$this, 'email_blocker_button_text_callback'],
1357 + 'rate_limit_message',
1358 + 'Rate Limit Message',
1359 + array($this, 'mxchat_rate_limit_message_callback'),
6489 1360 'mxchat-chatbot',
6490 1361 'mxchat_chatbot_section'
6491 1362 );
6492 1363
6493 1364 add_settings_field(
6494 - 'enable_name_field',
6495 - esc_html__('Require Name Field', 'mxchat'),
6496 - array($this, 'enable_name_field_callback'),
1365 + 'pre_chat_message',
1366 + 'Pre-Chat Message',
1367 + array($this, 'mxchat_pre_chat_message_callback'),
6497 1368 'mxchat-chatbot',
6498 1369 'mxchat_chatbot_section'
6499 1370 );
6500 1371
6501 - add_settings_field(
6502 - 'name_field_placeholder',
6503 - esc_html__('Name Field Placeholder', 'mxchat'),
6504 - array($this, 'name_field_placeholder_callback'),
1372 + add_settings_field(
1373 + 'append_to_body',
1374 + 'Append Chat Widget to Body',
1375 + array($this, 'mxchat_append_to_body_callback'),
6505 1376 'mxchat-chatbot',
6506 1377 'mxchat_chatbot_section'
6507 1378 );
6508 1379
6509 - add_settings_field(
6510 - 'intro_message',
6511 - esc_html__('Introductory Message', 'mxchat'),
6512 - array($this, 'mxchat_intro_message_callback'),
6513 - 'mxchat-chatbot',
6514 - 'mxchat_chatbot_section'
6515 - );
6516 -
6517 - add_settings_field(
6518 - 'input_copy',
6519 - esc_html__('Input Copy', 'mxchat'),
6520 - array($this, 'mxchat_input_copy_callback'),
6521 - 'mxchat-chatbot',
6522 - 'mxchat_chatbot_section'
6523 - );
6524 -
6525 - add_settings_field(
6526 - 'pre_chat_message',
6527 - esc_html__('Chat Teaser Pop-up', 'mxchat'),
6528 - array($this, 'mxchat_pre_chat_message_callback'),
6529 - 'mxchat-chatbot',
6530 - 'mxchat_chatbot_section'
6531 - );
6532 -
6533 - add_settings_field(
1380 + add_settings_field(
6534 1381 'privacy_toggle',
6535 - esc_html__('Toggle Privacy Notice', 'mxchat'),
1382 + 'Toggle Privacy Notice',
6536 1383 array($this, 'mxchat_privacy_toggle_callback'),
6537 1384 'mxchat-chatbot',
6538 1385 'mxchat_chatbot_section'
6539 1386 );
@@ -6539,9 +1386,9 @@
6539 1386 );
6540 1387
6541 1388 add_settings_field(
6542 1389 'complianz_toggle',
6543 - esc_html__('Enable Complianz', 'mxchat'),
1390 + 'Enable Complianz',
6544 1391 array($this, 'mxchat_complianz_toggle_callback'),
6545 1392 'mxchat-chatbot',
6546 1393 'mxchat_chatbot_section'
6547 1394 );
@@ -6547,9 +1394,9 @@
6547 1394 );
6548 1395
6549 1396 add_settings_field(
6550 1397 'link_target_toggle',
6551 - esc_html__('Open Links in a New Tab', 'mxchat'),
1398 + 'Open Links in a New Tab',
6552 1399 array($this, 'mxchat_link_target_toggle_callback'),
6553 1400 'mxchat-chatbot',
6554 1401 'mxchat_chatbot_section'
6555 1402 );
@@ -6554,114 +1401,118 @@
6554 1401 'mxchat_chatbot_section'
6555 1402 );
6556 1403
6557 1404 add_settings_field(
6558 - 'chat_persistence_toggle',
6559 - esc_html__('Enable Chat Persistence', 'mxchat'),
6560 - array($this, 'mxchat_chat_persistence_toggle_callback'),
6561 - 'mxchat-chatbot',
6562 - 'mxchat_chatbot_section'
1405 + 'chat_persistence_toggle',
1406 + 'Enable Chat Persistence',
1407 + array($this, 'mxchat_chat_persistence_toggle_callback'),
1408 + 'mxchat-chatbot',
1409 + 'mxchat_chatbot_section'
6563 1410 );
6564 1411
6565 1412 add_settings_field(
6566 - 'print_button_enabled',
6567 - esc_html__('Show Download Transcript Button', 'mxchat'),
6568 - array($this, 'mxchat_print_button_toggle_callback'),
6569 - 'mxchat-chatbot',
6570 - 'mxchat_chatbot_section'
6571 - );
1413 + 'popular_question_1',
1414 + 'Popular Question 1',
1415 + array($this, 'mxchat_popular_question_1_callback'),
1416 + 'mxchat-chatbot',
1417 + 'mxchat_chatbot_section'
1418 +);
6572 1419
6573 - add_settings_field(
6574 - 'reset_chat_enabled',
6575 - esc_html__('Show Start-New-Chat Button', 'mxchat'),
6576 - array($this, 'mxchat_reset_chat_toggle_callback'),
6577 - 'mxchat-chatbot',
6578 - 'mxchat_chatbot_section'
6579 - );
1420 +add_settings_field(
1421 + 'popular_question_2',
1422 + 'Popular Question 2',
1423 + array($this, 'mxchat_popular_question_2_callback'),
1424 + 'mxchat-chatbot',
1425 + 'mxchat_chatbot_section'
1426 +);
6580 1427
6581 - add_settings_field(
6582 - 'reset_chat_label',
6583 - esc_html__('Start-New-Chat Button Label', 'mxchat'),
6584 - array($this, 'mxchat_reset_chat_label_callback'),
6585 - 'mxchat-chatbot',
6586 - 'mxchat_chatbot_section'
6587 - );
1428 +add_settings_field(
1429 + 'popular_question_3',
1430 + 'Popular Question 3',
1431 + array($this, 'mxchat_popular_question_3_callback'),
1432 + 'mxchat-chatbot',
1433 + 'mxchat_chatbot_section'
1434 +);
6588 1435
6589 - add_settings_field(
6590 - 'popular_question_1',
6591 - esc_html__('Quick Question 1', 'mxchat'),
6592 - array($this, 'mxchat_popular_question_1_callback'),
6593 - 'mxchat-chatbot',
6594 - 'mxchat_chatbot_section'
6595 - );
6596 1436
6597 - add_settings_field(
6598 - 'popular_question_2',
6599 - esc_html__('Quick Question 2', 'mxchat'),
6600 - array($this, 'mxchat_popular_question_2_callback'),
6601 - 'mxchat-chatbot',
6602 - 'mxchat_chatbot_section'
6603 - );
6604 1437
6605 - add_settings_field(
6606 - 'popular_question_3',
6607 - esc_html__('Quick Question 3', 'mxchat'),
6608 - array($this, 'mxchat_popular_question_3_callback'),
6609 - 'mxchat-chatbot',
6610 - 'mxchat_chatbot_section'
6611 - );
1438 +// WooCommerce Settings Section
1439 +add_settings_section(
1440 + 'mxchat_woocommerce_section',
1441 + 'WooCommerce Settings',
1442 + null,
1443 + 'mxchat-embed'
1444 +);
6612 1445
6613 - add_settings_field(
6614 - 'additional_popular_questions',
6615 - esc_html__('Additional Quick Questions', 'mxchat'),
6616 - array($this, 'mxchat_additional_popular_questions_callback'),
6617 - 'mxchat-chatbot',
6618 - 'mxchat_chatbot_section'
6619 - );
1446 +// Loops Settings Section
1447 +add_settings_section(
1448 + 'mxchat_loops_section',
1449 + 'Loops Settings',
1450 + null,
1451 + 'mxchat-embed'
1452 +);
6620 1453
1454 +// WooCommerce Settings Fields
1455 +add_settings_field(
1456 + 'enable_woocommerce_integration',
1457 + 'Automatically Embed Products',
1458 + array($this, 'mxchat_enable_woocommerce_integration_callback'),
1459 + 'mxchat-embed',
1460 + 'mxchat_woocommerce_section'
1461 +);
6621 1462
6622 - add_settings_field(
6623 - 'rate_limits',
6624 - __('Rate Limits Settings', 'mxchat'),
6625 - array($this, 'mxchat_rate_limits_callback'),
6626 - 'mxchat-chatbot',
6627 - 'mxchat_chatbot_section'
6628 - );
6629 1463
6630 - // Loops Settings Section
6631 - add_settings_section(
6632 - 'mxchat_loops_section',
6633 - esc_html__('Loops Settings', 'mxchat'),
6634 - null,
6635 - 'mxchat-embed'
6636 - );
1464 +add_settings_field(
1465 + 'woocommerce_consumer_key',
1466 + 'WooCommerce Consumer Key',
1467 + array($this, 'mxchat_woocommerce_consumer_key_callback'),
1468 + 'mxchat-embed',
1469 + 'mxchat_woocommerce_section'
1470 +);
6637 1471
6638 - // Loops Settings Fields (API Key moved to API Keys tab)
6639 - add_settings_field(
6640 - 'loops_mailing_list',
6641 - esc_html__('Loops Mailing List', 'mxchat'),
6642 - array($this, 'mxchat_loops_mailing_list_callback'),
6643 - 'mxchat-embed',
6644 - 'mxchat_loops_section'
6645 - );
1472 +add_settings_field(
1473 + 'woocommerce_consumer_secret',
1474 + 'WooCommerce Consumer Secret',
1475 + array($this, 'mxchat_woocommerce_consumer_secret_callback'),
1476 + 'mxchat-embed',
1477 + 'mxchat_woocommerce_section'
1478 +);
6646 1479
6647 - add_settings_field(
6648 - 'triggered_phrase_response',
6649 - esc_html__('Triggered Phrase Response', 'mxchat'),
6650 - array($this, 'mxchat_triggered_phrase_response_callback'),
6651 - 'mxchat-embed',
6652 - 'mxchat_loops_section'
6653 - );
1480 +// Loops Settings Fields
1481 +add_settings_field(
1482 + 'loops_api_key',
1483 + 'Loops API Key',
1484 + array($this, 'mxchat_loops_api_key_callback'),
1485 + 'mxchat-embed',
1486 + 'mxchat_loops_section'
1487 +);
6654 1488
6655 - add_settings_field(
6656 - 'email_capture_response',
6657 - esc_html__('Email Capture Response', 'mxchat'),
6658 - array($this, 'mxchat_email_capture_response_callback'),
6659 - 'mxchat-embed',
6660 - 'mxchat_loops_section'
6661 - );
1489 +add_settings_field(
1490 + 'loops_mailing_list',
1491 + 'Loops Mailing List',
1492 + array($this, 'mxchat_loops_mailing_list_callback'),
1493 + 'mxchat-embed',
1494 + 'mxchat_loops_section'
1495 +);
6662 1496
6663 - // Brave Search Settings Fields
1497 +add_settings_field(
1498 + 'triggered_phrase_response',
1499 + 'Triggered Phrase Response',
1500 + array($this, 'mxchat_triggered_phrase_response_callback'),
1501 + 'mxchat-embed',
1502 + 'mxchat_loops_section'
1503 +);
1504 +
1505 +add_settings_field(
1506 + 'email_capture_response',
1507 + 'Email Capture Response',
1508 + array($this, 'mxchat_email_capture_response_callback'),
1509 + 'mxchat-embed',
1510 + 'mxchat_loops_section'
1511 +);
1512 +
1513 +
1514 + // Brave Search Settings Fields
6664 1515 add_settings_section(
6665 1516 'mxchat_brave_section',
6666 1517 __('Brave Search Settings', 'mxchat'),
6667 1518 array($this, 'mxchat_brave_section_callback'),
@@ -6667,10 +1518,17 @@
6667 1518 array($this, 'mxchat_brave_section_callback'),
6668 1519 'mxchat-embed'
6669 1520 );
6670 1521
6671 - // Brave API Key moved to API Keys tab
6672 1522 add_settings_field(
1523 + 'brave_api_key',
1524 + __('Brave API Key', 'mxchat'),
1525 + array($this, 'mxchat_brave_api_key_callback'),
1526 + 'mxchat-embed',
1527 + 'mxchat_brave_section'
1528 + );
1529 +
1530 + add_settings_field(
6673 1531 'brave_image_count',
6674 1532 __('Number of Images to Return', 'mxchat'),
6675 1533 array($this, 'mxchat_brave_image_count_callback'),
6676 1534 'mxchat-embed',
@@ -6708,545 +1566,202 @@
6708 1566 'mxchat-embed',
6709 1567 'mxchat_brave_section'
6710 1568 );
6711 1569
6712 - // Chat with PDF Intent Settings Fields
6713 - add_settings_section(
6714 - 'mxchat_pdf_intent_section',
6715 - __('Toolbar Settings & Intents', 'mxchat'),
6716 - array($this, 'mxchat_pdf_intent_section_callback'),
6717 - 'mxchat-embed'
6718 - );
6719 1570
6720 - add_settings_field(
6721 - 'chat_toolbar_toggle',
6722 - __('Show Chat Toolbar', 'mxchat'),
6723 - array($this, 'mxchat_chat_toolbar_toggle_callback'),
6724 - 'mxchat-embed',
6725 - 'mxchat_pdf_intent_section'
6726 - );
6727 1571
6728 - // PDF Upload Button Toggle
6729 - add_settings_field(
6730 - 'show_pdf_upload_button',
6731 - __('Show PDF Upload Button', 'mxchat'),
6732 - array($this, 'mxchat_show_pdf_upload_button_callback'),
6733 - 'mxchat-embed',
6734 - 'mxchat_pdf_intent_section'
6735 - );
6736 -
6737 - // Word Upload Button Toggle
6738 - add_settings_field(
6739 - 'show_word_upload_button',
6740 - __('Show Word Upload Button', 'mxchat'),
6741 - array($this, 'mxchat_show_word_upload_button_callback'),
6742 - 'mxchat-embed',
6743 - 'mxchat_pdf_intent_section'
6744 - );
6745 -
6746 - add_settings_field(
6747 - 'pdf_intent_trigger_text',
6748 - __('Intent Trigger Text', 'mxchat'),
6749 - array($this, 'mxchat_pdf_intent_trigger_text_callback'),
6750 - 'mxchat-embed',
6751 - 'mxchat_pdf_intent_section'
6752 - );
6753 -
6754 - add_settings_field(
6755 - 'pdf_intent_success_text',
6756 - __('Success Text', 'mxchat'),
6757 - array($this, 'mxchat_pdf_intent_success_text_callback'),
6758 - 'mxchat-embed',
6759 - 'mxchat_pdf_intent_section'
6760 - );
6761 -
6762 - add_settings_field(
6763 - 'pdf_intent_error_text',
6764 - __('Error Text', 'mxchat'),
6765 - array($this, 'mxchat_pdf_intent_error_text_callback'),
6766 - 'mxchat-embed',
6767 - 'mxchat_pdf_intent_section'
6768 - );
6769 -
6770 - // Add PDF Maximum Pages Field
6771 - add_settings_field(
6772 - 'pdf_max_pages',
6773 - __('Maximum Document Pages', 'mxchat'),
6774 - array($this, 'mxchat_pdf_max_pages_callback'),
6775 - 'mxchat-embed',
6776 - 'mxchat_pdf_intent_section'
6777 - );
6778 -
6779 - // Live Agent Settings Fields
1572 + // Theme Settings Section
6780 1573 add_settings_section(
6781 - 'mxchat_live_agent_section',
6782 - __('Live Agent Settings', 'mxchat'),
6783 - array($this, 'mxchat_live_agent_section_callback'),
6784 - 'mxchat-embed'
1574 + 'mxchat_theme_section',
1575 + 'Theme Settings',
1576 + null,
1577 + 'mxchat-theme'
6785 1578 );
6786 1579
6787 - // Live Agent Status Fields (add at top of live agent settings)
6788 1580 add_settings_field(
6789 - 'live_agent_status',
6790 - __('Live Agent Status', 'mxchat'),
6791 - array($this, 'mxchat_live_agent_status_callback'),
6792 - 'mxchat-embed',
6793 - 'mxchat_live_agent_section'
1581 + 'close_button_color',
1582 + 'Close Button & Title Color',
1583 + array($this, 'mxchat_close_button_color_callback'),
1584 + 'mxchat-theme',
1585 + 'mxchat_theme_section'
6794 1586 );
6795 1587
6796 - // Slack availability schedule (plans 8ccaa2 + 99d7a4). Each handoff channel
6797 - // owns an independent schedule rendered under its own Integrations tab; this
6798 - // one governs Slack only. Same callback as Telegram's, parameterized.
6799 1588 add_settings_field(
6800 - 'live_agent_schedule_slack',
6801 - __('Availability Schedule', 'mxchat'),
6802 - array($this, 'mxchat_live_agent_schedule_callback'),
6803 - 'mxchat-embed',
6804 - 'mxchat_live_agent_section',
6805 - array('channel' => 'slack')
1589 + 'chatbot_bg_color',
1590 + 'Chatbot Background Color',
1591 + array($this, 'mxchat_chatbot_bg_color_callback'),
1592 + 'mxchat-theme',
1593 + 'mxchat_theme_section'
6806 1594 );
6807 1595
6808 1596 add_settings_field(
6809 - 'live_agent_notification_message',
6810 - __('Notification Message', 'mxchat'),
6811 - array($this, 'mxchat_live_agent_notification_message_callback'),
6812 - 'mxchat-embed',
6813 - 'mxchat_live_agent_section'
1597 + 'user_message_bg_color',
1598 + 'User Message Background Color',
1599 + array($this, 'mxchat_user_message_bg_color_callback'),
1600 + 'mxchat-theme',
1601 + 'mxchat_theme_section'
6814 1602 );
6815 1603
6816 1604 add_settings_field(
6817 - 'live_agent_away_message',
6818 - __('Away Message', 'mxchat'),
6819 - array($this, 'mxchat_live_agent_away_message_callback'),
6820 - 'mxchat-embed',
6821 - 'mxchat_live_agent_section'
1605 + 'user_message_font_color',
1606 + 'User Message Font Color',
1607 + array($this, 'mxchat_user_message_font_color_callback'),
1608 + 'mxchat-theme',
1609 + 'mxchat_theme_section'
6822 1610 );
6823 1611
6824 1612 add_settings_field(
6825 - 'live_agent_user_ids',
6826 - __('Slack Agent User IDs', 'mxchat'),
6827 - array($this, 'mxchat_live_agent_user_ids_callback'),
6828 - 'mxchat-embed',
6829 - 'mxchat_live_agent_section'
1613 + 'bot_message_bg_color',
1614 + 'Bot Message Background Color',
1615 + array($this, 'mxchat_bot_message_bg_color_callback'),
1616 + 'mxchat-theme',
1617 + 'mxchat_theme_section'
6830 1618 );
6831 1619
6832 - // Shared handoff channel (plan 9f7756): route every handoff into one
6833 - // pre-existing channel as threads instead of creating chat-* channels.
6834 1620 add_settings_field(
6835 - 'live_agent_shared_channel',
6836 - __('Shared Handoff Channel', 'mxchat'),
6837 - array($this, 'mxchat_live_agent_shared_channel_callback'),
6838 - 'mxchat-embed',
6839 - 'mxchat_live_agent_section'
1621 + 'bot_message_font_color',
1622 + 'Bot Message Font Color',
1623 + array($this, 'mxchat_bot_message_font_color_callback'),
1624 + 'mxchat-theme',
1625 + 'mxchat_theme_section'
6840 1626 );
6841 1627
6842 - // Auto-archive per-conversation chat- channels on !endchat (plan 7458a7).
6843 - // Default OFF; never touches the shared handoff channel.
6844 1628 add_settings_field(
6845 - 'live_agent_archive_on_end_toggle',
6846 - __('Archive Channel When Chat Ends', 'mxchat'),
6847 - array($this, 'mxchat_live_agent_archive_on_end_callback'),
6848 - 'mxchat-embed',
6849 - 'mxchat_live_agent_section'
1629 + 'top_bar_bg_color',
1630 + 'Top Bar Background Color',
1631 + array($this, 'mxchat_top_bar_bg_color_callback'),
1632 + 'mxchat-theme',
1633 + 'mxchat_theme_section'
6850 1634 );
6851 1635
6852 1636 add_settings_field(
6853 - 'live_agent_webhook_url',
6854 - __('Slack Webhook URL', 'mxchat'),
6855 - array($this, 'mxchat_live_agent_webhook_url_callback'),
6856 - 'mxchat-embed',
6857 - 'mxchat_live_agent_section'
1637 + 'send_button_font_color',
1638 + 'Send Button Color',
1639 + array($this, 'mxchat_send_button_font_color_callback'),
1640 + 'mxchat-theme',
1641 + 'mxchat_theme_section'
6858 1642 );
6859 1643
6860 1644 add_settings_field(
6861 - 'live_agent_secret_key',
6862 - __('Slack Secret Key', 'mxchat'),
6863 - array($this, 'mxchat_live_agent_secret_key_callback'),
6864 - 'mxchat-embed',
6865 - 'mxchat_live_agent_section'
1645 + 'chat_input_font_color',
1646 + 'Chat Input Font Color',
1647 + array($this, 'mxchat_chat_input_font_color_callback'),
1648 + 'mxchat-theme',
1649 + 'mxchat_theme_section'
6866 1650 );
6867 1651
6868 - // Live Agent Integration Fields
6869 1652 add_settings_field(
6870 - 'live_agent_bot_token',
6871 - __('Slack Bot OAuth Token', 'mxchat'),
6872 - array($this, 'mxchat_live_agent_bot_token_callback'),
6873 - 'mxchat-embed',
6874 - 'mxchat_live_agent_section'
1653 + 'chatbot_background_color',
1654 + 'Floating Widget Background Color',
1655 + array($this, 'mxchat_chatbot_background_color_callback'),
1656 + 'mxchat-theme',
1657 + 'mxchat_theme_section'
6875 1658 );
6876 1659
6877 - // Telegram Integration Section
6878 - add_settings_section(
6879 - 'mxchat_telegram_section',
6880 - __('Telegram Settings', 'mxchat'),
6881 - array($this, 'mxchat_telegram_section_callback'),
6882 - 'mxchat-embed'
6883 - );
6884 -
6885 1660 add_settings_field(
6886 - 'telegram_status',
6887 - __('Live Agent Status', 'mxchat'),
6888 - array($this, 'mxchat_telegram_status_callback'),
6889 - 'mxchat-embed',
6890 - 'mxchat_telegram_section'
1661 + 'icon_color',
1662 + 'Chatbot Icon Color',
1663 + array($this, 'mxchat_icon_color_callback'),
1664 + 'mxchat-theme',
1665 + 'mxchat_theme_section'
6891 1666 );
6892 1667
6893 - // Telegram availability schedule (plan 99d7a4) — independent of Slack's,
6894 - // rendered right under the Telegram status toggle it extends.
6895 - add_settings_field(
6896 - 'live_agent_schedule_telegram',
6897 - __('Availability Schedule', 'mxchat'),
6898 - array($this, 'mxchat_live_agent_schedule_callback'),
6899 - 'mxchat-embed',
6900 - 'mxchat_telegram_section',
6901 - array('channel' => 'telegram')
6902 - );
6903 -
6904 - add_settings_field(
6905 - 'telegram_notification_message',
6906 - __('Notification Message', 'mxchat'),
6907 - array($this, 'mxchat_telegram_notification_message_callback'),
6908 - 'mxchat-embed',
6909 - 'mxchat_telegram_section'
6910 - );
6911 -
6912 - add_settings_field(
6913 - 'telegram_away_message',
6914 - __('Away Message', 'mxchat'),
6915 - array($this, 'mxchat_telegram_away_message_callback'),
6916 - 'mxchat-embed',
6917 - 'mxchat_telegram_section'
6918 - );
6919 -
6920 - add_settings_field(
6921 - 'telegram_bot_token',
6922 - __('Telegram Bot Token', 'mxchat'),
6923 - array($this, 'mxchat_telegram_bot_token_callback'),
6924 - 'mxchat-embed',
6925 - 'mxchat_telegram_section'
6926 - );
6927 -
6928 - add_settings_field(
6929 - 'telegram_group_id',
6930 - __('Telegram Group ID', 'mxchat'),
6931 - array($this, 'mxchat_telegram_group_id_callback'),
6932 - 'mxchat-embed',
6933 - 'mxchat_telegram_section'
6934 - );
6935 -
6936 - add_settings_field(
6937 - 'telegram_webhook_secret',
6938 - __('Webhook Secret Token', 'mxchat'),
6939 - array($this, 'mxchat_telegram_webhook_secret_callback'),
6940 - 'mxchat-embed',
6941 - 'mxchat_telegram_section'
6942 - );
6943 -
6944 1668 // General Settings Section
6945 1669 add_settings_section(
6946 1670 'mxchat_general_section',
6947 - esc_html__('YouTube Tutorials', 'mxchat'),
1671 + 'Frequently Asked Questions (FAQ)',
6948 1672 null,
6949 1673 'mxchat-general'
6950 1674 );
6951 -}
6952 1675
6953 -public function mxchat_prompts_page_init() {
6954 - register_setting(
6955 - 'mxchat_prompts_options',
6956 - 'mxchat_prompts_options',
6957 - array(
6958 - 'type' => 'array',
6959 - 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
6960 - 'default' => array(
6961 - 'mxchat_auto_sync_posts' => 0,
6962 - 'mxchat_auto_sync_pages' => 0,
6963 - 'mxchat_use_pinecone' => 0,
6964 - 'mxchat_pinecone_api_key' => '',
6965 - 'mxchat_pinecone_environment' => '',
6966 - 'mxchat_pinecone_index' => '',
6967 - 'mxchat_pinecone_host' => '',
6968 - ),
6969 - 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
6970 - )
6971 - );
6972 1676
6973 - add_action('admin_notices', array($this, 'sync_settings_notice'));
6974 1677 }
6975 1678
6976 -public function mxchat_transcripts_page_init() {
6977 - register_setting(
6978 - 'mxchat_transcripts_options',
6979 - 'mxchat_transcripts_options',
6980 - array(
6981 - 'type' => 'array',
6982 - 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
6983 - 'default' => array(
6984 - 'mxchat_enable_notifications' => 0,
6985 - 'mxchat_notification_email' => get_option('admin_email'),
6986 - 'mxchat_auto_delete_transcripts' => 'never',
6987 - ),
6988 - 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
6989 - )
6990 - );
1679 +public function mxchat_handle_activate_license() {
1680 + check_ajax_referer('mxchat_activate_license_nonce', 'security');
6991 1681
6992 - add_settings_section(
6993 - 'mxchat_transcripts_notification_section',
6994 - esc_html__('Chat Notification Settings', 'mxchat'),
6995 - array($this, 'mxchat_transcripts_notification_section_callback'),
6996 - 'mxchat-transcripts'
6997 - );
1682 + $license_key = isset($_POST['mxchat_activation_key']) ? sanitize_text_field($_POST['mxchat_activation_key']) : '';
1683 + $customer_email = isset($_POST['mxchat_pro_email']) ? sanitize_email($_POST['mxchat_pro_email']) : '';
6998 1684
6999 - add_settings_field(
7000 - 'mxchat_enable_notifications',
7001 - esc_html__('Enable Chat Notifications', 'mxchat'),
7002 - array($this, 'mxchat_enable_notifications_callback'),
7003 - 'mxchat-transcripts',
7004 - 'mxchat_transcripts_notification_section'
7005 - );
1685 + if (empty($license_key) || empty($customer_email)) {
1686 + wp_send_json_error('Email or License Key is missing');
1687 + }
7006 1688
7007 - add_settings_field(
7008 - 'mxchat_notification_email',
7009 - esc_html__('Notification Email Address', 'mxchat'),
7010 - array($this, 'mxchat_notification_email_callback'),
7011 - 'mxchat-transcripts',
7012 - 'mxchat_transcripts_notification_section'
7013 - );
1689 + $product_id = 'MxChatPRO';
7014 1690
7015 - add_settings_field(
7016 - 'mxchat_auto_delete_transcripts',
7017 - esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
7018 - array($this, 'mxchat_auto_delete_transcripts_callback'),
7019 - 'mxchat-transcripts',
7020 - 'mxchat_transcripts_notification_section'
7021 - );
1691 + $response = wp_remote_get("http://mxchat.ai/?wc-api=software-api&request=activation&email={$customer_email}&license_key={$license_key}&product_id={$product_id}");
7022 1692
7023 - add_settings_field(
7024 - 'mxchat_retention_days',
7025 - esc_html__('Custom Retention (Days)', 'mxchat'),
7026 - array($this, 'mxchat_retention_days_callback'),
7027 - 'mxchat-transcripts',
7028 - 'mxchat_transcripts_notification_section'
7029 - );
7030 -
7031 - add_settings_field(
7032 - 'mxchat_auto_email_transcript',
7033 - esc_html__('Auto-Email Full Transcript', 'mxchat'),
7034 - array($this, 'mxchat_auto_email_transcript_callback'),
7035 - 'mxchat-transcripts',
7036 - 'mxchat_transcripts_notification_section'
7037 - );
7038 -}
7039 -
7040 -
7041 -/**
7042 - * Sanitize all prompts options
7043 - *
7044 - * @param array $input The unsanitized options array
7045 - * @return array The sanitized options array
7046 - */
7047 -public function sanitize_prompts_options($input) {
7048 - // Log the incoming input.
7049 - //error_log('Sanitizing inputs: ' . print_r($input, true));
7050 -
7051 - $sanitized = array();
7052 -
7053 - // Boolean options
7054 - $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
7055 - $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
7056 -$sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
7057 -
7058 - // API Key: if less than 32 characters, flag as invalid.
7059 - $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
7060 - if (!empty($api_key) && strlen($api_key) < 32) {
7061 - add_settings_error(
7062 - 'mxchat_prompts_options',
7063 - 'invalid_api_key',
7064 - __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
7065 - );
7066 - $existing_options = get_option('mxchat_prompts_options', array());
7067 - $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
7068 - } else {
7069 - $sanitized['mxchat_pinecone_api_key'] = $api_key;
1693 + if (is_wp_error($response)) {
1694 + wp_send_json_error('Activation failed due to a server error');
7070 1695 }
7071 1696
7072 - // Environment and Index Name
7073 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
7074 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
1697 + $body = wp_remote_retrieve_body($response);
1698 + $data = json_decode($body);
7075 1699
7076 - // Host: Remove protocol and validate format.
7077 - $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
7078 - $host = preg_replace('#^https?://#', '', $host);
7079 - //error_log('Host after removing protocol: ' . $host);
7080 - if (!empty($host)) {
7081 - if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
7082 - add_settings_error(
7083 - 'mxchat_prompts_options',
7084 - 'invalid_host',
7085 - __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
7086 - );
7087 - $existing_options = get_option('mxchat_prompts_options', array());
7088 - $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
7089 - } else {
7090 - $sanitized['mxchat_pinecone_host'] = $host;
7091 - }
1700 + if ($data && isset($data->activated) && $data->activated) {
1701 + update_option('mxchat_license_status', 'active');
1702 + update_option('mxchat_pro_email', $customer_email);
1703 + update_option('mxchat_activation_key', $license_key);
1704 + wp_send_json_success();
7092 1705 } else {
7093 - $sanitized['mxchat_pinecone_host'] = '';
1706 + $error_message = isset($data->error) ? $data->error : 'Activation failed';
1707 + update_option('mxchat_license_status', 'inactive');
1708 + update_option('mxchat_license_error', $error_message);
1709 + wp_send_json_error($error_message);
7094 1710 }
7095 -
7096 - //error_log('Final sanitized array: ' . print_r($sanitized, true));
7097 -
7098 - return $sanitized;
7099 1711 }
7100 1712
7101 -public function sync_settings_notice() {
7102 - // Only show notice on our plugin page
7103 - if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
7104 - return;
7105 - }
1713 +public function mxchat_rate_limit_callback() {
1714 + $rate_limits = array('5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' here
1715 + $selected_rate_limit = isset($this->options['rate_limit']) ? $this->options['rate_limit'] : '100';
7106 1716
7107 - // Check if settings were updated
7108 - if (isset($_GET['settings-updated'])) {
7109 -
7110 - ?>
7111 - <div class="notice notice-success is-dismissible">
7112 - <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
7113 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
7114 - </div>
7115 - <?php
7116 -
1717 + echo '<div class="pro-feature-wrapper active">';
1718 + echo '<select id="rate_limit" name="mxchat_options[rate_limit]">';
1719 + foreach ($rate_limits as $limit) {
1720 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7117 1721 }
1722 + echo '</select>';
1723 + echo '</div>';
7118 1724 }
7119 -// Add this sanitization function to your class
7120 -public function sanitize_sync_setting($input) {
7121 - return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
7122 -}
7123 1725
7124 -public function mxchat_rate_limits_callback() {
7125 - $all_options = get_option('mxchat_options', []);
7126 -
7127 - // Define available rate limits
7128 - $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7129 -
7130 - // Define available timeframes
7131 - $timeframes = array(
7132 - 'hourly' => __('Per Hour', 'mxchat'),
7133 - 'daily' => __('Per Day', 'mxchat'),
7134 - 'weekly' => __('Per Week', 'mxchat'),
7135 - 'monthly' => __('Per Month', 'mxchat')
1726 +public function mxchat_rate_limit_message_callback() {
1727 + // Remove the is_activated check and make it always enabled
1728 + echo '<div class="pro-feature-wrapper active">';
1729 + printf(
1730 + '<textarea id="rate_limit_message" name="mxchat_options[rate_limit_message]" rows="3" cols="50">%s</textarea>',
1731 + isset($this->options['rate_limit_message']) ? esc_textarea($this->options['rate_limit_message']) : 'Rate limit exceeded. Please try again later.'
7136 1732 );
7137 -
7138 - // Get all roles plus a "logged_out" pseudo-role
7139 - $roles = wp_roles()->get_names();
7140 - $roles['logged_out'] = __('Logged Out Users', 'mxchat');
7141 -
7142 - // Start the wrapper
7143 - echo '<div class="pro-feature-wrapper active">';
7144 - echo '<div class="mxchat-rate-limits-container">';
7145 -
7146 - echo '<p class="description" style="margin-bottom: 20px;">' .
7147 - esc_html__('Set message limits for each user role and customize the experience when users reach those limits. You can use {limit}, {timeframe}, {count}, and {remaining} as placeholders.', 'mxchat') .
7148 - '</p>';
7149 -
7150 - // Add markdown link documentation
7151 - echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
7152 - echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
7153 - echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
7154 - echo '<ul style="margin-left: 20px;">';
7155 - echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
7156 - echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
7157 - echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
7158 - echo '</ul>';
7159 1733 echo '</div>';
1734 +}
7160 1735
7161 - // Output the controls for each role
7162 - foreach ($roles as $role_id => $role_name) {
7163 - // Get saved options or defaults
7164 - $default_limit = ($role_id === 'logged_out') ? '10' : '100';
7165 - $default_timeframe = 'daily';
7166 - $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
7167 1736
7168 - $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
7169 - ? $all_options['rate_limits'][$role_id]['limit']
7170 - : $default_limit;
1737 +public function mxchat_enable_woocommerce_integration_callback() {
1738 + $checked = isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1' ? 'checked' : '';
1739 + $disabled = $this->is_activated ? '' : 'disabled';
1740 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7171 1741
7172 - $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
7173 - ? $all_options['rate_limits'][$role_id]['timeframe']
7174 - : $default_timeframe;
1742 + echo '<div class="' . esc_attr($class) . '">';
1743 + echo '<label class="toggle-switch">';
1744 + echo '<input type="checkbox" id="enable_woocommerce_integration" name="mxchat_options[enable_woocommerce_integration]" value="1" ' . $checked . ' ' . $disabled . '>';
1745 + echo '<span class="slider"></span>';
1746 + echo '</label>';
7175 1747
7176 - $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
7177 - ? $all_options['rate_limits'][$role_id]['message']
7178 - : $default_message;
7179 -
7180 - // Output the row
7181 - echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
7182 -
7183 - // Role label
7184 - echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
7185 -
7186 - // Controls section
7187 - echo '<div class="mxchat-rate-limit-controls-wrapper">';
7188 -
7189 - // Rate limit and timeframe controls
7190 - echo '<div class="mxchat-rate-limit-controls">';
7191 -
7192 - // Limit dropdown
7193 - echo '<div>';
7194 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
7195 - echo '<select
7196 - id="rate_limits_' . esc_attr($role_id) . '_limit"
7197 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
7198 - class="mxchat-autosave-field">';
7199 - foreach ($rate_limits as $limit) {
7200 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7201 - }
7202 - echo '</select>';
1748 + if (!$this->is_activated) {
1749 + echo '<div class="pro-feature-overlay">';
1750 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
7203 1751 echo '</div>';
1752 + }
7204 1753
7205 - // Timeframe dropdown
7206 - echo '<div>';
7207 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
7208 - echo '<select
7209 - id="rate_limits_' . esc_attr($role_id) . '_timeframe"
7210 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
7211 - class="mxchat-autosave-field">';
7212 - foreach ($timeframes as $value => $label) {
7213 - echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
7214 - }
7215 - echo '</select>';
7216 - echo '</div>';
1754 + echo '</div>';
1755 +}
7217 1756
7218 - echo '</div>'; // End controls
7219 1757
7220 - // Custom message textarea
7221 - echo '<div class="mxchat-rate-limit-message">';
7222 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
7223 - echo '<textarea
7224 - id="rate_limits_' . esc_attr($role_id) . '_message"
7225 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
7226 - class="mxchat-autosave-field"
7227 - placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
7228 - esc_textarea($custom_message) .
7229 - '</textarea>';
7230 - echo '<p class="description">' .
7231 - esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
7232 - '</p>';
7233 - echo '</div>'; // End message
7234 1758
7235 - echo '</div>'; // End controls wrapper
7236 1759
7237 - echo '</div>'; // End row
7238 - }
7239 -
7240 - echo '</div>'; // End container
7241 -
7242 - echo '</div>'; // End pro-feature-wrapper
7243 -}
7244 -
7245 -private function mxchat_add_option_field($id, $title, $callback = '') {
1760 + private function mxchat_add_option_field($id, $title, $callback = '') {
7246 1761 add_settings_field(
7247 1762 $id,
7248 - __($title, 'mxchat'),
1763 + $title,
7249 1764 $callback ? array($this, $callback) : array($this, $id . '_callback'),
7250 1765 'mxchat-max',
7251 1766 'mxchat_setting_section_id',
7252 1767 $id === 'model' ? ['label_for' => 'model'] : []
@@ -7252,572 +1767,202 @@
7252 1767 $id === 'model' ? ['label_for' => 'model'] : []
7253 1768 );
7254 1769 }
7255 1770
7256 -// API Keys Section Callback
7257 -public function mxchat_api_keys_section_callback() {
7258 - echo '<p>' . esc_html__('Manage all your API keys in one place. Add the API keys for the services you want to use with your chatbot.', 'mxchat') . '</p>';
7259 -}
7260 1771
7261 -// OpenAI API Key
7262 -public function api_key_callback() {
7263 - $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
7264 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1772 + public function api_key_callback() {
1773 + $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
1774 + echo '<input type="password" id="api_key" name="mxchat_options[api_key]" value="' . $apiKey . '" class="regular-text" />';
1775 + echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
1776 + }
7265 1777
7266 - echo '<div class="api-key-wrapper">';
7267 - echo '<input type="text" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7268 - echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7269 - echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
7270 - echo $this->mxchat_provider_key_test_button('openai', 'api_key');
7271 - echo '</div>';
7272 -}
1778 + public function xai_api_key_callback() {
1779 + // Check if the feature is activated (paid feature)
1780 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
1781 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
7273 1782
7274 -// X.AI API Key
7275 -public function xai_api_key_callback() {
7276 - $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
7277 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1783 + // Render the input field for the X.AI API key
1784 + echo '<div class="' . esc_attr($class) . '">';
1785 + printf(
1786 + '<input type="password" id="xai_api_key" name="mxchat_options[xai_api_key]" value="%s" class="regular-text" %s />',
1787 + isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '',
1788 + $disabled
1789 + );
1790 + echo '<button type="button" id="toggleXaiApiKeyVisibility">Show</button>';
7278 1791
7279 - echo '<div class="api-key-wrapper">';
7280 - echo '<input type="text" id="xai_api_key" name="xai_api_key" value="' . $xaiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7281 - echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7282 - echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
7283 - echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key');
7284 - echo '</div>';
7285 -}
7286 -// Claude API Key
7287 -public function claude_api_key_callback() {
7288 - $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
7289 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1792 + // If the feature is not activated, show the overlay with a "Pro Only" message
1793 + if (!$this->is_activated) {
1794 + echo '<div class="pro-feature-overlay">';
1795 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1796 + echo '</div>';
1797 + }
7290 1798
7291 - echo '<div class="api-key-wrapper">';
7292 - echo '<input type="text" id="claude_api_key" name="claude_api_key" value="' . $claudeApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7293 - echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7294 - echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
7295 - echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key');
7296 - echo '</div>';
7297 -}
1799 + echo '</div>';
1800 + }
7298 1801
7299 -// DeepSeek API Key
7300 -public function deepseek_api_key_callback() {
7301 - $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
7302 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1802 + public function claude_api_key_callback() {
1803 + // Check if the feature is activated (paid feature)
1804 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
1805 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
7303 1806
7304 - echo '<div class="api-key-wrapper">';
7305 - echo '<input type="text" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7306 - echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7307 - echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
7308 - echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key');
7309 - echo '</div>';
7310 -}
1807 + // Render the input field for the Claude API key
1808 + echo '<div class="' . esc_attr($class) . '">';
1809 + printf(
1810 + '<input type="password" id="claude_api_key" name="mxchat_options[claude_api_key]" value="%s" class="regular-text" %s />',
1811 + isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '',
1812 + $disabled
1813 + );
1814 + echo '<button type="button" id="toggleClaudeApiKeyVisibility">Show</button>';
7311 1815
7312 -// Gemini API Key
7313 -public function gemini_api_key_callback() {
7314 - $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
7315 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1816 + // If the feature is not activated, show the overlay with a "Pro Only" message
1817 + if (!$this->is_activated) {
1818 + echo '<div class="pro-feature-overlay">';
1819 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1820 + echo '</div>';
1821 + }
7316 1822
7317 - echo '<div class="api-key-wrapper">';
7318 - echo '<input type="text" id="gemini_api_key" name="gemini_api_key" value="' . $geminiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7319 - echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7320 - echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
7321 - echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key');
7322 - echo '</div>';
7323 -}
1823 + echo '</div>';
1824 + }
7324 1825
1826 + public function mxchat_woocommerce_consumer_key_callback() {
1827 + $disabled = $this->is_activated ? '' : 'disabled';
1828 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7325 1829
7326 -// OpenRouter API Key
7327 -public function openrouter_api_key_callback() {
7328 - $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
7329 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1830 + echo '<div class="' . esc_attr($class) . '">';
1831 + printf(
1832 + '<input type="text" id="woocommerce_consumer_key" name="mxchat_options[woocommerce_consumer_key]" value="%s" class="regular-text" %s />',
1833 + isset($this->options['woocommerce_consumer_key']) ? esc_attr($this->options['woocommerce_consumer_key']) : '',
1834 + $disabled
1835 + );
7330 1836
7331 - echo '<div class="api-key-wrapper">';
7332 - echo '<input type="text" id="openrouter_api_key" name="openrouter_api_key" value="' . $openrouterApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7333 - echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7334 - echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
7335 - echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key');
7336 - echo '</div>';
7337 -}
1837 + if (!$this->is_activated) {
1838 + echo '<div class="pro-feature-overlay">';
1839 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1840 + echo '</div>';
1841 + }
7338 1842
7339 -/**
7340 - * Renders a "Test key" button + result target next to a built-in provider key
7341 - * field, and emits the shared delegated click handler ONCE (static guard). The
7342 - * button carries data-target = the key field id so the owner can test the value
7343 - * they just typed (test-before-save); the AJAX handler falls back to the saved
7344 - * key when the field is empty. Styled with the WP `button` class to match the
7345 - * adjacent Custom-provider "Test Connection" button on this same page.
7346 - * plan-mxchat-20260623-c41f74.
7347 - */
7348 -public function mxchat_provider_key_test_button($provider, $target_id) {
7349 - static $script_emitted = false;
7350 - $nonce = wp_create_nonce('mxchat_test_provider_key');
7351 - $html = '<div class="mxchat-key-test" style="margin-top:8px;">'
7352 - . '<button type="button" class="button mxchat-test-provider-key" data-provider="' . esc_attr($provider) . '" data-target="' . esc_attr($target_id) . '" data-nonce="' . esc_attr($nonce) . '">' . esc_html__('Test key', 'mxchat') . '</button>'
7353 - . '<span class="mxchat-test-provider-key-result" style="margin-left:10px;font-size:13px;vertical-align:middle;"></span>'
7354 - . '</div>';
7355 - if (!$script_emitted) {
7356 - $script_emitted = true;
7357 - $html .= $this->mxchat_provider_key_test_script();
7358 - }
7359 - return $html;
7360 -}
1843 + echo '</div>';
1844 + }
7361 1845
7362 -/**
7363 - * One-time delegated click handler shared by every .mxchat-test-provider-key
7364 - * button. Posts the typed key value + provider to mxchat_test_provider_key and
7365 - * renders the success/error message inline. Mirrors the Custom-provider test.
7366 - */
7367 -private function mxchat_provider_key_test_script() {
7368 - $t_testing = esc_js(__('Testing...', 'mxchat'));
7369 - $t_valid = esc_js(__('Key is valid.', 'mxchat'));
7370 - $t_failed = esc_js(__('Failed', 'mxchat'));
7371 - $t_req = esc_js(__('Request failed', 'mxchat'));
7372 - return '<script>(function(){'
7373 - . 'if (window.__mxchatProviderKeyTestWired) { return; }'
7374 - . 'window.__mxchatProviderKeyTestWired = true;'
7375 - . 'document.addEventListener("click", function(e){'
7376 - . 'var btn = e.target && e.target.closest ? e.target.closest(".mxchat-test-provider-key") : null;'
7377 - . 'if (!btn) { return; }'
7378 - . 'e.preventDefault();'
7379 - . 'var field = btn.getAttribute("data-target") ? document.getElementById(btn.getAttribute("data-target")) : null;'
7380 - . 'var out = btn.parentNode ? btn.parentNode.querySelector(".mxchat-test-provider-key-result") : null;'
7381 - . 'if (out) { out.textContent = "' . $t_testing . '"; out.style.color = "#646970"; }'
7382 - . 'btn.disabled = true;'
7383 - . 'var fd = new FormData();'
7384 - . 'fd.append("action", "mxchat_test_provider_key");'
7385 - . 'fd.append("_wpnonce", btn.getAttribute("data-nonce"));'
7386 - . 'fd.append("provider", btn.getAttribute("data-provider") || "");'
7387 - . 'fd.append("key", field ? field.value : "");'
7388 - . 'fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })'
7389 - . '.then(function(r){ return r.json(); })'
7390 - . '.then(function(j){'
7391 - . 'if (out) {'
7392 - . 'if (j && j.success) { out.textContent = "✓ " + ((j.data && j.data.message) ? j.data.message : "' . $t_valid . '"); out.style.color = "#00a32a"; }'
7393 - . 'else { out.textContent = "⚠ " + ((j && j.data && j.data.message) ? j.data.message : "' . $t_failed . '"); out.style.color = "#d63638"; }'
7394 - . '}'
7395 - . 'btn.disabled = false;'
7396 - . '})'
7397 - . '.catch(function(){ if (out) { out.textContent = "⚠ ' . $t_req . '"; out.style.color = "#d63638"; } btn.disabled = false; });'
7398 - . '});'
7399 - . '})();</script>';
7400 -}
1846 + public function mxchat_woocommerce_consumer_secret_callback() {
1847 + $disabled = $this->is_activated ? '' : 'disabled';
1848 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7401 1849
7402 -// Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
7403 -public function custom_provider_callback() {
7404 - $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
7405 - $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
7406 - $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
7407 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
7408 - $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
7409 - $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
7410 - $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
7411 - $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
7412 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7413 - $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
1850 + echo '<div class="' . esc_attr($class) . '">';
1851 + printf(
1852 + '<input type="password" id="woocommerce_consumer_secret" name="mxchat_options[woocommerce_consumer_secret]" value="%s" class="regular-text" %s />',
1853 + isset($this->options['woocommerce_consumer_secret']) ? esc_attr($this->options['woocommerce_consumer_secret']) : '',
1854 + $disabled
1855 + );
1856 + echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';
7414 1857
7415 - echo '<style>
7416 - .mxchat-cp { max-width: 680px; }
7417 - .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
7418 - .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
7419 - .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
7420 - .mxchat-cp .mxchat-cp-row > input[type="text"],
7421 - .mxchat-cp .mxchat-cp-row > input[type="password"],
7422 - .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
7423 - .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
7424 - .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
7425 - .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
7426 - .mxchat-cp .mxchat-cp-azure { margin: 0 0 18px; padding: 12px 14px; background: #f6f7ff; border: 1px solid #dfe1f5; border-left: 3px solid #7873f5; border-radius: 6px; max-width: 480px; }
7427 - .mxchat-cp .mxchat-cp-azure > .mxchat-cp-azure-title { display: block; font-weight: 600; color: #1d2327; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; margin: 0 0 8px; }
7428 - .mxchat-cp .mxchat-cp-azure ol { margin: 0; padding: 0 0 0 18px; color: #50575e; font-size: 12px; line-height: 1.7; }
7429 - .mxchat-cp .mxchat-cp-azure code { background: #eceefb; padding: 1px 5px; border-radius: 3px; font-size: 11px; }
7430 - </style>';
1858 + if (!$this->is_activated) {
1859 + echo '<div class="pro-feature-overlay">';
1860 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1861 + echo '</div>';
1862 + }
7431 1863
7432 - echo '<div class="api-key-wrapper mxchat-cp">';
7433 - echo '<p class="mxchat-cp-intro">' . esc_html__('Point MxChat at any OpenAI-compatible /v1/chat/completions endpoint: Ollama, LM Studio, vLLM, llama.cpp, LocalAI, Azure OpenAI, etc. Then select "Custom (OpenAI-compatible)" in the model picker.', 'mxchat') . '</p>';
1864 + echo '</div>';
1865 + }
7434 1866
7435 - // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout
7436 - // so admins can configure Azure without piecing it together from each field's hint.
7437 - echo '<div class="mxchat-cp-azure">';
7438 - echo '<span class="mxchat-cp-azure-title">' . esc_html__('Azure OpenAI quick start', 'mxchat') . '</span>';
7439 - echo '<ol>';
7440 - echo '<li>' . wp_kses(__('<strong>Base URL</strong> → <code>https://&lt;resource&gt;.openai.azure.com/openai/deployments/&lt;deployment&gt;</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7441 - echo '<li>' . wp_kses(__('<strong>API Key</strong> → your Azure OpenAI key (required)', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7442 - echo '<li>' . wp_kses(__('<strong>Auth Scheme</strong> → <code>api-key header (Azure OpenAI)</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7443 - echo '<li>' . wp_kses(__('<strong>API Version</strong> → required for Azure, e.g. <code>2024-08-01-preview</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7444 - echo '</ol>';
7445 - echo '</div>';
1867 + public function mxchat_loops_api_key_callback() {
1868 + $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7446 1869
7447 - echo '<div class="mxchat-cp-row">';
7448 - echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
7449 - echo '<input type="text" id="custom_provider_base_url" name="custom_provider_base_url" value="' . $base_url . '" class="regular-text mxchat-autosave-field" placeholder="http://localhost:11434/v1" autocomplete="off" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7450 - echo '<p class="description">' . esc_html__('Examples: Ollama http://localhost:11434/v1 · LM Studio http://localhost:1234/v1 · vLLM http://gpu:8000/v1 · Azure https://<resource>.openai.azure.com/openai/deployments/<deployment>', 'mxchat') . '</p>';
7451 - echo '</div>';
1870 + echo '<div class="api-key-wrapper">';
1871 + printf(
1872 + '<input type="password" id="loops_api_key" name="mxchat_options[loops_api_key]" value="%s" class="regular-text" />',
1873 + $loops_api_key
1874 + );
1875 + echo '<button type="button" id="toggleLoopsApiKeyVisibility">Show</button>';
1876 + echo '</div>';
1877 + echo '<p class="description">Enter your Loops API Key here. (See FAQ for details)</p>';
1878 + }
7452 1879
7453 - echo '<div class="mxchat-cp-row">';
7454 - echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
7455 - echo '<input type="password" id="custom_provider_api_key" name="custom_provider_api_key" value="' . $api_key . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7456 - echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
7457 - echo '</div>';
1880 + public function mxchat_loops_mailing_list_callback() {
1881 + // Retrieve Loops API key and lists
1882 + $loops_api_key = isset($this->options['loops_api_key']) ? $this->options['loops_api_key'] : '';
1883 + $selected_list = isset($this->options['loops_mailing_list']) ? $this->options['loops_mailing_list'] : '';
7458 1884
7459 - echo '<div class="mxchat-cp-row">';
7460 - echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
7461 - echo '<input type="text" id="custom_provider_model" name="custom_provider_model" value="' . $model_name . '" class="regular-text mxchat-autosave-field" placeholder="llama3.2" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7462 - echo '<p class="description">' . esc_html__('The model identifier the upstream server expects (e.g. llama3.2, mistral, gpt-oss). For Azure this is the deployment ID — leave empty if the Base URL already includes /deployments/<deployment>.', 'mxchat') . '</p>';
7463 - echo '</div>';
1885 + if ($loops_api_key) {
1886 + // Fetch lists from Loops API
1887 + $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7464 1888
7465 - echo '<div class="mxchat-cp-row">';
7466 - echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
7467 - echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7468 - echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
7469 - echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
7470 - echo '</select>';
7471 - echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
7472 - echo '</div>';
7473 -
7474 - echo '<div class="mxchat-cp-row">';
7475 - echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
7476 - echo '<input type="text" id="custom_provider_api_version" name="custom_provider_api_version" value="' . $api_version . '" class="regular-text mxchat-autosave-field" placeholder="2024-08-01-preview" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7477 - echo '<p class="description">' . esc_html__('Appended as ?api-version=... on the request URL. Required for Azure OpenAI; leave empty for non-Azure providers.', 'mxchat') . '</p>';
7478 - echo '</div>';
7479 -
7480 - // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
7481 - echo '<div class="mxchat-cp-row">';
7482 - echo '<label style="font-weight:600; display:block; margin:0 0 6px; color:#1d2327; font-size:13px;">' . esc_html__('Extended routing (opt-in)', 'mxchat') . '</label>';
7483 - echo '<label style="display:block; margin:0 0 6px; font-weight:400;"><input type="checkbox" id="custom_provider_for_embeddings" name="custom_provider_for_embeddings" value="on"' . checked($use_embed, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for embeddings', 'mxchat') . '</label>';
7484 - echo '<label style="display:block; margin:0 0 0; font-weight:400;"><input type="checkbox" id="custom_provider_for_images" name="custom_provider_for_images" value="on"' . checked($use_images, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for image generation', 'mxchat') . '</label>';
7485 - echo '<p class="description">' . esc_html__('When off, embeddings and image generation continue to use OpenAI (current behavior). Turn on only if your endpoint exposes OpenAI-compatible /embeddings or /images/generations routes (e.g. Ollama, vLLM, LocalAI).', 'mxchat') . '</p>';
7486 - echo '</div>';
7487 -
7488 - echo '<div class="mxchat-cp-row">';
7489 - echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
7490 - echo '<input type="text" id="custom_provider_embedding_model" name="custom_provider_embedding_model" value="' . $embed_model . '" class="regular-text mxchat-autosave-field" placeholder="nomic-embed-text" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7491 - echo '<p class="description">' . esc_html__('Only used when "Use custom provider for embeddings" is on. The embedding model name is separate from the chat model name above (e.g. Ollama embedding models: nomic-embed-text, mxbai-embed-large). Leave blank to fall back to the chat model name.', 'mxchat') . '</p>';
7492 - echo '</div>';
7493 -
7494 - echo '<div class="mxchat-cp-test">';
7495 - echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
7496 - echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
7497 - echo '</div>';
7498 -
7499 - echo '<script>(function(){
7500 - var btn = document.getElementById("mxchat-test-custom-provider");
7501 - if (!btn || btn._wired) { return; } btn._wired = true;
7502 - btn.addEventListener("click", function(){
7503 - var out = document.getElementById("mxchat-test-custom-provider-result");
7504 - out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
7505 - out.style.color = "#646970";
7506 - var fd = new FormData();
7507 - fd.append("action", "mxchat_test_custom_provider");
7508 - fd.append("_wpnonce", btn.getAttribute("data-nonce"));
7509 - fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
7510 - .then(function(r){ return r.json(); })
7511 - .then(function(j){
7512 - if (j && j.success) {
7513 - out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
7514 - out.style.color = "#00a32a";
7515 - } else {
7516 - out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
7517 - out.style.color = "#d63638";
1889 + if ($lists) {
1890 + echo '<select id="loops_mailing_list" name="mxchat_options[loops_mailing_list]">';
1891 + foreach ($lists as $list) {
1892 + echo '<option value="' . esc_attr($list['id']) . '" ' . selected($selected_list, $list['id'], false) . '>' . esc_html($list['name']) . '</option>';
7518 1893 }
7519 - })
7520 - .catch(function(){
7521 - out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
7522 - out.style.color = "#d63638";
7523 - });
7524 - });
7525 - })();</script>';
1894 + echo '</select>';
1895 + } else {
1896 + echo '<p class="description">No lists found. Please verify your API Key.</p>';
1897 + }
1898 + } else {
1899 + echo '<p class="description">Enter a valid Loops API Key to load mailing lists.</p>';
1900 + }
1901 + }
7526 1902
7527 - echo '</div>';
7528 -}
1903 + public function mxchat_triggered_phrase_response_callback() {
1904 + $triggered_response = isset($this->options['triggered_phrase_response']) ? $this->options['triggered_phrase_response'] : '';
1905 + echo '<textarea id="triggered_phrase_response" name="mxchat_options[triggered_phrase_response]" rows="3" cols="50">' . esc_textarea($triggered_response) . '</textarea>';
1906 + echo '<p class="description">Enter the chatbot response when a trigger keyword is detected, prompting the user to share their email.</p>';
1907 + }
7529 1908
7530 -// Voyage API Key
7531 -public function voyage_api_key_callback() {
7532 - $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
7533 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1909 + public function mxchat_email_capture_response_callback() {
1910 + $email_capture_response = isset($this->options['email_capture_response']) ? $this->options['email_capture_response'] : 'Thank you for providing your email! You\'ve been added to our list.';
1911 + echo '<textarea id="email_capture_response" name="mxchat_options[email_capture_response]" rows="3" cols="50">' . esc_textarea($email_capture_response) . '</textarea>';
1912 + echo '<p class="description">Enter the message to send when a user provides their email.</p>';
1913 + }
7534 1914
7535 - echo '<div class="api-key-wrapper">';
7536 - echo '<input type="text" id="voyage_api_key" name="voyage_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7537 - echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7538 - echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
7539 - echo '</div>';
7540 -}
7541 1915
7542 -public function mxchat_loops_api_key_callback() {
7543 - $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7544 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7545 -
7546 - echo '<div class="api-key-wrapper">';
7547 - echo sprintf(
7548 - '<input type="text" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
7549 - $loops_api_key,
7550 - $nonce
7551 - );
7552 - echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7553 - echo '</div>';
7554 - // Cross-reference back to where the list is chosen, so the two screens point
7555 - // at each other (plan-mxchat-20260802-907a63).
7556 - echo '<p class="description">' . wp_kses(
7557 - sprintf(
7558 - /* translators: %s: link to the Loops integration tab. */
7559 - __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'),
7560 - '<a href="#integrations-loops">' . esc_html__('Integrations, Loops', 'mxchat') . '</a>'
7561 - ),
7562 - self::mxchat_loops_pointer_allowed_html()
7563 - ) . '</p>';
7564 -}
7565 -public function mxchat_loops_mailing_list_callback() {
7566 - // Add error handling and type checking
7567 - $loops_api_key = '';
7568 - $selected_list = '';
7569 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7570 -
7571 - // Safely get the API key
7572 - if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
7573 - $loops_api_key = $this->options['loops_api_key'];
1916 + public function mxchat_pre_chat_message_callback() {
1917 + printf(
1918 + '<textarea id="pre_chat_message" name="mxchat_options[pre_chat_message]" rows="5" cols="50">%s</textarea>',
1919 + isset($this->options['pre_chat_message']) ? esc_textarea($this->options['pre_chat_message']) : ''
1920 + );
7574 1921 }
7575 1922
7576 - // Safely get the selected list
7577 - if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
7578 - $selected_list = $this->options['loops_mailing_list'];
1923 + // Callback for AI Instructions textarea
1924 + public function system_prompt_instructions_callback() {
1925 + printf(
1926 + '<textarea id="system_prompt_instructions" name="mxchat_options[system_prompt_instructions]" rows="5" cols="50">%s</textarea>',
1927 + isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''
1928 + );
7579 1929 }
7580 1930
7581 - if (!empty($loops_api_key)) {
7582 - $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7583 - if (is_array($lists) && !empty($lists)) {
7584 - echo '<div class="mxchat-field-wrapper">';
7585 - echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7586 -
7587 - // Add a default "Select a list" option
7588 - echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
7589 -
7590 - foreach ($lists as $list) {
7591 - if (is_array($list) && isset($list['id']) && isset($list['name'])) {
7592 - echo sprintf(
7593 - '<option value="%s" %s>%s</option>',
7594 - esc_attr($list['id']),
7595 - selected($selected_list, $list['id'], false),
7596 - esc_html($list['name'])
7597 - );
7598 - }
7599 - }
7600 - echo '</select>';
7601 - echo '</div>';
7602 - echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
7603 - } else {
7604 - echo '<p class="description">' . wp_kses(
7605 - self::mxchat_loops_api_key_pointer(
7606 - /* translators: %s: link to the API Keys tab. */
7607 - __('No lists found. Please check your Loops API key under %s.', 'mxchat')
7608 - ),
7609 - self::mxchat_loops_pointer_allowed_html()
7610 - ) . '</p>';
7611 - }
7612 - } else {
7613 - echo '<p class="description">' . wp_kses(
7614 - self::mxchat_loops_api_key_pointer(
7615 - /* translators: %s: link to the API Keys tab. */
7616 - __('Enter your Loops API key under %s to load mailing lists.', 'mxchat')
7617 - ),
7618 - self::mxchat_loops_pointer_allowed_html()
7619 - ) . '</p>';
7620 - }
7621 -}
7622 -
7623 -/**
7624 - * Build the "API Keys" pointer used by the Loops mailing-list field.
7625 - *
7626 - * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API
7627 - * Keys tab, but this field's copy still read as though the input were beside
7628 - * it, so users had nowhere to go. Both live on the SAME screen
7629 - * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this
7630 - * dropdown under Integrations > Loops — so the pointer is an in-page tab
7631 - * switch, not a cross-page link.
7632 - *
7633 - * A plain href="#api-keys" is all it takes: the shared admin shell
7634 - * (js/admin-sidebar.js) honours section-naming hashes on load AND on
7635 - * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old
7636 - * data-target workaround on these pointer anchors is gone.
7637 - *
7638 - * @param string $template Translatable string containing one %s placeholder.
7639 - * @return string
7640 - */
7641 -private static function mxchat_loops_api_key_pointer($template) {
7642 - return sprintf(
7643 - $template,
7644 - '<a href="#api-keys">' . esc_html__('API Keys', 'mxchat') . '</a>'
7645 - );
7646 -}
7647 -
7648 -/**
7649 - * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook.
7650 - */
7651 -private static function mxchat_loops_pointer_allowed_html() {
7652 - return array(
7653 - 'a' => array(
7654 - 'href' => array(),
7655 - 'data-target' => array(),
1931 +public function mxchat_model_callback() {
1932 + $models = array(
1933 + 'X.AI Models' => array(
1934 + 'grok-beta' => 'grok-beta (Early Beta)'
7656 1935 ),
1936 + 'Claude Models' => array(
1937 + 'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet (Most Intelligent)',
1938 + 'claude-3-opus-20240229' => 'Claude 3 Opus (Highly Complex Tasks)',
1939 + 'claude-3-sonnet-20240229' => 'Claude 3 Sonnet (Balanced)',
1940 + 'claude-3-haiku-20240307' => 'Claude 3 Haiku (Fastest)'
1941 + ),
1942 + 'OpenAI Models' => array(
1943 + 'gpt-4o' => 'GPT-4o (Recommended)',
1944 + 'gpt-4o-mini' => 'GPT-4o Mini (Fast and Lightweight)',
1945 + 'gpt-4-turbo' => 'GPT-4 Turbo (High-Performance)',
1946 + 'gpt-4' => 'GPT-4 (High Intelligence)',
1947 + 'gpt-3.5-turbo' => 'GPT-3.5 Turbo (Affordable and Fast)'
1948 + )
7657 1949 );
7658 -}
7659 -public function mxchat_triggered_phrase_response_callback() {
7660 - $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
7661 - $triggered_response = isset($this->options['triggered_phrase_response'])
7662 - ? $this->options['triggered_phrase_response']
7663 - : $default_response;
7664 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7665 1950
7666 - echo '<div class="mxchat-field-wrapper">';
7667 - echo sprintf(
7668 - '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7669 - $nonce,
7670 - esc_textarea($triggered_response)
7671 - );
7672 - echo '</div>';
7673 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '</p>';
7674 -}
1951 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';
7675 1952
7676 -public function mxchat_email_capture_response_callback() {
7677 - $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
7678 - $email_capture_response = isset($this->options['email_capture_response'])
7679 - ? $this->options['email_capture_response']
7680 - : $default_response;
7681 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1953 + echo '<select id="model" name="mxchat_options[model]">';
7682 1954
7683 - echo '<div class="mxchat-field-wrapper">';
7684 - echo sprintf(
7685 - '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7686 - $nonce,
7687 - esc_textarea($email_capture_response)
7688 - );
7689 - echo '</div>';
7690 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '</p>';
7691 -}
7692 -public function mxchat_pre_chat_message_callback() {
7693 - // Load the entire 'mxchat_options' array
7694 - $all_options = get_option('mxchat_options', []);
7695 -
7696 - // Retrieve the saved message or use the default value
7697 - $default_message = __('Hey there! Ask me anything!', 'mxchat');
7698 - $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
7699 -
7700 - // Output the textarea
7701 - printf(
7702 - '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
7703 - esc_textarea($pre_chat_message)
7704 - );
7705 -}
7706 -
7707 -// Callback for AI Instructions textarea
7708 -public function system_prompt_instructions_callback() {
7709 - // Retrieve the current value of the system prompt instructions
7710 - $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
7711 - // Render the textarea field
7712 - printf(
7713 - '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
7714 - $instructions
7715 - );
7716 - // Personalization hint
7717 - echo '<p class="description" style="margin-top: 8px;">';
7718 - echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
7719 - echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
7720 - echo '</p>';
7721 - // Sample instructions button
7722 - echo '<div class="mxchat-instructions-container">';
7723 - echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
7724 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7725 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7726 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7727 - echo '</svg>';
7728 - echo esc_html__('View Sample Instructions', 'mxchat');
7729 - echo '</button>';
7730 - echo '</div>';
7731 -
7732 - // Add modal to WordPress admin footer instead of inline
7733 - add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
7734 -}
7735 -
7736 -// New method to render modal in admin footer
7737 -public function render_sample_instructions_modal() {
7738 - static $modal_rendered = false;
7739 - if ($modal_rendered) return; // Prevent duplicate modals
7740 - $modal_rendered = true;
7741 -
7742 - echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
7743 - echo '<div class="mxchat-instructions-modal-content">';
7744 - echo '<div class="mxchat-instructions-modal-header">';
7745 - echo '<h3 class="mxchat-instructions-modal-title">';
7746 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7747 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7748 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7749 - echo '</svg>';
7750 - echo esc_html__('Sample AI Instructions', 'mxchat');
7751 - echo '</h3>';
7752 - echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
7753 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7754 - echo '<line x1="18" y1="6" x2="6" y2="18"/>';
7755 - echo '<line x1="6" y1="6" x2="18" y2="18"/>';
7756 - echo '</svg>';
7757 - echo '</button>';
7758 - echo '</div>';
7759 - echo '<div class="mxchat-instructions-modal-body">';
7760 - echo '<div class="mxchat-instructions-content">';
7761 - echo esc_html('You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
7762 -
7763 -# Response Style - CRITICALLY IMPORTANT
7764 -- MAXIMUM LENGTH: 1-3 short sentences per response
7765 -- Ultra-concise: Get straight to the answer with no filler
7766 -- No introductions like "Sure!" or "I\'d be happy to help"
7767 -- No phrases like "based on my knowledge" or "according to information"
7768 -- No explanatory text before giving the answer
7769 -- No summaries or repetition
7770 -- Hyperlink all URLs
7771 -- Respond in user\'s language
7772 -- Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
7773 -
7774 -# Knowledge Base Requirements - PREVENT HALLUCINATIONS
7775 -- ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
7776 -- If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
7777 -- NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
7778 -- When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
7779 -- Better to admit insufficient information than provide inaccurate answers');
7780 - echo '</div>';
7781 - echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
7782 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7783 - echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
7784 - echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
7785 - echo '</svg>';
7786 - echo esc_html__('Copy Instructions', 'mxchat');
7787 - echo '</button>';
7788 - echo '</div>';
7789 - echo '<div class="mxchat-instructions-modal-footer">';
7790 - echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
7791 - echo '</div>';
7792 - echo '</div>';
7793 - echo '</div>';
7794 -}
7795 -
7796 -
7797 -public function mxchat_model_callback() {
7798 - // Catalog refactor (plan-d14e89): single source of truth lives in
7799 - // includes/class-mxchat-model-catalog.php. Dropdown groups are the
7800 - // provider labels; each group maps model_id => "Label" strings.
7801 - if (!class_exists('MxChat_Model_Catalog')) {
7802 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
7803 - }
7804 - // Retrieve the currently selected model from saved options
7805 - $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.6-sol';
7806 -
7807 - // Pass the saved model so a provider-retired id keeps rendering as the
7808 - // current selection instead of a blank select (plan e46b8f).
7809 - $models = MxChat_Model_Catalog::settings_dropdown_groups($selected_model);
7810 -
7811 - // Begin the select dropdown
7812 - echo '<select id="model" name="model">';
7813 -
7814 - // Iterate over groups of models
7815 1955 foreach ($models as $group_label => $group_models) {
7816 1956 echo '<optgroup label="' . esc_attr($group_label) . '">';
7817 1957
7818 1958 foreach ($group_models as $model_value => $model_label) {
7819 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
1959 + // Disable if not activated for paid models (Claude or X.AI)
1960 + $disabled = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? 'disabled' : '';
1961 + $label_suffix = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? ' (Pro Only)' : '';
1962 +
1963 + // Output the <option> element
1964 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . ' ' . $disabled . '>' . esc_html($model_label . $label_suffix) . '</option>';
7820 1965 }
7821 1966
7822 1967 echo '</optgroup>';
7823 1968 }
@@ -7822,2395 +1967,787 @@
7822 1967 echo '</optgroup>';
7823 1968 }
7824 1969
7825 1970 echo '</select>';
1971 +}
7826 1972
7827 - // Add a note for OpenRouter
7828 - echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
7829 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
7830 - echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
7831 - echo '</p>';
7832 1973
7833 - // API Key Status Messages (hidden by default, shown by JS based on selected model)
7834 - $has_openai_key = !empty($this->options['api_key']);
7835 - $has_claude_key = !empty($this->options['claude_api_key']);
7836 - $has_xai_key = !empty($this->options['xai_api_key']);
7837 - $has_deepseek_key = !empty($this->options['deepseek_api_key']);
7838 - $has_gemini_key = !empty($this->options['gemini_api_key']);
7839 - $has_openrouter_key = !empty($this->options['openrouter_api_key']);
7840 1974
7841 - // OpenAI/GPT models
7842 - echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
7843 - if ($has_openai_key) {
7844 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
7845 - } else {
7846 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1975 + public function mxchat_top_bar_title_callback() {
1976 + printf(
1977 + '<input type="text" id="top_bar_title" name="mxchat_options[top_bar_title]" value="%s" />',
1978 + isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : ''
1979 + );
7847 1980 }
7848 - echo '</p>';
7849 1981
7850 - // Claude models
7851 - echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
7852 - if ($has_claude_key) {
7853 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
7854 - } else {
7855 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1982 + public function mxchat_intro_message_callback() {
1983 + printf(
1984 + '<textarea id="intro_message" name="mxchat_options[intro_message]" rows="5" cols="50">%s</textarea>',
1985 + isset($this->options['intro_message']) ? esc_textarea($this->options['intro_message']) : 'Hello! How can I assist you today?'
1986 + );
7856 1987 }
7857 - echo '</p>';
7858 1988
7859 - // X.AI models
7860 - echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
7861 - if ($has_xai_key) {
7862 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
7863 - } else {
7864 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for X.AI (Grok) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1989 + public function mxchat_input_copy_callback() {
1990 + printf(
1991 + '<input type="text" id="input_copy" name="mxchat_options[input_copy]" value="%s" placeholder="How can I assist?" />',
1992 + isset($this->options['input_copy']) ? esc_attr($this->options['input_copy']) : 'How can I assist?'
1993 + );
1994 + echo '<p class="description">This is the placeholder text for the chat input field.</p>';
7865 1995 }
7866 - echo '</p>';
7867 1996
7868 - // DeepSeek models
7869 - echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
7870 - if ($has_deepseek_key) {
7871 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
7872 - } else {
7873 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7874 - }
7875 - echo '</p>';
7876 1997
7877 - // Gemini models
7878 - echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
7879 - if ($has_gemini_key) {
7880 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
7881 - } else {
7882 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7883 - }
7884 - echo '</p>';
7885 1998
7886 - // OpenRouter models
7887 - echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
7888 - if ($has_openrouter_key) {
7889 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
7890 - } else {
7891 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7892 - }
7893 - echo '</p>';
7894 1999
7895 - // ADD THESE HIDDEN FIELDS RIGHT HERE:
7896 - $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
7897 - $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
7898 2000
7899 - echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
7900 - echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
7901 -}
7902 2001
7903 -// Update your existing callback method
7904 -public function enable_streaming_toggle_callback() {
7905 - // Get value from options array, default to 'on'
7906 - $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
7907 - $checked = ($enabled === 'on') ? 'checked' : '';
2002 + public function mxchat_close_button_color_callback() {
2003 + $disabled = $this->is_activated ? '' : 'disabled';
7908 2004
7909 - echo '<label class="toggle-switch">';
7910 - echo sprintf(
7911 - '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
7912 - esc_attr($checked)
2005 + echo '<div class="pro-feature-wrapper">';
2006 + printf(
2007 + '<input type="text" id="close_button_color" name="mxchat_options[close_button_color]" value="%s" class="my-color-field" data-default-color="#4a4a4a" %s />',
2008 + isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '',
2009 + esc_attr($disabled)
7913 2010 );
7914 - echo '<span class="slider"></span>';
7915 - echo '</label>';
7916 2011
7917 - // Test button — branded .mxch-btn with inline SVG (IDs preserved for AJAX binding)
7918 - echo '<div class="mxch-streaming-test-row">';
7919 - echo '<button type="button" id="mxchat-test-streaming-btn" class="mxch-btn mxch-btn-secondary">';
7920 - echo '<svg class="mxch-streaming-test-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>';
7921 - echo esc_html__('Test Streaming Compatibility', 'mxchat');
7922 - echo '</button>';
7923 - echo '<p id="mxchat-test-streaming-result" class="mxch-streaming-test-result"></p>';
7924 - echo '</div>';
7925 -}
7926 -
7927 -// Web Search toggle callback
7928 -public function enable_web_search_toggle_callback() {
7929 - // Get value from options array, default to 'off'
7930 - $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
7931 - $checked = ($enabled === 'on') ? 'checked' : '';
7932 -
7933 - // Get current model to determine if we should show/enable the toggle
7934 - $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
7935 -
7936 - // Models that DON'T support web search — OpenAI-docs-driven exception list.
7937 - // Keep hardcoded; the catalog can't infer "supports web search" per-model, so any
7938 - // future OpenAI model that lacks Responses-API web_search support is added here.
7939 - $unsupported_models = array('gpt-4.1-nano');
7940 -
7941 - // Web-search-capable chat-model allowlists, derived from the central model catalog
7942 - // (class-mxchat-model-catalog.php). When a new OpenAI/Gemini chat model is added there,
7943 - // the Web Search toggle picks it up automatically — no edit here.
7944 - // OpenAI grounds via the Responses-API web_search tool; Gemini grounds natively via the
7945 - // Google Search tool (plan 46b9ea wired the Gemini dispatch — every shipped Gemini chat
7946 - // model is 2.x/3.x and grounds, matching that path's empty opt-out list, so all catalog
7947 - // Gemini models are supported here).
7948 - if (!class_exists('MxChat_Model_Catalog')) {
7949 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
2012 + if (!$this->is_activated) {
2013 + echo '<div class="pro-feature-overlay">';
2014 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2015 + echo '</div>';
7950 2016 }
7951 - $chat_catalog = MxChat_Model_Catalog::chat_models();
7952 - $openai_models = (isset($chat_catalog['openai']['models']) && is_array($chat_catalog['openai']['models']))
7953 - ? array_keys($chat_catalog['openai']['models'])
7954 - : array();
7955 - $gemini_models = (isset($chat_catalog['gemini']['models']) && is_array($chat_catalog['gemini']['models']))
7956 - ? array_keys($chat_catalog['gemini']['models'])
7957 - : array();
7958 2017
7959 - $is_capable = in_array($current_model, $openai_models) || in_array($current_model, $gemini_models);
7960 - $is_supported = $is_capable && !in_array($current_model, $unsupported_models);
7961 -
7962 - // Wrapper div with data attributes for JS to show/hide. data-openai-models is kept for
7963 - // back-compat; data-gemini-models is the added second provider the JS now also honors.
7964 - echo '<div id="web-search-toggle-wrapper" data-openai-models="' . esc_attr(implode(',', $openai_models)) . '" data-gemini-models="' . esc_attr(implode(',', $gemini_models)) . '" data-unsupported-models="' . esc_attr(implode(',', $unsupported_models)) . '"' . (!$is_supported ? ' style="display:none;"' : '') . '>';
7965 -
7966 - echo '<label class="toggle-switch">';
7967 - echo sprintf(
7968 - '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
7969 - esc_attr($checked)
7970 - );
7971 - echo '<span class="slider"></span>';
7972 - echo '</label>';
7973 -
7974 2018 echo '</div>';
2019 + }
7975 2020
7976 - // Message shown when a model that can't ground (Claude, Grok, DeepSeek, OpenRouter, etc.) is selected
7977 - echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
7978 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
7979 - echo esc_html__('Web search is only available for OpenAI and Gemini models.', 'mxchat');
7980 - echo '</p>';
7981 -}
2021 + public function mxchat_chatbot_bg_color_callback() {
2022 + $disabled = $this->is_activated ? '' : 'disabled';
7982 2023
7983 -// AJAX handler to fetch OpenRouter models
7984 -public function fetch_openrouter_models() {
7985 - check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
2024 + echo '<div class="pro-feature-wrapper">';
2025 + printf(
2026 + '<input type="text" id="chatbot_bg_color" name="mxchat_options[chatbot_bg_color]" value="%s" class="my-color-field" data-default-color="#f9f9f9" %s />',
2027 + isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '',
2028 + esc_attr($disabled)
2029 + );
7986 2030
7987 - // plan-mxchat-20260731-c63fb6 — nonce is not authorization.
7988 - if (!current_user_can('manage_options')) {
7989 - wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')), 403);
7990 - }
2031 + if (!$this->is_activated) {
2032 + echo '<div class="pro-feature-overlay">';
2033 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2034 + echo '</div>';
2035 + }
7991 2036
7992 - $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
7993 -
7994 - if (empty($api_key)) {
7995 - wp_send_json_error(array('message' => 'API key is required'));
2037 + echo '</div>';
7996 2038 }
7997 -
7998 - $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
7999 - 'headers' => array(
8000 - 'Authorization' => 'Bearer ' . $api_key,
8001 - 'Content-Type' => 'application/json',
8002 - ),
8003 - 'timeout' => 15,
8004 - ));
8005 -
8006 - if (is_wp_error($response)) {
8007 - wp_send_json_error(array('message' => $response->get_error_message()));
8008 - }
8009 -
8010 - $body = wp_remote_retrieve_body($response);
8011 - $data = json_decode($body, true);
8012 -
8013 - if (isset($data['data']) && is_array($data['data'])) {
8014 - // Format the models for the frontend
8015 - $models = array_map(function($model) {
8016 - return array(
8017 - 'id' => $model['id'],
8018 - 'name' => $model['name'] ?? $model['id'],
8019 - 'description' => $model['description'] ?? '',
8020 - 'context_length' => $model['context_length'] ?? 0,
8021 - 'pricing' => array(
8022 - 'prompt' => $model['pricing']['prompt'] ?? 0,
8023 - 'completion' => $model['pricing']['completion'] ?? 0,
8024 - ),
8025 - );
8026 - }, $data['data']);
8027 -
8028 - wp_send_json_success(array('models' => $models));
8029 - } else {
8030 - wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
8031 - }
8032 -}
8033 2039
8034 -// Callback function for embedding model selection
8035 -public function embedding_model_callback() {
8036 - $models = array(
8037 - esc_html__('OpenAI Embeddings', 'mxchat') => array(
8038 - 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
8039 - 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
8040 - 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
8041 - ),
8042 - esc_html__('Voyage AI Embeddings', 'mxchat') => array(
8043 - 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
8044 - ),
8045 - esc_html__('Google Gemini Embeddings', 'mxchat') => array(
8046 - 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
8047 - )
8048 - );
8049 - $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
8050 - // With custom-provider embeddings on, this picker is inert — the effective
8051 - // model comes from the Custom Embedding Model field (plan ae02cb). Autosave
8052 - // fires only on user change events, so the disabled attribute cannot cause
8053 - // a missing-key save; JS keeps the state in sync with the toggle live.
8054 - $custom_embeddings_on = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
8055 - echo '<select id="embedding_model" name="embedding_model"' . ($custom_embeddings_on ? ' disabled' : '') . '>';
8056 - foreach ($models as $group_label => $group_models) {
8057 - echo '<optgroup label="' . esc_attr($group_label) . '">';
8058 - foreach ($group_models as $model_value => $model_label) {
8059 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
8060 - }
8061 - echo '</optgroup>';
8062 - }
8063 - echo '</select>';
8064 - echo '<p class="mxch-field-description mxchat-embedding-custom-note" id="mxchat_embedding_custom_note"' . ($custom_embeddings_on ? '' : ' style="display:none;"') . '>';
8065 - echo esc_html__('Custom provider embeddings are in use — the model is set in the Custom Embedding Model field under Custom Provider.', 'mxchat');
8066 - echo '</p>';
2040 + public function mxchat_user_message_bg_color_callback() {
2041 + $disabled = $this->is_activated ? '' : 'disabled';
8067 2042
8068 - // API Key Status Messages for Embedding Models
8069 - $has_openai_key = !empty($this->options['api_key']);
8070 - $has_voyage_key = !empty($this->options['voyage_api_key']);
8071 - $has_gemini_key = !empty($this->options['gemini_api_key']);
2043 + echo '<div class="pro-feature-wrapper">';
2044 + printf(
2045 + '<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 />',
2046 + isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '',
2047 + esc_attr($disabled)
2048 + );
8072 2049
8073 - // OpenAI Embeddings
8074 - echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
8075 - if ($has_openai_key) {
8076 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8077 - } else {
8078 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8079 - }
8080 - echo '</p>';
2050 + if (!$this->is_activated) {
2051 + echo '<div class="pro-feature-overlay">';
2052 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2053 + echo '</div>';
2054 + }
8081 2055
8082 - // Voyage AI Embeddings
8083 - echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
8084 - if ($has_voyage_key) {
8085 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
8086 - } else {
8087 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
2056 + echo '</div>';
8088 2057 }
8089 - echo '</p>';
8090 2058
8091 - // Gemini Embeddings
8092 - echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
8093 - if ($has_gemini_key) {
8094 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8095 - } else {
8096 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8097 - }
8098 - echo '</p>';
2059 + public function mxchat_user_message_font_color_callback() {
2060 + $disabled = $this->is_activated ? '' : 'disabled';
8099 2061
8100 -}
2062 + echo '<div class="pro-feature-wrapper">';
2063 + printf(
2064 + '<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 />',
2065 + isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '',
2066 + esc_attr($disabled)
2067 + );
8101 2068
2069 + if (!$this->is_activated) {
2070 + echo '<div class="pro-feature-overlay">';
2071 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2072 + echo '</div>';
2073 + }
8102 2074
8103 -public function mxchat_top_bar_title_callback() {
8104 - // Retrieve the current value of the top bar title from saved options
8105 - $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
2075 + echo '</div>';
2076 + }
8106 2077
8107 - // Render the input field
8108 - echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
8109 -}
8110 -public function mxchat_ai_agent_text_callback() {
8111 - // Retrieve the current value of the AI agent text from saved options
8112 - $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
8113 - // Render the input field
8114 - echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
8115 -}
2078 + public function mxchat_bot_message_bg_color_callback() {
2079 + $disabled = $this->is_activated ? '' : 'disabled';
8116 2080
2081 + echo '<div class="pro-feature-wrapper">';
2082 + printf(
2083 + '<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 />',
2084 + isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '',
2085 + esc_attr($disabled)
2086 + );
8117 2087
8118 -public function enable_email_block_callback() {
8119 - // Load full plugin options array
8120 - $all_options = get_option('mxchat_options', []);
2088 + if (!$this->is_activated) {
2089 + echo '<div class="pro-feature-overlay">';
2090 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2091 + echo '</div>';
2092 + }
8121 2093
8122 - // Get the value, default to 'off'
8123 - $enable_email_block = isset($all_options['enable_email_block']) ? $all_options['enable_email_block'] : 'off';
2094 + echo '</div>';
2095 + }
8124 2096
8125 - // Check if it's 'on'
8126 - $checked = ($enable_email_block === 'on') ? 'checked' : '';
2097 + public function mxchat_bot_message_font_color_callback() {
2098 + $disabled = $this->is_activated ? '' : 'disabled';
8127 2099
8128 - echo '<label class="toggle-switch">';
8129 - echo sprintf(
8130 - '<input type="checkbox" id="enable_email_block" name="enable_email_block" value="on" %s />',
8131 - esc_attr($checked)
8132 - );
8133 - echo '<span class="slider"></span>';
8134 - echo '</label>';
8135 -}
2100 + echo '<div class="pro-feature-wrapper">';
2101 + printf(
2102 + '<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 />',
2103 + isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '',
2104 + esc_attr($disabled)
2105 + );
8136 2106
8137 -public function email_blocker_header_content_callback() {
8138 - // Load the entire 'mxchat_options' array
8139 - $all_options = get_option('mxchat_options', []);
2107 + if (!$this->is_activated) {
2108 + echo '<div class="pro-feature-overlay">';
2109 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2110 + echo '</div>';
2111 + }
8140 2112
8141 - // Retrieve the saved content or default to empty
8142 - $content = isset($all_options['email_blocker_header_content'])
8143 - ? $all_options['email_blocker_header_content']
8144 - : '';
2113 + echo '</div>';
2114 + }
8145 2115
8146 - // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
8147 - echo '<textarea
8148 - id="email_blocker_header_content"
8149 - name="email_blocker_header_content"
8150 - rows="5"
8151 - cols="70"
8152 - data-setting="email_blocker_header_content"
8153 - >' . esc_textarea($content) . '</textarea>';
8154 -}
2116 + public function mxchat_top_bar_bg_color_callback() {
2117 + $disabled = $this->is_activated ? '' : 'disabled';
8155 2118
8156 -public function email_blocker_button_text_callback() {
8157 - // Load the entire 'mxchat_options' array
8158 - $all_options = get_option('mxchat_options', []);
2119 + echo '<div class="pro-feature-wrapper">';
2120 + printf(
2121 + '<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 />',
2122 + isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '',
2123 + esc_attr($disabled)
2124 + );
8159 2125
8160 - // Retrieve the saved button text or default to empty
8161 - $button_text = isset($all_options['email_blocker_button_text'])
8162 - ? $all_options['email_blocker_button_text']
8163 - : '';
2126 + if (!$this->is_activated) {
2127 + echo '<div class="pro-feature-overlay">';
2128 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2129 + echo '</div>';
2130 + }
8164 2131
8165 - // Use esc_attr to safely render the existing text
8166 - echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
8167 -}
2132 + echo '</div>';
2133 + }
8168 2134
8169 -//Enable name field callback
8170 -public function enable_name_field_callback() {
8171 - // Load full plugin options array
8172 - $all_options = get_option('mxchat_options', []);
8173 - // Get the value, default to 'off'
8174 - $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
8175 - // Check if it's 'on'
8176 - $checked = ($enable_name_field === 'on') ? 'checked' : '';
8177 - echo '<label class="toggle-switch">';
8178 - echo sprintf(
8179 - '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
8180 - esc_attr($checked)
8181 - );
8182 - echo '<span class="slider"></span>';
8183 - echo '</label>';
8184 -}
8185 -//Name field placeholder callback
8186 -public function name_field_placeholder_callback() {
8187 - $all_options = get_option('mxchat_options', []);
8188 - $placeholder = isset($all_options['name_field_placeholder'])
8189 - ? $all_options['name_field_placeholder']
8190 - : esc_html__('Enter your name', 'mxchat');
2135 + public function mxchat_send_button_font_color_callback() {
2136 + $disabled = $this->is_activated ? '' : 'disabled';
8191 2137
8192 - echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
8193 -}
2138 + echo '<div class="pro-feature-wrapper">';
2139 + printf(
2140 + '<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 />',
2141 + isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '',
2142 + esc_attr($disabled)
2143 + );
8194 2144
2145 + if (!$this->is_activated) {
2146 + echo '<div class="pro-feature-overlay">';
2147 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2148 + echo '</div>';
2149 + }
8195 2150
2151 + echo '</div>';
2152 + }
8196 2153
8197 -public function mxchat_intro_message_callback() {
8198 - // Load the entire 'mxchat_options' array
8199 - $all_options = get_option('mxchat_options', []);
8200 - // Retrieve the saved intro message or use the default
8201 - $default_message = __('Hello! How can I assist you today?', 'mxchat');
8202 - $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
8203 - // Escape on output (esc_textarea) — neutralizes any payload already stored before the
8204 - // Wordfence Stored-XSS fix (CWE-79, plan-3f8158) and prevents </textarea> context-breakout.
8205 - ?>
8206 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea( $saved_message ); ?></textarea>
8207 - <p class="description" style="margin-top: 8px;">
8208 - <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
8209 - <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
8210 - </p>
8211 - <?php
8212 -}
2154 + public function mxchat_chatbot_background_color_callback() {
2155 + $disabled = $this->is_activated ? '' : 'disabled';
8213 2156
8214 -public function mxchat_input_copy_callback() {
8215 - // Load the entire 'mxchat_options' array
8216 - $all_options = get_option('mxchat_options', []);
2157 + echo '<div class="pro-feature-wrapper">';
2158 + printf(
2159 + '<input type="text" id="chatbot_background_color" name="mxchat_options[chatbot_background_color]" value="%s" class="my-color-field" data-default-color="#000000" %s />',
2160 + isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '',
2161 + esc_attr($disabled)
2162 + );
8217 2163
8218 - // Retrieve the saved input copy or use the default value
8219 - $default_copy = __('How can I assist?', 'mxchat');
8220 - $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
2164 + if (!$this->is_activated) {
2165 + echo '<div class="pro-feature-overlay">';
2166 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2167 + echo '</div>';
2168 + }
8221 2169
8222 - // Output the input field with the saved value
8223 - printf(
8224 - '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
8225 - esc_attr($input_copy),
8226 - esc_attr__('How can I assist?', 'mxchat')
8227 - );
8228 -}
2170 + echo '</div>';
2171 + }
8229 2172
2173 + public function mxchat_icon_color_callback() {
2174 + $disabled = $this->is_activated ? '' : 'disabled';
8230 2175
8231 -public function mxchat_append_to_body_callback() {
8232 - // Fetch fresh options to ensure we have the latest saved values
8233 - $options = get_option('mxchat_options', array());
2176 + echo '<div class="pro-feature-wrapper">';
2177 + printf(
2178 + '<input type="text" id="icon_color" name="mxchat_options[icon_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
2179 + isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '',
2180 + esc_attr($disabled)
2181 + );
8234 2182
8235 - // Get value from options array, default to 'off'
8236 - $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
8237 - $checked = ($append_to_body === 'on') ? 'checked' : '';
2183 + if (!$this->is_activated) {
2184 + echo '<div class="pro-feature-overlay">';
2185 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2186 + echo '</div>';
2187 + }
8238 2188
8239 - // Get post type visibility settings
8240 - $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
8241 - $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
8242 - if (!is_array($visibility_list)) {
8243 - $visibility_list = array();
2189 + echo '</div>';
8244 2190 }
8245 2191
8246 - echo '<div class="mxchat-autosave-section">';
2192 + public function mxchat_chat_input_font_color_callback() {
2193 + $disabled = $this->is_activated ? '' : 'disabled';
8247 2194
8248 - // Main toggle
8249 - echo '<label class="toggle-switch">';
8250 - echo sprintf(
8251 - '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
8252 - esc_attr($checked)
8253 - );
8254 - echo '<span class="slider"></span>';
8255 - echo '</label>';
2195 + echo '<div class="pro-feature-wrapper">';
2196 + printf(
2197 + '<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 />',
2198 + isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '',
2199 + esc_attr($disabled)
2200 + );
8256 2201
8257 - // Post Type Visibility Options (only visible when auto-display is ON)
8258 - $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
8259 - echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8260 -
8261 - echo '<div class="mxchat-post-type-visibility-header">';
8262 - echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
8263 - echo '</div>';
8264 -
8265 - // Mode selector (radio buttons)
8266 - echo '<div class="mxchat-visibility-mode">';
8267 -
8268 - echo '<label class="mxchat-radio-label">';
8269 - echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
8270 - echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
8271 - echo '</label>';
8272 -
8273 - echo '<label class="mxchat-radio-label">';
8274 - echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
8275 - echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
8276 - echo '</label>';
8277 -
8278 - echo '<label class="mxchat-radio-label">';
8279 - echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
8280 - echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
8281 - echo '</label>';
8282 -
8283 - echo '</div>';
8284 -
8285 - // Post type checkboxes (only visible when mode is include or exclude)
8286 - $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
8287 - echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
8288 -
8289 - // Get all public post types
8290 - $post_types = get_post_types(array('public' => true), 'objects');
8291 -
8292 - foreach ($post_types as $post_type) {
8293 - // Skip attachments
8294 - if ($post_type->name === 'attachment') {
8295 - continue;
2202 + if (!$this->is_activated) {
2203 + echo '<div class="pro-feature-overlay">';
2204 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2205 + echo '</div>';
8296 2206 }
8297 2207
8298 - $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
8299 -
8300 - echo '<label class="mxchat-checkbox-label">';
8301 - echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
8302 - echo '<span>' . esc_html($post_type->label) . '</span>';
8303 - echo '</label>';
2208 + echo '</div>';
8304 2209 }
8305 2210
8306 - echo '</div>'; // End post-type-list
8307 - echo '</div>'; // End post-type-visibility-options
8308 - echo '</div>'; // End mxchat-autosave-section
8309 -}
8310 2211
8311 -public function mxchat_contextual_awareness_callback() {
8312 - // Get value from options array, default to 'off'
8313 - $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
8314 - $checked = ($contextual_awareness === 'on') ? 'checked' : '';
2212 +public function mxchat_append_to_body_callback() {
2213 + $append_to_body_checked = isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on' ? 'checked' : '';
8315 2214 echo '<label class="toggle-switch">';
8316 - echo sprintf(
8317 - '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
8318 - esc_attr($checked)
2215 + printf(
2216 + '<input type="checkbox" id="append_to_body" name="mxchat_options[append_to_body]" %s />',
2217 + esc_attr($append_to_body_checked)
8319 2218 );
8320 2219 echo '<span class="slider"></span>';
8321 2220 echo '</label>';
2221 +echo '<p class="description">Enable this option to automatically append the chat widget to the body of every page (recommended). No need to manually use the shortcode [mxchat_chatbot floating="yes"].</p>';
8322 2222 }
8323 2223
8324 -public function mxchat_citation_links_toggle_callback() {
8325 - // Get value from options array, default to 'on' (enabled by default)
8326 - $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
8327 - $checked = ($citation_links === 'on') ? 'checked' : '';
8328 - echo '<label class="toggle-switch">';
8329 - echo sprintf(
8330 - '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
8331 - esc_attr($checked)
8332 - );
8333 - echo '<span class="slider"></span>';
8334 - echo '</label>';
8335 -}
8336 2224
8337 -/**
8338 - * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
8339 - * Default ON. The widget reads this through the localized object; the
8340 - * mxchat_satisfaction_rating_enabled filter still lets developers force
8341 - * the value site-wide.
8342 - *
8343 - * The 5 customization fields (idle/question/thanks/placeholder/saved) are
8344 - * rendered inline here inside a single wrapper div whose initial display
8345 - * is set server-side from the toggle value (plan-29caac). Mirrors the
8346 - * auto-display chatbot pattern at mxchat_append_to_body_callback — no
8347 - * DOMContentLoaded race because rows exist as direct children of this
8348 - * callback's output, and the wrapper's display: none is inline at render
8349 - * time so refresh shows the correct state with no flash.
8350 - */
8351 -public function mxchat_satisfaction_rating_toggle_callback() {
8352 - $options = $this->options;
8353 - $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
8354 - $checked = ($value === 'on') ? 'checked' : '';
8355 -
8356 - $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
8357 - $idle = max(5, min(600, $idle));
8358 - $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
8359 - $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
8360 - $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
8361 - $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
8362 -
8363 - echo '<div class="mxchat-autosave-section">';
8364 -
8365 - echo '<label class="toggle-switch">';
8366 - echo sprintf(
8367 - '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
8368 - esc_attr($checked)
8369 - );
8370 - echo '<span class="slider"></span>';
8371 - echo '</label>';
8372 -
8373 - ?>
8374 - <style>
8375 - .mxchat-sub-options-field { margin: 12px 0; }
8376 - .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
8377 - #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
8378 - </style>
8379 - <?php
8380 -
8381 - $display_style = ($value === 'on') ? '' : 'display: none;';
8382 - echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8383 -
8384 - echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
8385 -
8386 - echo '<div class="mxchat-sub-options-field">';
8387 - echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
8388 - printf(
8389 - '<input type="number" id="satisfaction_rating_idle_seconds" name="satisfaction_rating_idle_seconds" value="%d" min="5" max="600" step="1" class="small-text" /> <span class="description">%s</span>',
8390 - (int) $idle,
8391 - esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
8392 - );
8393 - echo '</div>';
8394 -
8395 - echo '<div class="mxchat-sub-options-field">';
8396 - echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
8397 - printf(
8398 - '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8399 - esc_attr($question),
8400 - esc_attr__('Was this helpful?', 'mxchat')
8401 - );
8402 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
8403 - echo '</div>';
8404 -
8405 - echo '<div class="mxchat-sub-options-field">';
8406 - echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
8407 - printf(
8408 - '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
8409 - esc_attr($thanks),
8410 - esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
8411 - );
8412 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
8413 - echo '</div>';
8414 -
8415 - echo '<div class="mxchat-sub-options-field">';
8416 - echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
8417 - printf(
8418 - '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8419 - esc_attr($placeholder),
8420 - esc_attr__('Tell us what could be better…', 'mxchat')
8421 - );
8422 - echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
8423 - echo '</div>';
8424 -
8425 - echo '<div class="mxchat-sub-options-field">';
8426 - echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
8427 - printf(
8428 - '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8429 - esc_attr($saved),
8430 - esc_attr__('Thanks for the feedback.', 'mxchat')
8431 - );
8432 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
8433 - echo '</div>';
8434 -
8435 - echo '</div>'; // #satisfaction-rating-sub-options
8436 - echo '</div>'; // .mxchat-autosave-section
8437 -
8438 - ?>
8439 - <script>
8440 - (function() {
8441 - document.addEventListener('DOMContentLoaded', function() {
8442 - var toggle = document.getElementById('satisfaction_rating_enabled');
8443 - var subOptions = document.getElementById('satisfaction-rating-sub-options');
8444 - if (!toggle || !subOptions) return;
8445 - toggle.addEventListener('change', function() {
8446 - subOptions.style.display = toggle.checked ? '' : 'none';
8447 - });
8448 - });
8449 - })();
8450 - </script>
8451 - <?php
8452 -}
8453 -
8454 2225 public function mxchat_privacy_toggle_callback() {
8455 - // Load from mxchat_options array
8456 - $options = get_option('mxchat_options', []);
2226 + // Check if the privacy toggle is enabled
2227 + $privacy_toggle_checked = isset($this->options['privacy_toggle']) && $this->options['privacy_toggle'] === 'on' ? 'checked' : '';
8457 2228
8458 - // Get privacy toggle value with fallback
8459 - $privacy_toggle = isset($options['privacy_toggle']) ? $options['privacy_toggle'] : 'off';
8460 - $checked = ($privacy_toggle === 'on') ? 'checked' : '';
2229 + // Retrieve the stored privacy text if it exists
2230 + $privacy_text = isset($this->options['privacy_text']) ? wp_kses_post($this->options['privacy_text']) : 'By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.';
8461 2231
8462 - // Get privacy text with fallback
8463 - $privacy_text = isset($options['privacy_text'])
8464 - ? $options['privacy_text']
8465 - : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
8466 -
8467 2232 // Output the toggle switch
8468 2233 echo '<label class="toggle-switch">';
8469 - echo sprintf(
8470 - '<input type="checkbox" id="privacy_toggle" name="privacy_toggle" value="on" %s />',
8471 - esc_attr($checked)
2234 + printf(
2235 + '<input type="checkbox" id="privacy_toggle" name="mxchat_options[privacy_toggle]" %s />',
2236 + esc_attr($privacy_toggle_checked)
8472 2237 );
8473 2238 echo '<span class="slider"></span>';
8474 2239 echo '</label>';
2240 + echo '<p class="description">Enable this option to display a privacy notice below the chat widget.</p>';
8475 2241
8476 2242 // Output the custom text input field
8477 - echo sprintf(
8478 - '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
2243 + printf(
2244 + '<textarea id="privacy_text" name="mxchat_options[privacy_text]" rows="5" cols="50" class="regular-text">%s</textarea>',
8479 2245 esc_textarea($privacy_text)
8480 2246 );
2247 + echo '<p class="description">Enter the privacy policy text. You can include HTML links.</p>';
8481 2248 }
8482 2249
8483 2250
8484 2251 public function mxchat_complianz_toggle_callback() {
8485 - // Load from mxchat_options array
8486 - $options = get_option('mxchat_options', []);
2252 + // Check if the Complianz toggle is enabled
2253 + $complianz_toggle_checked = isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on' ? 'checked' : '';
8487 2254
8488 - // Get complianz toggle value with fallback
8489 - $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
8490 - $checked = ($complianz_toggle === 'on') ? 'checked' : '';
2255 + // Check if the plugin is activated (paid feature)
2256 + $disabled = $this->is_activated ? '' : 'disabled';
2257 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8491 2258
2259 + echo '<div class="' . esc_attr($class) . '">';
2260 +
8492 2261 // Output the toggle switch
8493 2262 echo '<label class="toggle-switch">';
8494 - echo sprintf(
8495 - '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
8496 - esc_attr($checked)
2263 + printf(
2264 + '<input type="checkbox" id="complianz_toggle" name="mxchat_options[complianz_toggle]" %s %s />',
2265 + esc_attr($complianz_toggle_checked),
2266 + esc_attr($disabled)
8497 2267 );
8498 2268 echo '<span class="slider"></span>';
8499 2269 echo '</label>';
8500 -}
2270 + echo '<p class="description">Enable this option to apply Complianz consent logic to the chatbot.</p>';
8501 2271
8502 -public function mxchat_link_target_toggle_callback() {
8503 - // Load from mxchat_options array
8504 - $options = get_option('mxchat_options', []);
2272 + // If the feature is not activated, show the Pro feature overlay
2273 + if (!$this->is_activated) {
2274 + echo '<div class="pro-feature-overlay">';
2275 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2276 + echo '</div>';
2277 + }
8505 2278
8506 - // Get link target toggle value with fallback
8507 - $link_target_toggle = isset($options['link_target_toggle']) ? $options['link_target_toggle'] : 'off';
8508 - $checked = ($link_target_toggle === 'on') ? 'checked' : '';
8509 -
8510 - // Output the toggle switch
8511 - echo '<label class="toggle-switch">';
8512 - echo sprintf(
8513 - '<input type="checkbox" id="link_target_toggle" name="link_target_toggle" value="on" %s />',
8514 - esc_attr($checked)
8515 - );
8516 - echo '<span class="slider"></span>';
8517 - echo '</label>';
2279 + echo '</div>';
8518 2280 }
8519 2281
8520 -public function mxchat_chat_persistence_toggle_callback() {
8521 - // Load from mxchat_options array
8522 - $options = get_option('mxchat_options', []);
8523 2282
8524 - // Get chat persistence toggle value with fallback
8525 - $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
8526 - $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
8527 2283
8528 - // Output the toggle switch
8529 - echo '<label class="toggle-switch">';
8530 - echo sprintf(
8531 - '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
8532 - esc_attr($checked)
8533 - );
8534 - echo '<span class="slider"></span>';
8535 - echo '</label>';
8536 -}
8537 2284
8538 -public function mxchat_print_button_toggle_callback() {
8539 - // Load from mxchat_options array
8540 - $options = get_option('mxchat_options', []);
8541 2285
8542 - // Default ON — the option was previously unexposed and the button always showed.
8543 - $print_button_enabled = isset($options['print_button_enabled']) ? $options['print_button_enabled'] : 'on';
8544 - $checked = ($print_button_enabled === 'on') ? 'checked' : '';
2286 +public function mxchat_link_target_toggle_callback() {
2287 + // Check if the toggle is enabled in the options
2288 + $link_target_toggle = isset($this->options['link_target_toggle']) && $this->options['link_target_toggle'] === 'on' ? 'checked' : '';
8545 2289
8546 2290 // Output the toggle switch
8547 2291 echo '<label class="toggle-switch">';
8548 - echo sprintf(
8549 - '<input type="checkbox" id="print_button_enabled" name="print_button_enabled" value="on" %s />',
8550 - esc_attr($checked)
2292 + printf(
2293 + '<input type="checkbox" id="link_target_toggle" name="mxchat_options[link_target_toggle]" %s />',
2294 + esc_attr($link_target_toggle)
8551 2295 );
8552 2296 echo '<span class="slider"></span>';
8553 2297 echo '</label>';
2298 + echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
8554 2299 }
8555 2300
8556 -/**
8557 - * Editor Assistant toggle (plan-8cb0cb). Standalone option, NOT in mxchat_options
8558 - * (bypasses the mxchat_sanitize strip-trap + autosave normalization). Default OFF.
8559 - * Saved by the mxchat_editor_assistant_enabled case in class-ajax-handler.php.
8560 - * Renders on Content → Settings (moved there from Settings → Behavior, plan-f7df40).
8561 - */
8562 -public function mxchat_editor_assistant_toggle_callback() {
8563 - $enabled = get_option('mxchat_editor_assistant_enabled', 'off');
8564 - $checked = ($enabled === 'on') ? 'checked' : '';
2301 +public function mxchat_chat_persistence_toggle_callback() {
2302 + // Check if chat persistence toggle is enabled
2303 + $chat_persistence_toggle_checked = isset($this->options['chat_persistence_toggle']) && $this->options['chat_persistence_toggle'] === 'on' ? 'checked' : '';
8565 2304
8566 - echo '<label class="toggle-switch">';
8567 - echo sprintf(
8568 - '<input type="checkbox" id="mxchat_editor_assistant_enabled" name="mxchat_editor_assistant_enabled" value="on" %s />',
8569 - esc_attr($checked)
8570 - );
8571 - echo '<span class="slider"></span>';
8572 - echo '</label>';
8573 -}
2305 + // Check if the plugin is activated (paid feature)
2306 + $disabled = $this->is_activated ? '' : 'disabled';
2307 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8574 2308
8575 -/**
8576 - * Hybrid keyword boost toggle (plan-38ffa1; rebuilt on the house toggle pattern
8577 - * in plan-64d34f — the hand-rolled .mxch-toggle markup matched neither selector
8578 - * the autosave JS uses to place its save confirmation, so the control looked
8579 - * dead). Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8580 - * mxchat_hybrid_keyword_toggle case in class-ajax-handler.php, which also runs
8581 - * capability detection on enable.
8582 - */
8583 -public function mxchat_hybrid_keyword_toggle_callback() {
8584 - $enabled = get_option('mxchat_hybrid_keyword_toggle', 'off');
8585 - $checked = ($enabled === 'on') ? 'checked' : '';
2309 + echo '<div class="' . esc_attr($class) . '">';
8586 2310
2311 + // Output the toggle switch
8587 2312 echo '<label class="toggle-switch">';
8588 - echo sprintf(
8589 - '<input type="checkbox" id="mxchat_hybrid_keyword_toggle" name="mxchat_hybrid_keyword_toggle" value="on" %s />',
8590 - esc_attr($checked)
2313 + printf(
2314 + '<input type="checkbox" id="chat_persistence_toggle" name="mxchat_options[chat_persistence_toggle]" %s %s />',
2315 + esc_attr($chat_persistence_toggle_checked),
2316 + esc_attr($disabled)
8591 2317 );
8592 2318 echo '<span class="slider"></span>';
8593 2319 echo '</label>';
8594 -}
2320 + echo '<p class="description">Enable to keep chat history when users navigate tabs or return to the site within 24 hours.</p>';
8595 2321
8596 -/**
8597 - * Smart asset loading toggle (plan-915355; rebuilt on the house toggle pattern
8598 - * in plan-64d34f, same dead-save-feedback defect as the hybrid keyword toggle).
8599 - * Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8600 - * mxchat_smart_asset_loading case in class-ajax-handler.php.
8601 - */
8602 -public function mxchat_smart_asset_loading_toggle_callback() {
8603 - $enabled = get_option('mxchat_smart_asset_loading', 'off');
8604 - $checked = ($enabled === 'on') ? 'checked' : '';
2322 + // If not activated, show Pro feature overlay
2323 + if (!$this->is_activated) {
2324 + echo '<div class="pro-feature-overlay">';
2325 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2326 + echo '</div>';
2327 + }
8605 2328
8606 - echo '<label class="toggle-switch">';
8607 - echo sprintf(
8608 - '<input type="checkbox" id="mxchat_smart_asset_loading" name="mxchat_smart_asset_loading" value="on" %s />',
8609 - esc_attr($checked)
8610 - );
8611 - echo '<span class="slider"></span>';
8612 - echo '</label>';
2329 + echo '</div>';
8613 2330 }
8614 2331
8615 -public function mxchat_reset_chat_toggle_callback() {
8616 - // Load from mxchat_options array. plan ac2e81 — default OFF (new, opt-in).
8617 - $options = get_option('mxchat_options', []);
8618 - $reset_chat_enabled = isset($options['reset_chat_enabled']) ? $options['reset_chat_enabled'] : 'off';
8619 - $checked = ($reset_chat_enabled === 'on') ? 'checked' : '';
8620 2332
8621 - echo '<label class="toggle-switch">';
8622 - echo sprintf(
8623 - '<input type="checkbox" id="reset_chat_enabled" name="reset_chat_enabled" value="on" %s />',
8624 - esc_attr($checked)
8625 - );
8626 - echo '<span class="slider"></span>';
8627 - echo '</label>';
8628 -}
8629 -
8630 -public function mxchat_reset_chat_label_callback() {
8631 - // Editable label for the "Start new chat" menu item. plan ac2e81.
8632 - $options = get_option('mxchat_options', []);
8633 - $reset_chat_label = isset($options['reset_chat_label']) ? $options['reset_chat_label'] : '';
8634 -
8635 - printf(
8636 - '<input type="text" id="reset_chat_label" name="reset_chat_label" value="%s" placeholder="%s" class="regular-text" />',
8637 - esc_attr($reset_chat_label),
8638 - esc_attr__('Start new chat', 'mxchat')
8639 - );
8640 -}
8641 -
8642 2333 public function mxchat_popular_question_1_callback() {
8643 - // Load the full plugin options array
8644 - $all_options = get_option('mxchat_options', []);
8645 -
8646 - // Retrieve the specific option for popular_question_1
8647 - $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
8648 -
8649 - // Render the input field
8650 2334 printf(
8651 - '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
8652 - esc_attr($popular_question_1),
8653 - esc_attr__('Enter Quick Question 1', 'mxchat')
2335 + '<input type="text" id="popular_question_1" name="mxchat_options[popular_question_1]" value="%s" placeholder="Enter Popular Question 1" />',
2336 + isset($this->options['popular_question_1']) ? esc_attr($this->options['popular_question_1']) : ''
8654 2337 );
2338 + echo '<p class="description">This will be the first popular question in the chatbot.</p>';
8655 2339 }
8656 2340
8657 -
8658 2341 public function mxchat_popular_question_2_callback() {
8659 - // Load the full plugin options array
8660 - $all_options = get_option('mxchat_options', []);
2342 + // Check if the plugin is activated (paid feature)
2343 + $disabled = $this->is_activated ? '' : 'disabled';
2344 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8661 2345
8662 - // Retrieve the specific option for popular_question_2
8663 - $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
2346 + echo '<div class="' . esc_attr($class) . '">';
8664 2347
8665 - // Render the input field
8666 2348 printf(
8667 - '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
8668 - esc_attr($popular_question_2),
8669 - esc_attr__('Enter Quick Question 2', 'mxchat')
2349 + '<input type="text" id="popular_question_2" name="mxchat_options[popular_question_2]" value="%s" placeholder="Enter Popular Question 2" %s />',
2350 + isset($this->options['popular_question_2']) ? esc_attr($this->options['popular_question_2']) : '',
2351 + esc_attr($disabled)
8670 2352 );
8671 -}
2353 + echo '<p class="description">This will be the second popular question in the chatbot.</p>';
8672 2354
8673 -
8674 -public function mxchat_popular_question_3_callback() {
8675 - // Load the full plugin options array
8676 - $all_options = get_option('mxchat_options', []);
8677 -
8678 - // Retrieve the specific option for popular_question_3
8679 - $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
8680 -
8681 - // Render the input field
8682 - printf(
8683 - '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
8684 - esc_attr($popular_question_3),
8685 - esc_attr(__('Enter Quick Question 3', 'mxchat'))
8686 - );
8687 -}
8688 -
8689 -public function mxchat_additional_popular_questions_callback() {
8690 - $options = get_option('mxchat_options', []);
8691 - $additional_questions = isset($options['additional_popular_questions'])
8692 - ? $options['additional_popular_questions']
8693 - : get_option('additional_popular_questions', array());
8694 -
8695 - echo '<div id="mxchat-additional-questions-container">';
8696 - if (!empty($additional_questions)) {
8697 - foreach ($additional_questions as $index => $question) {
8698 - printf(
8699 - '<div class="mxchat-question-row">
8700 - <input type="text" name="additional_popular_questions[]"
8701 - value="%s"
8702 - placeholder="%s"
8703 - class="regular-text mxchat-question-input"
8704 - data-question-index="%d" />
8705 - <button type="button" class="button mxchat-remove-question"
8706 - aria-label="%s">%s</button>
8707 - </div>',
8708 - esc_attr($question),
8709 - esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
8710 - $index,
8711 - esc_attr(__('Remove question', 'mxchat')),
8712 - esc_html__('Remove', 'mxchat')
8713 - );
8714 - }
8715 - } else {
8716 - printf(
8717 - '<div class="mxchat-question-row">
8718 - <input type="text" name="additional_popular_questions[]"
8719 - value=""
8720 - placeholder="%s"
8721 - class="regular-text mxchat-question-input"
8722 - data-question-index="0" />
8723 - <button type="button" class="button mxchat-remove-question"
8724 - aria-label="%s">%s</button>
8725 - </div>',
8726 - esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
8727 - esc_attr(__('Remove question', 'mxchat')),
8728 - esc_html__('Remove', 'mxchat')
8729 - );
2355 + // If not activated, show Pro feature overlay
2356 + if (!$this->is_activated) {
2357 + echo '<div class="pro-feature-overlay">';
2358 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2359 + echo '</div>';
8730 2360 }
8731 - echo '</div>';
8732 - printf(
8733 - '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
8734 - esc_attr(__('Add question', 'mxchat')),
8735 - esc_html__('Add Question', 'mxchat')
8736 - );
8737 -}
8738 2361
8739 -public function mxchat_brave_api_key_callback() {
8740 - $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
8741 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8742 -
8743 - echo '<div class="api-key-wrapper">';
8744 - echo sprintf(
8745 - '<input type="text" id="brave_api_key" name="brave_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
8746 - $brave_api_key,
8747 - $nonce
8748 - );
8749 - echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8750 2362 echo '</div>';
8751 - echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
8752 2363 }
8753 2364
8754 -public function mxchat_brave_image_count_callback() {
8755 - $brave_image_count = isset($this->options['brave_image_count'])
8756 - ? intval($this->options['brave_image_count'])
8757 - : 4;
8758 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2365 +public function mxchat_popular_question_3_callback() {
2366 + // Check if the plugin is activated (paid feature)
2367 + $disabled = $this->is_activated ? '' : 'disabled';
2368 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8759 2369
8760 - echo '<div class="mxchat-field-wrapper">';
8761 - echo sprintf(
8762 - '<input type="number" id="brave_image_count" name="brave_image_count"
8763 - value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8764 - $brave_image_count,
8765 - $nonce
8766 - );
8767 - echo '</div>';
8768 - echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
8769 -}
2370 + echo '<div class="' . esc_attr($class) . '">';
8770 2371
8771 -public function mxchat_brave_safe_search_callback() {
8772 - $brave_safe_search = isset($this->options['brave_safe_search'])
8773 - ? esc_attr($this->options['brave_safe_search'])
8774 - : 'strict';
8775 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8776 -
8777 - echo '<div class="mxchat-field-wrapper">';
8778 - echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
8779 - echo sprintf(
8780 - '<option value="strict" %s>%s</option>',
8781 - selected($brave_safe_search, 'strict', false),
8782 - __('Strict', 'mxchat')
2372 + printf(
2373 + '<input type="text" id="popular_question_3" name="mxchat_options[popular_question_3]" value="%s" placeholder="Enter Popular Question 3" %s />',
2374 + isset($this->options['popular_question_3']) ? esc_attr($this->options['popular_question_3']) : '',
2375 + esc_attr($disabled)
8783 2376 );
8784 - echo sprintf(
8785 - '<option value="off" %s>%s</option>',
8786 - selected($brave_safe_search, 'off', false),
8787 - __('Off', 'mxchat')
8788 - );
8789 - echo '</select>';
8790 - echo '</div>';
8791 - echo '<p class="description">' .
8792 - esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
8793 - '</p>';
8794 -}
2377 + echo '<p class="description">This will be the third popular question in the chatbot.</p>';
8795 2378
8796 -public function mxchat_brave_news_count_callback() {
8797 - $brave_news_count = isset($this->options['brave_news_count'])
8798 - ? intval($this->options['brave_news_count'])
8799 - : 3;
8800 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2379 + // If not activated, show Pro feature overlay
2380 + if (!$this->is_activated) {
2381 + echo '<div class="pro-feature-overlay">';
2382 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2383 + echo '</div>';
2384 + }
8801 2385
8802 - echo '<div class="mxchat-field-wrapper">';
8803 - echo sprintf(
8804 - '<input type="number" id="brave_news_count" name="brave_news_count"
8805 - value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8806 - $brave_news_count,
8807 - $nonce
8808 - );
8809 2386 echo '</div>';
8810 - echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
8811 2387 }
8812 2388
8813 -public function mxchat_brave_country_callback() {
8814 - $brave_country = isset($this->options['brave_country'])
8815 - ? esc_attr($this->options['brave_country'])
8816 - : 'us';
8817 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8818 2389
8819 - echo '<div class="mxchat-field-wrapper">';
8820 - echo sprintf(
8821 - '<input type="text" id="brave_country" name="brave_country"
8822 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8823 - $brave_country,
8824 - $nonce
8825 - );
8826 - echo '</div>';
8827 - echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
8828 -}
2390 +/**
2391 + * Callback for Brave API Key field.
2392 + */
2393 +public function mxchat_brave_api_key_callback() {
2394 + $options = get_option('mxchat_options');
2395 + $brave_api_key = isset($options['brave_api_key']) ? esc_attr($options['brave_api_key']) : '';
8829 2396
8830 -public function mxchat_brave_language_callback() {
8831 - $brave_language = isset($this->options['brave_language'])
8832 - ? esc_attr($this->options['brave_language'])
8833 - : 'en';
8834 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8835 -
8836 - echo '<div class="mxchat-field-wrapper">';
8837 - echo sprintf(
8838 - '<input type="text" id="brave_language" name="brave_language"
8839 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8840 - $brave_language,
8841 - $nonce
2397 + echo '<div class="api-key-wrapper">';
2398 + printf(
2399 + '<input type="password" id="brave_api_key" name="mxchat_options[brave_api_key]" value="%s" class="regular-text" />',
2400 + $brave_api_key
8842 2401 );
2402 + echo '<button type="button" id="toggleBraveApiKeyVisibility" class="button-secondary">Show</button>';
8843 2403 echo '</div>';
8844 - echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
8845 -}
2404 + echo '<p class="description">' . __('Enter your Brave Search API Key here. (See FAQ for details)', 'mxchat') . '</p>';
8846 2405
8847 -
8848 -
8849 -
8850 -
8851 -// Section Callback
8852 -public function mxchat_pdf_intent_section_callback() {
8853 - echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
2406 + ?>
2407 + <?php
8854 2408 }
8855 2409
8856 -public function mxchat_chat_toolbar_toggle_callback() {
8857 - // Get chat toolbar toggle value with fallback
8858 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
8859 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
8860 -
8861 - // Output the toggle switch
8862 - echo '<label class="toggle-switch">';
8863 - echo sprintf(
8864 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
8865 - esc_attr($checked)
8866 - );
8867 - echo '<span class="slider"></span>';
8868 - echo '</label>';
8869 -
8870 - echo '<p class="description">' . esc_html__('Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).', 'mxchat') . '</p>';
8871 -}
8872 -
8873 2410 /**
8874 - * Callback for PDF upload button toggle setting
2411 + * Callback for Number of Images to Return field.
8875 2412 */
8876 -public function mxchat_show_pdf_upload_button_callback() {
8877 - // Get toggle value with fallback
8878 - $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
8879 - $checked = ($show_pdf_button === 'on') ? 'checked' : '';
2413 +public function mxchat_brave_image_count_callback() {
2414 + $options = get_option('mxchat_options');
2415 + $brave_image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
8880 2416
8881 - // Output the toggle switch
8882 - echo '<label class="toggle-switch">';
8883 - echo sprintf(
8884 - '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
8885 - esc_attr($checked)
2417 + printf(
2418 + '<input type="number" id="brave_image_count" name="mxchat_options[brave_image_count]" value="%d" min="1" max="6" />',
2419 + $brave_image_count
8886 2420 );
8887 - echo '<span class="slider"></span>';
8888 - echo '</label>';
8889 -
8890 - echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
2421 + echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
8891 2422 }
8892 2423
8893 2424 /**
8894 - * Callback for Word upload button toggle setting
2425 + * Callback for Safe Search field.
8895 2426 */
8896 -public function mxchat_show_word_upload_button_callback() {
8897 - // Get toggle value with fallback
8898 - $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
8899 - $checked = ($show_word_button === 'on') ? 'checked' : '';
2427 +public function mxchat_brave_safe_search_callback() {
2428 + $options = get_option('mxchat_options');
2429 + $brave_safe_search = isset($options['brave_safe_search']) ? esc_attr($options['brave_safe_search']) : 'strict';
8900 2430
8901 - // Output the toggle switch
8902 - echo '<label class="toggle-switch">';
8903 - echo sprintf(
8904 - '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
8905 - esc_attr($checked)
8906 - );
8907 - echo '<span class="slider"></span>';
8908 - echo '</label>';
8909 -
8910 - echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
2431 + ?>
2432 + <select id="brave_safe_search" name="mxchat_options[brave_safe_search]">
2433 + <option value="strict" <?php selected($brave_safe_search, 'strict'); ?>><?php _e('Strict', 'mxchat'); ?></option>
2434 + <option value="off" <?php selected($brave_safe_search, 'off'); ?>><?php _e('Off', 'mxchat'); ?></option>
2435 + </select>
2436 + <p class="description"><?php _e('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat'); ?></p>
2437 + <?php
8911 2438 }
8912 2439
8913 -public function mxchat_pdf_intent_trigger_text_callback() {
8914 - $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
8915 2440
8916 - echo sprintf(
8917 - '<textarea id="pdf_intent_trigger_text"
8918 - name="pdf_intent_trigger_text"
8919 - rows="3"
8920 - cols="50"
8921 - placeholder="%s">%s</textarea>',
8922 - esc_attr__('Enter trigger text', 'mxchat'),
8923 - isset($this->options['pdf_intent_trigger_text'])
8924 - ? esc_textarea($this->options['pdf_intent_trigger_text'])
8925 - : esc_textarea($default_text)
8926 - );
8927 - echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
8928 -}
8929 -
8930 -public function mxchat_pdf_intent_success_text_callback() {
8931 - $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
8932 -
8933 - echo sprintf(
8934 - '<textarea id="pdf_intent_success_text"
8935 - name="pdf_intent_success_text"
8936 - rows="3"
8937 - cols="50"
8938 - placeholder="%s">%s</textarea>',
8939 - esc_attr__('Enter success text', 'mxchat'),
8940 - isset($this->options['pdf_intent_success_text'])
8941 - ? esc_textarea($this->options['pdf_intent_success_text'])
8942 - : esc_textarea($default_text)
8943 - );
8944 - echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
8945 -}
8946 -
8947 -public function mxchat_pdf_intent_error_text_callback() {
8948 - $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
8949 -
8950 - echo sprintf(
8951 - '<textarea id="pdf_intent_error_text"
8952 - name="pdf_intent_error_text"
8953 - rows="3"
8954 - cols="50"
8955 - placeholder="%s">%s</textarea>',
8956 - esc_attr__('Enter error text', 'mxchat'),
8957 - isset($this->options['pdf_intent_error_text'])
8958 - ? esc_textarea($this->options['pdf_intent_error_text'])
8959 - : esc_textarea($default_text)
8960 - );
8961 - echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
8962 -}
8963 -
8964 -public function mxchat_pdf_max_pages_callback() {
8965 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
8966 -
8967 - echo sprintf(
8968 - '<input type="range"
8969 - id="pdf_max_pages"
8970 - name="pdf_max_pages"
8971 - min="1"
8972 - max="69"
8973 - value="%d"
8974 - class="range-slider" />',
8975 - esc_attr($max_pages)
8976 - );
8977 - echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
8978 - echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
8979 -}
8980 -
8981 -public function mxchat_live_agent_status_callback() {
8982 - // Always get fresh options instead of using cached $this->options
8983 - $fresh_options = get_option('mxchat_options');
8984 - $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
8985 -
8986 - echo '<label class="toggle-switch">';
8987 - echo sprintf(
8988 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
8989 - checked($status, 'on', false)
8990 - );
8991 - echo '<span class="slider"></span>';
8992 - echo '</label>';
8993 - echo '<label for="live_agent_status" class="mxchat-status-label">';
8994 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
8995 - echo '</label>';
8996 -}
8997 -
8998 2441 /**
8999 - * Availability-schedule editor (plans 8ccaa2 + 99d7a4).
9000 - *
9001 - * ONE callback, parameterized by channel ('slack' | 'telegram' via the
9002 - * add_settings_field $args) — the markup and CSS are shared, only the bound
9003 - * option and the helper text differ. Each channel's editor renders under its
9004 - * own Integrations tab and governs ONLY that channel's handoff. While the
9005 - * master toggle is off the day grid is inert and handoff availability stays
9006 - * governed solely by that channel's manual status toggle.
9007 - *
9008 - * The day inputs carry NO name attribute and are marked .mxchat-la-field so the
9009 - * generic autosave skips them; the editor JS folds them into the channel's
9010 - * hidden live_agent_schedule_<channel> input and fires one change, reusing the
9011 - * existing autosave transport rather than growing a second one. All hooks the
9012 - * JS needs are CLASSES scoped inside .mxchat-la-schedule, never ids — the
9013 - * markup exists twice on the page.
2442 + * Callback for Number of News Articles field.
9014 2443 */
9015 -public function mxchat_live_agent_schedule_callback($args = array()) {
9016 - if (!class_exists('MxChat_Live_Agent_Schedule')) {
9017 - return;
9018 - }
9019 - $channel = (isset($args['channel']) && $args['channel'] === 'telegram') ? 'telegram' : 'slack';
9020 - $field = 'live_agent_schedule_' . $channel;
9021 - $sched = MxChat_Live_Agent_Schedule::get($channel);
9022 - $labels = MxChat_Live_Agent_Schedule::day_labels();
9023 - $tz = MxChat_Live_Agent_Schedule::timezone_label();
9024 - $enabled = !empty($sched['enabled']);
9025 - $channel_label = ($channel === 'telegram') ? __('Telegram', 'mxchat') : __('Slack', 'mxchat');
9026 - ?>
9027 - <div class="mxchat-la-schedule<?php echo $enabled ? ' is-active' : ''; ?>"
9028 - id="mxchat-la-schedule-<?php echo esc_attr($channel); ?>"
9029 - data-channel="<?php echo esc_attr($channel); ?>">
9030 - <label class="toggle-switch">
9031 - <input type="checkbox" id="<?php echo esc_attr($field); ?>_enabled"
9032 - class="mxchat-la-field mxchat-la-enabled" <?php checked($enabled); ?> />
9033 - <span class="slider"></span>
9034 - </label>
9035 - <label for="<?php echo esc_attr($field); ?>_enabled" class="mxchat-status-label">
9036 - <span class="status-text mxchat-la-status-text">
9037 - <?php echo $enabled
9038 - ? esc_html__('Scheduled hours', 'mxchat')
9039 - : esc_html__('Always available', 'mxchat'); ?>
9040 - </span>
9041 - </label>
2444 +public function mxchat_brave_news_count_callback() {
2445 + $options = get_option('mxchat_options');
2446 + $brave_news_count = isset($options['brave_news_count']) ? intval($options['brave_news_count']) : 3;
9042 2447
9043 - <div class="mxchat-la-days" aria-hidden="<?php echo $enabled ? 'false' : 'true'; ?>">
9044 - <?php foreach ($labels as $n => $label) :
9045 - $day = $sched['days'][$n];
9046 - $on = !empty($day['enabled']);
9047 - ?>
9048 - <div class="mxchat-la-day<?php echo $on ? ' is-on' : ''; ?>" data-day="<?php echo esc_attr($n); ?>">
9049 - <label class="mxchat-la-day-label">
9050 - <input type="checkbox" class="mxchat-la-field mxchat-la-day-enabled"
9051 - data-day="<?php echo esc_attr($n); ?>" <?php checked($on); ?> />
9052 - <span class="mxchat-la-day-name"><?php echo esc_html($label); ?></span>
9053 - </label>
9054 - <div class="mxchat-la-times">
9055 - <input type="time" class="mxchat-la-field mxchat-la-start"
9056 - data-day="<?php echo esc_attr($n); ?>"
9057 - value="<?php echo esc_attr($day['start']); ?>"
9058 - aria-label="<?php echo esc_attr(sprintf(__('%s start time', 'mxchat'), $label)); ?>" />
9059 - <span class="mxchat-la-dash">&ndash;</span>
9060 - <input type="time" class="mxchat-la-field mxchat-la-end"
9061 - data-day="<?php echo esc_attr($n); ?>"
9062 - value="<?php echo esc_attr($day['end']); ?>"
9063 - aria-label="<?php echo esc_attr(sprintf(__('%s end time', 'mxchat'), $label)); ?>" />
9064 - </div>
9065 - </div>
9066 - <?php endforeach; ?>
9067 - </div>
9068 -
9069 - <input type="hidden" name="<?php echo esc_attr($field); ?>" id="<?php echo esc_attr($field); ?>"
9070 - class="mxchat-la-hidden" value="<?php echo esc_attr(wp_json_encode($sched)); ?>" />
9071 - </div>
9072 - <p class="description">
9073 - <?php printf(
9074 - /* translators: 1: the handoff channel, e.g. Slack or Telegram; 2: the site's timezone, e.g. America/New_York */
9075 - esc_html__('When on, visitors are only offered a %1$s human handoff during these hours — outside them the chatbot keeps answering and never offers to fetch an agent. Applies to %1$s only. Times use the site timezone (%2$s). Set a day\'s end time earlier than its start for an overnight shift; identical start and end means all day.', 'mxchat'),
9076 - '<strong>' . esc_html($channel_label) . '</strong>',
9077 - '<strong>' . esc_html($tz) . '</strong>'
9078 - ); ?>
9079 - </p>
9080 - <?php
9081 -}
9082 -
9083 -public function mxchat_live_agent_away_message_callback() {
9084 - $message = isset($this->options['live_agent_away_message'])
9085 - ? $this->options['live_agent_away_message']
9086 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9087 -
9088 2448 printf(
9089 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
9090 - esc_textarea($message)
2449 + '<input type="number" id="brave_news_count" name="mxchat_options[brave_news_count]" value="%d" min="1" max="10" />',
2450 + $brave_news_count
9091 2451 );
9092 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
2452 + echo '<p class="description">' . __('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
9093 2453 }
9094 2454
9095 -public function mxchat_live_agent_notification_message_callback() {
9096 - $message = isset($this->options['live_agent_notification_message'])
9097 - ? $this->options['live_agent_notification_message']
9098 - : __('Live agent has been notified.', 'mxchat');
2455 +/**
2456 + * Callback for Country field.
2457 + */
2458 +public function mxchat_brave_country_callback() {
2459 + $options = get_option('mxchat_options');
2460 + $brave_country = isset($options['brave_country']) ? esc_attr($options['brave_country']) : 'us';
9099 2461
9100 2462 printf(
9101 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
9102 - esc_textarea($message)
2463 + '<input type="text" id="brave_country" name="mxchat_options[brave_country]" value="%s" maxlength="2" class="small-text" />',
2464 + $brave_country
9103 2465 );
9104 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
2466 + echo '<p class="description">' . __('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
9105 2467 }
9106 2468
9107 -public function mxchat_live_agent_webhook_url_callback() {
9108 - $webhook_url = isset($this->options['live_agent_webhook_url'])
9109 - ? esc_url($this->options['live_agent_webhook_url'])
9110 - : esc_url(get_option('live_agent_webhook_url', ''));
9111 -
9112 - printf(
9113 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
9114 - $webhook_url
9115 - );
9116 - echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9117 - echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
9118 -}
9119 -
9120 -public function mxchat_live_agent_secret_key_callback() {
9121 - printf(
9122 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
9123 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
9124 - );
9125 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9126 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
9127 -}
9128 -
9129 -public function mxchat_live_agent_bot_token_callback() {
9130 - printf(
9131 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
9132 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
9133 - );
9134 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9135 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
9136 -}
9137 -
9138 -public function mxchat_live_agent_user_ids_callback() {
9139 - $user_ids = isset($this->options['live_agent_user_ids'])
9140 - ? esc_textarea($this->options['live_agent_user_ids'])
9141 - : '';
9142 -
9143 - printf(
9144 - '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
9145 - $user_ids
9146 - );
9147 - echo '<p class="description">' . esc_html__('Enter Slack User IDs of agents who should be automatically invited to chat channels (one per line). Find user IDs in Slack profiles under "More" → "Copy member ID". Example: U1234567890', 'mxchat') . '</p>';
9148 -}
9149 -
9150 -public function mxchat_live_agent_shared_channel_callback() {
9151 - $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : '';
9152 - printf(
9153 - '<input type="text" id="live_agent_shared_channel" name="live_agent_shared_channel" value="%s" class="regular-text" placeholder="#support or C0123456789" />',
9154 - esc_attr($value)
9155 - );
9156 - echo '<p class="description">' . esc_html__('Optional. Route ALL live agent handoffs into this one existing Slack channel — each conversation becomes its own thread there. Enter a channel ID (starts with C) or a #channel-name, and invite your bot to the channel first (/invite @YourBot). Agents reply inside a conversation\'s thread; !endchat inside the thread ends that chat. Leave blank to keep creating a separate chat- channel per conversation.', 'mxchat') . '</p>';
9157 -
9158 - // Surface the last failed handoff so a wrong name / missing invite is
9159 - // visible right where it gets fixed. A successful handoff clears this.
9160 - $shared_error = get_option('mxchat_slack_shared_channel_error');
9161 - if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) {
9162 - echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . '</strong> — '
9163 - . esc_html(sprintf(
9164 - /* translators: %s: Slack API error code */
9165 - __('Slack said "%s". Handoffs are falling back to per-conversation channels until this is fixed. Check the channel name or ID and make sure the bot has been invited to it.', 'mxchat'),
9166 - $shared_error['error']
9167 - )) . '</p>';
9168 - }
9169 -}
9170 -
9171 -public function mxchat_live_agent_archive_on_end_callback() {
9172 - $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off';
9173 - printf(
9174 - '<input type="checkbox" id="live_agent_archive_on_end_toggle" name="live_agent_archive_on_end_toggle" value="on" %s />',
9175 - checked('on', $value, false)
9176 - );
9177 - echo '<label for="live_agent_archive_on_end_toggle" class="mxchat-status-label">' . esc_html__('Archive the conversation\'s chat- channel when an agent ends the chat with !endchat', 'mxchat') . '</label>';
9178 - echo '<p class="description">' . esc_html__('Keeps your Slack sidebar tidy on busy sites — each ended conversation\'s channel is archived instead of living forever. Archived channels stay searchable in Slack, so the record is never lost. Only applies to per-conversation chat- channels; a Shared Handoff Channel is never archived. If a returning visitor requests an agent again, a fresh channel is created automatically.', 'mxchat') . '</p>';
9179 -}
9180 -
9181 2469 /**
9182 - * Telegram Integration Callbacks
2470 + * Callback for Language field.
9183 2471 */
9184 -public function mxchat_telegram_section_callback() {
9185 - echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
9186 -}
2472 +public function mxchat_brave_language_callback() {
2473 + $options = get_option('mxchat_options');
2474 + $brave_language = isset($options['brave_language']) ? esc_attr($options['brave_language']) : 'en';
9187 2475
9188 -public function mxchat_telegram_status_callback() {
9189 - $fresh_options = get_option('mxchat_options');
9190 - $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
9191 -
9192 - echo '<label class="toggle-switch">';
9193 - echo sprintf(
9194 - '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
9195 - checked($status, 'on', false)
2476 + printf(
2477 + '<input type="text" id="brave_language" name="mxchat_options[brave_language]" value="%s" maxlength="2" class="small-text" />',
2478 + $brave_language
9196 2479 );
9197 - echo '<span class="slider"></span>';
9198 - echo '</label>';
9199 - echo '<label for="telegram_status" class="mxchat-status-label">';
9200 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9201 - echo '</label>';
2480 + echo '<p class="description">' . __('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
9202 2481 }
9203 2482
9204 -public function mxchat_telegram_notification_message_callback() {
9205 - $message = isset($this->options['telegram_notification_message'])
9206 - ? $this->options['telegram_notification_message']
9207 - : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
9208 2483
9209 - printf(
9210 - '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
9211 - esc_textarea($message)
9212 - );
9213 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9214 -}
9215 2484
9216 -public function mxchat_telegram_away_message_callback() {
9217 - $message = isset($this->options['telegram_away_message'])
9218 - ? $this->options['telegram_away_message']
9219 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9220 2485
9221 - printf(
9222 - '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
9223 - esc_textarea($message)
9224 - );
9225 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9226 -}
9227 2486
9228 -public function mxchat_telegram_bot_token_callback() {
9229 - printf(
9230 - '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
9231 - isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
9232 - );
9233 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_bot_token\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9234 - echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
9235 -}
9236 2487
9237 -public function mxchat_telegram_group_id_callback() {
9238 - printf(
9239 - '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
9240 - isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
9241 - );
9242 - echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
9243 -}
9244 2488
9245 -public function mxchat_telegram_webhook_secret_callback() {
9246 - $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
9247 2489
9248 - // Auto-generate secret if empty
9249 - if (empty($secret)) {
9250 - $secret = wp_generate_password(64, false, false);
9251 - $options = get_option('mxchat_options', []);
9252 - $options['telegram_webhook_secret'] = $secret;
9253 - update_option('mxchat_options', $options);
9254 - $this->options['telegram_webhook_secret'] = $secret;
9255 - }
9256 2490
9257 - printf(
9258 - '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
9259 - esc_attr($secret)
9260 - );
9261 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_webhook_secret\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9262 - echo '<p class="description">' . esc_html__('Secret token for webhook verification. Use this when setting up your Telegram webhook with the secret_token parameter.', 'mxchat') . '</p>';
9263 -}
2491 + public function mxchat_enqueue_admin_assets() {
2492 + wp_enqueue_style('wp-color-picker');
9264 2493
9265 -public function mxchat_similarity_threshold_callback() {
9266 - // Load from mxchat_options array
9267 - $options = get_option('mxchat_options', []);
2494 + // Get the plugin version or file modification time for cache busting
2495 + $plugin_version = '1.4'; // Replace this with your plugin's version
9268 2496
9269 - // Get value from options array with default of 35
9270 - $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
2497 + // File paths
2498 + $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
2499 + $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
2500 + $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
2501 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
9271 2502
9272 - echo '<div class="slider-container">';
9273 - echo sprintf(
9274 - '<input type="range"
9275 - id="similarity_threshold"
9276 - name="similarity_threshold"
9277 - min="20"
9278 - max="85"
9279 - step="1"
9280 - value="%s"
9281 - class="range-slider" />',
9282 - esc_attr($threshold)
9283 - );
9284 - echo sprintf(
9285 - '<span id="threshold_value" class="range-value">%s</span>',
9286 - esc_html($threshold)
9287 - );
9288 - echo '</div>';
9289 -}
2503 + // Check if files exist and get modification times
2504 + $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
2505 + $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
2506 + $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
2507 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
9290 2508
9291 -public function mxchat_max_input_length_callback() {
9292 - // Load from mxchat_options array (plan a3fae2 part C).
9293 - $options = get_option('mxchat_options', []);
2509 + // Enqueue scripts and styles with corrected paths
2510 + wp_enqueue_script(
2511 + 'mxchat-color-picker',
2512 + plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
2513 + array('wp-color-picker'),
2514 + $color_picker_version,
2515 + true
2516 + );
9294 2517
9295 - // 0 = unlimited (default — preserves current behavior, no cap).
9296 - $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0;
2518 + wp_enqueue_script(
2519 + 'mxchat-embedding-check',
2520 + plugin_dir_url(__FILE__) . '../js/embedding-check.js',
2521 + array(),
2522 + $embedding_check_version,
2523 + true
2524 + );
9297 2525
9298 - echo sprintf(
9299 - '<input type="number"
9300 - id="max_input_length"
9301 - name="max_input_length"
9302 - min="0"
9303 - max="100000"
9304 - step="1"
9305 - value="%s"
9306 - placeholder="0"
9307 - class="mxch-input mxch-input-sm" />',
9308 - esc_attr($max_input_length)
9309 - );
9310 -}
2526 + wp_enqueue_script(
2527 + 'mxchat-transcripts-js',
2528 + plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
2529 + array('jquery'),
2530 + $transcripts_js_version,
2531 + true
2532 + );
9311 2533
9312 -public function mxchat_rag_sources_limit_callback() {
9313 - // Load from mxchat_options array
9314 - $options = get_option('mxchat_options', []);
2534 + wp_enqueue_script(
2535 + 'mxchat-admin-js',
2536 + plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
2537 + array('jquery'),
2538 + $plugin_version,
2539 + true
2540 + );
9315 2541
9316 - // Get value from options array with default of 3
9317 - $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
9318 2542
9319 - echo '<div class="slider-container">';
9320 - echo sprintf(
9321 - '<input type="range"
9322 - id="rag_sources_limit"
9323 - name="rag_sources_limit"
9324 - min="3"
9325 - max="10"
9326 - step="1"
9327 - value="%s"
9328 - class="range-slider" />',
9329 - esc_attr($rag_sources_limit)
9330 - );
9331 - echo sprintf(
9332 - '<span id="rag_sources_limit_value" class="range-value">%s</span>',
9333 - esc_html($rag_sources_limit)
9334 - );
9335 - echo '</div>';
9336 -}
9337 2543
9338 -public function mxchat_rag_chunks_limit_callback() {
9339 - // Load from mxchat_options array
9340 - $options = get_option('mxchat_options', []);
2544 + // Localize the script with data for the activation process
2545 + wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
2546 + 'ajax_url' => admin_url('admin-ajax.php'),
2547 + 'nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
2548 + ));
9341 2549
9342 - // Get value from options array with default of 15
9343 - $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
2550 + wp_enqueue_style(
2551 + 'mxchat-admin-css',
2552 + plugin_dir_url(__FILE__) . '../css/admin-style.css',
2553 + array(),
2554 + $admin_css_version
2555 + );
9344 2556
9345 - echo '<div class="slider-container">';
9346 - echo sprintf(
9347 - '<input type="range"
9348 - id="rag_chunks_limit"
9349 - name="rag_chunks_limit"
9350 - min="8"
9351 - max="20"
9352 - step="1"
9353 - value="%s"
9354 - class="range-slider" />',
9355 - esc_attr($rag_chunks_limit)
9356 - );
9357 - echo sprintf(
9358 - '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
9359 - esc_html($rag_chunks_limit)
9360 - );
9361 - echo '</div>';
9362 -}
2557 + wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
2558 + 'ajax_url' => admin_url('admin-ajax.php'),
2559 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
2560 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
2561 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
2562 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
2563 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
2564 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
2565 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
2566 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
2567 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
2568 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
2569 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
2570 + 'pre_chat_message' => $this->options['pre_chat_message'] ?? 'Hey there! Ask me anything!',
2571 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9363 2572
9364 -/**
9365 - * Add body class on the Onboarding wizard page so CSS-only chrome surgery
9366 - * (collapsing the WP admin sidebar) only applies on this page.
9367 - * Plan: plan-mxchat-20260527-905439.
9368 - */
9369 -public function mxchat_add_onboarding_body_class($classes) {
9370 - if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') {
9371 - $classes .= ' mxchat-onboarding-focused';
9372 - }
9373 - return $classes;
9374 -}
2573 + // New fields for Loops Integration
2574 + 'loops_api_key' => $this->options['loops_api_key'] ?? '',
2575 + 'loops_mailing_list' => $this->options['loops_mailing_list'] ?? '',
2576 + 'triggered_phrase_response' => $this->options['triggered_phrase_response'] ?? 'Would you like to join our mailing list? Please provide your email below.',
2577 + 'email_capture_response' => $this->options['email_capture_response'] ?? 'Thank you for providing your email! You\'ve been added to our list.'
2578 + ));
9375 2579
9376 -public function mxchat_enqueue_admin_assets($hook_suffix = '') {
9377 - // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY
9378 - // guard here was the strpos() on $_GET['page'] below — which is
9379 - // attacker-controlled — so ANY logged-in user (Subscriber included) could
9380 - // load a page they are legitimately allowed to see, e.g.
9381 - // /wp-admin/profile.php?page=mxchat, and receive every nonce this method
9382 - // localizes. Three of the handlers behind those nonces verified the nonce
9383 - // but checked no capability. Every MxChat menu page is registered
9384 - // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for
9385 - // legitimate users.
9386 - if (!current_user_can('manage_options')) {
9387 - return;
9388 - }
2580 + // Localize the script to pass the nonce and other data to JavaScript
2581 + wp_localize_script('mxchat-admin-js', 'mxchatInlineEdit', array(
2582 + 'nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
2583 + 'ajax_url' => admin_url('admin-ajax.php')
2584 + ));
9389 2585
9390 - // Get plugin version
9391 - $version = MXCHAT_VERSION;
9392 2586
9393 - // Use file modification time for development (remove in production)
9394 - if (defined('WP_DEBUG') && WP_DEBUG) {
9395 - $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
9396 2587 }
9397 2588
9398 - $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
9399 - $plugin_url = plugin_dir_url(__FILE__) . '../';
2589 + public function mxchat_sanitize($input) {
2590 + $new_input = array();
9400 2591
9401 - // Only load on MxChat pages. Prefer the server-derived $hook_suffix that
9402 - // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be
9403 - // forged onto a screen MxChat does not own. Falls back to the legacy
9404 - // $_GET check only when the hook is unavailable (direct/legacy callers).
9405 - if ($hook_suffix !== '') {
9406 - if (strpos($hook_suffix, 'mxchat') === false) {
9407 - return;
2592 + if (isset($input['api_key'])) {
2593 + $new_input['api_key'] = sanitize_text_field($input['api_key']);
9408 2594 }
9409 - } elseif (strpos($current_page, 'mxchat') === false) {
9410 - return;
9411 - }
9412 2595
9413 - // Always load these on all MxChat pages
9414 - $this->enqueue_core_admin_assets($plugin_url, $version);
9415 - $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
9416 - $this->localize_admin_scripts($current_page);
9417 -}
9418 -private function enqueue_core_admin_assets($plugin_url, $version) {
9419 - // Core admin styles
9420 - wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
9421 - wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
2596 + if (isset($input['xai_api_key'])) {
2597 + $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
2598 + }
9422 2599
9423 - // New sidebar navigation styles (for main settings page)
9424 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
2600 + if (isset($input['claude_api_key'])) {
2601 + $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
2602 + }
9425 2603
9426 - // Core admin scripts
9427 - wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
9428 -}
9429 -private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
9430 - switch ($current_page) {
9431 - case 'mxchat-prompts':
9432 - // Shared shell JS: tab switching, deep-linking and the mobile menu
9433 - // for this page's flat nav (inline copies removed by plan c192a4).
9434 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9435 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9436 - 'copied' => __('Copied', 'mxchat'),
9437 - ));
9438 - // Knowledge processing page assets
9439 - wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
9440 - wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
9441 - // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
9442 - wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
9443 - // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the
9444 - // Testing tab's match-card / chunk-detail components, which are scoped
9445 - // under .mxch-testing-results. Load that stylesheet here so the inspector
9446 - // modal renders identically to the Testing tab.
9447 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version);
9448 - break;
2604 + if (isset($input['enable_woocommerce_integration'])) {
2605 + $new_input['enable_woocommerce_integration'] = isset($input['enable_woocommerce_integration']) && $input['enable_woocommerce_integration'] === '1' ? '1' : '0';
9449 2606
9450 - case 'mxchat-transcripts':
9451 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9452 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9453 - // Load transcripts-specific styles
9454 - wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
9455 - wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
9456 - break;
2607 + }
9457 2608
9458 - case 'mxchat-actions':
9459 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9460 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9461 - // Load actions-specific styles
9462 - wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
9463 - wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
2609 + if (isset($input['privacy_toggle'])) {
2610 + $new_input['privacy_toggle'] = $input['privacy_toggle'];
2611 + }
9464 2612
9465 - // Localize script data for actions page
9466 - $is_activated = get_option('mxchat_pro_license_status') === 'active';
9467 - wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
9468 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9469 - 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
9470 - 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9471 - 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
9472 - 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
9473 - 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
9474 - 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9475 - 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9476 - 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9477 - 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9478 - 'isActivated' => $is_activated,
9479 - 'i18n' => array(
9480 - 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'),
9481 - 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'),
9482 - 'saving' => __('Saving...', 'mxchat'),
9483 - 'saved' => __('Saved successfully!', 'mxchat'),
9484 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9485 - 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
9486 - 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
9487 - )
9488 - ));
9489 - break;
2613 + if (isset($input['complianz_toggle'])) {
2614 + $new_input['complianz_toggle'] = $input['complianz_toggle'];
2615 + }
9490 2616
9491 - case 'mxchat-activation':
9492 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9493 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9494 - // Load pro page-specific styles
9495 - wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
9496 - // Load pro page JavaScript
9497 - wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
9498 - // Load activation script for license activation/deactivation
9499 - wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
9500 - break;
2617 + // Handle custom privacy text input
2618 + if (isset($input['privacy_text'])) {
2619 + // Allow basic HTML for links
2620 + $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
2621 + }
9501 2622
9502 - case 'mxchat-content':
9503 - // Load admin sidebar CSS (shared styles for sidebar navigation)
9504 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9505 - // Load content page-specific styles
9506 - wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
9507 - // Load content page JavaScript
9508 - wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
9509 - break;
2623 + if (isset($input['system_prompt_instructions'])) {
2624 + $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
2625 + }
9510 2626
9511 - case 'mxchat-api-access':
9512 - // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
9513 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9514 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9515 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9516 - 'copied' => __('Copied', 'mxchat'),
9517 - ));
9518 - break;
2627 + if (isset($input['mxchat_pro_email'])) {
2628 + $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
2629 + }
9519 2630
9520 - case 'mxchat-max':
9521 - case 'mxchat-onboarding':
9522 - // Onboarding page — uses the shared admin shell PLUS the wizard
9523 - // overlay (plan-905439). admin-onboarding-wizard.css scopes the
9524 - // WP-chrome surgery to body.mxchat-onboarding-focused so it only
9525 - // applies on THIS page. The body class is added below via the
9526 - // admin_body_class filter.
9527 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9528 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9529 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9530 - 'copied' => __('Copied', 'mxchat'),
9531 - ));
9532 - // admin-style.css provides the .mxchat-instructions-modal-* classes
9533 - // the new Behavior step's "View Sample Instructions" modal needs.
9534 - // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay
9535 - // so the wizard's own rules win where they collide. plan-a2e4d6.
9536 - wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version);
9537 - wp_enqueue_style('mxchat-admin-onboarding-wizard-css', $plugin_url . 'css/admin-onboarding-wizard.css', array('mxchat-admin-sidebar-css', 'mxchat-admin-style-css'), $version);
9538 - wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true);
9539 - break;
9540 - default:
9541 - // Settings page: load the shared shell JS for #hash deep-linking
9542 - // to tabs (plan 4ede16). The page's own inline nav script owns
9543 - // clicks/accordion behaviour; the shell script adds load +
9544 - // hashchange activation and replaceState so plain href="#tab"
9545 - // anchors and shared URLs land on the right tab. Kept inside the
9546 - // default case because the settings page also needs everything
9547 - // below (Testing tab chatbot + streaming assets).
9548 - if ($current_page === 'mxchat-settings') {
9549 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9550 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9551 - 'copied' => __('Copied', 'mxchat'),
9552 - ));
9553 - }
2631 + if (isset($input['mxchat_activation_key'])) {
2632 + $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
2633 + }
9554 2634
9555 - wp_enqueue_script(
9556 - 'mxchat-test-streaming-js',
9557 - $plugin_url . 'js/mxchat-test-streaming.js',
9558 - ['jquery'],
9559 - $version,
9560 - true
9561 - );
2635 + if (isset($input['append_to_body'])) {
2636 + $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
2637 + }
9562 2638
9563 - wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
9564 - 'ajax_url' => admin_url('admin-ajax.php'),
9565 - 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
9566 - 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
9567 - ]);
2639 + if (isset($input['top_bar_title'])) {
2640 + $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
2641 + }
9568 2642
9569 - // Testing Tab: Load chatbot assets for the embedded testing chatbot
9570 - wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
9571 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
2643 + if (isset($input['intro_message'])) {
2644 + $new_input['intro_message'] = sanitize_text_field($input['intro_message']);
2645 + }
9572 2646
9573 - wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
9574 - wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
2647 + if (isset($input['input_copy'])) {
2648 + $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
2649 + }
9575 2650
9576 - // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
9577 - do_action('mxchat_enqueue_testing_tab_assets');
9578 2651
9579 - // Localize mxchatChat for the chatbot JS (same settings as frontend)
9580 - $options = get_option('mxchat_options', array());
9581 - $prompts_options = get_option('mxchat_prompts_options', array());
9582 - $theme_options = get_option('mxchat_theme_options', array());
9583 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
9584 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
9585 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
2652 + if (isset($input['rate_limit_message'])) {
2653 + $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
2654 + }
9586 2655
9587 - wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
9588 - 'ajax_url' => admin_url('admin-ajax.php'),
9589 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
9590 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
9591 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
9592 - 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
9593 - 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
9594 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9595 - 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
9596 - 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
9597 - 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
9598 - 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
9599 - 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
9600 - 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
9601 - 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
9602 - 'close_button_color' => $options['close_button_color'] ?? '#fff',
9603 - 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
9604 - 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
9605 - 'icon_color' => $options['icon_color'] ?? '#fff',
9606 - 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
9607 - 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
9608 - 'appendWidgetToBody' => 'off',
9609 - 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
9610 - 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
9611 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
9612 - 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
9613 - 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
9614 - 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
9615 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
9616 - 'email_collection_enabled' => 'off', // No email collection in testing
9617 - 'initial_email_state' => null,
9618 - 'skip_email_check' => true,
9619 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
9620 - 'skip_inline_colors' => $skip_inline_colors,
9621 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
9622 - ));
2656 + if (isset($input['rate_limit'])) {
2657 + $allowed_limits = array('5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
2658 + $rate_limit = sanitize_text_field($input['rate_limit']);
9623 2659
9624 - // Localize testing tab script data
9625 - wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
9626 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9627 - 'nonce' => wp_create_nonce('mxchat_test_nonce'),
9628 - 'isAdmin' => true,
9629 - 'testingEnabled' => true
9630 - ));
9631 -
9632 - // Add testing enabled flag for the chatbot to return debug data
9633 - add_action('admin_footer', function() {
9634 - echo '<script>window.mxchatTestingEnabled = true;</script>';
9635 - });
9636 -
9637 - break;
9638 - }
9639 -}
9640 -/**
9641 - * The base mxchatAdmin payload shared by every MxChat admin page.
9642 - *
9643 - * Extracted (plan c192a4) so page-specific re-localizations of the SAME
9644 - * global — the knowledge page prints a second `var mxchatAdmin` via the
9645 - * mxchat-knowledge-processing handle, and last-printed wins — can merge
9646 - * their extra keys on top of this instead of silently narrowing the object
9647 - * that mxchat-admin.js also reads on that page.
9648 - */
9649 -private function mxchat_get_admin_base_localization() {
9650 - return array(
9651 - 'ajax_url' => admin_url('admin-ajax.php'),
9652 - 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
9653 - 'admin_url' => admin_url(),
9654 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
9655 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
9656 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9657 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9658 - 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9659 - 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9660 - 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
9661 - 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9662 - 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9663 - 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9664 - 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9665 - 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9666 - 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
9667 - 'is_activated' => $this->is_activated ? '1' : '0',
9668 - 'status_refresh_interval' => 5000,
9669 - 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'),
9670 - 'unsaved_label' => __('Unsaved', 'mxchat'),
9671 - // Live-agent schedule status text (plan 8ccaa2).
9672 - 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'),
9673 - 'i18n_always_available' => __('Always available', 'mxchat'),
9674 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9675 - 'ajaxurl' => admin_url('admin-ajax.php')
9676 - );
9677 -}
9678 -private function localize_admin_scripts($current_page) {
9679 - // Base localization data for main admin script
9680 - $base_data = $this->mxchat_get_admin_base_localization();
9681 -
9682 - // Localize main admin script with base data
9683 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
9684 -
9685 - // Canonical chat-model catalog for the modal picker grid
9686 - // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php
9687 - // automatically appears here.
9688 - if (!class_exists('MxChat_Model_Catalog')) {
9689 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
9690 - }
9691 - wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape());
9692 -
9693 - // Page-specific localizations
9694 - $this->localize_page_specific_scripts($current_page);
9695 -}
9696 -private function localize_page_specific_scripts($current_page) {
9697 - switch ($current_page) {
9698 - case 'mxchat-prompts':
9699 - // Status updater localization
9700 - wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
9701 - 'ajax_url' => admin_url('admin-ajax.php'),
9702 - 'nonce' => wp_create_nonce('mxchat_status_nonce')
9703 - ));
9704 -
9705 - // Content selector localization
9706 - wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
9707 - 'ajaxurl' => admin_url('admin-ajax.php'),
9708 - 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
9709 - 'i18n' => array(
9710 - 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
9711 - 'selectAll' => __('Select All', 'mxchat'),
9712 - 'process' => __('Process Selected', 'mxchat'),
9713 - 'cancel' => __('Cancel', 'mxchat'),
9714 - 'noResults' => __('No content found.', 'mxchat'),
9715 - 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
9716 - 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
9717 - )
9718 - ));
9719 -
9720 - // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's
9721 - // base one) and last-printed wins — so it must carry the FULL base
9722 - // payload plus the knowledge-page extras, or every mxchatAdmin.*
9723 - // key mxchat-admin.js reads on this page comes up undefined
9724 - // (plan c192a4). Extras merge last: status_refresh_interval stays
9725 - // at this page's faster 2000ms cadence.
9726 - wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge(
9727 - $this->mxchat_get_admin_base_localization(),
9728 - array(
9729 - 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
9730 - 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
9731 - 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
9732 - 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9733 - 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
9734 - 'status_refresh_interval' => 2000,
9735 - 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
9736 - )
9737 - ));
9738 - break;
9739 -
9740 - case 'mxchat-activation':
9741 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9742 - // fixed here by a5b297): this second `var mxchatAdmin` must carry
9743 - // the full base payload plus the page extras.
9744 - wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge(
9745 - $this->mxchat_get_admin_base_localization(),
9746 - array(
9747 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
9748 - )
9749 - ));
9750 - break;
9751 -
9752 - case 'mxchat-content':
9753 - wp_localize_script('mxchat-content-js', 'mxchatContent', array(
9754 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9755 - 'nonce' => wp_create_nonce('mxchat_content_nonce'),
9756 - 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9757 - 'previewUrl' => home_url('/?p='),
9758 - 'isActivated' => $this->is_activated(),
9759 - 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
9760 - 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
9761 - // Whether Search Console is actually LINKED — distinct from hasGSC
9762 - // (add-on active). Reads the same option the add-on's settings
9763 - // card keys off; harmless false when the add-on is absent.
9764 - 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false),
9765 - 'seoOptimize' => array(
9766 - 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
9767 - 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
9768 - 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
9769 - 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
9770 - 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
9771 - 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
9772 - 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
9773 - ),
9774 - 'i18n' => array(
9775 - 'generating' => __('Generating...', 'mxchat'),
9776 - 'planning' => __('Planning content structure...', 'mxchat'),
9777 - 'images' => __('Generating images...', 'mxchat'),
9778 - 'writing' => __('Writing full content...', 'mxchat'),
9779 - 'creating' => __('Creating WordPress post...', 'mxchat'),
9780 - 'done' => __('Content generated successfully!', 'mxchat'),
9781 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9782 - 'editSuccess' => __('Content updated successfully.', 'mxchat'),
9783 - 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
9784 - )
9785 - ));
9786 - break;
9787 -
9788 - case 'mxchat-transcripts':
9789 - // Get chart data for localization
9790 - $chart_data = $this->get_transcripts_chart_data();
9791 -
9792 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9793 - // fixed here by a5b297): merge the base payload under the page keys.
9794 - // export_nonce/setting_nonce/ajax_url duplicate base values identically;
9795 - // delete_nonce and translate_nonce are the page-specific adds.
9796 - wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge(
9797 - $this->mxchat_get_admin_base_localization(),
9798 - array(
9799 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9800 - 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
9801 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9802 - 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
9803 - )
9804 - ));
9805 -
9806 - // Localize chart data separately - use array_values to ensure proper JSON array encoding
9807 - wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
9808 - 'labels' => array_values($chart_data['labels']),
9809 - 'chats' => array_values($chart_data['chats']),
9810 - 'messages' => array_values($chart_data['messages'])
9811 - ));
9812 - break;
9813 -
9814 - case 'mxchat-settings':
9815 - default:
9816 - // The 'mxchatStyleSettings' localize that used to live here was
9817 - // REMOVED by plan-mxchat-20260731-c63fb6.
9818 - //
9819 - // It targeted the script handle 'mxchat-color-picker', which is
9820 - // registered/enqueued NOWHERE in the plugin — so wp_localize_script()
9821 - // returned false and printed nothing. That accident was the only
9822 - // thing keeping it from being a live secret disclosure: the payload
9823 - // carried loops_api_key, live_agent_secret_key and
9824 - // live_agent_bot_token in full, and this whole method ran for any
9825 - // logged-in user (see the capability gate added to
9826 - // mxchat_enqueue_admin_assets). One future
9827 - // wp_enqueue_script('mxchat-color-picker', ...) would have printed
9828 - // three secrets into page HTML for Subscribers.
9829 - //
9830 - // Nothing consumed the object: a tree-wide grep for
9831 - // 'mxchatStyleSettings' returns only this call site, and js/ names
9832 - // loops_api_key only at mxchat-admin.js:572, as a field-NAME string
9833 - // in an autosave allowlist — not a value read. Removed entirely
9834 - // rather than deleting just the three secret keys, so there is no
9835 - // dead payload left for someone to re-arm.
9836 - break;
9837 - }
9838 -
9839 - // Additional localization that was in the original code
9840 - wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
9841 - 'ajax_url' => admin_url('admin-ajax.php'),
9842 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9843 - ));
9844 -}
9845 -
9846 -public function mxchat_sanitize($input) {
9847 - $new_input = array();
9848 -
9849 - if (isset($input['api_key'])) {
9850 - $new_input['api_key'] = sanitize_text_field($input['api_key']);
9851 - }
9852 -
9853 - if (isset($input['similarity_threshold'])) {
9854 - $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
9855 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
9856 - }
9857 -
9858 - if (isset($input['rag_sources_limit'])) {
9859 - $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
9860 - $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
9861 - }
9862 -
9863 - if (isset($input['rag_chunks_limit'])) {
9864 - $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
9865 - $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
9866 - }
9867 -
9868 - if (isset($input['xai_api_key'])) {
9869 - $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
9870 - }
9871 -
9872 - if (isset($input['claude_api_key'])) {
9873 - $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
9874 - }
9875 -
9876 - if (isset($input['enable_streaming_toggle'])) {
9877 - $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
9878 - } else {
9879 - // If checkbox not checked, it won't be in $input, so set to 'off'
9880 - $new_input['enable_streaming_toggle'] = 'off';
9881 - }
9882 -
9883 - if (isset($input['enable_web_search'])) {
9884 - $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
9885 - } else {
9886 - // If checkbox not checked, it won't be in $input, so set to 'off'
9887 - $new_input['enable_web_search'] = 'off';
9888 - }
9889 -
9890 - if (isset($input['deepseek_api_key'])) {
9891 - $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
9892 - }
9893 -
9894 - if (isset($input['gemini_api_key'])) {
9895 - $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
9896 - }
9897 -
9898 - if (isset($input['enable_woocommerce_integration'])) {
9899 - $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
9900 - }
9901 -
9902 - if (isset($input['privacy_toggle'])) {
9903 - $new_input['privacy_toggle'] = $input['privacy_toggle'];
9904 - }
9905 -
9906 - if (isset($input['complianz_toggle'])) {
9907 - $new_input['complianz_toggle'] = $input['complianz_toggle'];
9908 - }
9909 -
9910 - // Handle custom privacy text input
9911 - if (isset($input['privacy_text'])) {
9912 - // Allow basic HTML for links
9913 - $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
9914 - }
9915 -
9916 - if (isset($input['system_prompt_instructions'])) {
9917 - $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
9918 - }
9919 -
9920 - if (isset($input['mxchat_pro_email'])) {
9921 - $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
9922 - }
9923 -
9924 - if (isset($input['mxchat_activation_key'])) {
9925 - $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
9926 - }
9927 -
9928 - if (isset($input['append_to_body'])) {
9929 - $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
9930 - }
9931 -
9932 - // Post type visibility settings
9933 - if (isset($input['post_type_visibility_mode'])) {
9934 - $allowed_modes = array('all', 'include', 'exclude');
9935 - $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
9936 - ? $input['post_type_visibility_mode']
9937 - : 'all';
9938 - }
9939 -
9940 - if (isset($input['post_type_visibility_list'])) {
9941 - if (is_array($input['post_type_visibility_list'])) {
9942 - $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
2660 + if (in_array($rate_limit, $allowed_limits, true)) {
2661 + $new_input['rate_limit'] = $rate_limit;
9943 2662 } else {
9944 - $new_input['post_type_visibility_list'] = array();
2663 + // Set a default or fallback value in case of an invalid entry
2664 + $new_input['rate_limit'] = '100';
9945 2665 }
9946 2666 }
9947 2667
9948 - if (isset($input['contextual_awareness_toggle'])) {
9949 - $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
9950 -}
9951 2668
9952 - if (isset($input['citation_links_toggle'])) {
9953 - $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
9954 -}
9955 -
9956 - // Satisfaction rating prompt — defaults ON when unchecked (so first save
9957 - // doesn't accidentally disable it). The form posts 'on' when checked;
9958 - // unchecked checkboxes don't post a value at all, so we infer 'off' only
9959 - // when the autosave/PHP request explicitly clears it via empty string.
9960 - if (array_key_exists('satisfaction_rating_enabled', $input)) {
9961 - $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
9962 - }
9963 -
9964 - // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
9965 - // the 4 text strings are sanitized + capped server-side. Blank values are
9966 - // preserved so the integrator falls back to translated defaults.
9967 - if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
9968 - $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
9969 - }
9970 -
9971 - // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default,
9972 - // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out
9973 - // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist,
9974 - // so without this isset-handler the key is stripped on the next save of ANY field
9975 - // (the 2c02ea global-rate-limit footgun).
9976 - if (array_key_exists('max_input_length', $input)) {
9977 - $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length'])));
9978 - }
9979 - if (array_key_exists('satisfaction_rating_question', $input)) {
9980 - $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
9981 - }
9982 - if (array_key_exists('satisfaction_rating_thanks', $input)) {
9983 - $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
9984 - }
9985 - if (array_key_exists('satisfaction_rating_placeholder', $input)) {
9986 - $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
9987 - }
9988 - if (array_key_exists('satisfaction_rating_saved', $input)) {
9989 - $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
9990 - }
9991 -
9992 - if (isset($input['top_bar_title'])) {
9993 - $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
9994 - }
9995 -
9996 - if (isset($input['ai_agent_text'])) {
9997 - $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
2669 + if (isset($input['pre_chat_message'])) {
2670 + $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
9998 2671 }
9999 2672
10000 - if (isset($input['enable_email_block'])) {
10001 - $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
10002 - }
10003 -
10004 - if (isset($input['email_blocker_header_content'])) {
10005 - // wp_kses_post() allows standard HTML tags permitted by WordPress
10006 - $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
10007 - }
10008 - if (isset($input['email_blocker_button_text'])) {
10009 - $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
10010 - }
10011 - // Sanitize name field toggle
10012 - if (isset($input['enable_name_field'])) {
10013 - $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
10014 - } else {
10015 - $new_input['enable_name_field'] = 'off';
10016 - }
10017 - // Sanitize name field placeholder
10018 - if (isset($input['name_field_placeholder'])) {
10019 - $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
10020 - }
10021 - if (isset($input['intro_message'])) {
10022 - $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
10023 - }
10024 -
10025 - if (isset($input['input_copy'])) {
10026 - $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10027 - }
10028 -
10029 - if (isset($input['rate_limit_message'])) {
10030 - $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10031 - }
10032 -
10033 -// Handle the new rate limits format
10034 -if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
10035 - $new_input['rate_limits'] = array();
10036 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10037 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10038 -
10039 - foreach ($input['rate_limits'] as $role_id => $settings) {
10040 - $new_input['rate_limits'][$role_id] = array();
10041 -
10042 - // Sanitize limit
10043 - if (isset($settings['limit'])) {
10044 - $limit = sanitize_text_field($settings['limit']);
10045 - // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive
10046 - // integer (custom value) — mirrors the global branch (plan-2c02ea). Without
10047 - // the custom path the per-role custom input was dropped and reset to the role
10048 - // default on every save (plan-7e23e7).
10049 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10050 - $new_input['rate_limits'][$role_id]['limit'] = $limit;
10051 - } else {
10052 - $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
2673 + if (isset($input['model'])) {
2674 + $allowed_models = array(
2675 + 'grok-beta',
2676 + 'claude-3-5-sonnet-20241022',
2677 + 'claude-3-opus-20240229',
2678 + 'claude-3-sonnet-20240229',
2679 + 'claude-3-haiku-20240307',
2680 + 'gpt-4o',
2681 + 'gpt-4o-mini',
2682 + 'gpt-4-turbo',
2683 + 'gpt-4',
2684 + 'gpt-3.5-turbo',
2685 + );
2686 + if (in_array($input['model'], $allowed_models)) {
2687 + $new_input['model'] = sanitize_text_field($input['model']);
10053 2688 }
10054 2689 }
10055 2690
10056 - // Preserve the per-role custom value (mirrors the global branch's limit_custom).
10057 - if (isset($settings['limit_custom'])) {
10058 - $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']);
2691 + // Sanitize new pro features
2692 + if (isset($input['close_button_color'])) {
2693 + $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
10059 2694 }
10060 2695
10061 - // Sanitize timeframe
10062 - if (isset($settings['timeframe'])) {
10063 - $timeframe = sanitize_text_field($settings['timeframe']);
10064 - if (in_array($timeframe, $allowed_timeframes, true)) {
10065 - $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
10066 - } else {
10067 - $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
10068 - }
2696 + if (isset($input['chatbot_bg_color'])) {
2697 + $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
10069 2698 }
10070 2699
10071 - // Sanitize message
10072 - if (isset($settings['message'])) {
10073 - $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
2700 + if (isset($input['woocommerce_consumer_key'])) {
2701 + $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10074 2702 }
10075 - }
10076 -}
10077 2703
10078 -// Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea).
10079 -// Mirrors the per-role block above, adapted to the single global shape. Without
10080 -// this branch the whitelist-rebuild dropped rate_limits_global entirely on every
10081 -// save, so the global cap silently fell back to its 'unlimited' default.
10082 -// MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed.
10083 -if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) {
10084 - $g = $input['rate_limits_global'];
10085 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10086 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10087 - $global_out = array();
2704 + if (isset($input['woocommerce_consumer_secret'])) {
2705 + $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
2706 + }
10088 2707
10089 - if (isset($g['limit'])) {
10090 - $limit = sanitize_text_field($g['limit']);
10091 - // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the
10092 - // autosave handler / renderer), OR any positive integer (custom value).
10093 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10094 - $global_out['limit'] = $limit;
10095 - } else {
10096 - $global_out['limit'] = 'unlimited';
2708 + if (isset($input['user_message_bg_color'])) {
2709 + $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
10097 2710 }
10098 - }
10099 2711
10100 - if (isset($g['limit_custom'])) {
10101 - $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']);
10102 - }
2712 + if (isset($input['user_message_font_color'])) {
2713 + $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
2714 + }
10103 2715
10104 - if (isset($g['timeframe'])) {
10105 - $timeframe = sanitize_text_field($g['timeframe']);
10106 - $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily';
10107 - }
2716 + if (isset($input['bot_message_bg_color'])) {
2717 + $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
2718 + }
10108 2719
10109 - if (isset($g['message'])) {
10110 - $global_out['message'] = sanitize_textarea_field($g['message']);
10111 - }
2720 + if (isset($input['bot_message_font_color'])) {
2721 + $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
2722 + }
10112 2723
10113 - $new_input['rate_limits_global'] = $global_out;
10114 -}
2724 + if (isset($input['top_bar_bg_color'])) {
2725 + $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
2726 + }
10115 2727
10116 - if (isset($input['pre_chat_message'])) {
10117 - $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10118 - }
2728 + if (isset($input['send_button_font_color'])) {
2729 + $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
2730 + }
10119 2731
10120 - if (isset($input['voyage_api_key'])) {
10121 - $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
10122 - }
2732 + if (isset($input['chatbot_background_color'])) {
2733 + $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
2734 + }
10123 2735
10124 - // Add to your sanitize function
10125 - if (isset($input['embedding_model'])) {
10126 - // Catalog refactor (plan-d14e89): allowlist derived from the canonical
10127 - // catalog in includes/class-mxchat-model-catalog.php.
10128 - if (!class_exists('MxChat_Model_Catalog')) {
10129 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
2736 + if (isset($input['icon_color'])) {
2737 + $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
10130 2738 }
10131 - $allowed_models = MxChat_Model_Catalog::embedding_model_ids();
10132 - if (in_array($input['embedding_model'], $allowed_models)) {
10133 - $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
10134 - }
10135 - }
10136 2739
10137 -if (isset($input['model'])) {
10138 - if ($input['model'] === 'openrouter') {
10139 - $new_input['model'] = 'openrouter';
10140 - } else {
10141 - if (!class_exists('MxChat_Model_Catalog')) {
10142 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
2740 + if (isset($input['chat_input_font_color'])) {
2741 + $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
10143 2742 }
10144 - $allowed_models = MxChat_Model_Catalog::chat_model_ids();
10145 2743
10146 - if (in_array($input['model'], $allowed_models)) {
10147 - $new_input['model'] = sanitize_text_field($input['model']);
10148 - } else {
10149 - // Fallback for any deprecated model
10150 - $new_input['model'] = 'gpt-5.6-sol';
2744 + // Sanitize link_target_toggle
2745 + if (isset($input['link_target_toggle'])) {
2746 + $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
10151 2747 }
10152 - }
10153 -}
10154 -
10155 -if (isset($input['openrouter_selected_model'])) {
10156 - // Just sanitize it, don't validate against a whitelist
10157 - $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
10158 -}
10159 2748
10160 -// ADD THIS:
10161 -if (isset($input['openrouter_selected_model_name'])) {
10162 - $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
10163 -}
10164 -
10165 - if (isset($input['openrouter_api_key'])) {
10166 - $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
10167 - }
10168 -
10169 - // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
10170 - if (isset($input['custom_provider_base_url'])) {
10171 - $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
10172 - }
10173 - if (isset($input['custom_provider_api_key'])) {
10174 - $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
10175 - }
10176 - if (isset($input['custom_provider_model'])) {
10177 - $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
10178 - }
10179 - if (isset($input['custom_provider_auth_scheme'])) {
10180 - $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
10181 - $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
10182 - }
10183 - if (isset($input['custom_provider_for_embeddings'])) {
10184 - $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
10185 - }
10186 - if (isset($input['custom_provider_for_images'])) {
10187 - $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
10188 - }
10189 - if (isset($input['custom_provider_embedding_model'])) {
10190 - $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
10191 - }
10192 - if (isset($input['custom_provider_api_version'])) {
10193 - $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
10194 - }
10195 -
10196 -
10197 -
10198 - if (isset($input['woocommerce_consumer_key'])) {
10199 - $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10200 - }
10201 -
10202 - if (isset($input['woocommerce_consumer_secret'])) {
10203 - $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
10204 - }
10205 -
10206 -
10207 - // Sanitize link_target_toggle
10208 - if (isset($input['link_target_toggle'])) {
10209 - $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
10210 - }
10211 -
10212 - // Sanitize Loops API Key
2749 + // Sanitize Loops API Key
10213 2750 if (isset($input['loops_api_key'])) {
10214 2751 $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
10215 2752 }
10216 2753
@@ -10217,55 +2754,39 @@
10217 2754 if (isset($input['chat_persistence_toggle'])) {
10218 2755 $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
10219 2756 }
10220 2757
10221 - // No else clause: an absent key stays absent, so the front-end default ('on') applies
10222 - // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here).
10223 - if (isset($input['print_button_enabled'])) {
10224 - $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off';
10225 - }
10226 2758
10227 - // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label.
10228 - // No else on the toggle: an absent key stays absent so the front-end '?? off'
10229 - // default applies, and the full-array autosave rebuild preserves a saved value.
10230 - if (isset($input['reset_chat_enabled'])) {
10231 - $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off';
10232 - }
10233 2759
10234 - if (isset($input['reset_chat_label'])) {
10235 - $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']);
10236 - }
2760 +if (isset($input['popular_question_1'])) {
2761 + $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
2762 +}
10237 2763
10238 - if (isset($input['popular_question_1'])) {
10239 - $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
10240 - }
2764 +if (isset($input['popular_question_2'])) {
2765 + $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']);
2766 +}
10241 2767
10242 - if (isset($input['popular_question_2'])) {
10243 - $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']);
10244 - }
2768 +if (isset($input['popular_question_3'])) {
2769 + $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']);
2770 +}
10245 2771
10246 - if (isset($input['popular_question_3'])) {
10247 - $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']);
10248 - }
10249 2772
10250 - if (isset($input['additional_popular_questions']) && is_array($input['additional_popular_questions'])) {
10251 - $new_input['additional_popular_questions'] = array_map('sanitize_text_field', $input['additional_popular_questions']);
10252 - }
10253 -
10254 2773 // Sanitize Loops Mailing List
10255 2774 if (isset($input['loops_mailing_list'])) {
10256 2775 $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
10257 2776 }
10258 2777
10259 -// Sanitize Triggered Phrase Response
2778 + // Sanitize Triggered Phrase Response
10260 2779 if (isset($input['triggered_phrase_response'])) {
10261 2780 $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
10262 2781 }
2782 +
10263 2783 if (isset($input['email_capture_response'])) {
10264 - $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
2784 + $new_input['email_capture_response'] = sanitize_textarea_field($input['email_capture_response']);
10265 2785 }
10266 2786
10267 - // Sanitize Brave Search Settings
2787 +
2788 + // Sanitize Brave Search Settings
10268 2789 if (isset($input['brave_api_key'])) {
10269 2790 $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
10270 2791 }
10271 2792
@@ -10280,9 +2801,9 @@
10280 2801 }
10281 2802
10282 2803 if (isset($input['brave_news_count'])) {
10283 2804 $news_count = intval($input['brave_news_count']);
10284 - $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
2805 + $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
10285 2806 }
10286 2807
10287 2808 if (isset($input['brave_country'])) {
10288 2809 $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
@@ -10291,317 +2812,166 @@
10291 2812 if (isset($input['brave_language'])) {
10292 2813 $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
10293 2814 }
10294 2815
10295 - if (isset($input['chat_toolbar_toggle'])) {
10296 - $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
10297 - }
10298 2816
10299 - // Sanitize PDF upload button toggle
10300 - if (isset($input['show_pdf_upload_button'])) {
10301 - $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
10302 - } else {
10303 - $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
10304 - }
10305 2817
10306 - // Sanitize Word upload button toggle
10307 - if (isset($input['show_word_upload_button'])) {
10308 - $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
10309 - } else {
10310 - $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
10311 - }
10312 2818
10313 - if (isset($input['pdf_intent_trigger_text'])) {
10314 - $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
10315 - }
10316 2819
10317 - if (isset($input['pdf_intent_success_text'])) {
10318 - $new_input['pdf_intent_success_text'] = sanitize_text_field($input['pdf_intent_success_text']);
10319 - }
10320 2820
10321 - if (isset($input['pdf_intent_error_text'])) {
10322 - $new_input['pdf_intent_error_text'] = sanitize_text_field($input['pdf_intent_error_text']);
10323 - }
10324 2821
10325 - if (isset($input['pdf_max_pages'])) {
10326 - $new_input['pdf_max_pages'] = intval($input['pdf_max_pages']);
10327 - if ($new_input['pdf_max_pages'] < 1 || $new_input['pdf_max_pages'] > 69) {
10328 - $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
10329 - }
2822 + return $new_input;
10330 2823 }
10331 2824
10332 - if (isset($input['live_agent_webhook_url'])) {
10333 - $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
10334 - }
10335 - if (isset($input['live_agent_secret_key'])) {
10336 - $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
10337 - }
10338 2825
10339 - // Live Agent Integration
10340 - if (isset($input['live_agent_bot_token'])) {
10341 - $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
2826 + // Method to append the chatbot to the body
2827 + public function mxchat_append_chatbot_to_body() {
2828 + $options = get_option('mxchat_options');
2829 + if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
2830 + echo do_shortcode('[mxchat_chatbot floating="yes"]');
2831 + }
10342 2832 }
10343 2833
10344 - if (isset($input['live_agent_shared_channel'])) {
10345 - $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']);
10346 - }
10347 2834
10348 - // Default-OFF toggle: absent key stays absent (unchecked box = off).
10349 - if (isset($input['live_agent_archive_on_end_toggle'])) {
10350 - $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off';
10351 - }
10352 2835
10353 - if (isset($input['live_agent_user_ids'])) {
10354 - $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
10355 - }
2836 +private function mxchat_extract_main_content($html) {
2837 + $dom = new DOMDocument;
2838 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
2839 + @$dom->loadHTML($html);
2840 + libxml_clear_errors();
10356 2841
10357 - if (isset($input['live_agent_status'])) {
10358 - $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
10359 - }
10360 - if (isset($input['live_agent_away_message'])) {
10361 - $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
10362 - }
10363 - if (isset($input['live_agent_notification_message'])) {
10364 - $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
10365 - }
2842 + $xpath = new DOMXPath($dom);
10366 2843
10367 - // Telegram Integration
10368 - if (isset($input['telegram_status'])) {
10369 - $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
10370 - }
10371 - if (isset($input['telegram_bot_token'])) {
10372 - $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
10373 - }
10374 - if (isset($input['telegram_group_id'])) {
10375 - $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
10376 - }
10377 - if (isset($input['telegram_webhook_secret'])) {
10378 - $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
10379 - }
10380 - if (isset($input['telegram_notification_message'])) {
10381 - $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
10382 - }
10383 - if (isset($input['telegram_away_message'])) {
10384 - $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
10385 - }
2844 + // Simplified selectors focusing on common content areas
2845 + $selectors = [
2846 + '//article',
2847 + '//*[@id="content"]',
2848 + '//*[@class="entry-content"]',
2849 + '//main',
2850 + ];
10386 2851
10387 - // Sanitize script loading strategy
10388 - if (isset($input['script_loading_strategy'])) {
10389 - $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
10390 - $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
10391 - ? $input['script_loading_strategy']
10392 - : 'default';
10393 - }
10394 -
10395 - // Sanitize debug mode
10396 - if (isset($input['debug_mode'])) {
10397 - $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
10398 - }
10399 -
10400 - // Content Generator Settings
10401 - if (isset($input['content_model'])) {
10402 - $new_input['content_model'] = sanitize_text_field($input['content_model']);
10403 - }
10404 - if (isset($input['content_image_model'])) {
10405 - $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
10406 - }
10407 - if (isset($input['content_image_quality'])) {
10408 - $q = sanitize_text_field($input['content_image_quality']);
10409 - $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
10410 - }
10411 - if (isset($input['content_enable_images'])) {
10412 - $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
10413 - }
10414 - if (isset($input['content_use_placeholders'])) {
10415 - $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
10416 - }
10417 - if (isset($input['content_internal_linking'])) {
10418 - $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
10419 - }
10420 - if (isset($input['content_tool_use'])) {
10421 - $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
10422 - }
10423 - if (isset($input['content_image_count'])) {
10424 - $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count']));
10425 - }
10426 -
10427 - // SEO Optimize toggle fields
10428 - foreach (array('seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $seo_key) {
10429 - if (isset($input[$seo_key])) {
10430 - $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
2852 + foreach ($selectors as $selector) {
2853 + $nodes = $xpath->query($selector);
2854 + if ($nodes->length > 0) {
2855 + $content = '';
2856 + foreach ($nodes as $node) {
2857 + $content .= $dom->saveHTML($node);
2858 + }
2859 + return $content;
10431 2860 }
10432 2861 }
10433 2862
10434 - // Preserve content generator settings when saving from main settings page
10435 - // (where content fields are not in the form submission)
10436 - $existing = get_option('mxchat_options', array());
10437 - foreach (array('content_model', 'content_image_model', 'content_image_quality', 'content_image_count', 'content_enable_images', 'content_use_placeholders', 'content_internal_linking', 'content_tool_use', 'seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $key) {
10438 - if (!isset($new_input[$key]) && isset($existing[$key])) {
10439 - $new_input[$key] = $existing[$key];
10440 - }
10441 - }
10442 -
10443 - return $new_input;
2863 + // Fallback: Return the entire body content if no specific selector matches
2864 + $body = $dom->getElementsByTagName('body');
2865 + return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
10444 2866 }
10445 2867
10446 -/**
10447 - * Log a debug message if debug mode is enabled
10448 - *
10449 - * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
10450 - * @param string $message The log message
10451 - * @param array $data Optional additional data to log
10452 - * @return bool Whether the message was logged
10453 - */
10454 -public static function mxchat_log_debug( $type, $message, $data = array() ) {
10455 - $options = get_option( 'mxchat_options', array() );
10456 -
10457 - // Check if debug mode is enabled
10458 - if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
10459 - return false;
2868 +public function mxchat_handle_sitemap_submission() {
2869 + // Check if the form was submitted and the user has sufficient permissions
2870 + if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
2871 + return;
10460 2872 }
10461 2873
10462 - // Get current log
10463 - $log = get_option( 'mxchat_debug_log', array() );
10464 - if ( ! is_array( $log ) ) {
10465 - $log = array();
10466 - }
2874 + // Verify the nonce field for security
2875 + check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
10467 2876
10468 - // Add new entry
10469 - $entry = array(
10470 - 'time' => current_time( 'Y-m-d H:i:s' ),
10471 - 'type' => sanitize_key( $type ),
10472 - 'message' => sanitize_text_field( $message ),
10473 - );
2877 + // Sanitize and retrieve the submitted URL
2878 + $submitted_url = esc_url_raw($_POST['sitemap_url']); // Accept either a sitemap URL or a regular URL
10474 2879
10475 - if ( ! empty( $data ) ) {
10476 - $entry['data'] = $data;
2880 + // Fetch the content of the submitted URL
2881 + $response = wp_remote_get($submitted_url);
2882 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2883 + set_transient('mxchat_admin_notice_error', 'Failed to fetch the URL. Please check the URL and try again.', 30);
2884 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2885 + exit;
10477 2886 }
10478 2887
10479 - // Add to beginning of array (newest first)
10480 - array_unshift( $log, $entry );
2888 + $content_type = wp_remote_retrieve_header($response, 'content-type');
2889 + $body_content = wp_remote_retrieve_body($response);
10481 2890
10482 - // Keep only last 100 entries
10483 - if ( count( $log ) > 100 ) {
10484 - $log = array_slice( $log, 0, 100 );
10485 - }
2891 + // Check if the URL points to a sitemap (XML) or a regular HTML page
2892 + if (strpos($content_type, 'xml') !== false || strpos($body_content, '<urlset') !== false) {
2893 + // Handle Sitemap XML
2894 + $xml = simplexml_load_string($body_content);
2895 + if ($xml === false) {
2896 + set_transient('mxchat_admin_notice_error', 'Invalid sitemap XML. Please provide a valid sitemap.', 30);
2897 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2898 + exit;
2899 + }
10486 2900
10487 - // Save log
10488 - update_option( 'mxchat_debug_log', $log, false );
2901 + $embedding_success = true; // Flag to track if all embeddings are successful
10489 2902
10490 - return true;
10491 -}
2903 + foreach ($xml->url as $url_element) {
2904 + $page_url = (string)$url_element->loc;
10492 2905
10493 -/**
10494 - * Get the debug log entries
10495 - *
10496 - * @return array The debug log entries
10497 - */
10498 -public static function mxchat_get_debug_log() {
10499 - $log = get_option( 'mxchat_debug_log', array() );
10500 - return is_array( $log ) ? $log : array();
10501 -}
2906 + $page_response = wp_remote_get($page_url);
2907 + if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
2908 + continue;
2909 + }
10502 2910
10503 -/**
10504 - * Clear the debug log
10505 - *
10506 - * @return bool Whether the log was cleared
10507 - */
10508 -public static function mxchat_clear_debug_log() {
10509 - return delete_option( 'mxchat_debug_log' );
10510 -}
2911 + $page_html = wp_remote_retrieve_body($page_response);
2912 + $page_content = $this->mxchat_extract_main_content($page_html);
2913 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10511 2914
10512 -/**
10513 - * Export settings as JSON with masked API keys
10514 - *
10515 - * @return array The sanitized settings array
10516 - */
10517 -public static function mxchat_export_settings() {
10518 - $options = get_option( 'mxchat_options', array() );
2915 + if (!empty($sanitized_content)) {
2916 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2917 + if (is_array($embedding_vector)) {
2918 + MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $this->options['api_key']);
2919 + } else {
2920 + $embedding_success = false; // Set flag to false if any embedding fails
2921 + }
2922 + }
2923 + }
10519 2924
10520 - if ( ! is_array( $options ) ) {
10521 - return array();
10522 - }
2925 + if ($embedding_success) {
2926 + set_transient('mxchat_admin_notice_success', 'Sitemap content successfully submitted!', 30);
2927 + } else {
2928 + set_transient('mxchat_admin_notice_error', 'Some content failed to embed. Please check your API key and try again.', 30);
2929 + }
10523 2930
10524 - // List of API key fields to mask
10525 - $api_key_fields = array(
10526 - 'api_key',
10527 - 'xai_api_key',
10528 - 'claude_api_key',
10529 - 'deepseek_api_key',
10530 - 'voyage_api_key',
10531 - 'gemini_api_key',
10532 - 'openrouter_api_key',
10533 - 'loops_api_key',
10534 - 'brave_api_key',
10535 - 'live_agent_secret_key',
10536 - 'live_agent_bot_token',
10537 - 'telegram_bot_token',
10538 - 'telegram_webhook_secret',
10539 - 'woocommerce_consumer_key',
10540 - 'woocommerce_consumer_secret',
10541 - );
2931 + } else {
2932 + // Handle Regular URL (HTML Page)
2933 + $page_content = $this->mxchat_extract_main_content($body_content);
2934 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10542 2935
10543 - // Mask API keys (show only last 4 characters)
10544 - foreach ( $api_key_fields as $field ) {
10545 - if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
10546 - $value = $options[ $field ];
10547 - if ( strlen( $value ) > 4 ) {
10548 - $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
2936 + if (!empty($sanitized_content)) {
2937 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2938 + if (is_array($embedding_vector)) {
2939 + MxChat_Utils::submit_content_to_db($sanitized_content, $submitted_url, $this->options['api_key']);
2940 + set_transient('mxchat_admin_notice_success', 'URL content successfully submitted!', 30);
10549 2941 } else {
10550 - $options[ $field ] = '****';
2942 + set_transient('mxchat_admin_notice_error', 'Failed to generate embedding for the URL content. Please check your API key and try again.', 30);
10551 2943 }
2944 + } else {
2945 + set_transient('mxchat_admin_notice_error', 'No valid content found on the provided URL.', 30);
10552 2946 }
10553 2947 }
10554 2948
10555 - // Add metadata
10556 - $export = array(
10557 - 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
10558 - 'export_date' => current_time( 'Y-m-d H:i:s' ),
10559 - 'wordpress_version' => get_bloginfo( 'version' ),
10560 - 'php_version' => phpversion(),
10561 - 'settings' => $options,
10562 - );
10563 -
10564 - return $export;
2949 + // Redirect after setting the transient
2950 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2951 + exit;
10565 2952 }
10566 2953
10567 -/**
10568 - * Reset all settings to defaults
10569 - *
10570 - * @return bool Whether the reset was successful
10571 - */
10572 -public static function mxchat_reset_all_settings() {
10573 - // Delete main options
10574 - $deleted = delete_option( 'mxchat_options' );
10575 2954
10576 - // Also clear the debug log
10577 - delete_option( 'mxchat_debug_log' );
10578 2955
10579 - // Log the reset (will create new log since we just cleared it)
10580 - // We need to temporarily enable debug mode to log this
10581 - $temp_options = array( 'debug_mode' => 'on' );
10582 - update_option( 'mxchat_options', $temp_options );
2956 +private function mxchat_sanitize_content_for_api($content) {
2957 + // Remove script, style tags, and HTML comments
2958 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
2959 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
2960 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
10583 2961
10584 - self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
2962 + // Remove all HTML tags and decode HTML entities
2963 + $content = wp_strip_all_tags($content);
2964 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
10585 2965
10586 - // Now delete again to trigger re-initialization
10587 - delete_option( 'mxchat_options' );
2966 + // Trim and normalize whitespace
2967 + $content = trim(preg_replace('/\s+/', ' ', $content));
10588 2968
10589 - return $deleted;
2969 + return $content;
10590 2970 }
10591 2971
10592 - // Method to append the chatbot to the body
10593 - public function mxchat_append_chatbot_to_body() {
10594 - $options = get_option('mxchat_options');
10595 - if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
10596 - echo do_shortcode('[mxchat_chatbot floating="yes"]');
10597 - }
10598 - }
10599 2972
10600 2973
10601 -
10602 -
10603 -
10604 2974 private function mxchat_fetch_loops_mailing_lists($api_key) {
10605 2975 $url = 'https://app.loops.so/api/v1/lists';
10606 2976 $response = wp_remote_get($url, array(
10607 2977 'headers' => array(
@@ -10619,8 +2989,12 @@
10619 2989
10620 2990 return isset($lists) && is_array($lists) ? $lists : array();
10621 2991 }
10622 2992
2993 +
2994 +
2995 +
2996 +
10623 2997 function mxchat_calculate_cosine_similarity($vec1, $vec2) {
10624 2998 if (empty($vec1) || empty($vec2)) {
10625 2999 return 0.0;
10626 3000 }
@@ -10641,438 +3015,8 @@
10641 3015 return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
10642 3016 }
10643 3017 }
10644 3018
10645 -/**
10646 - * Validates nonce and deletes all chat prompts
10647 - */
10648 -public function mxchat_handle_delete_all_prompts() {
10649 - //error_log('=== DELETE ALL DEBUG START ===');
10650 -
10651 - // Verify nonce
10652 - if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
10653 - //error_log('DEBUG: Nonce verification failed');
10654 - wp_die(__('Nonce verification failed.', 'mxchat'));
10655 - }
10656 -
10657 - // Check permissions
10658 - if (!current_user_can('manage_options')) {
10659 - //error_log('DEBUG: Permission check failed');
10660 - wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
10661 - }
10662 -
10663 - // Get bot_id and content type filter from POST data
10664 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
10665 - $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
10666 -
10667 - $success = true;
10668 - $error_messages = array();
10669 -
10670 - // Get bot-specific Pinecone configuration
10671 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10672 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
10673 -
10674 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
10675 -
10676 - if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
10677 - // Delete from Pinecone (with optional content type filter)
10678 - $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
10679 -
10680 - if (!$result['success']) {
10681 - $success = false;
10682 - $error_messages[] = $result['message'];
10683 - }
10684 -
10685 - } else {
10686 - // Delete from WordPress database
10687 - global $wpdb;
10688 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
10689 -
10690 - // Build WHERE conditions
10691 - $where_clauses = array();
10692 - $where_values = array();
10693 -
10694 - // Bot filter
10695 - if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
10696 - $where_clauses[] = 'bot_id = %s';
10697 - $where_values[] = $bot_id;
10698 - }
10699 -
10700 - // Content type filter
10701 - if (!empty($content_type_filter)) {
10702 - $where_clauses[] = 'content_type = %s';
10703 - $where_values[] = $content_type_filter;
10704 - }
10705 -
10706 - if (!empty($where_clauses)) {
10707 - $where_sql = implode(' AND ', $where_clauses);
10708 - $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
10709 - } else {
10710 - // No filters — delete all
10711 - $result = $wpdb->query("DELETE FROM {$table_name}");
10712 - }
10713 -
10714 - if ($result === false) {
10715 - $success = false;
10716 - $error_messages[] = 'Failed to delete from WordPress database';
10717 - }
10718 - }
10719 -
10720 - // Redirect back with a success message and bot_id
10721 - $redirect_url = add_query_arg(array(
10722 - 'page' => 'mxchat-prompts',
10723 - 'bot_id' => $bot_id,
10724 - 'all_deleted' => $success ? 'true' : 'false'
10725 - ), admin_url('admin.php'));
10726 -
10727 - wp_safe_redirect($redirect_url);
10728 - exit;
10729 -}
10730 -
10731 -
10732 -
10733 - /**
10734 - * Handles deletion prompt with nonce validation
10735 - */
10736 - public function mxchat_handle_delete_prompt() {
10737 - // Sanitize and validate nonce
10738 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
10739 - if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
10740 - wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
10741 - }
10742 -
10743 - // Check permissions
10744 - if (!current_user_can('manage_options')) {
10745 - wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
10746 - }
10747 -
10748 - // Get ID and source parameters
10749 - $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
10750 - $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
10751 -
10752 - if (empty($id)) {
10753 - wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
10754 - }
10755 -
10756 - $success = false;
10757 - $error_message = '';
10758 -
10759 - // Resolve per-bot Pinecone settings — the global option is the wrong
10760 - // index entirely when the row belongs to a bot with its own host
10761 - $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default';
10762 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10763 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
10764 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
10765 -
10766 - // If source is not specified, determine based on Pinecone configuration
10767 - if (empty($source)) {
10768 - $source = $use_pinecone ? 'pinecone' : 'wordpress';
10769 - }
10770 -
10771 - if ($source === 'pinecone' || $use_pinecone) {
10772 - //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
10773 -
10774 - // Handle Pinecone deletion
10775 - if (empty($pinecone_options['mxchat_pinecone_host']) ||
10776 - empty($pinecone_options['mxchat_pinecone_api_key'])) {
10777 - wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
10778 - }
10779 -
10780 - // Delete from Pinecone using the vector ID directly
10781 - $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
10782 - $id,
10783 - $pinecone_options['mxchat_pinecone_api_key'],
10784 - $pinecone_options['mxchat_pinecone_host'],
10785 - $pinecone_options['mxchat_pinecone_namespace'] ?? ''
10786 - );
10787 - if ($result['success']) {
10788 - $success = true;
10789 -
10790 - // Remove from vector cache
10791 - $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
10792 - $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
10793 -
10794 - set_transient('mxchat_admin_notice_success',
10795 - esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
10796 - } else {
10797 - $error_message = $result['message'];
10798 - set_transient('mxchat_admin_notice_error',
10799 - esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
10800 - }
10801 - } else {
10802 - //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
10803 -
10804 - // Handle WordPress database deletion
10805 - global $wpdb;
10806 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
10807 -
10808 - // Clear cache and delete prompt
10809 - wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
10810 -
10811 - $result = $wpdb->delete(
10812 - $table_name,
10813 - array('id' => intval($id)),
10814 - array('%d')
10815 - );
10816 -
10817 - if ($result !== false) {
10818 - $success = true;
10819 - set_transient('mxchat_admin_notice_success',
10820 - esc_html__('Entry deleted successfully.', 'mxchat'), 30);
10821 - } else {
10822 - set_transient('mxchat_admin_notice_error',
10823 - esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
10824 - }
10825 - }
10826 -
10827 - // Redirect back to the prompts page
10828 - wp_safe_redirect(add_query_arg(
10829 - array(
10830 - 'page' => 'mxchat-prompts',
10831 - 'deleted' => $success ? 'true' : 'false'
10832 - ),
10833 - admin_url('admin.php')
10834 - ));
10835 - exit;
10836 - }
10837 -
10838 -
10839 -
10840 -
10841 - /**
10842 - * Averages multiple vectors into a single vector
10843 - */
10844 - private function mxchat_average_vectors($vectors) {
10845 - $vector_length = count($vectors[0]);
10846 - $sum_vector = array_fill(0, $vector_length, 0);
10847 -
10848 - foreach ($vectors as $vector) {
10849 - for ($i = 0; $i < $vector_length; $i++) {
10850 - $sum_vector[$i] += $vector[$i];
10851 - }
10852 - }
10853 -
10854 - // Divide each component by the number of vectors to get the average
10855 - $num_vectors = count($vectors);
10856 - for ($i = 0; $i < $vector_length; $i++) {
10857 - $sum_vector[$i] /= $num_vectors;
10858 - }
10859 -
10860 - return $sum_vector;
10861 - }
10862 -
10863 -
10864 -
10865 -
10866 - /**
10867 - * Generates embeddings from input text for MXChat
10868 - */
10869 - public function mxchat_generate_embedding($text) {
10870 - // Enable detailed logging for debugging
10871 - //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
10872 - //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
10873 -
10874 - $options = get_option('mxchat_options');
10875 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
10876 - //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
10877 -
10878 - // Determine provider and endpoint
10879 - if (strpos($selected_model, 'voyage') === 0) {
10880 - $api_key = $options['voyage_api_key'] ?? '';
10881 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
10882 - $provider_name = 'Voyage AI';
10883 - //error_log('[MXCHAT-EMBED] Using Voyage AI API');
10884 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
10885 - $api_key = $options['gemini_api_key'] ?? '';
10886 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
10887 - $provider_name = 'Google Gemini';
10888 - //error_log('[MXCHAT-EMBED] Using Google Gemini API');
10889 - } else {
10890 - $api_key = $options['api_key'] ?? '';
10891 - $endpoint = 'https://api.openai.com/v1/embeddings';
10892 - $provider_name = 'OpenAI';
10893 - //error_log('[MXCHAT-EMBED] Using OpenAI API');
10894 - }
10895 -
10896 - //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
10897 -
10898 - if (empty($api_key)) {
10899 - $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
10900 - //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
10901 - return $error_message;
10902 - }
10903 -
10904 - // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
10905 - $estimated_tokens = ceil(str_word_count($text) / 0.75);
10906 - //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
10907 -
10908 - if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
10909 - //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
10910 - // Consider truncating text here
10911 - }
10912 -
10913 - // Prepare request body based on provider
10914 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10915 - // Gemini API format
10916 - $request_body = array(
10917 - 'model' => 'models/' . $selected_model,
10918 - 'content' => array(
10919 - 'parts' => array(
10920 - array('text' => $text)
10921 - )
10922 - )
10923 - );
10924 -
10925 - // Set output dimensionality to 1536 for consistency with other models
10926 - $request_body['outputDimensionality'] = 1536;
10927 - } else {
10928 - // OpenAI/Voyage API format
10929 - $request_body = array(
10930 - 'model' => $selected_model,
10931 - 'input' => $text
10932 - );
10933 -
10934 - // Add output_dimension for voyage-3-large model
10935 - if ($selected_model === 'voyage-3-large') {
10936 - $request_body['output_dimension'] = 2048;
10937 - }
10938 - }
10939 -
10940 - //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
10941 -
10942 - // Prepare headers based on provider
10943 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10944 - // Gemini uses API key as query parameter
10945 - $endpoint .= '?key=' . $api_key;
10946 - $headers = array(
10947 - 'Content-Type' => 'application/json'
10948 - );
10949 - } else {
10950 - // OpenAI/Voyage use Bearer token
10951 - $headers = array(
10952 - 'Authorization' => 'Bearer ' . $api_key,
10953 - 'Content-Type' => 'application/json'
10954 - );
10955 - }
10956 -
10957 - // Make API request
10958 - //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
10959 - $response = wp_remote_post($endpoint, array(
10960 - 'body' => wp_json_encode($request_body),
10961 - 'headers' => $headers,
10962 - 'timeout' => 60 // Increased timeout for large inputs
10963 - ));
10964 -
10965 - // Handle wp_remote_post errors
10966 - if (is_wp_error($response)) {
10967 - $error_message = $response->get_error_message();
10968 - //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
10969 - return 'Connection error: ' . $error_message;
10970 - }
10971 -
10972 - // Get and check HTTP response code
10973 - $http_code = wp_remote_retrieve_response_code($response);
10974 - //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
10975 -
10976 - if ($http_code !== 200) {
10977 - $error_body = wp_remote_retrieve_body($response);
10978 - //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
10979 -
10980 - // Try to parse error for more details
10981 - $error_json = json_decode($error_body, true);
10982 - if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
10983 - $error_type = $error_json['error']['type'] ?? 'unknown';
10984 - $error_message = $error_json['error']['message'] ?? 'No message';
10985 - //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
10986 - //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
10987 -
10988 - // Customize error message for common API errors
10989 - if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
10990 - $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
10991 - } elseif ($error_type === 'authentication_error') {
10992 - $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
10993 - }
10994 -
10995 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
10996 - return $error_message;
10997 - }
10998 -
10999 - $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
11000 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11001 - return $error_message;
11002 - }
11003 -
11004 - // Parse response body
11005 - $response_body = wp_remote_retrieve_body($response);
11006 - //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
11007 -
11008 - $response_data = json_decode($response_body, true);
11009 -
11010 - if (json_last_error() !== JSON_ERROR_NONE) {
11011 - $error = json_last_error_msg();
11012 - //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
11013 - //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
11014 - return "Failed to parse API response: $error";
11015 - }
11016 -
11017 - // Handle different response formats based on provider
11018 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11019 - // Gemini API response format
11020 - if (isset($response_data['embedding']['values'])) {
11021 - $embedding_dimensions = count($response_data['embedding']['values']);
11022 - //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
11023 -
11024 - // Check if embedding dimensions are as expected (should be 1536)
11025 - if ($embedding_dimensions !== 1536) {
11026 - //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
11027 - }
11028 -
11029 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11030 - return $response_data['embedding']['values'];
11031 - } else {
11032 - //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
11033 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11034 -
11035 - if (isset($response_data['error'])) {
11036 - $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
11037 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11038 - return $error_message;
11039 - }
11040 -
11041 - $error_message = "Invalid Gemini API response format: No embedding found";
11042 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11043 - return $error_message;
11044 - }
11045 - } else {
11046 - // OpenAI/Voyage API response format
11047 - if (isset($response_data['data'][0]['embedding'])) {
11048 - $embedding_dimensions = count($response_data['data'][0]['embedding']);
11049 - //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
11050 -
11051 - // Check if embedding dimensions are as expected
11052 - if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
11053 - ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
11054 - //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
11055 - }
11056 -
11057 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11058 - return $response_data['data'][0]['embedding'];
11059 - } else {
11060 - //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
11061 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11062 -
11063 - if (isset($response_data['error'])) {
11064 - $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
11065 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11066 - return $error_message;
11067 - }
11068 -
11069 - $error_message = "Invalid API response format: No embedding found";
11070 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11071 - return $error_message;
11072 - }
11073 - }
11074 - }
11075 3019
11076 3020
11077 3021
11078 3022 }