PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.24
MxChat – AI Chatbot & Content Generation for WordPress v3.2.24
3.2.25 3.2.24 3.2.23 3.2.22 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 All 156 releases
mxchat-basic / includes / class-mxchat-admin.php

class-mxchat-admin.php in MxChat – AI Chatbot & Content Generation for WordPress 3.2.24, at includes/class-mxchat-admin.php

11,996 lines 534.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH')) {
3 exit; // Exit if accessed directly
4 }
5
6 class MxChat_Admin {
7 private $options;
8 private $chat_count;
9 private $is_activated;
10 private $knowledge_manager;
11
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) {
29 $this->options = get_option('mxchat_options');
30 $this->chat_count = get_option('mxchat_chat_count', 0);
31 $this->is_activated = $this->is_license_active();
32 $this->knowledge_manager = $knowledge_manager;
33
34 // Seed defaults on init, not here — the constructor runs on
35 // plugins_loaded, before the mxchat textdomain loads (init, priority 10),
36 // so translating the default strings here both triggers WP 6.7's
37 // _load_textdomain_just_in_time notice and stores the untranslated
38 // English fallbacks. Priority 20 lands after mxchat_load_textdomain().
39 if (!$this->options) {
40 add_action('init', array($this, 'initialize_default_options'), 20);
41 }
42
43 // Add admin menu and initialize settings
44 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
45 // Pro & Extensions registers at priority 30 so it always lands last in
46 // the sidebar — below API Access (priority 20) and below any other
47 // submenu that hooks at default priority 10.
48 add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
49 // Onboarding visibility — runs LAST so it can remove the submenu after every
50 // other add_submenu_page() call. The page stays reachable by direct URL.
51 add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999);
52 add_action('admin_init', array($this, 'mxchat_page_init'));
53 add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
54 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
55 // Add body class for the Onboarding wizard (plan-905439) so the
56 // chrome-surgery CSS in admin-onboarding-wizard.css can scope its
57 // WP-sidebar collapse to this page only.
58 add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class'));
59 add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
60 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
61 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
62 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
63 add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
64 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
65 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
66 add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
67 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
68 add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
69 add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
70 add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
71 add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
72 add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
73
74 // Leads tab (inside Transcripts)
75 add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
76 add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
77 add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
78
79 add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
80 add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
81 add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
82 add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
83 // Self-heal: the cleanup event is otherwise only scheduled at activation or
84 // when the retention setting CHANGES — if it is ever lost (deactivate cycle,
85 // cron-option wipe, DB restore) nothing re-registers it and retention goes
86 // silently inert while the UI still says it is on (plan-bc08a6).
87 add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled'));
88
89 add_action('admin_init', array($this, 'register_pinecone_settings'));
90 add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
91
92 add_action('admin_notices', array($this, 'display_admin_notices'));
93
94 add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
95 add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
96 add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
97
98 // wp_ajax_mxchat_save_selected_bot is registered (and handled) in
99 // admin/class-ajax-handler.php — a duplicate registration here pointed
100 // at a method this class never defined, a load-order-dependent fatal
101 // waiting to fire (plan 52bcad).
102 add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
103 add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
104
105 // Actions page AJAX handlers
106 add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
107 add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
108 add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
109 add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
110 add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
111 add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
112 add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
113 add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
114 add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
115 add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
116
117 // Slack test connection
118 add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
119
120 // Translation handlers
121 add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
122 add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
123
124 // 3.2.3: Embedding model switch protection
125 add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
126 add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
127 add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax'));
128 add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
129 add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice'));
130 }
131
132 /**
133 * Nudge admins to configure a Telegram webhook secret (plan-0c17b5).
134 *
135 * Shown only when a Telegram bot token is configured (integration active)
136 * AND no webhook secret is set. Without a secret the webhook falls back to a
137 * Telegram source-IP check — safer than the old fail-open, but a real secret
138 * is the recommended protection. Dismissible; does not block anything.
139 */
140 public function mxchat_telegram_secret_notice() {
141 if (!current_user_can('manage_options')) {
142 return;
143 }
144 $options = get_option('mxchat_options', array());
145 $has_token = !empty($options['telegram_bot_token']);
146 $has_secret = !empty($options['telegram_webhook_secret']);
147 if (!$has_token) {
148 return;
149 }
150
151 // Inbound rejections recorded by verify_telegram_request() (plan 30398e).
152 // When the webhook is actually being rejected this stops being a hardening
153 // suggestion and becomes an outage report: it shows even when a secret IS
154 // set (a wrong or unregistered secret rejects just as hard as none), and it
155 // ignores the dismissal flag, because a nudge someone dismissed in July
156 // must not silence live breakage. It self-clears on the first accepted
157 // request, so a fixed install stops nagging without anyone touching it.
158 $rejects = get_option('mxchat_telegram_webhook_rejects', array());
159 $reject_count = (is_array($rejects) && !empty($rejects['count'])) ? (int) $rejects['count'] : 0;
160
161 if ($reject_count < 1) {
162 // Nothing is failing — the original advisory, unchanged.
163 if ($has_secret) {
164 return;
165 }
166 if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') {
167 return;
168 }
169 }
170
171 $settings_url = admin_url('admin.php?page=mxchat-settings#integrations-telegram');
172 ?>
173 <?php if ($reject_count > 0) : ?>
174 <div class="notice notice-error mxchat-telegram-reject-notice">
175 <p><strong><?php esc_html_e('MxChat: Telegram is sending replies your site is rejecting', 'mxchat'); ?></strong></p>
176 <p>
177 <?php
178 echo esc_html(sprintf(
179 /* translators: 1: number of rejected webhook requests, 2: local date and time of the most recent one */
180 _n(
181 '%1$s incoming webhook request has been rejected (most recently %2$s), so agent replies from Telegram are not reaching your visitors.',
182 '%1$s incoming webhook requests have been rejected (most recently %2$s), so agent replies from Telegram are not reaching your visitors.',
183 $reject_count,
184 'mxchat'
185 ),
186 number_format_i18n($reject_count),
187 !empty($rejects['last_ts'])
188 ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $rejects['last_ts'])
189 : __('unknown time', 'mxchat')
190 ));
191 ?>
192 </p>
193 <p><?php echo esc_html($this->mxchat_telegram_reject_advice($rejects['last_reason'] ?? '')); ?></p>
194 <p>
195 <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
196 </p>
197 </div>
198 <?php else : ?>
199 <div class="notice notice-warning is-dismissible mxchat-telegram-secret-notice">
200 <p><strong><?php esc_html_e('MxChat: Telegram webhook is running without a secret token', 'mxchat'); ?></strong></p>
201 <p>
202 <?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'); ?>
203 </p>
204 <p>
205 <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
206 </p>
207 </div>
208 <?php endif; ?>
209 <script>
210 (function(){
211 var n = document.querySelector('.mxchat-telegram-secret-notice');
212 if (!n) return;
213 n.addEventListener('click', function(e){
214 if (e.target && e.target.classList.contains('notice-dismiss')) {
215 var d = new FormData();
216 d.append('action', 'mxchat_dismiss_telegram_secret_notice');
217 d.append('nonce', '<?php echo esc_js(wp_create_nonce('mxchat_dismiss_telegram_secret')); ?>');
218 fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', { method: 'POST', body: d, credentials: 'same-origin' });
219 }
220 });
221 })();
222 </script>
223 <?php
224 }
225
226 /**
227 * Turn a webhook rejection reason code into the sentence that tells the site
228 * owner what to actually do (plan 30398e). The three reasons map to three
229 * different fixes, and saying which one applies is most of the value; shared
230 * by the admin notice and the Telegram settings readout so there is one
231 * wording, not two.
232 *
233 * @param string $reason Reason code recorded by verify_telegram_request().
234 * @return string
235 */
236 public function mxchat_telegram_reject_advice($reason) {
237 switch ((string) $reason) {
238 case 'no_secret_ip_mismatch':
239 return __('Requests are arriving from an address outside Telegram\'s published ranges, which is normal behind Cloudflare or a reverse proxy. Set a webhook secret in the Telegram settings and re-register your webhook.', 'mxchat');
240 case 'missing_header':
241 return __('Your webhook was registered without the secret. Open the Register Webhook URL link on the Telegram settings tab again — it now includes the secret token.', 'mxchat');
242 case 'secret_mismatch':
243 return __('The secret Telegram is sending does not match the one saved here. Save your settings, then re-register the webhook using the link on the Telegram settings tab.', 'mxchat');
244 default:
245 return __('Re-register your webhook from the Telegram settings tab.', 'mxchat');
246 }
247 }
248
249 /**
250 * AJAX: persist dismissal of the Telegram-secret admin notice (plan-0c17b5).
251 */
252 public function mxchat_dismiss_telegram_secret_notice_ajax() {
253 if (!current_user_can('manage_options')
254 || !check_ajax_referer('mxchat_dismiss_telegram_secret', 'nonce', false)) {
255 wp_send_json_error();
256 }
257 update_option('mxchat_dismissed_telegram_secret_notice', '1', 'no');
258 wp_send_json_success();
259 }
260
261 /**
262 * 3.2.3: Preflight check before allowing the embedding model dropdown to
263 * switch. Pure option comparison — no counts, no DB queries beyond the
264 * cached options. The dialog is shown whenever the user has previously
265 * embedded with a different model than the one they're switching to.
266 */
267 public function mxchat_check_embedding_switch_ajax() {
268 check_ajax_referer('mxchat_admin_nonce', 'security');
269 if (!current_user_can('manage_options')) {
270 wp_send_json_error(__('Unauthorized', 'mxchat'));
271 }
272
273 $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
274 $options = get_option('mxchat_options', array());
275 if (isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
276 // The standard dropdown is inert while custom embeddings are on —
277 // whatever value it posts, the next embed uses the custom identity.
278 $new_model = MxChat_Utils::get_selected_embedding_model($options);
279 }
280 $active_model = MxChat_Utils::get_active_embedding_model();
281
282 $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
283
284 $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
285 $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
286
287 wp_send_json_success(array(
288 'is_mismatch' => $is_mismatch,
289 'active_model' => $active_model,
290 'active_label' => MxChat_Utils::embedding_model_label($active_model),
291 'new_model' => $new_model,
292 'new_label' => MxChat_Utils::embedding_model_label($new_model),
293 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
294 'active_dims' => $active_dims,
295 'new_dims' => $new_dims,
296 ));
297 }
298
299 /**
300 * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
301 * pair so the banner reappears on the next switch event.
302 */
303 public function mxchat_dismiss_embedding_mismatch_ajax() {
304 check_ajax_referer('mxchat_admin_nonce', 'security');
305 if (!current_user_can('manage_options')) {
306 wp_send_json_error(__('Unauthorized', 'mxchat'));
307 }
308
309 $options = get_option('mxchat_options', array());
310 $selected = MxChat_Utils::get_selected_embedding_model($options);
311 $active = MxChat_Utils::get_active_embedding_model();
312 update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
313 wp_send_json_success();
314 }
315
316 /**
317 * 3.2.3: Persistent admin banner shown whenever the active embedding model
318 * (last used to actually embed something) differs from the currently
319 * selected model. Pure option comparison — no DB queries on every page
320 * load. The banner auto-clears once both match again, i.e. after a delete
321 * + re-embed cycle.
322 */
323 public function mxchat_embedding_mismatch_notice() {
324 if (!current_user_can('manage_options')) {
325 return;
326 }
327
328 $options = get_option('mxchat_options', array());
329 $selected = MxChat_Utils::get_selected_embedding_model($options);
330 $active = MxChat_Utils::get_active_embedding_model();
331
332 if (empty($active) || empty($selected) || $active === $selected) {
333 return;
334 }
335
336 $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
337 if ($dismissed === $active . '|' . $selected) {
338 return;
339 }
340
341 $active_label = MxChat_Utils::embedding_model_label($active);
342 $selected_label = MxChat_Utils::embedding_model_label($selected);
343 $active_dims = MxChat_Utils::embedding_model_dimensions($active);
344 $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
345 $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
346
347 $kb_url = admin_url('admin.php?page=mxchat-prompts');
348 $actions_url = admin_url('admin.php?page=mxchat-actions');
349
350 ?>
351 <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
352 data-active="<?php echo esc_attr($active); ?>"
353 data-selected="<?php echo esc_attr($selected); ?>">
354 <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
355 <p>
356 <?php
357 printf(
358 /* translators: 1: previously-used model name, 2: currently-selected model name */
359 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'),
360 '<code>' . esc_html($active_label) . '</code>',
361 '<code>' . esc_html($selected_label) . '</code>'
362 );
363 ?>
364 </p>
365 <?php if ($dims_differ) : ?>
366 <p>
367 <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
368 <?php
369 printf(
370 /* translators: 1: old dim count, 2: new dim count */
371 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'),
372 (int) $active_dims,
373 (int) $selected_dims
374 );
375 ?>
376 </p>
377 <?php endif; ?>
378 <p>
379 <?php esc_html_e('To fix this:', 'mxchat'); ?>
380 <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
381 <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
382 <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
383 </p>
384 </div>
385 <script>
386 (function($){
387 $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
388 $.post(ajaxurl, {
389 action: 'mxchat_dismiss_embedding_mismatch',
390 security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
391 });
392 });
393 })(jQuery);
394 </script>
395 <?php
396 }
397
398 private function is_license_active() {
399 $license_status = get_option('mxchat_license_status', 'inactive');
400 return ($license_status === 'active');
401 }
402
403 public function initialize_default_options() {
404 // Re-check under the hook: another request may have seeded the option
405 // between the constructor's check on plugins_loaded and init firing.
406 if (get_option('mxchat_options')) {
407 return;
408 }
409 $default_options = array(
410 'api_key' => '',
411 'xai_api_key' => '',
412 'claude_api_key' => '',
413 'deepseek_api_key' => '',
414 'voyage_api_key' => '',
415 'gemini_api_key' => '',
416 'enable_streaming_toggle' => 'off',
417 'enable_web_search' => 'off',
418 'embedding_model' => 'text-embedding-ada-002',
419 '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:
420
421 # Response Style - CRITICALLY IMPORTANT
422 - MAXIMUM LENGTH: 1-3 short sentences per response
423 - Ultra-concise: Get straight to the answer with no filler
424 - No introductions like "Sure!" or "I\'d be happy to help"
425 - No phrases like "based on my knowledge" or "according to information"
426 - No explanatory text before giving the answer
427 - No summaries or repetition
428 - Hyperlink all URLs
429 - Respond in user\'s language
430 - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
431
432 # Knowledge Base Requirements - PREVENT HALLUCINATIONS
433 - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
434 - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
435 - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
436 - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
437 - Better to admit insufficient information than provide inaccurate answers',
438 'model' => 'gpt-5.6-sol',
439 'rate_limit_logged_out' => '100',
440 'role_rate_limits' => array(),
441 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
442 'enable_email_block' => '',
443 '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'),
444 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
445 'enable_name_field' => 'off', // NEW
446 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
447 'enable_consent_checkbox' => 'off', // b062c4 — default OFF: changes an existing form on every install
448 'consent_checkbox_label' => __('I agree to the Privacy Policy.', 'mxchat'),
449 'consent_checkbox_required' => 'off',
450 // Lead capture options (c0cfaf). Both default to today's behaviour:
451 // the form is hidden from logged-in visitors, and email is required.
452 'lead_capture_logged_in_toggle' => 'off',
453 'lead_capture_require_email_toggle' => 'on',
454 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
455 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
456 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
457 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
458 'append_to_body' => 'off',
459 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
460 'post_type_visibility_list' => array(), // Array of post type slugs
461 'contextual_awareness_toggle' => 'off',
462 'citation_links_toggle' => 'on',
463 'satisfaction_rating_enabled' => 'off',
464 'satisfaction_rating_idle_seconds' => 60,
465 'satisfaction_rating_question' => '',
466 'satisfaction_rating_thanks' => '',
467 'satisfaction_rating_placeholder' => '',
468 'satisfaction_rating_saved' => '',
469 'close_button_color' => '#fff',
470 'chatbot_bg_color' => '#fff',
471 'user_message_bg_color' => '#fff',
472 'user_message_font_color' => '#212121',
473 'bot_message_bg_color' => '#212121',
474 'bot_message_font_color' => '#fff',
475 'top_bar_bg_color' => '#212121',
476 'send_button_font_color' => '#212121',
477 'chat_input_font_color' => '#212121',
478 'chatbot_background_color' => '#212121',
479 'icon_color' => '#fff',
480 'enable_woocommerce_integration' => '0',
481 'link_target_toggle' => 'off',
482 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
483
484 // New fields for Loops Integration
485 'loops_api_key' => '',
486 'loops_mailing_list' => '',
487 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
488 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
489 'popular_question_1' => '',
490 'popular_question_2' => '',
491 'popular_question_3' => '',
492 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
493 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
494 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
495 'pdf_max_pages' => 69,
496 'show_pdf_upload_button' => 'on',
497 'show_word_upload_button' => 'on',
498
499 // Live Agent Integration (Slack)
500 'live_agent_webhook_url' => '',
501 'live_agent_secret_key' => '',
502 'live_agent_bot_token' => '',
503 'live_agent_message_bg_color' => '#ffffff',
504 'live_agent_message_font_color' => '#333333',
505
506 // Telegram Integration
507 'telegram_status' => 'off',
508 'telegram_bot_token' => '',
509 'telegram_group_id' => '',
510 'telegram_webhook_secret' => '',
511 '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'),
512 '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'),
513
514 // Webhook handoff destination (plan d88e22, outbound-only)
515 'webhook_handoff_status' => 'off',
516 'webhook_handoff_url' => '',
517 'webhook_handoff_secret' => '',
518 'webhook_handoff_notification_message' => __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat'),
519 'webhook_handoff_away_message' => __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'),
520
521 'chat_toolbar_toggle' => 'off',
522 'mode_indicator_bg_color' => '#767676',
523 'mode_indicator_font_color' => '#ffffff',
524 'toolbar_icon_color' => '#212121',
525
526 // Optimization settings
527 'script_loading_strategy' => 'default',
528
529 // Debug settings
530 'debug_mode' => 'off',
531 );
532
533
534 // Merge existing options with defaults
535 $existing_options = get_option('mxchat_options', array());
536 $merged_options = wp_parse_args($existing_options, $default_options);
537
538 // Update the options if they have changed
539 if ($existing_options !== $merged_options) {
540 update_option('mxchat_options', $merged_options);
541 }
542
543 // Add default limits for each role
544 $roles = wp_roles()->get_names();
545 foreach ($roles as $role_id => $role_name) {
546 $default_options['role_rate_limits'][$role_id] = '100';
547 }
548
549 return $default_options;
550
551 // Update the $this->options property
552 $this->options = $merged_options;
553 }
554
555 public function mxchat_add_plugin_page() {
556 // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file).
557 require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
558
559 // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu
560 // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now
561 // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding).
562 add_menu_page(
563 esc_html__('MxChat', 'mxchat'),
564 esc_html__('MxChat', 'mxchat'),
565 'manage_options',
566 'mxchat-max',
567 array($this, 'mxchat_create_dashboard_page'),
568 'dashicons-testimonial',
569 6
570 );
571
572 // Onboarding submenu — first child under MxChat (plan-d14e89).
573 // First registration uses menu_slug === parent slug 'mxchat-max' →
574 // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the
575 // first child shows as "Onboarding" instead of a redundant pair.
576 add_submenu_page(
577 'mxchat-max',
578 esc_html__('MxChat Onboarding', 'mxchat'),
579 esc_html__('Onboarding', 'mxchat'),
580 'manage_options',
581 'mxchat-max',
582 array($this, 'mxchat_create_dashboard_page')
583 );
584 // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link
585 // + legacy redirects still target this slug). Parent === null keeps it
586 // out of the menu while remaining accessible by URL.
587 add_submenu_page(
588 null,
589 esc_html__('MxChat Onboarding', 'mxchat'),
590 esc_html__('Onboarding', 'mxchat'),
591 'manage_options',
592 'mxchat-onboarding',
593 array($this, 'mxchat_create_dashboard_page')
594 );
595
596 // Settings submenu — same callback as before, just at a new slug.
597 add_submenu_page(
598 'mxchat-max',
599 esc_html__('MxChat Settings', 'mxchat'),
600 esc_html__('Settings', 'mxchat'),
601 'manage_options',
602 'mxchat-settings',
603 array($this, 'mxchat_create_admin_page')
604 );
605
606 // Submenu page for Knowledge
607 add_submenu_page(
608 'mxchat-max',
609 esc_html__('Prompts', 'mxchat'),
610 esc_html__('Knowledge', 'mxchat'),
611 'manage_options',
612 'mxchat-prompts',
613 array($this, 'mxchat_create_prompts_page')
614 );
615
616 add_submenu_page(
617 'mxchat-max',
618 esc_html__('Chat Transcripts', 'mxchat'),
619 esc_html__('Transcripts', 'mxchat'),
620 'manage_options',
621 'mxchat-transcripts',
622 array($this, 'mxchat_create_transcripts_page')
623 );
624
625 add_submenu_page(
626 'mxchat-max',
627 esc_html__('MxChat Actions', 'mxchat'),
628 esc_html__('Actions', 'mxchat'),
629 'manage_options',
630 'mxchat-actions',
631 array($this, 'mxchat_actions_page_html')
632 );
633
634 // Content Generator page
635 add_submenu_page(
636 'mxchat-max',
637 esc_html__('Content', 'mxchat'),
638 esc_html__('Content', 'mxchat'),
639 'manage_options',
640 'mxchat-content',
641 array($this, 'mxchat_create_content_page')
642 );
643
644 }
645
646 /**
647 * Register the Pro & Extensions submenu on a later admin_menu priority so it
648 * always renders as the bottom-most item in the MxChat sidebar — below
649 * configuration pages like API Access (priority 20).
650 */
651 public function mxchat_add_pro_extensions_page() {
652 add_submenu_page(
653 'mxchat-max',
654 esc_html__('Pro & Extensions', 'mxchat'),
655 esc_html__('Pro & Extensions', 'mxchat'),
656 'manage_options',
657 'mxchat-activation',
658 array($this, 'mxchat_create_activation_page')
659 );
660 }
661
662 public function mxchat_create_addons_page() {
663 require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
664 $addons_page = new MxChat_Addons();
665 $addons_page->render_page();
666 }
667
668 /**
669 * Render the Content Generator admin page
670 */
671 public function mxchat_create_content_page() {
672 require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
673 // The Editor Assistant toggle on the Settings tab renders through
674 // mxchat_render_field_wrapper(), which lives in admin-settings-page.php
675 // (plan-f7df40 relocation) — load it the same way the settings page does.
676 require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
677 mxchat_render_content_page($this);
678 }
679
680 /**
681 * Test actual streaming functionality in the WordPress environment
682 */
683 public function mxchat_handle_test_streaming_actual() {
684 check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
685
686 // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler
687 // reads the site's provider keys and spends them on an outbound call, so it
688 // is billable abuse for any logged-in user who obtained the nonce.
689 if (!current_user_can('manage_options')) {
690 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
691 }
692
693 // Check if headers have already been sent
694 if (headers_sent()) {
695 wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
696 return;
697 }
698
699 // Check for required functions
700 if (!function_exists('curl_init')) {
701 wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
702 return;
703 }
704
705 // Get user's selected model and API key
706 $options = get_option('mxchat_options', []);
707 $selected_model = $options['model'] ?? 'gpt-5.6-sol';
708
709 // Get the provider from the model
710 $model_parts = explode('-', $selected_model);
711 $provider = strtolower($model_parts[0]);
712
713 // Get the appropriate API key
714 $api_key = '';
715 switch ($provider) {
716 case 'gpt':
717 case 'o1':
718 $api_key = $options['api_key'] ?? '';
719 break;
720 case 'claude':
721 $api_key = $options['claude_api_key'] ?? '';
722 break;
723 case 'grok':
724 $api_key = $options['xai_api_key'] ?? '';
725 break;
726 case 'deepseek':
727 $api_key = $options['deepseek_api_key'] ?? '';
728 break;
729 case 'gemini':
730 $api_key = $options['gemini_api_key'] ?? '';
731 break;
732 default:
733 // Default to OpenAI for unknown models
734 $api_key = $options['api_key'] ?? '';
735 $provider = 'gpt';
736 break;
737 }
738
739 if (empty($api_key)) {
740 wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
741 return;
742 }
743
744 // Test streaming with the selected model and provider
745 try {
746 $this->perform_streaming_test($provider, $selected_model, $api_key);
747 } catch (Exception $e) {
748 wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
749 }
750 }
751
752 /**
753 * Perform the actual streaming test
754 */
755 private function perform_streaming_test($provider, $model, $api_key) {
756 // Set streaming headers
757 header('Content-Type: text/event-stream');
758 header('Cache-Control: no-cache');
759 header('X-Accel-Buffering: no'); // Disable nginx buffering
760
761 // Prepare test message
762 $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
763
764 // Configure API request based on provider
765 $url = '';
766 $headers = [];
767 $body = [];
768
769 switch ($provider) {
770 case 'gpt':
771 case 'o1':
772 $url = 'https://api.openai.com/v1/chat/completions';
773 $headers = [
774 'Content-Type: application/json',
775 'Authorization: Bearer ' . $api_key
776 ];
777 $body = [
778 'model' => $model,
779 'messages' => [['role' => 'user', 'content' => $test_message]],
780 'max_tokens' => 50,
781 'temperature' => 0.3,
782 'stream' => true
783 ];
784 break;
785
786 case 'claude':
787 $url = 'https://api.anthropic.com/v1/messages';
788 $headers = [
789 'Content-Type: application/json',
790 'x-api-key: ' . $api_key,
791 'anthropic-version: 2023-06-01'
792 ];
793 $body = [
794 'model' => $model,
795 'messages' => [['role' => 'user', 'content' => $test_message]],
796 'max_tokens' => 50,
797 'temperature' => 0.3,
798 'stream' => true
799 ];
800 // Claude flagships from Opus 4.7 onward reject the temperature
801 // param outright (400). Reuse the catalog's decision — this path
802 // previously sent temperature unconditionally, so the streaming
803 // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5.
804 if (class_exists('MxChat_Model_Catalog')
805 && method_exists('MxChat_Model_Catalog', 'supports_temperature')
806 && !MxChat_Model_Catalog::supports_temperature($model)) {
807 unset($body['temperature']);
808 }
809 break;
810
811 case 'grok':
812 $url = 'https://api.x.ai/v1/chat/completions';
813 $headers = [
814 'Content-Type: application/json',
815 'Authorization: Bearer ' . $api_key
816 ];
817 $body = [
818 'model' => $model,
819 'messages' => [['role' => 'user', 'content' => $test_message]],
820 'max_tokens' => 50,
821 'temperature' => 0.3,
822 'stream' => true
823 ];
824 break;
825
826 case 'deepseek':
827 $url = 'https://api.deepseek.com/v1/chat/completions';
828 $headers = [
829 'Content-Type: application/json',
830 'Authorization: Bearer ' . $api_key
831 ];
832 $body = [
833 'model' => $model,
834 'messages' => [['role' => 'user', 'content' => $test_message]],
835 'max_tokens' => 50,
836 'temperature' => 0.3,
837 'stream' => true,
838 // DeepSeek V4 defaults to thinking mode ON — reasoning would
839 // consume the 50-token test budget and return no visible text.
840 'thinking' => ['type' => 'disabled']
841 ];
842 break;
843
844 default:
845 echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
846 flush();
847 return;
848 }
849
850 // Initialize cURL
851 $ch = curl_init();
852 curl_setopt($ch, CURLOPT_URL, $url);
853 curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
854 curl_setopt($ch, CURLOPT_POST, true);
855 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
856 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
857 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
858 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
859 curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
860 return $this->process_streaming_test_data($data, $provider);
861 });
862
863 // Send initial test message
864 echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
865 flush();
866
867 $result = curl_exec($ch);
868 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
869 $curl_error = curl_error($ch);
870 curl_close($ch);
871
872 if ($curl_error) {
873 echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
874 flush();
875 return;
876 }
877
878 if ($http_code !== 200) {
879 echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
880 flush();
881 return;
882 }
883
884 // Send completion signal
885 echo "data: [DONE]\n\n";
886 flush();
887 }
888
889 /**
890 * Process streaming data for the test
891 */
892 private function process_streaming_test_data($data, $provider) {
893 static $chunk_count = 0;
894
895 $lines = explode("\n", $data);
896
897 foreach ($lines as $line) {
898 if (trim($line) === '') {
899 continue;
900 }
901
902 // Handle different provider formats
903 if ($provider === 'claude') {
904 // Claude uses event: and data: format
905 if (strpos($line, 'data: ') === 0) {
906 $json_str = substr($line, 6);
907 $json = json_decode($json_str, true);
908
909 if (isset($json['type']) && $json['type'] === 'content_block_delta') {
910 if (isset($json['delta']['text'])) {
911 $chunk_count++;
912 echo "data: " . json_encode([
913 'content' => $json['delta']['text'],
914 'test_chunk' => $chunk_count
915 ]) . "\n\n";
916 flush();
917 }
918 }
919 }
920 } else {
921 // OpenAI, X.AI, DeepSeek format
922 if (strpos($line, 'data: ') === 0) {
923 $json_str = substr($line, 6);
924
925 if ($json_str === '[DONE]') {
926 // Don't echo [DONE] here, let the main function handle it
927 continue;
928 }
929
930 $json = json_decode($json_str, true);
931 if (isset($json['choices'][0]['delta']['content'])) {
932 $chunk_count++;
933 echo "data: " . json_encode([
934 'content' => $json['choices'][0]['delta']['content'],
935 'test_chunk' => $chunk_count
936 ]) . "\n\n";
937 flush();
938 }
939 }
940 }
941 }
942
943 return strlen($data);
944 }
945
946 /**
947 * Updated version of your existing test method (keep this as a fallback)
948 */
949 public function mxchat_handle_test_streaming() {
950 check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
951
952 // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but
953 // fail here so the alias never becomes a bypass if that call is refactored.
954 if (!current_user_can('manage_options')) {
955 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
956 }
957
958 // Use the actual streaming test instead
959 $this->mxchat_handle_test_streaming_actual();
960 }
961
962
963 public function register_pinecone_settings() {
964 register_setting(
965 'mxchat_pinecone_addon_options',
966 'mxchat_pinecone_addon_options',
967 array(
968 'type' => 'array',
969 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
970 'default' => array(
971 'mxchat_use_pinecone' => '0',
972 'mxchat_pinecone_api_key' => '',
973 'mxchat_pinecone_host' => '',
974 'mxchat_pinecone_index' => '',
975 'mxchat_pinecone_environment' => '',
976 'mxchat_pinecone_top_k' => '50'
977 )
978 )
979 );
980 }
981
982 public function sanitize_pinecone_settings($input) {
983 $sanitized = array();
984
985 $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
986 $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
987 $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
988 $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
989 $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
990
991 // d0cae1: this function REBUILDS the array, so the topK key must be
992 // carried here or any form save strips it. Clamp mirrors the read site.
993 $top_k = absint($input['mxchat_pinecone_top_k'] ?? 50);
994 $sanitized['mxchat_pinecone_top_k'] = (string) (($top_k >= 1 && $top_k <= 1000) ? $top_k : 50);
995
996 // Remove https:// from host if present
997 $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
998
999 // Index type (plan 362c31). The document index is opt-in, and its host
1000 // must have passed Check index (or come from Create index for me) before
1001 // the choice sticks — a classic host routed through the documents API
1002 // answers 400 on every query. The verified host is carried from the
1003 // stored option; only the AJAX handlers set it, never the form.
1004 $existing = get_option('mxchat_pinecone_addon_options', array());
1005 $existing = is_array($existing) ? $existing : array();
1006 $verified_host = (string) ($existing['mxchat_pinecone_docs_verified_host'] ?? '');
1007 $index_type = (($input['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector';
1008 $host_for_check = strtolower(trim($sanitized['mxchat_pinecone_host'], '/'));
1009 if ($index_type === 'document' && ($host_for_check === '' || $host_for_check !== strtolower($verified_host))) {
1010 $index_type = 'vector';
1011 if (function_exists('add_settings_error')) {
1012 add_settings_error('mxchat_pinecone_addon_options', 'mxchat_pinecone_docs_unverified', __('The document index host has not been checked, so the index type stayed on Vector index. Click Check index (or Create index for me) and save again.', 'mxchat'));
1013 }
1014 }
1015 // 3e83e4: never point the live chatbot at a document index whose copy is
1016 // still running — the save keeps the previous type unless the owner
1017 // ticked Switch anyway. Only a vector → document switch is gated.
1018 $existing_type = (($existing['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector';
1019 if ($index_type === 'document' && $existing_type !== 'document' && class_exists('MxChat_Pinecone_Documents') && empty($input['mxchat_pinecone_docs_switch_anyway'])) {
1020 $running = MxChat_Pinecone_Documents::migration_blocks_switch($host_for_check);
1021 if ($running !== null) {
1022 $index_type = 'vector';
1023 if (function_exists('add_settings_error')) {
1024 add_settings_error('mxchat_pinecone_addon_options', 'mxchat_pinecone_docs_copy_running', MxChat_Pinecone_Documents::switch_blocked_message($running));
1025 }
1026 }
1027 }
1028 $sanitized['mxchat_pinecone_index_type'] = $index_type;
1029 $sanitized['mxchat_pinecone_docs_verified_host'] = $verified_host;
1030 $vector_host = str_replace(['https://', 'http://'], '', sanitize_text_field($input['mxchat_pinecone_vector_host'] ?? ($existing['mxchat_pinecone_vector_host'] ?? '')));
1031 $sanitized['mxchat_pinecone_vector_host'] = trim($vector_host, '/');
1032 $sanitized['mxchat_pinecone_vector_index'] = sanitize_text_field($input['mxchat_pinecone_vector_index'] ?? ($existing['mxchat_pinecone_vector_index'] ?? ''));
1033 $docs_cloud = sanitize_key($input['mxchat_pinecone_docs_cloud'] ?? ($existing['mxchat_pinecone_docs_cloud'] ?? 'aws'));
1034 $sanitized['mxchat_pinecone_docs_cloud'] = in_array($docs_cloud, array('aws', 'gcp', 'azure'), true) ? $docs_cloud : 'aws';
1035 $docs_region = sanitize_text_field($input['mxchat_pinecone_docs_region'] ?? ($existing['mxchat_pinecone_docs_region'] ?? 'us-east-1'));
1036 $sanitized['mxchat_pinecone_docs_region'] = $docs_region !== '' ? $docs_region : 'us-east-1';
1037 $docs_language = sanitize_key($input['mxchat_pinecone_docs_language'] ?? ($existing['mxchat_pinecone_docs_language'] ?? 'en'));
1038 $sanitized['mxchat_pinecone_docs_language'] = (class_exists('MxChat_Pinecone_Documents') && array_key_exists($docs_language, MxChat_Pinecone_Documents::languages())) ? $docs_language : 'en';
1039 // The namespace has no form field; carry the stored value so a form save cannot drop it.
1040 if (isset($existing['mxchat_pinecone_namespace'])) {
1041 $sanitized['mxchat_pinecone_namespace'] = sanitize_text_field($existing['mxchat_pinecone_namespace']);
1042 }
1043
1044 return $sanitized;
1045 }
1046
1047 public function register_openai_vectorstore_settings() {
1048 register_setting(
1049 'mxchat_openai_vectorstore_options',
1050 'mxchat_openai_vectorstore_options',
1051 array(
1052 'type' => 'array',
1053 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
1054 'default' => array(
1055 'mxchat_use_openai_vectorstore' => '0',
1056 'mxchat_vectorstore_ids' => '',
1057 'mxchat_vectorstore_max_results' => 5,
1058 'mxchat_vectorstore_sync_enabled' => '0',
1059 'mxchat_vectorstore_sync_store_id' => ''
1060 )
1061 )
1062 );
1063 }
1064
1065 public function sanitize_openai_vectorstore_settings($input) {
1066 $sanitized = array();
1067
1068 $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
1069 $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
1070 $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
1071
1072 // Knowledge-base sync (write path, plan 15b5c6). Store ID may be blank —
1073 // the sync falls back to the first retrieval ID above.
1074 $sanitized['mxchat_vectorstore_sync_enabled'] = isset($input['mxchat_vectorstore_sync_enabled']) ? '1' : '0';
1075 $sanitized['mxchat_vectorstore_sync_store_id'] = sanitize_text_field($input['mxchat_vectorstore_sync_store_id'] ?? '');
1076
1077 // Ensure max results is within reasonable range
1078 if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
1079 $sanitized['mxchat_vectorstore_max_results'] = 1;
1080 }
1081 if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
1082 $sanitized['mxchat_vectorstore_max_results'] = 20;
1083 }
1084
1085 return $sanitized;
1086 }
1087
1088 /**
1089 * AJAX handler to test OpenAI Vector Store connection
1090 */
1091 public function mxchat_test_vectorstore_connection() {
1092 check_ajax_referer('mxchat_admin_nonce', 'nonce');
1093
1094 if (!current_user_can('manage_options')) {
1095 wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1096 return;
1097 }
1098
1099 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
1100 $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
1101 $mxchat_options = get_option('mxchat_options', array());
1102 $api_key = $mxchat_options['api_key'] ?? '';
1103
1104 if (empty($api_key)) {
1105 wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
1106 return;
1107 }
1108
1109 if (empty($vectorstore_ids)) {
1110 wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
1111 return;
1112 }
1113
1114 // Get the first Vector Store ID for testing
1115 $ids_array = array_map('trim', explode(',', $vectorstore_ids));
1116 $test_id = $ids_array[0];
1117
1118 // Test by retrieving the Vector Store info
1119 $response = wp_remote_get(
1120 'https://api.openai.com/v1/vector_stores/' . $test_id,
1121 array(
1122 'headers' => array(
1123 'Authorization' => 'Bearer ' . $api_key,
1124 'Content-Type' => 'application/json',
1125 'OpenAI-Beta' => 'assistants=v2'
1126 ),
1127 'timeout' => 30
1128 )
1129 );
1130
1131 if (is_wp_error($response)) {
1132 wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
1133 return;
1134 }
1135
1136 $status_code = wp_remote_retrieve_response_code($response);
1137 $body = json_decode(wp_remote_retrieve_body($response), true);
1138
1139 if ($status_code === 200 && isset($body['id'])) {
1140 $file_count = $body['file_counts']['completed'] ?? 0;
1141 $name = $body['name'] ?? $test_id;
1142 wp_send_json_success(array(
1143 'message' => sprintf(
1144 __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
1145 esc_html($name),
1146 $file_count
1147 )
1148 ));
1149 } elseif ($status_code === 404) {
1150 wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
1151 } elseif ($status_code === 401) {
1152 wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
1153 } else {
1154 $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
1155 wp_send_json_error(array('message' => $error_message));
1156 }
1157 }
1158
1159 /**
1160 * AJAX handler to test Slack connection and validate scopes
1161 */
1162 public function mxchat_test_slack_connection() {
1163 check_ajax_referer('mxchat_admin_nonce', 'nonce');
1164
1165 if (!current_user_can('manage_options')) {
1166 wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1167 return;
1168 }
1169
1170 $bot_token = $this->options['live_agent_bot_token'] ?? '';
1171
1172 if (empty($bot_token)) {
1173 wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
1174 return;
1175 }
1176
1177 // Test 1: Validate bot token with auth.test
1178 $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
1179 'headers' => array(
1180 'Authorization' => 'Bearer ' . $bot_token,
1181 'Content-Type' => 'application/json'
1182 ),
1183 'timeout' => 15
1184 ));
1185
1186 if (is_wp_error($auth_response)) {
1187 wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
1188 return;
1189 }
1190
1191 $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
1192
1193 if (!isset($auth_body['ok']) || !$auth_body['ok']) {
1194 $error = $auth_body['error'] ?? 'unknown_error';
1195 $error_messages = array(
1196 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
1197 'not_authed' => __('No authentication token provided.', 'mxchat'),
1198 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
1199 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
1200 );
1201 $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
1202 wp_send_json_error(array('message' => $message));
1203 return;
1204 }
1205
1206 $team_name = $auth_body['team'] ?? 'Unknown Workspace';
1207 $bot_name = $auth_body['user'] ?? 'Unknown Bot';
1208
1209 // Test 2: Check if we can list channels (tests channels:read scope)
1210 $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
1211 'headers' => array(
1212 'Authorization' => 'Bearer ' . $bot_token,
1213 'Content-Type' => 'application/json'
1214 ),
1215 'body' => json_encode(array('limit' => 1)),
1216 'timeout' => 15
1217 ));
1218
1219 $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
1220 $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
1221
1222 // Test 3: Check if we can create channels (tests channels:manage scope)
1223 // We'll just check the error message without actually creating
1224 $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
1225 'headers' => array(
1226 'Authorization' => 'Bearer ' . $bot_token,
1227 'Content-Type' => 'application/json'
1228 ),
1229 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
1230 'timeout' => 15
1231 ));
1232
1233 $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
1234
1235 // If channel was created, delete it immediately
1236 if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
1237 wp_remote_post('https://slack.com/api/conversations.archive', array(
1238 'headers' => array(
1239 'Authorization' => 'Bearer ' . $bot_token,
1240 'Content-Type' => 'application/json'
1241 ),
1242 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
1243 'timeout' => 15
1244 ));
1245 $can_create_channels = true;
1246 } else {
1247 $create_error = $create_body['error'] ?? '';
1248 // name_taken means we have permission but channel exists
1249 $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
1250
1251 // Check for missing scope errors
1252 if ($create_error === 'missing_scope') {
1253 $can_create_channels = false;
1254 }
1255 }
1256
1257 // Build result message
1258 $results = array();
1259 $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
1260 $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
1261 $results[] = '';
1262 $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
1263 $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
1264
1265 $missing_scopes = array();
1266 if (!$can_read_channels) $missing_scopes[] = 'channels:read';
1267 if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
1268
1269 if (!empty($missing_scopes)) {
1270 wp_send_json_error(array(
1271 'message' => implode("\n", $results),
1272 'missing_scopes' => $missing_scopes,
1273 'partial' => true
1274 ));
1275 } else {
1276 wp_send_json_success(array(
1277 'message' => implode("\n", $results)
1278 ));
1279 }
1280 }
1281
1282 public function mxchat_display_admin_notice() {
1283 // Success notice
1284 if ($message = get_transient('mxchat_admin_notice_success')) {
1285 ?>
1286 <div class="notice notice-success is-dismissible">
1287 <p><?php echo esc_html($message); ?></p>
1288 <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
1289 </div>
1290 <?php
1291 delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1292 }
1293
1294 // Error notice
1295 if ($message = get_transient('mxchat_admin_notice_error')) {
1296 ?>
1297 <div class="notice notice-error is-dismissible">
1298 <p><?php echo esc_html($message); ?></p>
1299 <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
1300 </div>
1301 <?php
1302 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1303 }
1304 }
1305
1306 public function show_live_agent_disabled_banner() {
1307 $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1308
1309 if ($show_disabled_notice) {
1310 ?>
1311 <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1312 <div class="mxchat-pro-notification">
1313 <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1314 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1315 <line x1="18" y1="6" x2="6" y2="18"></line>
1316 <line x1="6" y1="6" x2="18" y2="18"></line>
1317 </svg>
1318 </button>
1319 <div class="mxchat-live-agent-content">
1320 <h3>🔧 Live Agent Integration Updated!</h3>
1321 <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>
1322 </div>
1323 </div>
1324 </div>
1325 <?php
1326 }
1327 }
1328 /**
1329 * Render the Onboarding page. Delegates to the procedural renderer in
1330 * includes/admin-onboarding-page.php. Wired to both `?page=mxchat-max`
1331 * (legacy top-level URL) and `?page=mxchat-onboarding` (the canonical
1332 * Onboarding submenu).
1333 *
1334 * When the user has dismissed onboarding and lands on `mxchat-max` (the
1335 * legacy URL, since the Onboarding submenu has been removed), redirect to
1336 * Settings instead — the page is "graduated" and we shouldn't dump them
1337 * back onto it. They can still navigate here directly via the unhide link.
1338 */
1339 public function mxchat_create_dashboard_page() {
1340 require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
1341
1342 $current = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1343 if ($current === 'mxchat-max' && function_exists('mxchat_onboarding_is_dismissed') && mxchat_onboarding_is_dismissed()) {
1344 wp_safe_redirect(admin_url('admin.php?page=mxchat-settings'));
1345 exit;
1346 }
1347
1348 if (function_exists('mxchat_render_onboarding_page')) {
1349 mxchat_render_onboarding_page();
1350 return;
1351 }
1352 // Defensive: if the include failed to load, fall back to the old Settings page
1353 // so the top-level menu never lands on an empty screen.
1354 $this->mxchat_create_admin_page();
1355 }
1356
1357 /**
1358 * Hide the Onboarding submenu when the user has dismissed it (either
1359 * manually or via auto-graduation). The page itself remains routable so
1360 * the Settings "Show MxChat Onboarding again" link can navigate back to it.
1361 */
1362 public function mxchat_apply_onboarding_visibility() {
1363 if (!function_exists('mxchat_onboarding_is_dismissed')) {
1364 return;
1365 }
1366 if (mxchat_onboarding_is_dismissed()) {
1367 // The first MxChat child is the same-slug-as-parent registration
1368 // (slug 'mxchat-max', labelled "Onboarding") added in plan-d14e89.
1369 // Remove it so the menu opens straight to Settings after dismiss.
1370 remove_submenu_page('mxchat-max', 'mxchat-max');
1371 }
1372 }
1373
1374 public function mxchat_create_admin_page() {
1375 $this->add_live_agent_nonce();
1376 $this->add_theme_migration_nonce();
1377
1378 // Include and render the new sidebar-based settings page
1379 require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1380 mxchat_render_settings_page($this);
1381 }
1382
1383 public function dismiss_live_agent_notice() {
1384 // Add debugging
1385 //error_log('dismiss_live_agent_notice called');
1386 //error_log('POST data: ' . print_r($_POST, true));
1387
1388 // Verify nonce
1389 if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1390 //error_log('Nonce verification failed');
1391 wp_die('Security check failed');
1392 }
1393
1394 // Remove the notice flag
1395 $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1396 //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
1397
1398 wp_send_json_success();
1399 }
1400 public function add_live_agent_nonce() {
1401 if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1402 // Make sure your admin script is enqueued and localize the data
1403 wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1404 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1405 'ajaxurl' => admin_url('admin-ajax.php')
1406 ));
1407 }
1408 }
1409
1410 /**
1411 * Show theme migration notice for Pro users with AI-generated themes
1412 * Only shown once - dismissible and stored in options
1413 */
1414 public function show_theme_migration_banner() {
1415 // Only show if Pro is activated
1416 if (!$this->is_activated) {
1417 return;
1418 }
1419
1420 // Check if notice should be shown
1421 $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1422
1423 if ($show_notice) {
1424 ?>
1425 <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1426 <div class="mxchat-pro-notification">
1427 <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1428 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1429 <line x1="18" y1="6" x2="6" y2="18"></line>
1430 <line x1="6" y1="6" x2="18" y2="18"></line>
1431 </svg>
1432 </button>
1433 <div class="mxchat-theme-migration-content">
1434 <h3>🎨 AI Theme Migration Required</h3>
1435 <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>
1436 </div>
1437 </div>
1438 </div>
1439 <?php
1440 }
1441 }
1442
1443 /**
1444 * Dismiss theme migration notice via AJAX
1445 */
1446 public function dismiss_theme_migration_notice() {
1447 // Verify nonce
1448 if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1449 wp_die('Security check failed');
1450 }
1451
1452 // Remove the notice flag
1453 delete_option('mxchat_show_theme_migration_notice');
1454
1455 wp_send_json_success();
1456 }
1457
1458 /**
1459 * Add nonce for theme migration notice dismiss
1460 */
1461 public function add_theme_migration_nonce() {
1462 if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1463 wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1464 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1465 'ajaxurl' => admin_url('admin-ajax.php')
1466 ));
1467 }
1468 }
1469
1470 public function mxchat_create_transcripts_page() {
1471 global $wpdb;
1472 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1473
1474 // Get basic stats
1475 $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1476 $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
1477
1478 // Count unique users with detailed breakdown
1479 $total_users = $wpdb->get_var("
1480 SELECT COUNT(DISTINCT
1481 CASE
1482 WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1483 WHEN user_id != 0 THEN CONCAT('user_', user_id)
1484 WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1485 AND user_identifier NOT LIKE 'Detail-Oriented User'
1486 AND user_identifier NOT LIKE 'Language Learner'
1487 AND user_identifier NOT LIKE 'Casual Browser'
1488 AND user_identifier NOT LIKE 'Policy Enforcer'
1489 AND user_identifier NOT LIKE 'Researcher'
1490 AND user_identifier NOT LIKE 'Loyalty Member'
1491 AND user_identifier NOT LIKE 'Gift Buyer'
1492 AND user_identifier NOT LIKE 'Parent or Caregiver'
1493 THEN user_identifier
1494 ELSE session_id
1495 END
1496 )
1497 FROM $table_name
1498 WHERE role != 'assistant'
1499 ");
1500
1501 // Get user type breakdown
1502 $registered_users = $wpdb->get_var("
1503 SELECT COUNT(DISTINCT user_email)
1504 FROM $table_name
1505 WHERE user_email != '' AND user_email IS NOT NULL
1506 ");
1507
1508 $guest_users = $wpdb->get_var("
1509 SELECT COUNT(DISTINCT user_identifier)
1510 FROM $table_name
1511 WHERE (user_email = '' OR user_email IS NULL)
1512 AND role != 'assistant'
1513 AND user_identifier NOT LIKE 'Tech-Savvy User'
1514 AND user_identifier NOT LIKE 'Detail-Oriented User'
1515 AND user_identifier NOT LIKE 'Language Learner'
1516 AND user_identifier NOT LIKE 'Casual Browser'
1517 AND user_identifier NOT LIKE 'Policy Enforcer'
1518 AND user_identifier NOT LIKE 'Researcher'
1519 AND user_identifier NOT LIKE 'Loyalty Member'
1520 AND user_identifier NOT LIKE 'Gift Buyer'
1521 AND user_identifier NOT LIKE 'Parent or Caregiver'
1522 ");
1523
1524 // Get agent test messages count
1525 $agent_tests = $wpdb->get_var("
1526 SELECT COUNT(DISTINCT session_id)
1527 FROM $table_name
1528 WHERE user_identifier IN (
1529 'Tech-Savvy User',
1530 'Detail-Oriented User',
1531 'Language Learner',
1532 'Casual Browser',
1533 'Policy Enforcer',
1534 'Researcher',
1535 'Loyalty Member',
1536 'Gift Buyer',
1537 'Parent or Caregiver'
1538 )
1539 ");
1540 // Get activity metrics
1541 $today_chats = $wpdb->get_var("
1542 SELECT COUNT(DISTINCT session_id)
1543 FROM $table_name
1544 WHERE DATE(timestamp) = CURDATE()
1545 ");
1546
1547 $week_chats = $wpdb->get_var("
1548 SELECT COUNT(DISTINCT session_id)
1549 FROM $table_name
1550 WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1551 ");
1552
1553 $month_chats = $wpdb->get_var("
1554 SELECT COUNT(DISTINCT session_id)
1555 FROM $table_name
1556 WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1557 ");
1558
1559 // Get daily chat data for last 7 days
1560 $daily_stats = $wpdb->get_results("
1561 SELECT
1562 DATE(timestamp) as date,
1563 COUNT(DISTINCT session_id) as chats,
1564 COUNT(*) as messages
1565 FROM $table_name
1566 WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1567 GROUP BY DATE(timestamp)
1568 ORDER BY date ASC
1569 ");
1570
1571 // Get average messages per chat
1572 $avg_messages = $wpdb->get_var("
1573 SELECT AVG(message_count)
1574 FROM (
1575 SELECT session_id, COUNT(*) as message_count
1576 FROM $table_name
1577 GROUP BY session_id
1578 ) as chat_counts
1579 ");
1580 $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1581
1582 // Get busiest hour
1583 $busiest_hour = $wpdb->get_row("
1584 SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1585 FROM $table_name
1586 GROUP BY HOUR(timestamp)
1587 ORDER BY chat_count DESC
1588 LIMIT 1
1589 ");
1590
1591 // Prepare chart data
1592 $chart_labels = array();
1593 $chart_chats = array();
1594 $chart_messages = array();
1595
1596 // Fill last 7 days with data
1597 for ($i = 6; $i >= 0; $i--) {
1598 $date = date('Y-m-d', strtotime("-$i days"));
1599 $day_name = date('D', strtotime("-$i days"));
1600 $chart_labels[] = $day_name;
1601
1602 $found = false;
1603 foreach ($daily_stats as $stat) {
1604 if ($stat->date === $date) {
1605 $chart_chats[] = (int)$stat->chats;
1606 $chart_messages[] = (int)$stat->messages;
1607 $found = true;
1608 break;
1609 }
1610 }
1611 if (!$found) {
1612 $chart_chats[] = 0;
1613 $chart_messages[] = 0;
1614 }
1615 }
1616
1617 // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1618 $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
1619
1620 // Prepare page data for the template
1621 $page_data = array(
1622 'total_chats' => $total_chats,
1623 'total_messages' => $total_messages,
1624 'total_users' => $total_users,
1625 'registered_users' => $registered_users,
1626 'guest_users' => $guest_users,
1627 'agent_tests' => $agent_tests,
1628 'today_chats' => $today_chats,
1629 'week_chats' => $week_chats,
1630 'month_chats' => $month_chats,
1631 'avg_messages' => $avg_messages,
1632 'busiest_hour' => $busiest_hour,
1633 'chart_labels' => $chart_labels,
1634 'chart_chats' => $chart_chats,
1635 'chart_messages' => $chart_messages,
1636 'satisfaction_stats' => $satisfaction_stats,
1637 );
1638
1639 // Include and render the new template
1640 require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1641 mxchat_render_transcripts_page($this, $page_data);
1642 }
1643
1644 /**
1645 * Per-bot satisfaction rating rollup over the last $days days. Used by the
1646 * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1647 *
1648 * @param int $days Window in days.
1649 * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1650 */
1651 public function get_satisfaction_rating_stats($days = 30) {
1652 global $wpdb;
1653 $table = $wpdb->prefix . 'mxchat_session_ratings';
1654 if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1655 return array();
1656 }
1657 $days = max(1, (int) $days);
1658 $rows = $wpdb->get_results($wpdb->prepare(
1659 "SELECT bot_id,
1660 COUNT(*) AS total,
1661 SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1662 SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1663 FROM {$table}
1664 WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1665 GROUP BY bot_id
1666 ORDER BY total DESC",
1667 $days
1668 ));
1669 $out = array();
1670 foreach ((array) $rows as $row) {
1671 $total = (int) $row->total;
1672 $positive = (int) $row->positive;
1673 $negative = (int) $row->negative;
1674 $out[] = array(
1675 'bot_id' => $row->bot_id ?: 'default',
1676 'total' => $total,
1677 'positive' => $positive,
1678 'negative' => $negative,
1679 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1680 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1681 );
1682 }
1683 return $out;
1684 }
1685
1686 /**
1687 * Get chart data for transcripts page
1688 * Used by both page render and script localization
1689 *
1690 * @return array Chart data with labels, chats, and messages arrays
1691 */
1692 private function get_transcripts_chart_data() {
1693 global $wpdb;
1694 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1695
1696 // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1697 $daily_stats = $wpdb->get_results("
1698 SELECT
1699 DATE(timestamp) as date,
1700 COUNT(DISTINCT session_id) as chats,
1701 COUNT(*) as messages
1702 FROM $table_name
1703 WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1704 GROUP BY DATE(timestamp)
1705 ORDER BY date ASC
1706 ");
1707
1708 // Prepare chart data
1709 $chart_labels = array();
1710 $chart_chats = array();
1711 $chart_messages = array();
1712
1713 // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1714 for ($i = 6; $i >= 0; $i--) {
1715 $date = date('Y-m-d', strtotime("-$i days"));
1716 $day_name = date('D', strtotime("-$i days"));
1717 $chart_labels[] = $day_name;
1718
1719 $found = false;
1720 if ($daily_stats) {
1721 foreach ($daily_stats as $stat) {
1722 if ($stat->date === $date) {
1723 $chart_chats[] = (int)$stat->chats;
1724 $chart_messages[] = (int)$stat->messages;
1725 $found = true;
1726 break;
1727 }
1728 }
1729 }
1730 if (!$found) {
1731 $chart_chats[] = 0;
1732 $chart_messages[] = 0;
1733 }
1734 }
1735
1736 return array(
1737 'labels' => $chart_labels,
1738 'chats' => $chart_chats,
1739 'messages' => $chart_messages
1740 );
1741 }
1742
1743 public function mxchat_transcripts_notification_section_callback() {
1744 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>';
1745 }
1746 public function mxchat_enable_notifications_callback() {
1747 $options = get_option('mxchat_transcripts_options', array());
1748 $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1749 ?>
1750 <label for="mxchat_enable_notifications">
1751 <input type="checkbox" id="mxchat_enable_notifications"
1752 name="mxchat_transcripts_options[mxchat_enable_notifications]"
1753 value="1" <?php checked(1, $enabled); ?>>
1754 <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1755 </label>
1756 <p class="description">
1757 <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
1758 </p>
1759 <?php
1760 }
1761 public function mxchat_notification_email_callback() {
1762 $options = get_option('mxchat_transcripts_options', array());
1763 $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1764 ?>
1765 <?php /* type="text", not "email": the browser rejects a comma-separated list outright (plan 2f131a). Validation is server-side in MxChat_Utils. */ ?>
1766 <input type="text" id="mxchat_notification_email"
1767 name="mxchat_transcripts_options[mxchat_notification_email]"
1768 value="<?php echo esc_attr($email); ?>"
1769 class="regular-text">
1770 <p class="description">
1771 <?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); ?>
1772 </p>
1773 <?php
1774 }
1775
1776 public function mxchat_auto_delete_transcripts_callback() {
1777 $options = get_option('mxchat_transcripts_options', array());
1778 $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1779 ?>
1780 <select id="mxchat_auto_delete_transcripts"
1781 name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1782 <option value="never" <?php selected($interval, 'never'); ?>>
1783 <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1784 </option>
1785 <option value="1week" <?php selected($interval, '1week'); ?>>
1786 <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1787 </option>
1788 <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1789 <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1790 </option>
1791 <option value="1month" <?php selected($interval, '1month'); ?>>
1792 <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1793 </option>
1794 </select>
1795 <p class="description">
1796 <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
1797 </p>
1798 <?php
1799 }
1800
1801 /**
1802 * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1803 * and deletes transcripts older than the given number of days. Set to 0 to fall
1804 * back to the dropdown (or "Never" if the dropdown is also Never).
1805 *
1806 * Devs can override the final day count via the `mxchat_transcript_retention_days`
1807 * filter — runs in `cleanup_old_transcripts()` after this option is read.
1808 *
1809 * (plan-mxchat-20260509-9b80b1)
1810 */
1811 public function mxchat_retention_days_callback() {
1812 $options = get_option('mxchat_transcripts_options', array());
1813 $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1814 ?>
1815 <input type="number"
1816 id="mxchat_retention_days"
1817 name="mxchat_transcripts_options[mxchat_retention_days]"
1818 value="<?php echo esc_attr($days); ?>"
1819 min="0"
1820 max="3650"
1821 step="1"
1822 style="width: 90px;" />
1823 <p class="description">
1824 <?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'); ?>
1825 <br>
1826 <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1827 <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
1828 </p>
1829 <?php
1830 }
1831
1832 public function mxchat_auto_email_transcript_callback() {
1833 $options = get_option('mxchat_transcripts_options', array());
1834 $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1835 $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1836 $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1837 ?>
1838 <label>
1839 <input type="checkbox"
1840 id="mxchat_auto_email_transcript_enabled"
1841 name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1842 value="1"
1843 <?php checked($enabled, 1); ?>>
1844 <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1845 </label>
1846 <br><br>
1847 <label for="mxchat_auto_email_transcript_delay">
1848 <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1849 </label>
1850 <select id="mxchat_auto_email_transcript_delay"
1851 name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1852 <option value="15" <?php selected($delay, '15'); ?>>
1853 <?php esc_html_e('15 minutes', 'mxchat'); ?>
1854 </option>
1855 <option value="30" <?php selected($delay, '30'); ?>>
1856 <?php esc_html_e('30 minutes', 'mxchat'); ?>
1857 </option>
1858 <option value="60" <?php selected($delay, '60'); ?>>
1859 <?php esc_html_e('1 hour', 'mxchat'); ?>
1860 </option>
1861 </select>
1862 <br><br>
1863 <label>
1864 <input type="checkbox"
1865 id="mxchat_auto_email_transcript_require_contact"
1866 name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1867 value="1"
1868 <?php checked($require_contact, 1); ?>>
1869 <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1870 </label>
1871 <p class="description">
1872 <?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'); ?>
1873 <br>
1874 <?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'); ?>
1875 </p>
1876 <?php
1877 }
1878
1879
1880
1881 public function sanitize_transcripts_options($input) {
1882 $sanitized = array();
1883
1884 $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
1885
1886 if (isset($input['mxchat_notification_email'])) {
1887 // Same list rule as the Transcripts autosave path (plan 2f131a). These two
1888 // paths disagreeing is how the original bug survived: this one DID call
1889 // is_email(), but on sanitize_email()'s output — which is valid even when
1890 // the input was two addresses mashed into one. See MxChat_Utils.
1891 $parsed = MxChat_Utils::parse_notification_emails($input['mxchat_notification_email']);
1892 if ($parsed['error'] !== '') {
1893 add_settings_error(
1894 'mxchat_transcripts_options',
1895 'invalid_email',
1896 $parsed['error'],
1897 'error'
1898 );
1899 // Keep whatever was already stored. Do NOT fall back to admin_email:
1900 // that fallback belongs to a genuinely EMPTY field, and using it here
1901 // would quietly redirect notifications away from the address on screen.
1902 $existing = get_option('mxchat_transcripts_options', array());
1903 if (is_array($existing) && isset($existing['mxchat_notification_email'])) {
1904 $sanitized['mxchat_notification_email'] = $existing['mxchat_notification_email'];
1905 }
1906 } else {
1907 $sanitized['mxchat_notification_email'] = implode(', ', $parsed['emails']);
1908 }
1909 }
1910
1911 // Sanitize auto-delete setting
1912 $valid_intervals = array('never', '1week', '2weeks', '1month');
1913 if (isset($input['mxchat_auto_delete_transcripts'])) {
1914 $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1915 ? $input['mxchat_auto_delete_transcripts']
1916 : 'never';
1917 } else {
1918 $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1919 }
1920
1921 // Sanitize custom retention-days override (plan-9b80b1).
1922 if (isset($input['mxchat_retention_days'])) {
1923 $days = (int) $input['mxchat_retention_days'];
1924 $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1925 } else {
1926 // Absent key = a partial save (WP-CLI patch, a snippet, any
1927 // update_option with a subset — this filter runs on ALL of them).
1928 // Preserve the stored value instead of zeroing it: resetting here
1929 // silently discarded a hand-set retention on the next unrelated
1930 // save of this option (plan-3c3338). The page's own autosave path
1931 // bypasses this filter entirely (direct $wpdb write), so this
1932 // branch only ever sees programmatic saves.
1933 $mxch_prev = get_option('mxchat_transcripts_options', array());
1934 $sanitized['mxchat_retention_days'] = (is_array($mxch_prev) && isset($mxch_prev['mxchat_retention_days']))
1935 ? max(0, min(3650, (int) $mxch_prev['mxchat_retention_days']))
1936 : 0;
1937 }
1938
1939 // Get old values to check if auto-delete or retention-days changed.
1940 $old_options = get_option('mxchat_transcripts_options');
1941 $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1942 $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
1943
1944 // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1945 // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1946 // reason to keep the daily cron registered.
1947 $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1948 $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1949 if ($interval_changed || $retention_changed) {
1950 $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1951 $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1952 }
1953
1954 // Sanitize auto-email transcript settings
1955 $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
1956
1957 $valid_delays = array('15', '30', '60');
1958 if (isset($input['mxchat_auto_email_transcript_delay'])) {
1959 $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1960 ? $input['mxchat_auto_email_transcript_delay']
1961 : '30';
1962 } else {
1963 $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1964 }
1965
1966 // Sanitize require contact info setting
1967 $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1968
1969 return $sanitized;
1970 }
1971
1972 /**
1973 * Schedule or unschedule the transcript cleanup cron job
1974 */
1975 public function schedule_transcript_cleanup($interval) {
1976 // Clear any existing scheduled event
1977 $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1978 if ($timestamp) {
1979 wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1980 }
1981
1982 // Schedule new event whenever retention is active. "active" is the canonical
1983 // value passed by sanitize_transcripts_options when either the dropdown != never
1984 // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1985 // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1986 if ($interval !== 'never') {
1987 // Schedule to run daily at 3 AM
1988 $next_run = strtotime('tomorrow 3:00 AM');
1989 wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1990 }
1991 }
1992
1993 /**
1994 * Self-heal guard: keep the cleanup cron in sync with the retention setting.
1995 *
1996 * Runs on admin_init. Cost when nothing is wrong: one get_option() (cached) and
1997 * one wp_next_scheduled() (reads the cached cron option) — no writes. It only
1998 * schedules when retention is active but the event is missing, and only
1999 * unschedules when retention is off but the event survived. Both directions
2000 * reuse schedule_transcript_cleanup() so there is exactly one scheduling path.
2001 * Legacy dropdown values (1week/2weeks/1month) count as active, matching the
2002 * helper's own semantics. Deliberately not gated on DISABLE_WP_CRON: scheduling
2003 * writes the cron option regardless of how cron is executed, so a server-side
2004 * cron runner still picks the event up.
2005 */
2006 public function ensure_transcript_cleanup_scheduled() {
2007 $options = get_option('mxchat_transcripts_options', array());
2008 $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
2009 $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
2010 $active = ($interval !== 'never') || ($days > 0);
2011 $scheduled = (bool) wp_next_scheduled('mxchat_cleanup_old_transcripts');
2012
2013 if ($active && !$scheduled) {
2014 $this->schedule_transcript_cleanup('active');
2015 } elseif (!$active && $scheduled) {
2016 $this->schedule_transcript_cleanup('never');
2017 }
2018 }
2019
2020 /**
2021 * Delete old transcripts based on the configured interval
2022 */
2023 public function cleanup_old_transcripts() {
2024 $options = get_option('mxchat_transcripts_options', array());
2025 $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
2026 $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
2027
2028 // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
2029 $days = 0;
2030 if ($custom_days > 0) {
2031 $days = $custom_days;
2032 } else {
2033 switch ($interval) {
2034 case '1week': $days = 7; break;
2035 case '2weeks': $days = 14; break;
2036 case '1month': $days = 30; break;
2037 case 'never':
2038 default:
2039 $days = 0;
2040 }
2041 }
2042
2043 // Devs can override the final day count programmatically.
2044 $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
2045
2046 if ($days <= 0) {
2047 return; // Retention disabled — bail.
2048 }
2049
2050 global $wpdb;
2051 $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
2052 $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2053 $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
2054
2055 // Defensive: if the main table doesn't exist (fresh-ish install), bail.
2056 if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
2057 return;
2058 }
2059
2060 $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
2061
2062 // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
2063 // the cron will pick up where it left off on the next tick (within hours).
2064 $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
2065
2066 $sessions_to_delete = $wpdb->get_col(
2067 $wpdb->prepare(
2068 "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
2069 $cutoff_date,
2070 $batch_cap
2071 )
2072 );
2073
2074 if (empty($sessions_to_delete)) {
2075 return;
2076 }
2077
2078 $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
2079
2080 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
2081 // $placeholders is a server-built list of literal "%s" tokens.
2082 $deleted_transcripts = (int) $wpdb->query(
2083 $wpdb->prepare(
2084 "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
2085 $sessions_to_delete
2086 )
2087 );
2088
2089 if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
2090 $wpdb->query(
2091 $wpdb->prepare(
2092 "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
2093 $sessions_to_delete
2094 )
2095 );
2096 }
2097
2098 if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
2099 $wpdb->query(
2100 $wpdb->prepare(
2101 "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
2102 $sessions_to_delete
2103 )
2104 );
2105 }
2106 // phpcs:enable
2107
2108 update_option('mxchat_retention_last_swept_at', time(), false);
2109 update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
2110 }
2111
2112 public function export_chat_transcripts() {
2113 if (!current_user_can('manage_options')) {
2114 wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2115 }
2116
2117 check_ajax_referer('mxchat_export_transcripts', 'security');
2118
2119 global $wpdb;
2120 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2121
2122 // Get all transcripts ordered by session and timestamp
2123 $results = $wpdb->get_results(
2124 "SELECT session_id, user_email, user_identifier, role, message, timestamp
2125 FROM {$table_name}
2126 ORDER BY session_id, timestamp ASC"
2127 );
2128
2129 if (empty($results)) {
2130 wp_send_json_error(array('message' => 'No transcripts found.'));
2131 wp_die();
2132 }
2133
2134 // Set headers for CSV download
2135 header('Content-Type: text/csv');
2136 header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
2137 header('Pragma: no-cache');
2138 header('Expires: 0');
2139
2140 // Create output stream
2141 $output = fopen('php://output', 'w');
2142
2143 // Add UTF-8 BOM for proper Excel encoding
2144 fputs($output, "\xEF\xBB\xBF");
2145
2146 // Add CSV headers
2147 fputcsv($output, array(
2148 'Session ID',
2149 'Email',
2150 'User Identifier',
2151 'Role',
2152 'Message',
2153 'Timestamp'
2154 ));
2155
2156 // Add data rows
2157 foreach ($results as $row) {
2158 fputcsv($output, array(
2159 $row->session_id,
2160 $row->user_email,
2161 $row->user_identifier,
2162 $row->role,
2163 $row->message,
2164 $row->timestamp
2165 ));
2166 }
2167
2168 fclose($output);
2169 wp_die();
2170 }
2171
2172 // ============================================================================
2173 // Leads tab (inside Transcripts)
2174 //
2175 // Leads are derived from existing data — no dedicated table. Primary source:
2176 // wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
2177 // source: the mxchat_sessions table's visitor_email/visitor_name columns
2178 // (plus any unmigrated legacy `mxchat_email_{sid}` wp_options rows) for
2179 // "orphan" leads who submitted the pre-chat form but never chatted.
2180 // ============================================================================
2181
2182 /**
2183 * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
2184 */
2185 public function mxchat_fetch_leads() {
2186 if (!current_user_can('manage_options')) {
2187 wp_send_json_error(['message' => 'Insufficient permissions']);
2188 wp_die();
2189 }
2190
2191 $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
2192
2193 wp_send_json(self::mxchat_collect_leads([
2194 'page' => isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1,
2195 'per_page' => isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25,
2196 'search' => isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '',
2197 'date_cutoff' => self::mxchat_leads_date_cutoff($date_range),
2198 'status' => isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all',
2199 'page_url' => isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '',
2200 'sort' => isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen',
2201 'sort_dir' => (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'asc' : 'desc',
2202 ]));
2203 wp_die();
2204 }
2205
2206 /**
2207 * Build the Leads payload: the transcripts-derived list plus the chat-deleted
2208 * and orphan buckets, paginated and hydrated exactly as the Leads tab shows it.
2209 *
2210 * Extracted from mxchat_fetch_leads() so the REST route (f958cf) reads leads
2211 * through the same query rather than growing a second one that would drift —
2212 * in particular from the address-less lead key introduced by c0cfaf. Callers
2213 * own their own capability check and their own per_page ceiling; this method
2214 * reads no superglobals and echoes nothing.
2215 *
2216 * @param array $args page, per_page, search, date_cutoff (MySQL datetime or ''),
2217 * status (all|orphan|chat_deleted), page_url, sort, sort_dir.
2218 * @return array
2219 */
2220 public static function mxchat_collect_leads(array $args = []) {
2221 global $wpdb;
2222 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2223
2224 $page = max(1, (int) ($args['page'] ?? 1));
2225 $per_page = max(1, (int) ($args['per_page'] ?? 25));
2226 $offset = ($page - 1) * $per_page;
2227 $search = (string) ($args['search'] ?? '');
2228 $status = (string) ($args['status'] ?? 'all');
2229 $page_filter = (string) ($args['page_url'] ?? '');
2230 $sort = (string) ($args['sort'] ?? 'last_seen');
2231 $sort_dir = (isset($args['sort_dir']) && $args['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
2232
2233 $date_cutoff = (string) ($args['date_cutoff'] ?? '');
2234 $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2235
2236 // Base WHERE for transcripts leads.
2237 //
2238 // Email is the row key whenever there IS one. With "Require Email Address"
2239 // turned off (c0cfaf) a capture can be name-only, and keying on email
2240 // would drop it from this list entirely — the lead would be collected and
2241 // then invisible. Those rows key on session id instead, written as
2242 // "session:<id>" so the two kinds of key can never collide.
2243 //
2244 // The widening is gated on the option: while email is required (the
2245 // default, and every install that has not opted in) both the WHERE and the
2246 // GROUP BY reduce to exactly what they were before.
2247 $lead_key_sql = self::mxchat_leads_key_sql();
2248 $email_optional = self::mxchat_leads_email_optional();
2249
2250 $where_clauses = $email_optional
2251 ? ["((user_email IS NOT NULL AND user_email != '') OR (user_name IS NOT NULL AND user_name != ''))"]
2252 : ["user_email IS NOT NULL", "user_email != ''"];
2253 $where_params = [];
2254
2255 if ($date_cutoff) {
2256 $where_clauses[] = 'timestamp >= %s';
2257 $where_params[] = $date_cutoff;
2258 }
2259 if ($page_filter && $has_page_url_column) {
2260 $where_clauses[] = 'originating_page_url = %s';
2261 $where_params[] = $page_filter;
2262 }
2263 if ($search !== '') {
2264 $like = '%' . $wpdb->esc_like($search) . '%';
2265 $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
2266 $where_params[] = $like;
2267 $where_params[] = $like;
2268 }
2269 $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
2270
2271 // Aggregate query grouped by the lead key (email, or session id when the
2272 // capture had no email). MAX(user_email) is safe as the display address:
2273 // rows sharing an email key all carry that same address, and rows keyed by
2274 // session have no address to disagree about.
2275 $select_sql = "SELECT {$lead_key_sql} AS lead_key, MAX(user_email) AS user_email,
2276 MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2277 COUNT(DISTINCT session_id) AS conversation_count";
2278
2279 $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
2280 $group_order_limit = " GROUP BY lead_key ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
2281
2282 $transcripts_sql = $wpdb->prepare(
2283 "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
2284 array_merge($where_params, [$per_page, $offset])
2285 );
2286 $transcript_rows = $wpdb->get_results($transcripts_sql);
2287
2288 // Count of unique transcript-based leads under the same filters.
2289 $count_sql = $wpdb->prepare(
2290 "SELECT COUNT(DISTINCT {$lead_key_sql}) FROM {$table} {$where_sql}",
2291 $where_params
2292 );
2293 $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
2294
2295 // Hydrate each row: name, latest_session_id, top page.
2296 $leads = [];
2297 foreach ($transcript_rows as $row) {
2298 $detail = $has_page_url_column
2299 ? $wpdb->get_row($wpdb->prepare(
2300 "SELECT session_id, user_name, originating_page_url, originating_page_title
2301 FROM {$table} WHERE {$lead_key_sql} = %s ORDER BY timestamp DESC LIMIT 1",
2302 $row->lead_key
2303 ))
2304 : $wpdb->get_row($wpdb->prepare(
2305 "SELECT session_id, user_name FROM {$table}
2306 WHERE {$lead_key_sql} = %s ORDER BY timestamp DESC LIMIT 1",
2307 $row->lead_key
2308 ));
2309
2310 $leads[] = [
2311 'lead_key' => $row->lead_key,
2312 'email' => (string) $row->user_email,
2313 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2314 'conversation_count' => (int) $row->conversation_count,
2315 'last_seen' => $row->last_seen,
2316 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
2317 'first_seen' => $row->first_seen,
2318 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
2319 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2320 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
2321 'is_orphan' => false,
2322 'status' => 'active',
2323 ];
2324 }
2325
2326 // Non-transcript lead sources. Built once here, then filtered/merged based on the
2327 // status filter below. Deduplication priority when the same email appears in multiple
2328 // sources: transcripts > chat_deleted > orphan.
2329 $transcripts_emails_seen = array_flip(array_map(
2330 function ($r) { return self::mxchat_leads_dedup_key($r); },
2331 $leads
2332 ));
2333
2334 // Chat-deleted leads: had a conversation that an admin removed. Preserved via
2335 // mxchat_lead_del_* options, with timestamps so they respect date filters.
2336 $chat_deleted_leads_all = [];
2337 if ($status === 'all' || $status === 'chat_deleted') {
2338 $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
2339 // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
2340 $chat_deleted_leads_all = array_values(array_filter(
2341 $chat_deleted_leads_all,
2342 function ($row) use ($transcripts_emails_seen) {
2343 return !isset($transcripts_emails_seen[self::mxchat_leads_dedup_key($row)]);
2344 }
2345 ));
2346 foreach ($chat_deleted_leads_all as $row) {
2347 $transcripts_emails_seen[self::mxchat_leads_dedup_key($row)] = true;
2348 }
2349 }
2350
2351 // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
2352 // when a date filter is active.
2353 $orphan_leads_all = [];
2354 if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
2355 $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
2356 $orphan_leads_all = array_values(array_filter(
2357 $orphan_leads_all,
2358 function ($row) use ($transcripts_emails_seen) {
2359 return !isset($transcripts_emails_seen[self::mxchat_leads_dedup_key($row)]);
2360 }
2361 ));
2362 }
2363
2364 // Apply status filter to the transcripts-derived list.
2365 if ($status === 'orphan' || $status === 'chat_deleted') {
2366 $leads = [];
2367 $transcripts_lead_count = 0;
2368 }
2369
2370 // Stitch the current page from the three buckets in priority order.
2371 $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
2372 $remaining_slots = $per_page - count($leads);
2373
2374 if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
2375 $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
2376 if ($start < count($chat_deleted_leads_all)) {
2377 $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
2378 $remaining_slots = $per_page - count($leads);
2379 }
2380 }
2381
2382 if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
2383 $before = $transcripts_lead_count + count($chat_deleted_leads_all);
2384 $start = max(0, ($page - 1) * $per_page - $before);
2385 if ($start < count($orphan_leads_all)) {
2386 $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
2387 }
2388 }
2389
2390 $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
2391
2392 // Stats strip: always computed over full dataset, unaffected by filters.
2393 $stats = self::mxchat_leads_stats($table, $has_page_url_column);
2394
2395 // Top pages: top 5 by distinct emails captured.
2396 $top_pages = [];
2397 if ($has_page_url_column) {
2398 $top_pages_rows = $wpdb->get_results(
2399 "SELECT originating_page_url AS url,
2400 MAX(originating_page_title) AS title,
2401 COUNT(DISTINCT user_email) AS lead_count
2402 FROM {$table}
2403 WHERE user_email IS NOT NULL AND user_email != ''
2404 AND originating_page_url IS NOT NULL AND originating_page_url != ''
2405 GROUP BY originating_page_url
2406 ORDER BY lead_count DESC, url ASC
2407 LIMIT 5"
2408 );
2409 foreach ($top_pages_rows as $p) {
2410 $top_pages[] = [
2411 'url' => $p->url,
2412 'title' => $p->title ?: $p->url,
2413 'lead_count' => (int) $p->lead_count,
2414 ];
2415 }
2416 }
2417
2418 // Consent state per lead (b062c4). Chat-deleted rows already carry it from
2419 // their preserved options; the rest read the newest session-store record
2420 // for that email. Empty string = NOT RECORDED (pre-feature capture or the
2421 // checkbox was off) — distinct from 'no', which is a recorded decline.
2422 $can_read_consent = class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'latest_consent');
2423 foreach ($leads as &$lead_consent_ref) {
2424 if (array_key_exists('consent', $lead_consent_ref)) {
2425 continue;
2426 }
2427 $consent = $can_read_consent ? MxChat_Session_Store::latest_consent($lead_consent_ref['email']) : null;
2428 $lead_consent_ref['consent'] = $consent ? $consent['given'] : '';
2429 $lead_consent_ref['consent_at'] = $consent ? $consent['recorded_at'] : '';
2430 $lead_consent_ref['consent_label'] = $consent ? wp_strip_all_tags($consent['label']) : '';
2431 }
2432 unset($lead_consent_ref);
2433
2434 return [
2435 'success' => true,
2436 'leads' => $leads,
2437 'page' => $page,
2438 'per_page' => $per_page,
2439 'total_count' => $total_count,
2440 'total_pages' => $total_pages,
2441 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
2442 'showing_end' => min($offset + $per_page, $total_count),
2443 'stats' => $stats,
2444 'top_pages' => $top_pages,
2445 ];
2446 }
2447
2448 /**
2449 * Delete one or more leads by email. Removes every transcripts row for that
2450 * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2451 * mxchat_history_{sid}) and any orphan option entries matching the email.
2452 */
2453 public function mxchat_delete_leads() {
2454 if (!current_user_can('manage_options')) {
2455 wp_send_json_error(['message' => 'Insufficient permissions']);
2456 wp_die();
2457 }
2458 check_ajax_referer('mxchat_delete_leads', 'security');
2459
2460 // The tab sends back the key it was given, which is an address for most
2461 // leads and "session:<id>" for a name-only capture (c0cfaf). Splitting
2462 // here keeps sanitize_email() as the gate for the email half — an empty
2463 // or malformed value is dropped rather than turned into a WHERE clause
2464 // that would match every address-less row at once.
2465 $keys = self::mxchat_leads_split_keys(
2466 isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : []
2467 );
2468 $emails = $keys['emails'];
2469 $sessions = $keys['sessions'];
2470
2471 if (empty($emails) && empty($sessions)) {
2472 wp_send_json_error(['message' => 'No emails provided']);
2473 wp_die();
2474 }
2475
2476 $summary = ['deleted_sessions' => 0, 'deleted_rows' => 0];
2477 if (!empty($emails)) {
2478 $summary = self::mxchat_wipe_leads_by_email($emails);
2479 }
2480 if (!empty($sessions)) {
2481 $session_summary = self::mxchat_wipe_leads_by_session($sessions);
2482 $summary['deleted_sessions'] += $session_summary['deleted_sessions'];
2483 $summary['deleted_rows'] += $session_summary['deleted_rows'];
2484 }
2485
2486 wp_send_json([
2487 'success' => true,
2488 'deleted_leads' => count($emails) + count($sessions),
2489 'deleted_sessions' => $summary['deleted_sessions'],
2490 'deleted_rows' => $summary['deleted_rows'],
2491 ]);
2492 wp_die();
2493 }
2494
2495 /**
2496 * Wipe address-less leads by session id (c0cfaf) — the session-keyed twin of
2497 * mxchat_wipe_leads_by_email(). Same per-session option cleanup; no
2498 * email-keyed orphan sweep, because these leads have no address to sweep on.
2499 */
2500 private static function mxchat_wipe_leads_by_session(array $session_ids) {
2501 global $wpdb;
2502 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2503 $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2504 $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
2505
2506 $deleted_sessions = 0;
2507 $deleted_rows = 0;
2508
2509 foreach ($session_ids as $sid) {
2510 if ($sid === '') {
2511 continue;
2512 }
2513
2514 $rows_removed = $wpdb->delete($table, ['session_id' => $sid], ['%s']);
2515 if ($rows_removed !== false) {
2516 $deleted_rows += (int) $rows_removed;
2517 }
2518
2519 $deleted_sessions++;
2520 wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2521 delete_option('mxchat_history_' . $sid);
2522 delete_option('mxchat_email_' . $sid);
2523 delete_option('mxchat_name_' . $sid);
2524 delete_option('mxchat_agent_name_' . $sid);
2525 delete_option('mxchat_lead_del_email_' . $sid);
2526 delete_option('mxchat_lead_del_name_' . $sid);
2527 delete_option('mxchat_lead_del_ts_' . $sid);
2528 delete_option('mxchat_lead_del_consent_' . $sid);
2529 delete_option('mxchat_lead_del_consent_label_' . $sid);
2530 delete_option('mxchat_lead_del_consent_at_' . $sid);
2531 if (class_exists('MxChat_Session_Store')) {
2532 MxChat_Session_Store::delete_session($sid); // b64b77
2533 }
2534
2535 if ($has_translations) {
2536 $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2537 }
2538 }
2539
2540 return ['deleted_sessions' => $deleted_sessions, 'deleted_rows' => $deleted_rows];
2541 }
2542
2543 /**
2544 * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2545 * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2546 *
2547 * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2548 * Input emails must already be sanitized with sanitize_email().
2549 */
2550 private static function mxchat_wipe_leads_by_email(array $emails) {
2551 global $wpdb;
2552 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2553 $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2554 $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
2555
2556 $deleted_sessions = 0;
2557 $deleted_rows = 0;
2558 $emails_lc = array_map('strtolower', $emails);
2559
2560 foreach ($emails as $email) {
2561 $session_ids = $wpdb->get_col($wpdb->prepare(
2562 "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2563 $email
2564 ));
2565
2566 $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2567 if ($rows_removed !== false) {
2568 $deleted_rows += (int) $rows_removed;
2569 }
2570
2571 foreach ($session_ids as $sid) {
2572 $deleted_sessions++;
2573 wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2574 delete_option('mxchat_history_' . $sid);
2575 delete_option('mxchat_email_' . $sid);
2576 delete_option('mxchat_name_' . $sid);
2577 delete_option('mxchat_agent_name_' . $sid);
2578 delete_option('mxchat_lead_del_email_' . $sid);
2579 delete_option('mxchat_lead_del_name_' . $sid);
2580 delete_option('mxchat_lead_del_ts_' . $sid);
2581 delete_option('mxchat_lead_del_consent_' . $sid);
2582 delete_option('mxchat_lead_del_consent_label_' . $sid);
2583 delete_option('mxchat_lead_del_consent_at_' . $sid);
2584 if (class_exists('MxChat_Session_Store')) {
2585 MxChat_Session_Store::delete_session($sid); // b64b77
2586 }
2587 if ($has_translations) {
2588 $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2589 }
2590 }
2591 }
2592
2593 // Table-side twin of the option sweep below (5658f2): orphan pre-chat
2594 // captures now live in the sessions table's identity columns.
2595 if (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'find_by_email')) {
2596 foreach ($emails as $email) {
2597 foreach (MxChat_Session_Store::find_by_email($email) as $sid) {
2598 MxChat_Session_Store::delete_session($sid);
2599 }
2600 }
2601 }
2602
2603 // Clean up any lingering option entries (unmigrated orphan pre-chat captures +
2604 // chat_deleted preservations) whose stored value matches one of the emails being wiped.
2605 $lingering = $wpdb->get_results(
2606 "SELECT option_name, option_value FROM {$wpdb->options}
2607 WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2608 );
2609 foreach ($lingering as $opt) {
2610 if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2611 continue;
2612 }
2613 if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2614 $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2615 delete_option('mxchat_lead_del_email_' . $sid);
2616 delete_option('mxchat_lead_del_name_' . $sid);
2617 delete_option('mxchat_lead_del_ts_' . $sid);
2618 delete_option('mxchat_lead_del_consent_' . $sid);
2619 delete_option('mxchat_lead_del_consent_label_' . $sid);
2620 delete_option('mxchat_lead_del_consent_at_' . $sid);
2621 } else {
2622 $sid = substr($opt->option_name, strlen('mxchat_email_'));
2623 delete_option('mxchat_email_' . $sid);
2624 delete_option('mxchat_name_' . $sid);
2625 }
2626 }
2627
2628 wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2629
2630 return [
2631 'deleted_sessions' => $deleted_sessions,
2632 'deleted_rows' => $deleted_rows,
2633 ];
2634 }
2635
2636 /**
2637 * Stream a leads CSV. scope=all exports every lead under current filters is not
2638 * supported to keep semantics simple; caller either exports all leads or a
2639 * specific set of selected emails.
2640 */
2641 public function mxchat_export_leads() {
2642 if (!current_user_can('manage_options')) {
2643 wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2644 }
2645 check_ajax_referer('mxchat_export_leads', 'security');
2646
2647 $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2648 $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2649 // Selection keys arrive in the same shape the Leads tab renders them:
2650 // an address, or "session:<id>" for a name-only capture (c0cfaf).
2651 $selection_keys = self::mxchat_leads_split_keys(
2652 isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : []
2653 );
2654 $emails_in_clean = $selection_keys['emails'];
2655 $sessions_in = $selection_keys['sessions'];
2656
2657 global $wpdb;
2658 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2659 $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2660
2661 // Collect leads from transcripts. Keyed by email, or by session id when
2662 // the capture had no address (c0cfaf) — gated on the option, so with email
2663 // required this is the same query and the same rows as before.
2664 $lead_key_sql = self::mxchat_leads_key_sql();
2665 $email_filter = self::mxchat_leads_email_optional()
2666 ? "((user_email IS NOT NULL AND user_email != '') OR (user_name IS NOT NULL AND user_name != ''))"
2667 : "user_email IS NOT NULL AND user_email != ''";
2668
2669 $transcripts_sql = "SELECT {$lead_key_sql} AS lead_key,
2670 MAX(user_email) AS email,
2671 MAX(timestamp) AS last_seen,
2672 COUNT(DISTINCT session_id) AS conversation_count
2673 FROM {$table}
2674 WHERE {$email_filter}";
2675 $params = [];
2676 $selected_keys = array_merge(
2677 $emails_in_clean,
2678 array_map(function ($sid) { return 'session:' . $sid; }, $sessions_in)
2679 );
2680 if ($scope === 'selected' && !empty($selected_keys)) {
2681 $placeholders = implode(',', array_fill(0, count($selected_keys), '%s'));
2682 $transcripts_sql .= " AND {$lead_key_sql} IN ({$placeholders})";
2683 $params = $selected_keys;
2684 }
2685 $transcripts_sql .= " GROUP BY lead_key ORDER BY last_seen DESC";
2686
2687 $rows = !empty($params)
2688 ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2689 : $wpdb->get_results($transcripts_sql);
2690
2691 // Hydrate each row with name + top page.
2692 $export_rows = [];
2693 foreach ($rows as $row) {
2694 $detail = $has_page_url_column
2695 ? $wpdb->get_row($wpdb->prepare(
2696 "SELECT user_name, originating_page_url FROM {$table}
2697 WHERE {$lead_key_sql} = %s ORDER BY timestamp DESC LIMIT 1",
2698 $row->lead_key
2699 ))
2700 : $wpdb->get_row($wpdb->prepare(
2701 "SELECT user_name FROM {$table}
2702 WHERE {$lead_key_sql} = %s ORDER BY timestamp DESC LIMIT 1",
2703 $row->lead_key
2704 ));
2705 $export_rows[] = [
2706 'email' => (string) $row->email,
2707 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2708 'conversation_count' => (int) $row->conversation_count,
2709 'last_seen' => $row->last_seen,
2710 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2711 ];
2712 }
2713
2714 // Include orphan + chat_deleted leads when exporting all.
2715 if ($scope === 'all') {
2716 $transcripts_emails_lc = array_flip(array_map(
2717 function ($r) { return strtolower($r['email']); },
2718 $export_rows
2719 ));
2720 foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2721 if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2722 $transcripts_emails_lc[strtolower($cd['email'])] = true;
2723 $export_rows[] = [
2724 'email' => $cd['email'],
2725 'name' => $cd['name'],
2726 'conversation_count' => 0,
2727 'last_seen' => $cd['last_seen'],
2728 'top_page_url' => '',
2729 'consent' => isset($cd['consent']) ? $cd['consent'] : '',
2730 'consent_at' => isset($cd['consent_at']) ? $cd['consent_at'] : '',
2731 'consent_label' => isset($cd['consent_label']) ? $cd['consent_label'] : '',
2732 ];
2733 }
2734 foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2735 if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2736 $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2737 $export_rows[] = [
2738 'email' => $orphan['email'],
2739 'name' => $orphan['name'],
2740 'conversation_count' => 0,
2741 'last_seen' => '',
2742 'top_page_url' => '',
2743 ];
2744 }
2745 }
2746
2747 if (empty($export_rows)) {
2748 wp_send_json_error(['message' => 'No leads to export.']);
2749 wp_die();
2750 }
2751
2752 // Consent columns (b062c4). Chat-deleted rows already carry the preserved
2753 // values; the rest read the newest session-store record for that email.
2754 // Empty consent = "not recorded" — a pre-feature capture, NOT a decline.
2755 $can_read_consent = class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'latest_consent');
2756 foreach ($export_rows as &$export_consent_ref) {
2757 if (array_key_exists('consent', $export_consent_ref)) {
2758 continue;
2759 }
2760 $consent = $can_read_consent ? MxChat_Session_Store::latest_consent($export_consent_ref['email']) : null;
2761 $export_consent_ref['consent'] = $consent ? $consent['given'] : '';
2762 $export_consent_ref['consent_at'] = $consent ? $consent['recorded_at'] : '';
2763 $export_consent_ref['consent_label'] = $consent ? wp_strip_all_tags($consent['label']) : '';
2764 }
2765 unset($export_consent_ref);
2766
2767 $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2768 header('Content-Type: text/csv');
2769 header('Content-Disposition: attachment; filename="' . $filename . '"');
2770 header('Pragma: no-cache');
2771 header('Expires: 0');
2772
2773 $output = fopen('php://output', 'w');
2774 fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2775
2776 if ($fields_mode === 'email_only') {
2777 fputcsv($output, ['Email']);
2778 foreach ($export_rows as $r) {
2779 fputcsv($output, [$r['email']]);
2780 }
2781 } else {
2782 fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page', 'Consent', 'Consent recorded', 'Consent text shown']);
2783 foreach ($export_rows as $r) {
2784 fputcsv($output, [
2785 $r['email'],
2786 $r['name'],
2787 $r['conversation_count'],
2788 $r['last_seen'],
2789 $r['top_page_url'],
2790 $r['consent'] !== '' ? $r['consent'] : 'not recorded',
2791 $r['consent_at'],
2792 $r['consent_label'],
2793 ]);
2794 }
2795 }
2796
2797 fclose($output);
2798 wp_die();
2799 }
2800
2801 /**
2802 * Stats strip payload (independent of filters).
2803 */
2804 private static function mxchat_leads_stats($table, $has_page_url_column) {
2805 global $wpdb;
2806
2807 $total_transcripts_emails = (int) $wpdb->get_var(
2808 "SELECT COUNT(DISTINCT user_email) FROM {$table}
2809 WHERE user_email IS NOT NULL AND user_email != ''"
2810 );
2811
2812 $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2813 "SELECT COUNT(*) FROM (
2814 SELECT user_email FROM {$table}
2815 WHERE user_email IS NOT NULL AND user_email != ''
2816 GROUP BY user_email
2817 HAVING MIN(timestamp) >= %s
2818 ) AS new_leads",
2819 gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2820 ));
2821
2822 $total_convos = (int) $wpdb->get_var(
2823 "SELECT COUNT(DISTINCT session_id) FROM {$table}
2824 WHERE user_email IS NOT NULL AND user_email != ''"
2825 );
2826
2827 $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2828 $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
2829
2830 // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2831 // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2832 $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2833
2834 $avg = $total_transcripts_emails > 0
2835 ? round($total_convos / $total_transcripts_emails, 1)
2836 : 0;
2837
2838 // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2839 // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2840 // inflate this number.
2841 $orphan_pct = $total_leads > 0
2842 ? (int) round(($orphan_count / $total_leads) * 100)
2843 : 0;
2844
2845 return [
2846 'total_leads' => $total_leads,
2847 'new_this_week' => $new_this_week,
2848 'avg_convos' => $avg,
2849 'orphan_pct' => $orphan_pct,
2850 'orphan_count' => $orphan_count,
2851 'chat_deleted_count' => $chat_deleted_count,
2852 ];
2853 }
2854
2855 /**
2856 * Collect leads who had a conversation that an admin later deleted (preserved via
2857 * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2858 * original last-seen timestamp so they still sort and filter sensibly.
2859 *
2860 * @param string $search Optional email/name substring filter.
2861 * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2862 * @return array
2863 */
2864 private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2865 global $wpdb;
2866 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2867
2868 $rows = $wpdb->get_results(
2869 "SELECT option_name, option_value FROM {$wpdb->options}
2870 WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2871 );
2872 if (empty($rows)) {
2873 return [];
2874 }
2875
2876 // Emails that currently have transcripts rows should not appear as chat_deleted —
2877 // they've come back and chatted, so they're active leads again.
2878 $emails_in_transcripts = array_map(
2879 'strtolower',
2880 (array) $wpdb->get_col(
2881 "SELECT DISTINCT user_email FROM {$table}
2882 WHERE user_email IS NOT NULL AND user_email != ''"
2883 )
2884 );
2885 $emails_in_transcripts = array_flip($emails_in_transcripts);
2886
2887 $needle = strtolower(trim((string) $search));
2888 $by_email = [];
2889
2890 foreach ($rows as $opt) {
2891 $email = sanitize_email(trim((string) $opt->option_value));
2892 if (!$email) {
2893 continue;
2894 }
2895 if (isset($emails_in_transcripts[strtolower($email)])) {
2896 continue;
2897 }
2898 $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2899 if (!$sid) {
2900 continue;
2901 }
2902 $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2903 $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2904
2905 if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2906 continue;
2907 }
2908 if ($needle !== '') {
2909 $hay = strtolower($email . ' ' . $name);
2910 if (strpos($hay, $needle) === false) {
2911 continue;
2912 }
2913 }
2914
2915 $key = strtolower($email);
2916 if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2917 // Consent proof preserved at chat-delete time (b062c4) — the
2918 // session row is gone, so these options are the only copy.
2919 $consent_state = (string) get_option('mxchat_lead_del_consent_' . $sid, '');
2920
2921 $by_email[$key] = [
2922 'email' => $email,
2923 'name' => $name,
2924 'conversation_count' => 0,
2925 'last_seen' => $ts,
2926 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2927 'first_seen' => $ts,
2928 'latest_session_id' => '',
2929 'top_page_url' => '',
2930 'top_page_title' => '',
2931 'is_orphan' => false,
2932 'status' => 'chat_deleted',
2933 'consent' => $consent_state,
2934 'consent_at' => $consent_state !== '' ? (string) get_option('mxchat_lead_del_consent_at_' . $sid, '') : '',
2935 'consent_label' => $consent_state !== '' ? wp_strip_all_tags((string) get_option('mxchat_lead_del_consent_label_' . $sid, '')) : '',
2936 ];
2937 }
2938 }
2939
2940 // Newest chat_deleted first.
2941 usort($by_email, function ($a, $b) {
2942 return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2943 });
2944 return array_values($by_email);
2945 }
2946
2947 /**
2948 * Count unique emails preserved as "chat deleted" (for the stats strip).
2949 */
2950 private static function mxchat_count_chat_deleted_leads() {
2951 global $wpdb;
2952 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2953
2954 $emails = $wpdb->get_col(
2955 "SELECT DISTINCT option_value FROM {$wpdb->options}
2956 WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2957 );
2958 if (empty($emails)) {
2959 return 0;
2960 }
2961
2962 $transcripts_emails = array_map(
2963 'strtolower',
2964 (array) $wpdb->get_col(
2965 "SELECT DISTINCT user_email FROM {$table}
2966 WHERE user_email IS NOT NULL AND user_email != ''"
2967 )
2968 );
2969 $transcripts_emails = array_flip($transcripts_emails);
2970
2971 $count = 0;
2972 $seen = [];
2973 foreach ($emails as $raw) {
2974 $email = strtolower(trim((string) $raw));
2975 if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2976 continue;
2977 }
2978 $seen[$email] = true;
2979 $count++;
2980 }
2981 return $count;
2982 }
2983
2984 /**
2985 * Find leads who submitted the pre-chat form but never produced a transcripts row.
2986 * Returned rows have no conversation_count, no timestamp.
2987 *
2988 * @param string $search Optional email/name substring filter.
2989 * @return array
2990 */
2991 private static function mxchat_collect_orphan_leads($search = '') {
2992 global $wpdb;
2993 $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2994
2995 // Primary source since 5658f2: the sessions table's identity columns.
2996 // The legacy option scan stays for installs still mid-migration.
2997 // Ask for name-only sessions too when the owner made email optional
2998 // (c0cfaf) — that is the only source an address-less lead has.
2999 $store_rows = (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'identity_rows'))
3000 ? MxChat_Session_Store::identity_rows(self::mxchat_leads_email_optional())
3001 : [];
3002
3003 $option_rows = $wpdb->get_results(
3004 "SELECT option_name, option_value FROM {$wpdb->options}
3005 WHERE option_name LIKE 'mxchat_email_%'"
3006 );
3007 if (empty($option_rows) && empty($store_rows)) {
3008 return [];
3009 }
3010
3011 // Collect all session_ids that have real transcripts rows so we can exclude them.
3012 $session_ids_with_rows = $wpdb->get_col(
3013 "SELECT DISTINCT session_id FROM {$table}
3014 WHERE user_email IS NOT NULL AND user_email != ''"
3015 );
3016 $session_ids_with_rows = array_flip($session_ids_with_rows);
3017
3018 // Seen emails in transcripts (so orphans only include truly never-chatted leads).
3019 $emails_in_transcripts = array_map(
3020 'strtolower',
3021 (array) $wpdb->get_col(
3022 "SELECT DISTINCT user_email FROM {$table}
3023 WHERE user_email IS NOT NULL AND user_email != ''"
3024 )
3025 );
3026 $emails_in_transcripts = array_flip($emails_in_transcripts);
3027
3028 $orphans_by_email = [];
3029 $needle = strtolower(trim((string) $search));
3030
3031 // Normalize both sources into [sid, email, name] candidates. Table rows
3032 // first — a session can only live in one home, and dedup-by-email below
3033 // handles any overlap either way.
3034 $candidates = [];
3035 foreach ($store_rows as $row) {
3036 $candidates[] = [
3037 'sid' => (string) $row['session_id'],
3038 'email' => (string) $row['visitor_email'],
3039 'name' => is_string($row['visitor_name'] ?? null) ? $row['visitor_name'] : '',
3040 ];
3041 }
3042 foreach ($option_rows as $opt) {
3043 $sid = substr($opt->option_name, strlen('mxchat_email_'));
3044 $name_option = $sid ? get_option('mxchat_name_' . $sid, '') : '';
3045 $candidates[] = [
3046 'sid' => (string) $sid,
3047 'email' => (string) $opt->option_value,
3048 'name' => is_string($name_option) ? $name_option : '',
3049 ];
3050 }
3051
3052 // A capture with no address is an orphan too, and the commonest one: a
3053 // name-only lead (c0cfaf) has no transcript row until the visitor actually
3054 // sends a message, so this collector is the ONLY place it can surface.
3055 // Keying it on email would drop it silently — collected, then invisible.
3056 $email_optional = self::mxchat_leads_email_optional();
3057
3058 foreach ($candidates as $cand) {
3059 $email = sanitize_email(trim($cand['email']));
3060 $name = trim($cand['name']);
3061 $sid = $cand['sid'];
3062 if (!$sid) {
3063 continue;
3064 }
3065 if (!$email) {
3066 // Address-less rows are only leads when the owner made email
3067 // optional; otherwise they are incomplete captures, and skipping
3068 // them keeps this list identical to what it has always shown.
3069 if (!$email_optional || $name === '') {
3070 continue;
3071 }
3072 }
3073 // Exclude leads who have any transcripts rows (they appear in the main list).
3074 if ($email && isset($emails_in_transcripts[strtolower($email)])) {
3075 continue;
3076 }
3077 if (isset($session_ids_with_rows[$sid])) {
3078 continue;
3079 }
3080
3081 if ($needle !== '') {
3082 $hay = strtolower($email . ' ' . $name);
3083 if (strpos($hay, $needle) === false) {
3084 continue;
3085 }
3086 }
3087
3088 $key = $email !== '' ? strtolower($email) : 'session:' . $sid;
3089 if (!isset($orphans_by_email[$key])) {
3090 $orphans_by_email[$key] = [
3091 'lead_key' => $key,
3092 'email' => $email,
3093 'name' => $name,
3094 'conversation_count' => 0,
3095 'last_seen' => '',
3096 'last_seen_display' => __('No conversation yet', 'mxchat'),
3097 'first_seen' => '',
3098 // An address-less orphan carries its session id: that is the
3099 // only handle the delete and export paths have on it. Rows
3100 // that DO have an address keep the empty value they always
3101 // had, so the "View convo" button stays hidden for them.
3102 'latest_session_id' => $email !== '' ? '' : $sid,
3103 'top_page_url' => '',
3104 'top_page_title' => '',
3105 'is_orphan' => true,
3106 'status' => 'orphan',
3107 ];
3108 }
3109 }
3110
3111 return array_values($orphans_by_email);
3112 }
3113
3114 /**
3115 * Is the pre-chat email field optional? (c0cfaf)
3116 *
3117 * When it is, a lead can exist with a name and no address, and every place
3118 * that treats email as the row key has to widen. Default ON — an install that
3119 * never touched the setting behaves exactly as it did before.
3120 */
3121 private static function mxchat_leads_email_optional() {
3122 $options = get_option('mxchat_options', []);
3123 return is_array($options) && ($options['lead_capture_require_email_toggle'] ?? 'on') !== 'on';
3124 }
3125
3126 /**
3127 * SQL expression for a lead's key: its email address, or "session:<id>" when
3128 * the capture had no address (c0cfaf).
3129 *
3130 * The literal prefix is what keeps the two key spaces apart — an address can
3131 * never contain a colon before its local part, so a session key can never be
3132 * mistaken for an email or vice versa. NULLIF collapses '' and NULL to the
3133 * same thing, since the column uses both for "no email given".
3134 *
3135 * Contains no user input: safe to interpolate into a prepared statement.
3136 */
3137 private static function mxchat_leads_key_sql() {
3138 return "COALESCE(NULLIF(user_email, ''), CONCAT('session:', session_id))";
3139 }
3140
3141 /**
3142 * The PHP-side twin of mxchat_leads_key_sql(), used to dedupe rows arriving
3143 * from the three lead sources. Email keys stay lowercased, exactly as before,
3144 * so dedup behaviour for addressed leads is unchanged.
3145 */
3146 private static function mxchat_leads_dedup_key($row) {
3147 $email = isset($row['email']) ? trim((string) $row['email']) : '';
3148 if ($email !== '') {
3149 return strtolower($email);
3150 }
3151 if (!empty($row['lead_key'])) {
3152 return (string) $row['lead_key'];
3153 }
3154 return 'session:' . (isset($row['latest_session_id']) ? (string) $row['latest_session_id'] : '');
3155 }
3156
3157 /**
3158 * Split a list of client-supplied lead keys into real email addresses and
3159 * session keys. The Leads tab sends back whatever key it was given, so both
3160 * shapes arrive on the same parameter (c0cfaf).
3161 *
3162 * Anything that is neither a valid address nor a well-formed session key is
3163 * dropped — in particular an empty string, which as a bare email would match
3164 * every address-less row in the table at once.
3165 */
3166 private static function mxchat_leads_split_keys(array $raw) {
3167 $emails = [];
3168 $sessions = [];
3169 foreach ($raw as $value) {
3170 $value = trim((string) $value);
3171 if ($value === '') {
3172 continue;
3173 }
3174 if (strpos($value, 'session:') === 0) {
3175 $sid = MxChat_Utils::sanitize_session_id(substr($value, 8));
3176 if ($sid !== '' && $sid !== 'null') {
3177 $sessions[] = $sid;
3178 }
3179 continue;
3180 }
3181 $clean = sanitize_email($value);
3182 if ($clean) {
3183 $emails[] = $clean;
3184 }
3185 }
3186 return ['emails' => array_values(array_unique($emails)), 'sessions' => array_values(array_unique($sessions))];
3187 }
3188
3189 /**
3190 * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
3191 */
3192 private static function mxchat_leads_date_cutoff($date_range) {
3193 switch ($date_range) {
3194 case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
3195 case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
3196 case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
3197 case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
3198 case 'all':
3199 default: return '';
3200 }
3201 }
3202
3203 /**
3204 * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
3205 */
3206 private static function mxchat_leads_format_relative($timestamp) {
3207 if (!$timestamp) {
3208 return '';
3209 }
3210 $ts = strtotime($timestamp . ' UTC');
3211 if (!$ts) {
3212 return '';
3213 }
3214 $diff = time() - $ts;
3215 if ($diff < 60) return __('just now', 'mxchat');
3216 if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
3217 if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
3218 if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
3219 return wp_date('M j', $ts);
3220 }
3221
3222 /**
3223 * Handle translation of chat messages via AJAX
3224 */
3225 public function mxchat_translate_messages() {
3226 if (!current_user_can('manage_options')) {
3227 wp_send_json_error(['error' => 'Insufficient permissions']);
3228 wp_die();
3229 }
3230
3231 $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3232 $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
3233 $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
3234 $messages = json_decode($messages_json, true);
3235
3236 if (empty($session_id)) {
3237 wp_send_json_error(['error' => 'No session ID provided']);
3238 wp_die();
3239 }
3240
3241 if (empty($messages) || !is_array($messages)) {
3242 wp_send_json_error(['error' => 'No messages to translate']);
3243 wp_die();
3244 }
3245
3246 // Language names for prompting
3247 $languages = [
3248 'en' => 'English',
3249 'es' => 'Spanish',
3250 'fr' => 'French',
3251 'de' => 'German',
3252 'it' => 'Italian',
3253 'pt' => 'Portuguese',
3254 'nl' => 'Dutch',
3255 'ru' => 'Russian',
3256 'zh' => 'Chinese',
3257 'ja' => 'Japanese',
3258 'ko' => 'Korean',
3259 'ar' => 'Arabic',
3260 'hi' => 'Hindi',
3261 'tr' => 'Turkish',
3262 'pl' => 'Polish',
3263 'vi' => 'Vietnamese',
3264 'th' => 'Thai',
3265 'id' => 'Indonesian',
3266 'sv' => 'Swedish',
3267 'da' => 'Danish'
3268 ];
3269
3270 $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
3271
3272 // Build combined text for translation (numbered for parsing)
3273 $numbered_messages = [];
3274 foreach ($messages as $i => $msg) {
3275 $content = isset($msg['content']) ? trim($msg['content']) : '';
3276 if (!empty($content)) {
3277 $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
3278 }
3279 }
3280
3281 if (empty($numbered_messages)) {
3282 wp_send_json_error(['error' => 'No valid messages to translate']);
3283 wp_die();
3284 }
3285
3286 $combined_text = implode("\n\n", $numbered_messages);
3287
3288 // Prepare the translation prompt
3289 $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.";
3290
3291 // Get user's selected model and determine provider
3292 $options = get_option('mxchat_options', []);
3293 $selected_model = $options['model'] ?? 'gpt-5.6-sol';
3294
3295 // Check if using OpenRouter
3296 if ($selected_model === 'openrouter') {
3297 $provider = 'openrouter';
3298 $selected_model = $options['openrouter_selected_model'] ?? '';
3299 $api_key = $options['openrouter_api_key'] ?? '';
3300
3301 if (empty($selected_model)) {
3302 wp_send_json_error(['error' => 'No OpenRouter model selected']);
3303 wp_die();
3304 }
3305 } else {
3306 // Determine provider from model name
3307 $model_parts = explode('-', $selected_model);
3308 $provider = strtolower($model_parts[0]);
3309
3310 // Get the appropriate API key based on provider
3311 $api_key = '';
3312 switch ($provider) {
3313 case 'gpt':
3314 case 'o1':
3315 $api_key = $options['api_key'] ?? '';
3316 break;
3317 case 'claude':
3318 $api_key = $options['claude_api_key'] ?? '';
3319 break;
3320 case 'grok':
3321 $api_key = $options['xai_api_key'] ?? '';
3322 break;
3323 case 'deepseek':
3324 $api_key = $options['deepseek_api_key'] ?? '';
3325 break;
3326 case 'gemini':
3327 $api_key = $options['gemini_api_key'] ?? '';
3328 break;
3329 default:
3330 // Default to OpenAI
3331 $api_key = $options['api_key'] ?? '';
3332 $provider = 'gpt';
3333 break;
3334 }
3335 }
3336
3337 if (empty($api_key)) {
3338 wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
3339 wp_die();
3340 }
3341
3342 // Make API request based on provider
3343 $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
3344
3345 if (is_wp_error($response)) {
3346 wp_send_json_error(['error' => $response->get_error_message()]);
3347 wp_die();
3348 }
3349
3350 // Parse the response to extract translated messages
3351 $translations = [];
3352 foreach ($messages as $msg) {
3353 $index = $msg['index'];
3354 $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
3355 if (preg_match($pattern, $response, $matches)) {
3356 $translations[] = [
3357 'index' => $index,
3358 'translated' => trim($matches[1])
3359 ];
3360 }
3361 }
3362
3363 // Save translations to database
3364 if (!empty($translations)) {
3365 $this->save_transcript_translation($session_id, $target_lang, $translations);
3366 }
3367
3368 wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
3369 wp_die();
3370 }
3371
3372 /**
3373 * Save transcript translation to database
3374 */
3375 private function save_transcript_translation($session_id, $language_code, $translations) {
3376 global $wpdb;
3377 $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
3378
3379 // Check if table exists, create if not
3380 if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3381 mxchat_create_translations_table();
3382 }
3383
3384 $now = current_time('mysql');
3385 $translations_json = wp_json_encode($translations);
3386
3387 // Use REPLACE to insert or update
3388 $wpdb->query($wpdb->prepare(
3389 "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
3390 VALUES (%s, %s, %s, %s, %s)",
3391 $session_id,
3392 $language_code,
3393 $translations_json,
3394 $now,
3395 $now
3396 ));
3397 }
3398
3399 /**
3400 * Get saved translation for a session
3401 */
3402 public function mxchat_get_transcript_translation() {
3403 if (!current_user_can('manage_options')) {
3404 wp_send_json_error(['error' => 'Insufficient permissions']);
3405 wp_die();
3406 }
3407
3408 $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3409
3410 if (empty($session_id)) {
3411 wp_send_json_error(['error' => 'No session ID provided']);
3412 wp_die();
3413 }
3414
3415 global $wpdb;
3416 $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
3417
3418 // Check if table exists
3419 if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3420 wp_send_json(['success' => true, 'has_translation' => false]);
3421 wp_die();
3422 }
3423
3424 // Get the most recent translation for this session
3425 $result = $wpdb->get_row($wpdb->prepare(
3426 "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
3427 $session_id
3428 ));
3429
3430 if ($result) {
3431 $translations = json_decode($result->translations, true);
3432 wp_send_json([
3433 'success' => true,
3434 'has_translation' => true,
3435 'language' => $result->language_code,
3436 'translations' => $translations
3437 ]);
3438 } else {
3439 wp_send_json(['success' => true, 'has_translation' => false]);
3440 }
3441 wp_die();
3442 }
3443
3444 /**
3445 * Translate text using the user's selected provider and model
3446 */
3447 private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
3448 switch ($provider) {
3449 case 'claude':
3450 return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
3451 case 'grok':
3452 return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
3453 case 'deepseek':
3454 return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
3455 case 'gemini':
3456 return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
3457 case 'openrouter':
3458 return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
3459 case 'gpt':
3460 case 'o1':
3461 default:
3462 return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
3463 }
3464 }
3465
3466 /**
3467 * Translate text using OpenAI API
3468 */
3469 private function translate_with_openai($api_key, $model, $system_prompt, $text) {
3470 $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
3471 'timeout' => 60,
3472 'headers' => [
3473 'Authorization' => 'Bearer ' . $api_key,
3474 'Content-Type' => 'application/json'
3475 ],
3476 'body' => wp_json_encode([
3477 'model' => $model,
3478 'messages' => [
3479 ['role' => 'system', 'content' => $system_prompt],
3480 ['role' => 'user', 'content' => $text]
3481 ],
3482 'temperature' => 0.3
3483 ])
3484 ]);
3485
3486 if (is_wp_error($response)) {
3487 return $response;
3488 }
3489
3490 $body = json_decode(wp_remote_retrieve_body($response), true);
3491
3492 if (isset($body['error'])) {
3493 return new WP_Error('api_error', $body['error']['message']);
3494 }
3495
3496 if (isset($body['choices'][0]['message']['content'])) {
3497 return $body['choices'][0]['message']['content'];
3498 }
3499
3500 return new WP_Error('api_error', 'Invalid API response');
3501 }
3502
3503 /**
3504 * Translate text using Claude API
3505 */
3506 private function translate_with_claude($api_key, $model, $system_prompt, $text) {
3507 // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3508 // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3509 if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3510 elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3511 $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
3512 'timeout' => 60,
3513 'headers' => [
3514 'x-api-key' => $api_key,
3515 'anthropic-version' => '2023-06-01',
3516 'Content-Type' => 'application/json'
3517 ],
3518 'body' => wp_json_encode([
3519 'model' => $model,
3520 'max_tokens' => 4096,
3521 // Prompt-cache breakpoint (plan 1ff43b): the translate instruction
3522 // repeats across every message in a batch, so cache reads bill at
3523 // 0.1x. Below the model's minimum prefix it silently no-ops.
3524 'system' => trim((string) $system_prompt) === '' ? $system_prompt : [
3525 ['type' => 'text', 'text' => $system_prompt, 'cache_control' => ['type' => 'ephemeral']]
3526 ],
3527 'messages' => [
3528 ['role' => 'user', 'content' => $text]
3529 ]
3530 ])
3531 ]);
3532
3533 if (is_wp_error($response)) {
3534 return $response;
3535 }
3536
3537 $body = json_decode(wp_remote_retrieve_body($response), true);
3538
3539 if (isset($body['error'])) {
3540 return new WP_Error('api_error', $body['error']['message']);
3541 }
3542
3543 if (isset($body['content'][0]['text'])) {
3544 return $body['content'][0]['text'];
3545 }
3546
3547 return new WP_Error('api_error', 'Invalid API response');
3548 }
3549
3550 /**
3551 * Translate text using xAI (Grok) API
3552 */
3553 private function translate_with_xai($api_key, $model, $system_prompt, $text) {
3554 $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
3555 'timeout' => 60,
3556 'headers' => [
3557 'Authorization' => 'Bearer ' . $api_key,
3558 'Content-Type' => 'application/json'
3559 ],
3560 'body' => wp_json_encode([
3561 'model' => $model,
3562 'messages' => [
3563 ['role' => 'system', 'content' => $system_prompt],
3564 ['role' => 'user', 'content' => $text]
3565 ],
3566 'temperature' => 0.3
3567 ])
3568 ]);
3569
3570 if (is_wp_error($response)) {
3571 return $response;
3572 }
3573
3574 $body = json_decode(wp_remote_retrieve_body($response), true);
3575
3576 if (isset($body['error'])) {
3577 return new WP_Error('api_error', $body['error']['message']);
3578 }
3579
3580 if (isset($body['choices'][0]['message']['content'])) {
3581 return $body['choices'][0]['message']['content'];
3582 }
3583
3584 return new WP_Error('api_error', 'Invalid API response');
3585 }
3586
3587 /**
3588 * Translate text using DeepSeek API
3589 */
3590 private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
3591 $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
3592 'timeout' => 60,
3593 'headers' => [
3594 'Authorization' => 'Bearer ' . $api_key,
3595 'Content-Type' => 'application/json'
3596 ],
3597 'body' => wp_json_encode([
3598 'model' => $model,
3599 'messages' => [
3600 ['role' => 'system', 'content' => $system_prompt],
3601 ['role' => 'user', 'content' => $text]
3602 ],
3603 'temperature' => 0.3,
3604 // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
3605 // slow responses); translation wants non-thinking.
3606 'thinking' => ['type' => 'disabled']
3607 ])
3608 ]);
3609
3610 if (is_wp_error($response)) {
3611 return $response;
3612 }
3613
3614 $body = json_decode(wp_remote_retrieve_body($response), true);
3615
3616 if (isset($body['error'])) {
3617 return new WP_Error('api_error', $body['error']['message']);
3618 }
3619
3620 if (isset($body['choices'][0]['message']['content'])) {
3621 return $body['choices'][0]['message']['content'];
3622 }
3623
3624 return new WP_Error('api_error', 'Invalid API response');
3625 }
3626
3627 /**
3628 * Translate text using Google Gemini API
3629 */
3630 private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
3631 if ($model === 'gemini-3-pro-preview') {
3632 $model = 'gemini-3.1-pro-preview';
3633 }
3634 $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
3635
3636 $response = wp_remote_post($url, [
3637 'timeout' => 60,
3638 'headers' => [
3639 'Content-Type' => 'application/json'
3640 ],
3641 'body' => wp_json_encode([
3642 'contents' => [
3643 [
3644 'parts' => [
3645 ['text' => $system_prompt . "\n\n" . $text]
3646 ]
3647 ]
3648 ],
3649 'generationConfig' => [
3650 'temperature' => 0.3
3651 ]
3652 ])
3653 ]);
3654
3655 if (is_wp_error($response)) {
3656 return $response;
3657 }
3658
3659 $body = json_decode(wp_remote_retrieve_body($response), true);
3660
3661 if (isset($body['error'])) {
3662 return new WP_Error('api_error', $body['error']['message']);
3663 }
3664
3665 if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
3666 return $body['candidates'][0]['content']['parts'][0]['text'];
3667 }
3668
3669 return new WP_Error('api_error', 'Invalid API response');
3670 }
3671
3672 /**
3673 * Translate text using OpenRouter API
3674 */
3675 private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
3676 $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
3677 'timeout' => 60,
3678 'headers' => [
3679 'Authorization' => 'Bearer ' . $api_key,
3680 'Content-Type' => 'application/json',
3681 'HTTP-Referer' => home_url(),
3682 'X-Title' => 'MxChat Translation'
3683 ],
3684 'body' => wp_json_encode([
3685 'model' => $model,
3686 'messages' => [
3687 ['role' => 'system', 'content' => $system_prompt],
3688 ['role' => 'user', 'content' => $text]
3689 ],
3690 'temperature' => 0.3
3691 ])
3692 ]);
3693
3694 if (is_wp_error($response)) {
3695 return $response;
3696 }
3697
3698 $body = json_decode(wp_remote_retrieve_body($response), true);
3699
3700 if (isset($body['error'])) {
3701 return new WP_Error('api_error', $body['error']['message']);
3702 }
3703
3704 if (isset($body['choices'][0]['message']['content'])) {
3705 return $body['choices'][0]['message']['content'];
3706 }
3707
3708 return new WP_Error('api_error', 'Invalid API response');
3709 }
3710
3711 public function mxchat_fetch_chat_history() {
3712 global $wpdb;
3713 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3714 $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3715
3716 if (!current_user_can('manage_options')) {
3717 wp_send_json_error(['message' => 'Insufficient permissions']);
3718 wp_die();
3719 }
3720
3721 $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3722 $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3723 $offset = ($page - 1) * $per_page;
3724 $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3725 $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3726 $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3727 if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3728 $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3729 $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3730 $ratings_join = '';
3731 $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3732 if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3733 // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3734 $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3735 $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3736 }
3737
3738 // Build search condition
3739 $search_condition = '';
3740 $search_params = [];
3741 if (!empty($search)) {
3742 $search_condition = "WHERE (
3743 session_id LIKE %s
3744 OR user_email LIKE %s
3745 OR user_name LIKE %s
3746 OR user_identifier LIKE %s
3747 OR message LIKE %s
3748 )";
3749 $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3750 }
3751
3752 // Get total count
3753 $count_query = !empty($search)
3754 ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3755 : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3756 $total_sessions = (int) $wpdb->get_var($count_query);
3757
3758 // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3759 // and order by rating value (NULLs last) with recency as tiebreaker.
3760 if ($ratings_join) {
3761 $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3762 } else {
3763 $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3764 }
3765 $session_query = !empty($search)
3766 ? $wpdb->prepare(
3767 "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3768 GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3769 array_merge($search_params, [$per_page, $offset])
3770 )
3771 : $wpdb->prepare(
3772 "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3773 GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3774 $per_page, $offset
3775 );
3776 $session_ids = $wpdb->get_col($session_query);
3777
3778 $total_pages = ceil($total_sessions / $per_page);
3779
3780 if (empty($session_ids)) {
3781 wp_send_json([
3782 'success' => true,
3783 'sessions' => [],
3784 'page' => $page,
3785 'total_pages' => 0,
3786 'total_sessions' => 0,
3787 'showing_start' => 0,
3788 'showing_end' => 0
3789 ]);
3790 wp_die();
3791 }
3792
3793 // Check for optional columns/tables
3794 $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3795 $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3796
3797 // Batch-fetch session ratings for this page (plan-a5b006).
3798 $ratings_map = array();
3799 if ($rating_table_exists && !empty($session_ids)) {
3800 $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3801 $rating_rows = $wpdb->get_results($wpdb->prepare(
3802 "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3803 $session_ids
3804 ));
3805 foreach ($rating_rows as $row) {
3806 $ratings_map[$row->session_id] = array(
3807 'value' => (int) $row->rating_value,
3808 'feedback' => (string) $row->rating_feedback,
3809 );
3810 }
3811 }
3812
3813 // Build session list data
3814 $sessions = [];
3815 foreach ($session_ids as $session_id) {
3816 // Get session metadata
3817 $session_data = $originating_columns_exist
3818 ? $wpdb->get_row($wpdb->prepare(
3819 "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3820 FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3821 $session_id
3822 ))
3823 : $wpdb->get_row($wpdb->prepare(
3824 "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3825 WHERE session_id = %s LIMIT 1",
3826 $session_id
3827 ));
3828
3829 // Get message count and latest timestamp
3830 $message_stats = $wpdb->get_row($wpdb->prepare(
3831 "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3832 $session_id
3833 ));
3834
3835 // Get first user message as preview
3836 $first_user_msg = $wpdb->get_var($wpdb->prepare(
3837 "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3838 $session_id
3839 ));
3840 $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3841
3842 // Build display name
3843 $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3844 $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3845 $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3846
3847 $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3848 $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3849
3850 // Format time - show relative for recent, date for older
3851 $timestamp = strtotime($message_stats->latest . ' UTC');
3852 $now = time();
3853 $diff = $now - $timestamp;
3854 if ($diff < 3600) {
3855 $time_display = floor($diff / 60) . 'm ago';
3856 } elseif ($diff < 86400) {
3857 $time_display = floor($diff / 3600) . 'h ago';
3858 } elseif ($diff < 604800) {
3859 $time_display = floor($diff / 86400) . 'd ago';
3860 } else {
3861 $time_display = wp_date('M j', $timestamp);
3862 }
3863
3864 // Get initials for avatar
3865 $initials = strtoupper(substr($display_name, 0, 2));
3866 if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3867 $parts = explode(' ', $display_name);
3868 $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3869 }
3870
3871 $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3872 $rating_value = $rating_entry ? $rating_entry['value'] : null;
3873 $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3874
3875 $sessions[] = [
3876 'session_id' => $session_id,
3877 'display_name' => $display_name,
3878 'display_sub' => $display_sub,
3879 'initials' => $initials,
3880 'preview' => $preview,
3881 'message_count' => (int) $message_stats->count,
3882 'time_display' => $time_display,
3883 'timestamp' => $message_stats->latest,
3884 'rating_value' => $rating_value,
3885 'rating_feedback' => $rating_feedback,
3886 ];
3887 }
3888
3889 wp_send_json([
3890 'success' => true,
3891 'sessions' => $sessions,
3892 'page' => $page,
3893 'total_pages' => $total_pages,
3894 'total_sessions' => $total_sessions,
3895 'showing_start' => $offset + 1,
3896 'showing_end' => min($offset + $per_page, $total_sessions)
3897 ]);
3898 wp_die();
3899 }
3900
3901 /**
3902 * Fetch single conversation details for split-panel view
3903 */
3904 public function mxchat_fetch_conversation() {
3905 global $wpdb;
3906 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3907 $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3908
3909 if (!current_user_can('manage_options')) {
3910 wp_send_json_error(['message' => 'Insufficient permissions']);
3911 wp_die();
3912 }
3913
3914 $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3915 if (empty($session_id)) {
3916 wp_send_json_error(['message' => 'No session ID provided']);
3917 wp_die();
3918 }
3919
3920 // Check for optional columns/tables
3921 $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3922 $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3923
3924 // Get session metadata
3925 $session_data = $originating_columns_exist
3926 ? $wpdb->get_row($wpdb->prepare(
3927 "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3928 FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3929 $session_id
3930 ))
3931 : $wpdb->get_row($wpdb->prepare(
3932 "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3933 WHERE session_id = %s LIMIT 1",
3934 $session_id
3935 ));
3936
3937 if (!$session_data) {
3938 wp_send_json_error(['message' => 'Session not found']);
3939 wp_die();
3940 }
3941
3942 // Get clicked URLs
3943 $clicked_urls = [];
3944 if ($url_table_exists) {
3945 $url_clicks = $wpdb->get_results($wpdb->prepare(
3946 "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3947 WHERE session_id = %s ORDER BY click_timestamp ASC",
3948 $session_id
3949 ));
3950 foreach ($url_clicks as $click) {
3951 $clicked_urls[] = $click->clicked_url;
3952 }
3953 }
3954
3955 // Get all messages
3956 $messages = $wpdb->get_results($wpdb->prepare(
3957 "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3958 $session_id
3959 ));
3960
3961 // Build user info
3962 $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3963 $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3964 $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3965
3966 $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3967 $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3968
3969 // Get initials
3970 $initials = strtoupper(substr($display_name, 0, 2));
3971 if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3972 $parts = explode(' ', $display_name);
3973 $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3974 }
3975
3976 // Page info
3977 $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3978 $page_title = '';
3979 if ($page_url) {
3980 $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3981 }
3982
3983 // Format messages for output
3984 $formatted_messages = [];
3985 foreach ($messages as $msg) {
3986 $is_user = ($msg->role === 'user');
3987 // Live-agent replies (Slack/Telegram handoff) persist with role 'agent'.
3988 // Kept OUT of $is_bot so the RAG Sources link below stays bot-only.
3989 $is_agent = ($msg->role === 'agent');
3990 $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3991
3992 $content = wp_kses(
3993 stripslashes($msg->message),
3994 [
3995 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3996 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3997 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3998 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3999 'img' => ['src' => [], 'alt' => [], 'class' => []],
4000 'h3' => ['class' => []],
4001 'h4' => ['class' => []],
4002 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
4003 'select' => ['class' => [], 'data-attribute' => []],
4004 'option' => ['value' => []],
4005 'span' => ['class' => []],
4006 'del' => [], 'ins' => [],
4007 ]
4008 );
4009 $formatted_content = $this->format_transcript_message($content);
4010
4011 $has_rag = $is_bot && !empty($msg->rag_context);
4012
4013 $formatted_messages[] = [
4014 'id' => $msg->id,
4015 'role' => $msg->role,
4016 'is_user' => $is_user,
4017 'is_agent' => $is_agent,
4018 'is_bot' => $is_bot,
4019 'content' => $formatted_content,
4020 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
4021 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
4022 'has_rag' => $has_rag
4023 ];
4024 }
4025
4026 // First message timestamp for "started" display
4027 $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
4028
4029 // Pull rating_feedback for this session (if any) so the details drawer can show it.
4030 $rating_feedback = '';
4031 $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
4032 if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
4033 $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
4034 "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
4035 $session_id
4036 ));
4037 }
4038
4039 wp_send_json([
4040 'success' => true,
4041 'session_id' => $session_id,
4042 'user' => [
4043 'name' => $display_name,
4044 'sub' => $display_sub,
4045 'initials' => $initials,
4046 'email' => $user_email,
4047 'identifier' => $user_identifier
4048 ],
4049 'page' => [
4050 'url' => $page_url,
4051 'title' => $page_title
4052 ],
4053 'clicked_urls' => $clicked_urls,
4054 'messages' => $formatted_messages,
4055 'message_count' => count($messages),
4056 'started' => $started,
4057 'rating_feedback' => $rating_feedback
4058 ]);
4059 wp_die();
4060 }
4061
4062
4063 /**
4064 * ALTERNATIVE: Simpler helper method using string replacement
4065 */
4066 private function highlight_clicked_links($message_content, $clicked_urls) {
4067 if (empty($clicked_urls)) {
4068 return wp_kses(
4069 $message_content,
4070 [
4071 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
4072 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
4073 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
4074 ]
4075 );
4076 }
4077
4078 // First apply standard sanitization
4079 $message_content = wp_kses(
4080 $message_content,
4081 [
4082 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
4083 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
4084 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
4085 ]
4086 );
4087
4088 // Process each clicked URL
4089 foreach ($clicked_urls as $clicked_url) {
4090 // Try multiple patterns to catch different link formats
4091 $patterns = [
4092 // Standard link format
4093 '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
4094 // Link with trailing slash
4095 '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
4096 // Encoded entities version
4097 '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
4098 ];
4099
4100 foreach ($patterns as $pattern) {
4101 if (preg_match($pattern, $message_content)) {
4102 $message_content = preg_replace_callback(
4103 $pattern,
4104 function($matches) {
4105 $full_match = $matches[0];
4106 $attributes = $matches[1];
4107
4108 // Check if it already has the class
4109 if (strpos($full_match, 'mxchat-clicked-link') !== false) {
4110 return $full_match;
4111 }
4112
4113 // Check if class attribute exists
4114 if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
4115 // Add to existing class
4116 $new_attributes = preg_replace(
4117 '/class=["\']([^"\']*)["\']/',
4118 'class="$1 mxchat-clicked-link"',
4119 $attributes
4120 );
4121 } else {
4122 // Add new class attribute
4123 $new_attributes = $attributes . ' class="mxchat-clicked-link"';
4124 }
4125
4126 // Add title if not present
4127 if (strpos($new_attributes, 'title=') === false) {
4128 $new_attributes .= ' title="User clicked this link"';
4129 }
4130
4131 return '<a' . $new_attributes . '>';
4132 },
4133 $message_content
4134 );
4135
4136 // If we found and replaced, break out of the patterns loop
4137 break;
4138 }
4139 }
4140 }
4141
4142 return $message_content;
4143 }
4144
4145 public function mxchat_create_prompts_page() {
4146 //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
4147
4148 global $wpdb;
4149 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
4150
4151 $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
4152 $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
4153
4154 // Display success message if all prompts were deleted
4155 if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
4156 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>';
4157 }
4158
4159 // Set up pagination, search query, and content type filter
4160 $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
4161 $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
4162 $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
4163 $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
4164 $per_page = 25;
4165
4166 //error_log('DEBUG: Search query: ' . $search_query);
4167 //error_log('DEBUG: Content type filter: ' . $content_type_filter);
4168 //error_log('DEBUG: Current page: ' . $current_page);
4169 //error_log('DEBUG: Per page: ' . $per_page);
4170
4171 // ================================
4172 // MULTI-BOT CONFIGURATION
4173 // ================================
4174
4175 // Check for multi-bot and set up bot selection
4176 if (class_exists('MxChat_Multi_Bot_Manager')) {
4177 $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4178 $available_bots = $multi_bot_manager->get_available_bots();
4179
4180 // Get saved bot selection (user-specific first, then site-wide default)
4181 $user_id = get_current_user_id();
4182 $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
4183 if (empty($saved_bot_id)) {
4184 $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
4185 }
4186
4187 // Allow URL override but default to saved selection
4188 $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
4189 $multibot_active = true;
4190 } else {
4191 $current_bot_id = 'default';
4192 $multibot_active = false;
4193 }
4194
4195 // ================================
4196 // DATA SOURCE CONFIGURATION
4197 // ================================
4198
4199 // Get bot-specific Pinecone settings
4200 $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
4201 $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
4202 $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
4203
4204 // Get OpenAI Vector Store settings
4205 $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
4206 $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
4207
4208 //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
4209 //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
4210 //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
4211 //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
4212
4213 if ($use_pinecone && !empty($pinecone_api_key)) {
4214 //error_log('DEBUG: Using PINECONE data source with bot-specific config');
4215 // PINECONE DATA SOURCE
4216 $data_source = 'pinecone';
4217
4218 // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
4219 // UPDATED 2.5.6: Added content_type_filter parameter
4220 $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
4221
4222 // TEMPORARY DEBUG - Add this right after the fetch call
4223 //error_log('=== DEBUG: Bot switching issue ===');
4224 //error_log('Current bot ID: ' . $current_bot_id);
4225 //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
4226 //error_log('Records returned: ' . count($records['data'] ?? []));
4227 //error_log('Total records: ' . ($records['total'] ?? 0));
4228
4229 // Check first few records to see their bot_id
4230 if (!empty($records['data'])) {
4231 foreach (array_slice($records['data'], 0, 3) as $i => $record) {
4232 $record_bot_id = $record->bot_id ?? 'NOT_SET';
4233 //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
4234 }
4235 }
4236 //error_log('=== END DEBUG ===');
4237
4238 $total_records = $records['total'] ?? 0;
4239 $prompts = $records['data'] ?? array();
4240 $total_in_database = $records['total_in_database'] ?? 0;
4241 $showing_recent_only = $records['showing_recent_only'] ?? false;
4242 // Plan dd6e10: over 500 vectors the total is the index/namespace vector
4243 // count and pages come from Pinecone's cursor — the template renders
4244 // Previous / Next instead of numbered pages on that path.
4245 $count_unit = $records['count_unit'] ?? '';
4246 $cursor_pagination = !empty($records['cursor_pagination']);
4247 $has_next = !empty($records['has_next']);
4248
4249 $total_pages = ceil($total_records / $per_page);
4250
4251 } else {
4252 //error_log('DEBUG: Using WORDPRESS DB data source');
4253 // WORDPRESS DB DATA SOURCE (your existing logic)
4254 $data_source = 'wordpress';
4255
4256 // Initialize these variables for WordPress DB
4257 $total_in_database = 0;
4258 $showing_recent_only = false;
4259 $count_unit = '';
4260 $cursor_pagination = false;
4261 $has_next = false;
4262
4263 $offset = ($current_page - 1) * $per_page;
4264
4265 // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
4266 $where_clauses = array();
4267 $where_values = array();
4268
4269 if ($search_query) {
4270 $where_clauses[] = "article_content LIKE %s";
4271 $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
4272 }
4273
4274 if ($content_type_filter) {
4275 $where_clauses[] = "content_type = %s";
4276 $where_values[] = $content_type_filter;
4277 }
4278
4279 $sql_where = "";
4280 if (!empty($where_clauses)) {
4281 $sql_where = "WHERE " . implode(" AND ", $where_clauses);
4282 }
4283
4284 // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
4285 // This ensures pagination shows X entries per page, not X chunks
4286 // Entries with empty source_url are counted individually
4287 if (!empty($where_values)) {
4288 // Count unique source_urls + count of rows with empty source_url
4289 $count_query = $wpdb->prepare(
4290 "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
4291 (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
4292 array_merge($where_values, $where_values)
4293 );
4294 } else {
4295 $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
4296 (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
4297 }
4298 $total_records = $wpdb->get_var($count_query);
4299 $total_pages = ceil($total_records / $per_page);
4300
4301 // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
4302 // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
4303 if (!empty($where_values)) {
4304 $urls_query = $wpdb->prepare(
4305 "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
4306 GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
4307 array_merge($where_values, array($per_page, $offset))
4308 );
4309 } else {
4310 $urls_query = $wpdb->prepare(
4311 "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
4312 GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
4313 $per_page, $offset
4314 );
4315 }
4316 $page_urls = $wpdb->get_results($urls_query);
4317
4318 // Step 2: Fetch all rows for these source_urls
4319 $prompts = array();
4320 if (!empty($page_urls)) {
4321 // Build URL order map to preserve newest-first ordering from step 1
4322 $url_order_map = array();
4323 $url_list = array();
4324 $has_empty_url = false;
4325 $order_index = 0;
4326 foreach ($page_urls as $url_row) {
4327 if (empty($url_row->source_url)) {
4328 $has_empty_url = true;
4329 $url_order_map['__empty__'] = $order_index++;
4330 } else {
4331 $url_list[] = $url_row->source_url;
4332 $url_order_map[$url_row->source_url] = $order_index++;
4333 }
4334 }
4335
4336 // Build query to fetch all rows for these URLs
4337 $url_conditions = array();
4338 $url_values = array();
4339
4340 if (!empty($url_list)) {
4341 $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
4342 $url_conditions[] = "source_url IN ($placeholders)";
4343 $url_values = array_merge($url_values, $url_list);
4344 }
4345
4346 if ($has_empty_url) {
4347 $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
4348 }
4349
4350 if (!empty($url_conditions)) {
4351 $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
4352
4353 // Add original filters back
4354 if (!empty($where_clauses)) {
4355 $url_where .= " AND " . implode(" AND ", $where_clauses);
4356 $url_values = array_merge($url_values, $where_values);
4357 }
4358
4359 if (!empty($url_values)) {
4360 $prompts_query = $wpdb->prepare(
4361 "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
4362 $url_values
4363 );
4364 } else {
4365 $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
4366 }
4367
4368 $prompts = $wpdb->get_results($prompts_query);
4369
4370 // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
4371 usort($prompts, function($a, $b) use ($url_order_map) {
4372 $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
4373 $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
4374 $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
4375 $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
4376
4377 // First sort by URL order (newest URLs first)
4378 if ($order_a !== $order_b) {
4379 return $order_a - $order_b;
4380 }
4381
4382 // Within same URL, sort by timestamp DESC (newest chunks first)
4383 return strtotime($b->timestamp) - strtotime($a->timestamp);
4384 });
4385 }
4386 }
4387 }
4388
4389 // ================================
4390 // PAGINATION GENERATION
4391 // ================================
4392
4393 // Generate pagination links
4394 if ($total_pages > 1) {
4395 // Build a clean base URL with only necessary parameters
4396 $pagination_args = array('page' => 'mxchat-prompts');
4397
4398 // Preserve bot_id parameter if multi-bot is active
4399 if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
4400 $pagination_args['bot_id'] = $current_bot_id;
4401 }
4402
4403 // Preserve search query and nonce if present
4404 if ($search_query) {
4405 $pagination_args['search'] = $search_query;
4406 if (!empty($nonce)) {
4407 $pagination_args['_wpnonce'] = $nonce;
4408 }
4409 }
4410
4411 // Preserve content type filter if present
4412 if ($content_type_filter) {
4413 $pagination_args['content_type'] = $content_type_filter;
4414 }
4415
4416 // Build clean base URL
4417 $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
4418
4419 $page_links = paginate_links(array(
4420 'base' => $base_url . '%_%',
4421 'format' => '&paged=%#%',
4422 'prev_text' => __('&laquo; Previous', 'mxchat'),
4423 'next_text' => __('Next &raquo;', 'mxchat'),
4424 'total' => $total_pages,
4425 'current' => $current_page,
4426 'type' => 'plain',
4427 ));
4428 } else {
4429 $page_links = '';
4430 }
4431
4432 // ================================
4433 // PROCESSING STATUS RETRIEVAL
4434 // ================================
4435
4436 // Retrieve processing statuses using queue-based method
4437 $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
4438 $pdf_status = $processing_statuses['pdf_status'];
4439 $sitemap_status = $processing_statuses['sitemap_status'];
4440 $is_processing = $processing_statuses['is_processing'];
4441
4442 //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
4443
4444 // ================================
4445 // RENDER PAGE WITH NEW SIDEBAR LAYOUT
4446 // ================================
4447
4448 // Include the new knowledge page template
4449 require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
4450
4451 // Package all page data for the render function
4452 $page_data = array(
4453 'prompts' => $prompts,
4454 'total_records' => $total_records,
4455 'total_pages' => $total_pages,
4456 'current_page' => $current_page,
4457 'per_page' => $per_page,
4458 'page_links' => $page_links,
4459 'search_query' => $search_query,
4460 'content_type_filter' => $content_type_filter,
4461 'data_source' => $data_source,
4462 'use_pinecone' => $use_pinecone,
4463 'use_vectorstore' => $use_vectorstore,
4464 'multibot_active' => $multibot_active,
4465 'current_bot_id' => $current_bot_id,
4466 'pdf_status' => $pdf_status,
4467 'sitemap_status' => $sitemap_status,
4468 'is_processing' => $is_processing,
4469 'total_in_database' => $total_in_database ?? 0,
4470 'showing_recent_only' => $showing_recent_only ?? false,
4471 'count_unit' => $count_unit ?? '',
4472 'cursor_pagination' => $cursor_pagination ?? false,
4473 'has_next' => $has_next ?? false,
4474 );
4475
4476 // Render the new sidebar-based page
4477 mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
4478 }
4479
4480 /**
4481 * Get bot-specific Pinecone configuration
4482 * Used in the knowledge retrieval functions
4483 */
4484 private function get_bot_pinecone_config($bot_id = 'default') {
4485 //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
4486
4487 // If default bot or multi-bot add-on not active, use default Pinecone config
4488 if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
4489 //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
4490 $addon_options = get_option('mxchat_pinecone_addon_options', array());
4491 $config = array(
4492 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
4493 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
4494 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
4495 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
4496 );
4497 //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
4498 return $config;
4499 }
4500
4501 //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
4502
4503 // Hook for multi-bot add-on to provide bot-specific Pinecone config
4504 $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
4505
4506 if (!empty($bot_pinecone_config)) {
4507 //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
4508 //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
4509 //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
4510 //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
4511 } else {
4512 //error_log("MXCHAT DEBUG: Filter returned empty config!");
4513 }
4514
4515 return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
4516 }
4517
4518 public function mxchat_delete_chat_history() {
4519 if (!current_user_can('manage_options')) {
4520 echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4521 wp_die();
4522 }
4523 check_ajax_referer('mxchat_delete_chat_history', 'security');
4524
4525 if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
4526 echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
4527 wp_die();
4528 }
4529
4530 global $wpdb;
4531 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4532 $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
4533 $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
4534
4535 // When true, any lead attached to these sessions is fully wiped (all their sessions,
4536 // across the whole table). Default false: the chat rows go away but the lead is
4537 // preserved as a separate "chat deleted" lead in the Leads tab.
4538 $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
4539
4540 $deleted_count = 0;
4541 $preserved_as_deleted_leads = 0;
4542 $emails_to_fully_wipe = [];
4543
4544 foreach ((array) $_POST['delete_session_ids'] as $session_id) {
4545 $session_id_sanitized = MxChat_Utils::sanitize_session_id($session_id);
4546 if ($session_id_sanitized === '') {
4547 continue;
4548 }
4549
4550 // Capture the lead info attached to this session *before* we delete the rows.
4551 $lead_row = $wpdb->get_row($wpdb->prepare(
4552 "SELECT user_email, user_name, MAX(timestamp) AS last_ts
4553 FROM {$table_name}
4554 WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
4555 GROUP BY user_email, user_name
4556 ORDER BY last_ts DESC LIMIT 1",
4557 $session_id_sanitized
4558 ));
4559
4560 wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
4561 $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
4562
4563 if ($has_translations) {
4564 $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
4565 }
4566
4567 // Read the consent record BEFORE delete_session() destroys the row —
4568 // a preserved "chat deleted" lead must keep its consent proof (b062c4).
4569 $consent_to_preserve = null;
4570 if ($lead_row && !empty($lead_row->user_email) && class_exists('MxChat_Session_Store')) {
4571 $consent_state = MxChat_Session_Store::get($session_id_sanitized, 'consent', '');
4572 if ($consent_state !== '' && $consent_state !== false) {
4573 $consent_to_preserve = [
4574 'given' => (string) $consent_state,
4575 'label' => (string) MxChat_Session_Store::get($session_id_sanitized, 'consent_label', ''),
4576 'at' => (string) MxChat_Session_Store::get($session_id_sanitized, 'consent_at', ''),
4577 ];
4578 }
4579 }
4580
4581 delete_option('mxchat_history_' . $session_id_sanitized);
4582 delete_option('mxchat_agent_name_' . $session_id_sanitized);
4583 if (class_exists('MxChat_Session_Store')) {
4584 MxChat_Session_Store::delete_session($session_id_sanitized); // b64b77
4585 }
4586
4587 if ($lead_row && !empty($lead_row->user_email)) {
4588 if ($also_delete_lead) {
4589 // Full-wipe requested — queue the email so that all their sessions and
4590 // related options get swept below. Also clear this session's pre-chat
4591 // capture options (they're no longer meaningful).
4592 $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
4593 delete_option('mxchat_email_' . $session_id_sanitized);
4594 delete_option('mxchat_name_' . $session_id_sanitized);
4595 } else {
4596 // Preserve the lead in a "Chat deleted" state via distinct option keys so
4597 // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
4598 update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
4599 if (!empty($lead_row->user_name)) {
4600 update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
4601 }
4602 if (!empty($lead_row->last_ts)) {
4603 update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
4604 }
4605 if ($consent_to_preserve !== null) {
4606 update_option('mxchat_lead_del_consent_' . $session_id_sanitized, $consent_to_preserve['given'], false);
4607 update_option('mxchat_lead_del_consent_label_' . $session_id_sanitized, $consent_to_preserve['label'], false);
4608 update_option('mxchat_lead_del_consent_at_' . $session_id_sanitized, $consent_to_preserve['at'], false);
4609 }
4610 // Clean up pre-chat capture options for this session — chat_deleted supersedes.
4611 delete_option('mxchat_email_' . $session_id_sanitized);
4612 delete_option('mxchat_name_' . $session_id_sanitized);
4613 $preserved_as_deleted_leads++;
4614 }
4615 } else {
4616 // No lead attached — nothing to preserve. Clean up any orphan options anyway.
4617 delete_option('mxchat_email_' . $session_id_sanitized);
4618 delete_option('mxchat_name_' . $session_id_sanitized);
4619 }
4620
4621 $deleted_count++;
4622 }
4623
4624 // Opt-in full-lead wipe: sweep every remaining row + every option key (including
4625 // chat_deleted preservation) for each affected email. Reuses the same internal
4626 // helper as the Leads-tab Delete button for consistency.
4627 if (!empty($emails_to_fully_wipe)) {
4628 self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
4629 }
4630
4631 wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
4632
4633 echo wp_json_encode([
4634 'success' => sprintf(
4635 esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
4636 $deleted_count
4637 ),
4638 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
4639 'leads_fully_wiped' => count($emails_to_fully_wipe),
4640 ]);
4641 wp_die();
4642 }
4643
4644 /**
4645 * Format transcript message content with markdown processing
4646 * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
4647 */
4648 private function format_transcript_message($text) {
4649 if (empty($text)) {
4650 return '';
4651 }
4652
4653 // Normalize line endings and clean up excessive whitespace
4654 $text = str_replace("\r\n", "\n", $text);
4655 $text = str_replace("\r", "\n", $text);
4656
4657 // Clean up existing <br> tags that may have been saved (legacy data)
4658 // Convert <br>, <br/>, <br /> back to newlines for consistent processing
4659 $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
4660
4661 // Collapse 3+ consecutive newlines to just 2 (paragraph break)
4662 $text = preg_replace('/\n{3,}/', "\n\n", $text);
4663
4664 // Process markdown headers (# Header)
4665 $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
4666 $level = strlen($matches[1]);
4667 $content = esc_html(trim($matches[2]));
4668 return "<h{$level}>{$content}</h{$level}>";
4669 }, $text);
4670
4671 // Process code blocks with triple backticks
4672 $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
4673 $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
4674 $code = esc_html($matches[2]);
4675 return "<pre><code{$language}>{$code}</code></pre>";
4676 }, $text);
4677
4678 // Process inline code with single backticks
4679 $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
4680
4681 // Process bold text **text** or __text__
4682 $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
4683 $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
4684
4685 // Process italic text *text* or _text_ (but not if part of URL)
4686 $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
4687 $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
4688
4689 // Process markdown links [text](url)
4690 $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
4691 $link_text = esc_html($matches[1]);
4692 $url = esc_url($matches[2]);
4693 return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
4694 }, $text);
4695
4696 // Process citation-style brackets [URL]
4697 $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
4698 $url = esc_url($matches[1]);
4699 return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
4700 }, $text);
4701
4702 // Process standalone URLs (not already in links or img src)
4703 $text = preg_replace_callback(
4704 '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
4705 function($matches) {
4706 $url = esc_url($matches[1]);
4707 // Truncate display URL if too long
4708 $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
4709 return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
4710 },
4711 $text
4712 );
4713
4714 // Process mailto links
4715 $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
4716 $link_text = esc_html($matches[1]);
4717 $mailto = esc_url($matches[2]);
4718 return "<a href=\"{$mailto}\">{$link_text}</a>";
4719 }, $text);
4720
4721 // Convert paragraphs: split by double newlines, wrap in <p> tags
4722 // This creates proper paragraph structure instead of excessive <br> tags
4723 $paragraphs = preg_split('/\n\n+/', $text);
4724
4725 // Filter out empty paragraphs but preserve content like "0"
4726 $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
4727 return $p !== '';
4728 }));
4729
4730 if (empty($paragraphs)) {
4731 // No content after filtering
4732 return '';
4733 } elseif (count($paragraphs) > 1) {
4734 // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
4735 $formatted_paragraphs = array_map(function($p) {
4736 return nl2br($p);
4737 }, $paragraphs);
4738 $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4739 } else {
4740 // Single paragraph - just convert newlines to <br>
4741 $text = nl2br($paragraphs[0]);
4742 }
4743
4744 return $text;
4745 }
4746
4747 /**
4748 * AJAX handler to fetch RAG context for a specific message
4749 * Used by the transcript viewer to show retrieved documents
4750 */
4751 public function mxchat_get_rag_context() {
4752 // Check permissions
4753 if (!current_user_can('manage_options')) {
4754 wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4755 wp_die();
4756 }
4757
4758 // Validate message ID
4759 if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4760 wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4761 wp_die();
4762 }
4763
4764 $message_id = absint($_POST['message_id']);
4765
4766 global $wpdb;
4767 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4768
4769 // Fetch the RAG context for this message
4770 $result = $wpdb->get_row($wpdb->prepare(
4771 "SELECT rag_context FROM {$table_name} WHERE id = %d",
4772 $message_id
4773 ));
4774
4775 if (!$result || empty($result->rag_context)) {
4776 wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4777 wp_die();
4778 }
4779
4780 // Decode the JSON data
4781 $rag_context = json_decode($result->rag_context, true);
4782
4783 if (json_last_error() !== JSON_ERROR_NONE) {
4784 wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4785 wp_die();
4786 }
4787
4788 wp_send_json_success($rag_context);
4789 wp_die();
4790 }
4791
4792 public function display_admin_notices() {
4793 // Check if we're on a MXChat admin page
4794 $screen = get_current_screen();
4795 if (!$screen || strpos($screen->base, 'mxchat') === false) {
4796 return;
4797 }
4798
4799 $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4800
4801 // Check for error notices
4802 $error_notice = get_transient('mxchat_admin_notice_error');
4803 if ($error_notice) {
4804 echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4805 delete_transient('mxchat_admin_notice_error');
4806 }
4807
4808 // Check for success notices
4809 $success_notice = get_transient('mxchat_admin_notice_success');
4810 if ($success_notice) {
4811 echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4812 delete_transient('mxchat_admin_notice_success');
4813 }
4814
4815 // Check for info notices
4816 $info_notice = get_transient('mxchat_admin_notice_info');
4817 if ($info_notice) {
4818 echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4819 delete_transient('mxchat_admin_notice_info');
4820 }
4821 }
4822
4823
4824 public function mxchat_create_activation_page() {
4825 // Include the new Pro & Extensions page template
4826 require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
4827
4828 // Get addons configuration from the MxChat_Addons class
4829 require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4830 $addons_instance = new MxChat_Addons();
4831 $addons_config = $addons_instance->get_addons_config();
4832
4833 // Render the consolidated Pro & Extensions page
4834 mxchat_render_pro_page($this, $addons_config);
4835 }
4836
4837 /**
4838 * Check if current activation is linked to a domain
4839 * This checks YOUR website's database, not the user's local database
4840 */
4841 public function is_current_activation_linked($domain) {
4842 $license_key = get_option('mxchat_activation_key');
4843 $email = get_option('mxchat_pro_email');
4844
4845 if (empty($license_key) || empty($email)) {
4846 return false;
4847 }
4848
4849 // Check with YOUR website's API
4850 $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4851 'body' => array(
4852 'license_key' => $license_key,
4853 'email' => $email,
4854 'domain' => $domain
4855 ),
4856 'timeout' => 10,
4857 'sslverify' => false
4858 ));
4859
4860 if (is_wp_error($response)) {
4861 return false;
4862 }
4863
4864 $body = json_decode(wp_remote_retrieve_body($response), true);
4865 return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
4866 }
4867
4868
4869 public function mxchat_actions_page_html() {
4870 if (!current_user_can('manage_options')) {
4871 return;
4872 }
4873
4874 global $wpdb;
4875 $table_name = $wpdb->prefix . 'mxchat_intents';
4876
4877 // Get stats for dashboard
4878 $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4879 $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4880 $disabled_actions = $total_actions - $enabled_actions;
4881
4882 // Get unique action types count
4883 $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
4884
4885 // Get action type distribution
4886 $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");
4887 $available_callbacks = $this->mxchat_get_available_callbacks();
4888 $callback_groups = $this->mxchat_get_available_callbacks(true, true);
4889
4890 $action_type_distribution = array();
4891 foreach ($type_distribution_raw as $row) {
4892 $label = isset($available_callbacks[$row->callback_function]['label'])
4893 ? $available_callbacks[$row->callback_function]['label']
4894 : $row->callback_function;
4895 $action_type_distribution[$label] = $row->count;
4896 }
4897
4898 // Native function-calling (AI Tools) data — plan-mxchat-20260617-a41dee.
4899 // The AI Tools checklist reads from MxChat_Tool_Registry, the SAME single
4900 // source the chat-time function-calling loop reads, so the two never drift.
4901 if (!class_exists('MxChat_Tool_Registry')) {
4902 require_once plugin_dir_path(__FILE__) . 'class-mxchat-tool-registry.php';
4903 }
4904 if (!class_exists('MxChat_Model_Catalog')) {
4905 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
4906 }
4907 $fc_options = get_option('mxchat_options', array());
4908 $fc_current_model = isset($fc_options['model']) ? $fc_options['model'] : 'gpt-5.6-sol';
4909 $fc_model_capable = class_exists('MxChat_Model_Catalog')
4910 ? MxChat_Model_Catalog::supports_tools($fc_current_model) : true;
4911 $active_tab = (isset($_GET['tab']) && $_GET['tab'] === 'ai-tools') ? 'ai-tools' : 'dashboard';
4912
4913 // Enrich each AI Tool with the dashicon its callback already uses on the
4914 // Trigger Phrases "Choose what it does" grid, so the AI Tools cards/modal
4915 // share the same iconography (plan 8bbf98 part 4). View-layer only — the
4916 // registry's model-facing data is untouched. Default admin-generic.
4917 $fc_tools = MxChat_Tool_Registry::available_tools();
4918 foreach ($fc_tools as &$fc_tool_ref) {
4919 $fc_cb_ref = $fc_tool_ref['callback'];
4920 $fc_tool_ref['icon'] = isset($available_callbacks[$fc_cb_ref]['icon'])
4921 ? $available_callbacks[$fc_cb_ref]['icon']
4922 : 'admin-generic';
4923 }
4924 unset($fc_tool_ref);
4925
4926 // Count of ACTIVE tools — drives the AI Tools sidebar nav badge, mirroring
4927 // $total_actions for Trigger Phrases. A tool in the list = active (plan
4928 // d450a7), so the badge shows the same number the list pane shows (plan 5f7409).
4929 $total_tools = count(array_filter($fc_tools, function ($t) {
4930 return !empty($t['enabled']);
4931 }));
4932
4933 // Brave-key dependency check (plan 183856): Web Search + Image Search run on
4934 // the Brave Search API. If either is enabled as a tool but no brave_api_key is
4935 // configured, surface a graceful "key not set" notice so the admin isn't met
4936 // with a silently no-firing tool.
4937 $fc_brave_missing = false;
4938 $brave_key = isset($fc_options['brave_api_key']) ? trim($fc_options['brave_api_key']) : '';
4939 if ($brave_key === '') {
4940 foreach ($fc_tools as $fc_t) {
4941 if (!empty($fc_t['enabled']) && isset($fc_t['requires_key']) && $fc_t['requires_key'] === 'brave_api_key') {
4942 $fc_brave_missing = true;
4943 break;
4944 }
4945 }
4946 }
4947
4948 // Prepare page data
4949 $page_data = array(
4950 'total_actions' => $total_actions,
4951 'enabled_actions' => $enabled_actions,
4952 'disabled_actions' => $disabled_actions,
4953 'action_types_count' => $action_types_count,
4954 'action_type_distribution' => $action_type_distribution,
4955 'available_callbacks' => $available_callbacks,
4956 'callback_groups' => $callback_groups,
4957 // AI Tools section
4958 'active_tab' => $active_tab,
4959 'fc_enabled' => MxChat_Tool_Registry::is_enabled(),
4960 'total_tools' => $total_tools,
4961 'fc_tools' => $fc_tools,
4962 'fc_current_model' => $fc_current_model,
4963 'fc_model_capable' => $fc_model_capable,
4964 'fc_brave_missing' => $fc_brave_missing,
4965 'fc_saved' => isset($_GET['mxchat_fc_saved']),
4966 );
4967
4968 // Include and render the new template
4969 require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4970 mxchat_render_actions_page($this, $page_data);
4971 }
4972
4973 /**
4974 * LEGACY HTML - Preserved below for reference, to be removed in future update
4975 */
4976 function mxchat_actions_page_legacy_html() {
4977 // This function is deprecated and no longer used
4978 // The new template is in includes/admin-actions-page.php
4979 ?>
4980 <div class="wrap mxchat-wrapper">
4981 <!-- Hero Section -->
4982 <div class="mxchat-hero">
4983 <h1 class="mxchat-main-title">
4984 <span class="mxchat-gradient-text">Actions</span> Manager
4985 </h1>
4986 <p class="mxchat-hero-subtitle">
4987 <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
4988 </p>
4989 </div>
4990
4991 <!-- Actions Header with Search and Filter -->
4992 <div class="mxchat-actions-header">
4993 <div class="mxchat-actions-filters">
4994 <form method="get" class="mxchat-search-form">
4995 <input type="hidden" name="page" value="mxchat-actions">
4996 <div class="mxchat-search-group">
4997 <span class="dashicons dashicons-search"></span>
4998 <input type="text" name="s" class="mxchat-search-input"
4999 placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
5000 value="<?php echo esc_attr($search_term); ?>">
5001 </div>
5002 <select name="callback_filter" class="mxchat-action-filter">
5003 <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
5004 <?php foreach ($available_callbacks as $function => $callback_data) :
5005 $label = $callback_data['label']; ?>
5006 <option value="<?php echo esc_attr($function); ?>"
5007 <?php selected($callback_filter, $function); ?>>
5008 <?php echo esc_html($label); ?>
5009 </option>
5010 <?php endforeach; ?>
5011 </select>
5012 <button type="submit" class="mxchat-button-secondary">
5013 <?php esc_html_e('Filter', 'mxchat'); ?>
5014 </button>
5015 </form>
5016 </div>
5017 <div class="mxchat-actions-controls">
5018 <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
5019 <span class="dashicons dashicons-plus-alt"></span>
5020 <?php esc_html_e('Add New Action', 'mxchat'); ?>
5021 </button>
5022 </div>
5023 </div>
5024
5025 <!-- Actions Grid Layout - All actions in a single grid -->
5026 <div class="mxchat-actions-grid">
5027 <div class="mxchat-cards-container">
5028 <?php if (!empty($actions)) : ?>
5029 <?php foreach ($actions as $action) :
5030 $callback_function = $action->callback_function;
5031 $callback_label = isset($available_callbacks[$callback_function]['label'])
5032 ? $available_callbacks[$callback_function]['label']
5033 : $callback_function;
5034 $threshold_value = isset($action->similarity_threshold)
5035 ? round($action->similarity_threshold * 100)
5036 : 85;
5037
5038 // Check if this is a form action
5039 $is_form_action = strpos($action->intent_label, 'Form ') === 0;
5040
5041 // Get action status (enabled/disabled) - default to true if column doesn't exist
5042 $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
5043
5044 // Get enabled bots for display
5045 $enabled_bots = [];
5046 if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
5047 $enabled_bots = json_decode($action->enabled_bots, true);
5048 if (!is_array($enabled_bots)) {
5049 $enabled_bots = ['default'];
5050 }
5051 } else {
5052 $enabled_bots = ['default']; // Backward compatibility
5053 }
5054 ?>
5055 <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
5056 <div class="mxchat-card-header">
5057 <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
5058 <div class="mxchat-card-toggle">
5059 <label class="mxchat-switch">
5060 <input type="checkbox" class="mxchat-action-toggle"
5061 data-action-id="<?php echo esc_attr($action->id); ?>"
5062 <?php checked($is_enabled); ?>>
5063 <span class="mxchat-slider round"></span>
5064 </label>
5065 </div>
5066 </div>
5067
5068 <div class="mxchat-card-body">
5069 <div class="mxchat-card-description">
5070 <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
5071 <?php echo esc_html($callback_label); ?>
5072 </div>
5073
5074 <div class="mxchat-card-phrases">
5075 <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
5076 <div class="mxchat-phrases-preview">
5077 <?php
5078 // Check if the helper function exists, otherwise use a simple substring
5079 if (method_exists($this, 'get_trimmed_phrases')) {
5080 echo esc_html($this->get_trimmed_phrases($action->phrases));
5081 } else {
5082 echo esc_html(strlen($action->phrases) > 100 ?
5083 substr($action->phrases, 0, 97) . '...' :
5084 $action->phrases);
5085 }
5086 ?>
5087 </div>
5088 </div>
5089
5090 <div class="mxchat-threshold-control">
5091 <div class="mxchat-threshold-label">
5092 <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
5093 <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
5094 </div>
5095 </div>
5096
5097 <!-- Bot Availability Display (Read-only) -->
5098 <div class="mxchat-card-bots">
5099 <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
5100 <div class="mxchat-bot-badges">
5101 <?php
5102 foreach ($enabled_bots as $bot_id) {
5103 if ($bot_id === 'default') {
5104 echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
5105 } else {
5106 // Try to get bot name from multi-bot manager
5107 if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
5108 $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
5109 $available_bots = $multi_bot_manager->get_available_bots();
5110 $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
5111 echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
5112 } else {
5113 echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
5114 }
5115 }
5116 }
5117 ?>
5118 </div>
5119 </div>
5120 </div>
5121
5122 <div class="mxchat-card-footer">
5123 <?php
5124 // Check if it's a form action
5125 $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
5126
5127 // Check if it's a recommendation flow action
5128 $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
5129
5130 if ($is_form_action) {
5131 $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
5132 ?>
5133 <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
5134 class="mxchat-button-primary">
5135 <span class="dashicons dashicons-feedback"></span>
5136 <?php esc_html_e('Edit Form', 'mxchat'); ?>
5137 </a>
5138 <?php } elseif ($is_flow_action) {
5139 ?>
5140 <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
5141 class="mxchat-button-primary">
5142 <span class="dashicons dashicons-list-view"></span>
5143 <?php esc_html_e('Manage Flows', 'mxchat'); ?>
5144 </a>
5145 <?php } else { ?>
5146 <button type="button"
5147 class="mxchat-button-secondary mxchat-edit-button"
5148 data-action-id="<?php echo esc_attr($action->id); ?>"
5149 data-phrases="<?php echo esc_attr($action->phrases); ?>"
5150 data-label="<?php echo esc_attr($action->intent_label); ?>"
5151 data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
5152 data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
5153 data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
5154 <span class="dashicons dashicons-edit"></span>
5155 <?php esc_html_e('Edit', 'mxchat'); ?>
5156 </button>
5157 <form method="post"
5158 action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
5159 class="mxchat-delete-form"
5160 onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
5161 <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
5162 <input type="hidden" name="action" value="mxchat_delete_intent">
5163 <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
5164 <button type="submit" class="mxchat-button-text mxchat-delete-button">
5165 <span class="dashicons dashicons-trash"></span>
5166 <?php esc_html_e('Delete', 'mxchat'); ?>
5167 </button>
5168 </form>
5169 <?php } ?>
5170 </div>
5171 </div>
5172 <?php endforeach; ?>
5173 <?php else : ?>
5174 <!-- If no actions found -->
5175 <div class="mxchat-no-actions">
5176 <div class="mxchat-empty-state">
5177 <span class="dashicons dashicons-format-chat"></span>
5178 <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
5179 <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
5180 <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
5181 <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
5182 </button>
5183 </div>
5184 </div>
5185 <?php endif; ?>
5186 </div>
5187 </div>
5188
5189 <?php if ($total_pages > 1) : ?>
5190 <div class="mxchat-pagination">
5191 <?php
5192 echo paginate_links(array(
5193 'base' => add_query_arg('paged', '%#%'),
5194 'format' => '',
5195 'prev_text' => __('&laquo; Previous', 'mxchat'),
5196 'next_text' => __('Next &raquo;', 'mxchat'),
5197 'total' => $total_pages,
5198 'current' => $page
5199 ));
5200 ?>
5201 </div>
5202 <?php endif; ?>
5203
5204 <!-- Add/Edit Action Modal with Step-Based Approach -->
5205 <!-- Complete Modal HTML with Defined Groups Variable -->
5206 <div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
5207 <div class="mxchat-modal-content">
5208 <span class="mxchat-modal-close">&times;</span>
5209
5210 <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
5211 <!-- Dynamic nonce field -->
5212 <div id="action-nonce-container">
5213 <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
5214 </div>
5215 <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
5216 <input type="hidden" name="intent_id" id="edit_action_id" value="">
5217 <input type="hidden" name="callback_function" id="callback_function" value="">
5218
5219 <!-- Step 1: Action Type Selection -->
5220 <div id="mxchat-action-step-1" class="mxchat-action-step active">
5221 <div class="mxchat-step-indicator">
5222 <div class="mxchat-step-number">1</div>
5223 <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
5224 </div>
5225
5226 <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
5227 <div class="mxchat-action-type-search">
5228 <span class="dashicons dashicons-search"></span>
5229 <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
5230 </div>
5231
5232 <?php
5233 // Get the callbacks - IMPORTANT: Define the $groups variable here
5234 $groups = $this->mxchat_get_available_callbacks(true, true);
5235 ?>
5236
5237 <div class="mxchat-action-type-categories">
5238 <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
5239 <?php
5240 // Get unique categories from the defined groups
5241 foreach ($groups as $group_label => $group_callbacks) :
5242 $category_slug = sanitize_title($group_label);
5243 ?>
5244 <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
5245 <?php endforeach; ?>
5246 </div>
5247
5248 <div class="mxchat-action-types-grid">
5249 <?php
5250 // Generate action cards from available callbacks
5251 foreach ($groups as $group_label => $group_callbacks) :
5252 $category_slug = sanitize_title($group_label);
5253
5254 foreach ($group_callbacks as $function => $data) :
5255 $label = $data['label'];
5256 $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
5257 $description = isset($data['description']) ? $data['description'] : '';
5258 $is_addon = isset($data['addon']) && $data['addon'] !== false;
5259 $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
5260 $is_installed = isset($data['installed']) ? $data['installed'] : true;
5261 $is_promo = !empty($data['addon_promo']) && !$is_installed;
5262
5263 // Determine card status and styling
5264 $card_class = 'mxchat-action-type-card';
5265 $icon_class = 'mxchat-action-type-icon';
5266 $status_badge = '';
5267
5268 if ($is_promo) {
5269 // Promotional card — not selectable, just informational
5270 $card_class .= ' not-installed mxchat-promo-card';
5271 $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
5272 } elseif ($is_addon && !$is_installed) {
5273 // Add-on not installed
5274 $card_class .= ' not-installed';
5275 $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
5276 }
5277
5278 // Default description if none provided
5279 if (empty($description)) {
5280 $description = sprintf(
5281 esc_html__('Use the %s action in your chatbot', 'mxchat'),
5282 $label
5283 );
5284 }
5285 ?>
5286 <div class="<?php echo esc_attr($card_class); ?>"
5287 data-category="<?php echo esc_attr($category_slug); ?>"
5288 <?php if (!$is_promo) : ?>
5289 data-value="<?php echo esc_attr($function); ?>"
5290 data-label="<?php echo esc_attr($label); ?>"
5291 <?php endif; ?>
5292 data-pro="false"
5293 data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
5294 data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
5295 <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
5296 <div class="<?php echo esc_attr($icon_class); ?>">
5297 <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
5298 </div>
5299 <div class="mxchat-action-type-info">
5300 <h4><?php echo esc_html($label); ?></h4>
5301 <p><?php echo esc_html($description); ?></p>
5302 <?php if (!empty($status_badge)) : ?>
5303 <?php echo $status_badge; ?>
5304 <?php endif; ?>
5305
5306 <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
5307 <div class="mxchat-addon-info">
5308 <?php echo esc_html(sprintf(
5309 __('Requires %s', 'mxchat'),
5310 $addon_name
5311 )); ?>
5312 — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
5313 </div>
5314 <?php endif; ?>
5315 </div>
5316 </div>
5317 <?php endforeach;
5318 endforeach; ?>
5319 </div>
5320 </div>
5321
5322 <div class="mxchat-modal-actions">
5323 <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
5324 <?php esc_html_e('Cancel', 'mxchat'); ?>
5325 </button>
5326 </div>
5327 </div>
5328
5329 <!-- Step 2: Action Configuration -->
5330 <div id="mxchat-action-step-2" class="mxchat-action-step">
5331 <div class="mxchat-step-indicator">
5332 <div class="mxchat-step-number">2</div>
5333 <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
5334 </div>
5335
5336 <div class="mxchat-selected-action">
5337 <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
5338 <span class="dashicons dashicons-arrow-left-alt"></span>
5339 <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
5340 </button>
5341 <div class="mxchat-selected-action-info">
5342 <div id="selected-action-icon" class="mxchat-action-type-icon">
5343 <span class="dashicons dashicons-admin-generic"></span>
5344 </div>
5345 <div class="mxchat-selected-action-details">
5346 <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
5347 <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
5348 </div>
5349 </div>
5350 </div>
5351
5352 <div class="mxchat-form-group">
5353 <label for="intent_label">
5354 <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
5355 </label>
5356 <input name="intent_label" type="text" id="intent_label" required
5357 class="mxchat-intent-input"
5358 placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
5359 </div>
5360
5361 <div class="mxchat-form-group">
5362 <label for="phrases">
5363 <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
5364 </label>
5365 <textarea name="phrases" id="action_phrases" rows="5" required
5366 class="mxchat-intent-textarea"
5367 placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
5368 </div>
5369
5370 <div class="mxchat-form-group">
5371 <label for="similarity_threshold">
5372 <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
5373 <span class="mxchat-threshold-value-display">85%</span>
5374 </label>
5375 <div class="mxchat-slider-group modal-slider">
5376 <input type="range"
5377 name="similarity_threshold"
5378 id="similarity_threshold"
5379 min="10"
5380 max="95"
5381 value="85"
5382 class="mxchat-intent-slider"
5383 oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
5384 </div>
5385 <div class="mxchat-threshold-hint">
5386 <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
5387 </div>
5388 </div>
5389
5390 <!-- Bot Selection Section -->
5391 <div class="mxchat-form-group">
5392 <label for="enabled_bots">
5393 <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
5394 </label>
5395 <div class="mxchat-bot-selector">
5396 <div class="mxchat-bot-option">
5397 <label class="mxchat-checkbox-label">
5398 <input type="checkbox"
5399 name="enabled_bots[]"
5400 value="default"
5401 id="bot_default"
5402 checked="checked">
5403 <span class="mxchat-checkmark"></span>
5404 <?php esc_html_e('Default Bot', 'mxchat'); ?>
5405 </label>
5406 </div>
5407
5408 <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
5409 $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
5410 $available_bots = $multi_bot_manager->get_available_bots();
5411
5412 foreach ($available_bots as $bot_id => $bot_name) :
5413 if ($bot_id === 'default') continue; // Skip default, already shown above
5414 ?>
5415 <div class="mxchat-bot-option">
5416 <label class="mxchat-checkbox-label">
5417 <input type="checkbox"
5418 name="enabled_bots[]"
5419 value="<?php echo esc_attr($bot_id); ?>"
5420 id="bot_<?php echo esc_attr($bot_id); ?>">
5421 <span class="mxchat-checkmark"></span>
5422 <?php echo esc_html($bot_name); ?>
5423 </label>
5424 </div>
5425 <?php
5426 endforeach;
5427 endif; ?>
5428 </div>
5429 </div>
5430
5431 <div class="mxchat-modal-actions">
5432 <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
5433 <?php esc_html_e('Cancel', 'mxchat'); ?>
5434 </button>
5435 <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
5436 <?php esc_html_e('Save Action', 'mxchat'); ?>
5437 </button>
5438 </div>
5439 </div>
5440 </form>
5441 </div>
5442 </div>
5443
5444 <div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
5445 <div class="mxchat-action-loading-spinner"></div>
5446 <div class="mxchat-action-loading-text">
5447 <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
5448 </div>
5449 </div>
5450 </div><!-- .mxchat-wrapper -->
5451 <?php
5452 }
5453 private function get_trimmed_phrases($phrases, $max_length = 100) {
5454 if (strlen($phrases) <= $max_length) {
5455 return $phrases;
5456 }
5457
5458 $trimmed = substr($phrases, 0, $max_length);
5459 $last_comma = strrpos($trimmed, ',');
5460
5461 if ($last_comma !== false) {
5462 $trimmed = substr($trimmed, 0, $last_comma);
5463 }
5464
5465 return $trimmed . '...';
5466 }
5467 public function mxchat_add_enabled_column_to_intents() {
5468 global $wpdb;
5469 $table_name = $wpdb->prefix . 'mxchat_intents';
5470
5471 // Check if the column already exists
5472 $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
5473
5474 if (empty($columns)) {
5475 // Add the column with default value of 1 (enabled)
5476 $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
5477 }
5478 }
5479
5480 public function mxchat_handle_delete_intent() {
5481 if ( ! current_user_can( 'manage_options' ) ) {
5482 wp_die( esc_html__('Unauthorized user', 'mxchat') );
5483 }
5484
5485 check_admin_referer('mxchat_delete_intent_nonce');
5486
5487 if (isset($_POST['intent_id'])) {
5488 global $wpdb;
5489 $table_name = $wpdb->prefix . 'mxchat_intents';
5490 $intent_id = intval($_POST['intent_id']);
5491
5492 $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5493 }
5494
5495 wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5496 exit;
5497 }
5498 public function mxchat_handle_edit_intent() {
5499 // Security checks (nonce and permissions)
5500 if (!current_user_can('manage_options')) {
5501 wp_die(esc_html__('Unauthorized user', 'mxchat'));
5502 }
5503 check_admin_referer('mxchat_edit_intent');
5504
5505 // Get POST data
5506 $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
5507 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5508 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5509 $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
5510 $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
5511
5512 // Handle enabled_bots
5513 $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5514 $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5515
5516 // Ensure default is always included for backward compatibility
5517 if (!in_array('default', $enabled_bots)) {
5518 $enabled_bots[] = 'default';
5519 }
5520
5521 $enabled_bots_json = json_encode($enabled_bots);
5522
5523 // Validate inputs
5524 if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
5525 $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5526 return;
5527 }
5528
5529 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5530 if (empty($phrases_array)) {
5531 $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5532 return;
5533 }
5534
5535 // Generate embeddings with improved error handling
5536 $vectors = [];
5537 $failed_phrases = [];
5538
5539 foreach ($phrases_array as $phrase) {
5540 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5541 if (is_array($embedding_vector)) {
5542 $vectors[] = $embedding_vector;
5543 } else {
5544 $failed_phrases[] = $phrase;
5545 }
5546 }
5547
5548 if (!empty($failed_phrases)) {
5549 $this->handle_embedding_error(
5550 sprintf(
5551 __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5552 implode(', ', $failed_phrases)
5553 )
5554 );
5555 return;
5556 }
5557
5558 if (empty($vectors)) {
5559 $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5560 return;
5561 }
5562
5563 $combined_vector = $this->mxchat_average_vectors($vectors);
5564 $serialized_vector = maybe_serialize($combined_vector);
5565
5566 // Update the database
5567 global $wpdb;
5568 $table_name = $wpdb->prefix . 'mxchat_intents';
5569
5570 $result = $wpdb->update(
5571 $table_name,
5572 array(
5573 'intent_label' => $intent_label,
5574 'phrases' => implode(', ', $phrases_array),
5575 'embedding_vector' => $serialized_vector,
5576 'similarity_threshold' => $similarity_threshold,
5577 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
5578 ),
5579 array('id' => $intent_id),
5580 array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
5581 array('%d') // Where format: integer
5582 );
5583
5584 if (false === $result) {
5585 $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
5586 return;
5587 }
5588
5589 // Set success message and redirect
5590 set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
5591
5592 $redirect_url = add_query_arg(
5593 array(
5594 'page' => 'mxchat-actions'
5595 ),
5596 admin_url('admin.php')
5597 );
5598 wp_safe_redirect($redirect_url);
5599 exit;
5600 }
5601 public function mxchat_handle_add_intent() {
5602 if (!current_user_can('manage_options')) {
5603 wp_die(esc_html__('Unauthorized user', 'mxchat'));
5604 }
5605 check_admin_referer('mxchat_add_intent_nonce');
5606 global $wpdb;
5607 $table_name = $wpdb->prefix . 'mxchat_intents';
5608
5609 // Sanitize and get form data
5610 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5611 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5612 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5613
5614 // Get similarity threshold from form (convert percentage to decimal)
5615 $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5616
5617 // Handle enabled_bots
5618 $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5619 $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5620
5621 // Ensure default is always included for backward compatibility with existing actions
5622 if (!in_array('default', $enabled_bots)) {
5623 $enabled_bots[] = 'default';
5624 }
5625
5626 $enabled_bots_json = json_encode($enabled_bots);
5627
5628 // Validate required fields
5629 if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
5630 $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5631 return;
5632 }
5633
5634 // Validate callback function
5635 $available_callbacks = $this->mxchat_get_available_callbacks();
5636 if (!array_key_exists($callback_function, $available_callbacks)) {
5637 $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
5638 return;
5639 }
5640
5641 // Check if this is an add-on promotional placeholder (not a real action)
5642 if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
5643 $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
5644 $this->handle_embedding_error(sprintf(
5645 __('This action requires the %s to be installed and activated.', 'mxchat'),
5646 $addon_name
5647 ));
5648 return;
5649 }
5650
5651 // Process phrases
5652 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5653 if (empty($phrases_array)) {
5654 $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5655 return;
5656 }
5657
5658 // Generate embeddings with improved error handling
5659 $vectors = [];
5660 $failed_phrases = [];
5661 foreach ($phrases_array as $phrase) {
5662 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5663 if (is_array($embedding_vector)) {
5664 $vectors[] = $embedding_vector;
5665 } else {
5666 $failed_phrases[] = $phrase;
5667 }
5668 }
5669
5670 // Check for embedding failures
5671 if (!empty($failed_phrases)) {
5672 $this->handle_embedding_error(
5673 sprintf(
5674 __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5675 implode(', ', $failed_phrases)
5676 )
5677 );
5678 return;
5679 }
5680
5681 if (empty($vectors)) {
5682 $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5683 return;
5684 }
5685
5686 // Create combined vector and insert into database
5687 $combined_vector = $this->mxchat_average_vectors($vectors);
5688 $serialized_vector = maybe_serialize($combined_vector);
5689
5690 $result = $wpdb->insert($table_name, [
5691 'intent_label' => $intent_label,
5692 'phrases' => implode(', ', $phrases_array),
5693 'embedding_vector' => $serialized_vector,
5694 'callback_function' => $callback_function,
5695 'similarity_threshold' => $similarity_threshold,
5696 'enabled_bots' => $enabled_bots_json, // NEW field
5697 ]);
5698
5699 if ($result === false) {
5700 $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
5701 return;
5702 }
5703
5704 // Set success message and redirect
5705 set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
5706 wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5707 exit;
5708 }
5709
5710
5711
5712
5713 private function handle_embedding_error($message, $redirect = true) {
5714 // Store the error message in the existing transient
5715 set_transient('mxchat_admin_notice_error', $message, 60);
5716
5717 if ($redirect) {
5718 // Redirect back to the actions page
5719 $redirect_url = add_query_arg(
5720 array(
5721 'page' => 'mxchat-actions'
5722 ),
5723 admin_url('admin.php')
5724 );
5725 wp_safe_redirect($redirect_url);
5726 exit;
5727 }
5728 }
5729
5730 /**
5731 * AJAX handler to fetch actions list for the new split-panel UI
5732 */
5733 public function mxchat_fetch_actions_list() {
5734 check_ajax_referer('mxchat_actions_nonce', 'security');
5735
5736 if (!current_user_can('manage_options')) {
5737 wp_send_json_error(__('Unauthorized', 'mxchat'));
5738 }
5739
5740 global $wpdb;
5741 $table_name = $wpdb->prefix . 'mxchat_intents';
5742
5743 $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
5744 $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
5745 $offset = ($page - 1) * $per_page;
5746 $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
5747 $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
5748 $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
5749
5750 // Build WHERE clause
5751 $where = '1=1';
5752 $params = array();
5753
5754 if ($search) {
5755 $search_like = '%' . $wpdb->esc_like($search) . '%';
5756 $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
5757 $params[] = $search_like;
5758 $params[] = $search_like;
5759 }
5760
5761 if ($callback_filter) {
5762 $where .= ' AND callback_function = %s';
5763 $params[] = $callback_filter;
5764 }
5765
5766 // Get total count
5767 $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
5768 if (!empty($params)) {
5769 $count_query = $wpdb->prepare($count_query, $params);
5770 }
5771 $total_actions = $wpdb->get_var($count_query);
5772
5773 // Get actions
5774 $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
5775 $all_params = array_merge($params, array($per_page, $offset));
5776 $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
5777
5778 // Get available callbacks for labels/icons
5779 $available_callbacks = $this->mxchat_get_available_callbacks();
5780
5781 // Prefetch individual phrase counts for all fetched actions
5782 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5783 $phrase_counts = array();
5784 if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5785 $action_ids = wp_list_pluck($actions, 'id');
5786 if (!empty($action_ids)) {
5787 $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5788 $count_results = $wpdb->get_results($wpdb->prepare(
5789 "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
5790 $action_ids
5791 ));
5792 foreach ($count_results as $row) {
5793 $phrase_counts[$row->intent_id] = intval($row->cnt);
5794 }
5795 }
5796 }
5797
5798 // Format actions for response
5799 $formatted_actions = array();
5800 foreach ($actions as $action) {
5801 $callback_data = isset($available_callbacks[$action->callback_function])
5802 ? $available_callbacks[$action->callback_function]
5803 : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5804
5805 $enabled_bots = json_decode($action->enabled_bots, true);
5806 if (!is_array($enabled_bots)) {
5807 $enabled_bots = array('default');
5808 }
5809
5810 $formatted_actions[] = array(
5811 'id' => intval($action->id),
5812 'label' => $action->intent_label,
5813 'phrases' => $action->phrases,
5814 'callback_function' => $action->callback_function,
5815 'callback_label' => $callback_data['label'],
5816 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5817 'threshold' => round($action->similarity_threshold * 100),
5818 'enabled' => (bool) $action->enabled,
5819 'enabled_bots' => $enabled_bots,
5820 'has_legacy_vector' => !empty($action->embedding_vector),
5821 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5822 );
5823 }
5824
5825 $total_pages = ceil($total_actions / $per_page);
5826 $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5827 $showing_end = min($offset + $per_page, $total_actions);
5828
5829 wp_send_json_success(array(
5830 'actions' => $formatted_actions,
5831 'page' => $page,
5832 'per_page' => $per_page,
5833 'total_actions' => intval($total_actions),
5834 'total_pages' => $total_pages,
5835 'showing_start' => $showing_start,
5836 'showing_end' => $showing_end,
5837 ));
5838 }
5839
5840 /**
5841 * AJAX handler to toggle action enabled status
5842 */
5843 public function mxchat_toggle_action_status() {
5844 check_ajax_referer('mxchat_actions_nonce', 'security');
5845
5846 if (!current_user_can('manage_options')) {
5847 wp_send_json_error(__('Unauthorized', 'mxchat'));
5848 }
5849
5850 $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5851 $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
5852
5853 if (!$action_id) {
5854 wp_send_json_error(__('Invalid action ID', 'mxchat'));
5855 }
5856
5857 global $wpdb;
5858 $table_name = $wpdb->prefix . 'mxchat_intents';
5859
5860 $result = $wpdb->update(
5861 $table_name,
5862 array('enabled' => $enabled ? 1 : 0),
5863 array('id' => $action_id),
5864 array('%d'),
5865 array('%d')
5866 );
5867
5868 if ($result === false) {
5869 wp_send_json_error(__('Failed to update action status', 'mxchat'));
5870 }
5871
5872 wp_send_json_success(array('enabled' => (bool) $enabled));
5873 }
5874
5875 /**
5876 * AJAX handler to bulk delete actions
5877 */
5878 public function mxchat_bulk_delete_actions() {
5879 check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5880
5881 if (!current_user_can('manage_options')) {
5882 wp_send_json_error(__('Unauthorized', 'mxchat'));
5883 }
5884
5885 $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5886
5887 if (empty($action_ids)) {
5888 wp_send_json_error(__('No actions selected', 'mxchat'));
5889 }
5890
5891 global $wpdb;
5892 $table_name = $wpdb->prefix . 'mxchat_intents';
5893
5894 $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5895 $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5896 $result = $wpdb->query($query);
5897
5898 if ($result === false) {
5899 wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5900 }
5901
5902 // Also delete individual phrases for these intents
5903 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5904 if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5905 $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5906 }
5907
5908 wp_send_json_success(array('deleted' => $result));
5909 }
5910
5911 /**
5912 * AJAX handler to add a new intent/action
5913 */
5914 public function mxchat_add_intent_ajax() {
5915 check_ajax_referer('mxchat_add_intent_nonce', 'security');
5916
5917 if (!current_user_can('manage_options')) {
5918 wp_send_json_error(__('Unauthorized', 'mxchat'));
5919 }
5920
5921 global $wpdb;
5922 $table_name = $wpdb->prefix . 'mxchat_intents';
5923
5924 // Sanitize input
5925 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5926 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5927 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5928 $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5929 $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5930
5931 // Validate
5932 // Check if using new individual phrases mode or legacy mode
5933 $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5934 $use_individual = !empty($individual_phrases);
5935
5936 // Validate required fields (phrases not required when using individual mode)
5937 if (empty($intent_label) || empty($callback_function)) {
5938 wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5939 }
5940 if (!$use_individual && empty($phrases_input)) {
5941 wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5942 }
5943
5944 // Ensure default bot is included
5945 if (!in_array('default', $enabled_bots)) {
5946 $enabled_bots[] = 'default';
5947 }
5948 $enabled_bots_json = json_encode($enabled_bots);
5949
5950 if ($use_individual) {
5951 // New mode: individual phrases each get their own vector
5952 // Insert the intent row with empty legacy fields
5953 $result = $wpdb->insert(
5954 $table_name,
5955 array(
5956 'intent_label' => $intent_label,
5957 'phrases' => '',
5958 'embedding_vector' => '',
5959 'similarity_threshold' => $similarity_threshold,
5960 'callback_function' => $callback_function,
5961 'enabled' => 1,
5962 'enabled_bots' => $enabled_bots_json,
5963 )
5964 );
5965
5966 if ($result === false) {
5967 wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5968 }
5969
5970 $intent_id = $wpdb->insert_id;
5971
5972 // Insert each phrase individually with its own embedding
5973 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5974 $failed_phrases = array();
5975 foreach ($individual_phrases as $phrase) {
5976 $phrase = trim($phrase);
5977 if (empty($phrase)) continue;
5978
5979 $embedding_vector = $this->mxchat_generate_embedding($phrase);
5980 if (is_wp_error($embedding_vector)) {
5981 $failed_phrases[] = $phrase;
5982 continue;
5983 }
5984
5985 $wpdb->insert(
5986 $phrases_table,
5987 array(
5988 'intent_id' => $intent_id,
5989 'phrase' => $phrase,
5990 'embedding_vector' => maybe_serialize($embedding_vector),
5991 )
5992 );
5993 }
5994
5995 $response = array('id' => $intent_id);
5996 if (!empty($failed_phrases)) {
5997 $response['failed_phrases'] = $failed_phrases;
5998 }
5999 wp_send_json_success($response);
6000
6001 } else {
6002 // Legacy mode: combine all phrases into one embedding (backwards compatible)
6003 $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
6004 if (empty($phrases_array)) {
6005 wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
6006 }
6007
6008 // Generate embedding (combine phrases into single string for embedding)
6009 $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
6010 if (is_wp_error($embedding_vector)) {
6011 // Fallback: store without embedding
6012 $serialized_vector = null;
6013 } else {
6014 $serialized_vector = maybe_serialize($embedding_vector);
6015 }
6016
6017 // Insert
6018 $result = $wpdb->insert(
6019 $table_name,
6020 array(
6021 'intent_label' => $intent_label,
6022 'phrases' => implode(', ', $phrases_array),
6023 'embedding_vector' => $serialized_vector,
6024 'similarity_threshold' => $similarity_threshold,
6025 'callback_function' => $callback_function,
6026 'enabled' => 1,
6027 'enabled_bots' => $enabled_bots_json,
6028 )
6029 );
6030
6031 if ($result === false) {
6032 wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
6033 }
6034
6035 wp_send_json_success(array('id' => $wpdb->insert_id));
6036 }
6037 }
6038
6039 /**
6040 * AJAX handler to edit an existing intent/action
6041 */
6042 public function mxchat_edit_intent_ajax() {
6043 check_ajax_referer('mxchat_edit_intent', 'security');
6044
6045 if (!current_user_can('manage_options')) {
6046 wp_send_json_error(__('Unauthorized', 'mxchat'));
6047 }
6048
6049 global $wpdb;
6050 $table_name = $wpdb->prefix . 'mxchat_intents';
6051
6052 // Sanitize input
6053 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
6054 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
6055 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
6056 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
6057 $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
6058 $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
6059
6060 // Validate
6061 if (!$intent_id || empty($intent_label)) {
6062 wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
6063 }
6064
6065 // Check if phrases are managed individually (empty phrases_input means individual mode)
6066 $uses_individual_phrases = empty($phrases_input);
6067
6068 if ($uses_individual_phrases) {
6069 // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
6070 $update_data = array(
6071 'intent_label' => $intent_label,
6072 'similarity_threshold' => $similarity_threshold,
6073 'callback_function' => $callback_function,
6074 'enabled_bots' => json_encode($enabled_bots),
6075 );
6076 } else {
6077 // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
6078 $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
6079 if (empty($phrases_array)) {
6080 wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
6081 }
6082
6083 // Generate new embedding (combine phrases into single string for embedding)
6084 $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
6085 if (is_wp_error($embedding_vector)) {
6086 // Keep existing embedding
6087 $update_data = array(
6088 'intent_label' => $intent_label,
6089 'phrases' => implode(', ', $phrases_array),
6090 'similarity_threshold' => $similarity_threshold,
6091 'callback_function' => $callback_function,
6092 'enabled_bots' => json_encode($enabled_bots),
6093 );
6094 } else {
6095 $serialized_vector = maybe_serialize($embedding_vector);
6096 $update_data = array(
6097 'intent_label' => $intent_label,
6098 'phrases' => implode(', ', $phrases_array),
6099 'embedding_vector' => $serialized_vector,
6100 'similarity_threshold' => $similarity_threshold,
6101 'callback_function' => $callback_function,
6102 'enabled_bots' => json_encode($enabled_bots),
6103 );
6104 }
6105 }
6106
6107 // Ensure default bot is included
6108 if (!in_array('default', $enabled_bots)) {
6109 $enabled_bots[] = 'default';
6110 }
6111 $update_data['enabled_bots'] = json_encode($enabled_bots);
6112
6113 $result = $wpdb->update(
6114 $table_name,
6115 $update_data,
6116 array('id' => $intent_id),
6117 null,
6118 array('%d')
6119 );
6120
6121 if ($result === false) {
6122 wp_send_json_error(__('Failed to update action.', 'mxchat'));
6123 }
6124
6125 wp_send_json_success(array('updated' => true));
6126 }
6127
6128 /**
6129 * AJAX handler to delete a single intent/action
6130 */
6131 public function mxchat_delete_intent_ajax() {
6132 check_ajax_referer('mxchat_delete_intent_nonce', 'security');
6133
6134 if (!current_user_can('manage_options')) {
6135 wp_send_json_error(__('Unauthorized', 'mxchat'));
6136 }
6137
6138 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
6139
6140 if (!$intent_id) {
6141 wp_send_json_error(__('Invalid action ID', 'mxchat'));
6142 }
6143
6144 global $wpdb;
6145 $table_name = $wpdb->prefix . 'mxchat_intents';
6146
6147 $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
6148
6149 if ($result === false) {
6150 wp_send_json_error(__('Failed to delete action', 'mxchat'));
6151 }
6152
6153 // Also delete individual phrases for this intent
6154 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
6155 if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
6156 $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
6157 }
6158
6159 wp_send_json_success(array('deleted' => true));
6160 }
6161
6162 /**
6163 * AJAX handler to add a single phrase with its own embedding to an intent
6164 */
6165 public function mxchat_add_phrase_ajax() {
6166 check_ajax_referer('mxchat_add_phrase_nonce', 'security');
6167
6168 if (!current_user_can('manage_options')) {
6169 wp_send_json_error(__('Unauthorized', 'mxchat'));
6170 }
6171
6172 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
6173 $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
6174
6175 if (!$intent_id || empty($phrase)) {
6176 wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
6177 }
6178
6179 // Verify the intent exists
6180 global $wpdb;
6181 $intents_table = $wpdb->prefix . 'mxchat_intents';
6182 $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
6183 if (!$intent) {
6184 wp_send_json_error(__('Action not found.', 'mxchat'));
6185 }
6186
6187 // Generate embedding for this single phrase
6188 $embedding_vector = $this->mxchat_generate_embedding($phrase);
6189 if (is_wp_error($embedding_vector)) {
6190 wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
6191 }
6192
6193 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
6194 $result = $wpdb->insert(
6195 $phrases_table,
6196 array(
6197 'intent_id' => $intent_id,
6198 'phrase' => $phrase,
6199 'embedding_vector' => maybe_serialize($embedding_vector),
6200 )
6201 );
6202
6203 if ($result === false) {
6204 wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
6205 }
6206
6207 wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
6208 }
6209
6210 /**
6211 * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
6212 */
6213 public function mxchat_delete_phrase_ajax() {
6214 check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
6215
6216 if (!current_user_can('manage_options')) {
6217 wp_send_json_error(__('Unauthorized', 'mxchat'));
6218 }
6219
6220 $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
6221 if (!$phrase_id) {
6222 wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
6223 }
6224
6225 global $wpdb;
6226 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
6227 $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
6228
6229 if ($result === false) {
6230 wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
6231 }
6232
6233 wp_send_json_success(array('deleted' => true));
6234 }
6235
6236 /**
6237 * AJAX handler to fetch individual phrases for an intent
6238 */
6239 public function mxchat_get_phrases_ajax() {
6240 check_ajax_referer('mxchat_get_phrases_nonce', 'security');
6241
6242 if (!current_user_can('manage_options')) {
6243 wp_send_json_error(__('Unauthorized', 'mxchat'));
6244 }
6245
6246 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
6247 if (!$intent_id) {
6248 wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
6249 }
6250
6251 global $wpdb;
6252 $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
6253
6254 $phrases = array();
6255 if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
6256 $phrases = $wpdb->get_results($wpdb->prepare(
6257 "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
6258 $intent_id
6259 ));
6260 }
6261
6262 wp_send_json_success(array('phrases' => $phrases));
6263 }
6264
6265 /**
6266 * AJAX handler to clear legacy phrases and embedding from the main intents table
6267 */
6268 public function mxchat_delete_legacy_phrases_ajax() {
6269 check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
6270
6271 if (!current_user_can('manage_options')) {
6272 wp_send_json_error(__('Unauthorized', 'mxchat'));
6273 }
6274
6275 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
6276 if (!$intent_id) {
6277 wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
6278 }
6279
6280 global $wpdb;
6281 $table_name = $wpdb->prefix . 'mxchat_intents';
6282
6283 $result = $wpdb->update(
6284 $table_name,
6285 array('phrases' => '', 'embedding_vector' => ''),
6286 array('id' => $intent_id),
6287 array('%s', '%s'),
6288 array('%d')
6289 );
6290
6291 if ($result === false) {
6292 wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
6293 }
6294
6295 wp_send_json_success(array('cleared' => true));
6296 }
6297
6298 /**
6299 * Enhanced get_available_callbacks function with form action exclusion
6300 *
6301 * @param bool $grouped Whether to return callbacks grouped by category
6302 * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
6303 * @return array Callbacks data with icons, descriptions and availability status
6304 */
6305 private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
6306 // Load WordPress plugin functions if needed
6307 if (!function_exists('get_plugins')) {
6308 require_once ABSPATH . 'wp-admin/includes/plugin.php';
6309 }
6310
6311 // Get active plugins
6312 $active_plugins = get_option('active_plugins', array());
6313
6314 // Functions to exclude from the action selector only if Pro is activated
6315 // If user doesn't have Pro, show these so they can see what they're missing
6316 $excluded_when_pro_active_functions = array(
6317 'mxchat_handle_form_collection' // Forms add-on action
6318 );
6319
6320 // Always excluded functions (regardless of Pro status)
6321 $always_excluded_functions = array();
6322
6323 // Combine exclusion lists based on Pro activation status
6324 $excluded_functions = $always_excluded_functions;
6325 if ($this->is_activated) {
6326 // Only exclude add-on managed functions if Pro is active
6327 $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
6328 }
6329
6330 // Define add-on plugin files and their corresponding action functions
6331 $addon_plugins = array(
6332 'mxchat-woo/mxchat-woo.php' => array(
6333 'functions' => array(
6334 'mxchat_handle_product_recommendations',
6335 'mxchat_handle_order_history',
6336 'mxchat_show_product_card',
6337 'mxchat_add_to_cart',
6338 'mxchat_checkout_redirect',
6339 'mxchat_handle_featured_products'
6340 ),
6341 'name' => __('WooCommerce Add-on', 'mxchat'),
6342 'pro_required' => true
6343 ),
6344 'mxchat-perplexity/mxchat-perplexity.php' => array(
6345 'functions' => array('mxchat_perplexity_research'),
6346 'name' => __('Perplexity Add-on', 'mxchat'),
6347 'pro_required' => true
6348 ),
6349 'mxchat-forms/mxchat-forms.php' => array(
6350 'functions' => array('mxchat_handle_form_collection'),
6351 'name' => __('Forms Add-on', 'mxchat'),
6352 'pro_required' => true
6353 ),
6354 // Add other add-ons and their functions here
6355 );
6356
6357 // Get the functions that are provided by active add-ons
6358 $addon_provided_functions = array();
6359 $addon_function_mapping = array(); // Maps functions to their add-on info
6360
6361 // Check which add-ons are active
6362 foreach ($addon_plugins as $plugin_file => $addon_info) {
6363 $is_active = in_array($plugin_file, $active_plugins);
6364
6365 // For each function in this addon
6366 foreach ($addon_info['functions'] as $function) {
6367 // Consider a function installed only if:
6368 // 1. The add-on is active AND
6369 // 2. Either it doesn't require Pro OR Pro is activated
6370 $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
6371
6372 // If the add-on is installed, mark this function as provided by an add-on
6373 if ($is_installed) {
6374 $addon_provided_functions[] = $function;
6375 }
6376
6377 // Store addon info for this function regardless of installation status
6378 $addon_function_mapping[$function] = array(
6379 'addon' => basename(dirname($plugin_file)),
6380 'addon_name' => $addon_info['name'],
6381 'pro_required' => $addon_info['pro_required'],
6382 'is_active' => $is_active,
6383 'is_installed' => $is_installed
6384 );
6385 }
6386 }
6387
6388 // Core callbacks - always available in the base plugin
6389 $core_callbacks = array(
6390 'mxchat_handle_email_capture' => array(
6391 'label' => __('Loops Email Capture', 'mxchat'),
6392 'pro_only' => false,
6393 'group' => __('Customer Engagement', 'mxchat'),
6394 'icon' => 'email-alt',
6395 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
6396 'addon' => false, // Not from an add-on
6397 'installed' => true // Always installed with base plugin
6398 ),
6399 'mxchat_handle_search_request' => array(
6400 'label' => __('Brave Web Search', 'mxchat'),
6401 'pro_only' => false,
6402 'group' => __('Search Features', 'mxchat'),
6403 'icon' => 'search',
6404 'description' => __('Let users search the web directly from the chat (requires a Brave Search API key)', 'mxchat'),
6405 'addon' => false,
6406 'installed' => true
6407 ),
6408 'mxchat_handle_image_search_request' => array(
6409 'label' => __('Brave Image Search', 'mxchat'),
6410 'pro_only' => false,
6411 'group' => __('Search Features', 'mxchat'),
6412 'icon' => 'format-image',
6413 'description' => __('Search and display images in the chat conversation (requires a Brave Search API key)', 'mxchat'),
6414 'addon' => false,
6415 'installed' => true
6416 ),
6417 // Pro core features - check is_activated property
6418 'mxchat_generate_image' => array(
6419 'label' => __('Generate Image (OpenAI)', 'mxchat'),
6420 'pro_only' => false,
6421 'group' => __('Other Features', 'mxchat'),
6422 'icon' => 'art',
6423 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
6424 'addon' => false,
6425 'installed' => true
6426 ),
6427 'mxchat_generate_gemini_image' => array(
6428 'label' => __('Generate Image (Gemini)', 'mxchat'),
6429 'pro_only' => false,
6430 'group' => __('Other Features', 'mxchat'),
6431 'icon' => 'art',
6432 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
6433 'addon' => false,
6434 'installed' => true
6435 ),
6436 'mxchat_handle_pdf_discussion' => array(
6437 'label' => __('Chat with PDF', 'mxchat'),
6438 'pro_only' => false,
6439 'group' => __('Other Features', 'mxchat'),
6440 'icon' => 'media-document',
6441 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
6442 'addon' => false,
6443 'installed' => true
6444 ),
6445 'mxchat_live_agent_handover' => array(
6446 'label' => __('Slack Live Agent', 'mxchat'),
6447 'pro_only' => false,
6448 'group' => __('Customer Engagement', 'mxchat'),
6449 'icon' => 'admin-users',
6450 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
6451 'addon' => false,
6452 'installed' => true
6453 ),
6454 'mxchat_telegram_live_agent_handover' => array(
6455 'label' => __('Telegram Live Agent', 'mxchat'),
6456 'pro_only' => false,
6457 'group' => __('Customer Engagement', 'mxchat'),
6458 'icon' => 'format-chat',
6459 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
6460 'addon' => false,
6461 'installed' => true
6462 ),
6463 'mxchat_webhook_live_agent_handover' => array(
6464 'label' => __('Webhook Live Agent', 'mxchat'),
6465 'pro_only' => false,
6466 'group' => __('Customer Engagement', 'mxchat'),
6467 'icon' => 'external',
6468 'description' => __('Send the conversation to your own webhook URL so your team can follow up', 'mxchat'),
6469 'addon' => false,
6470 'installed' => true
6471 ),
6472 'mxchat_handle_switch_to_chatbot_intent' => array(
6473 'label' => __('Back to Chatbot', 'mxchat'),
6474 'pro_only' => false,
6475 'group' => __('Customer Engagement', 'mxchat'),
6476 'icon' => 'backup',
6477 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
6478 'addon' => false,
6479 'installed' => true
6480 ),
6481 );
6482
6483 // Add-on callbacks with placeholders - only include if the add-on is NOT active
6484 // These are promotional/informational only — not selectable as real actions
6485 $addon_callbacks = array(
6486 // WooCommerce Add-on
6487 'mxchat_handle_product_recommendations' => array(
6488 'label' => __('Product Recommendations', 'mxchat'),
6489 'pro_only' => false,
6490 'addon_promo' => true,
6491 'group' => __('WooCommerce Features', 'mxchat'),
6492 'icon' => 'cart',
6493 'description' => __('Suggest products based on customer preferences', 'mxchat'),
6494 ),
6495 'mxchat_handle_order_history' => array(
6496 'label' => __('Order History', 'mxchat'),
6497 'pro_only' => false,
6498 'addon_promo' => true,
6499 'group' => __('WooCommerce Features', 'mxchat'),
6500 'icon' => 'clipboard',
6501 'description' => __('Allow customers to check their order status', 'mxchat'),
6502 ),
6503 'mxchat_show_product_card' => array(
6504 'label' => __('Show Product Card', 'mxchat'),
6505 'pro_only' => false,
6506 'addon_promo' => true,
6507 'group' => __('WooCommerce Features', 'mxchat'),
6508 'icon' => 'products',
6509 'description' => __('Display product information in the chat', 'mxchat'),
6510 ),
6511 'mxchat_add_to_cart' => array(
6512 'label' => __('Add to Cart', 'mxchat'),
6513 'pro_only' => false,
6514 'addon_promo' => true,
6515 'group' => __('WooCommerce Features', 'mxchat'),
6516 'icon' => 'plus-alt',
6517 'description' => __('Add products to cart directly from chat', 'mxchat'),
6518 ),
6519 'mxchat_checkout_redirect' => array(
6520 'label' => __('Proceed to Checkout', 'mxchat'),
6521 'pro_only' => false,
6522 'addon_promo' => true,
6523 'group' => __('WooCommerce Features', 'mxchat'),
6524 'icon' => 'arrow-right-alt',
6525 'description' => __('Redirect customer to checkout page', 'mxchat'),
6526 ),
6527 'mxchat_handle_featured_products' => array(
6528 'label' => __('Featured Products Showcase', 'mxchat'),
6529 'pro_only' => false,
6530 'addon_promo' => true,
6531 'group' => __('WooCommerce Features', 'mxchat'),
6532 'icon' => 'star-filled',
6533 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
6534 ),
6535
6536 // Perplexity Add-on
6537 'mxchat_perplexity_research' => array(
6538 'label' => __('Perplexity Research', 'mxchat'),
6539 'pro_only' => false,
6540 'addon_promo' => true,
6541 'group' => __('Search Features', 'mxchat'),
6542 'icon' => 'book-alt',
6543 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
6544 ),
6545
6546 // Forms Add-on
6547 'mxchat_handle_form_collection' => array(
6548 'label' => __('Form Collection', 'mxchat'),
6549 'pro_only' => false,
6550 'addon_promo' => true,
6551 'group' => __('Form Features', 'mxchat'),
6552 'icon' => 'feedback',
6553 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
6554 ),
6555 );
6556
6557 // Enhance add-on callbacks with installation status and addon info
6558 foreach ($addon_callbacks as $function => $data) {
6559 if (isset($addon_function_mapping[$function])) {
6560 $addon_info = $addon_function_mapping[$function];
6561
6562 $addon_callbacks[$function]['addon'] = $addon_info['addon'];
6563 $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6564 $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
6565
6566 // Set pro_only based on add-on configuration
6567 $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6568 } else {
6569 $addon_callbacks[$function]['addon'] = 'unknown';
6570 $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
6571 $addon_callbacks[$function]['installed'] = false;
6572 }
6573 }
6574
6575 // Initialize callbacks with core features
6576 $callbacks = $core_callbacks;
6577
6578 // Get callbacks from active add-ons
6579 $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
6580
6581 // Add placeholder callbacks only for add-ons that aren't active
6582 if ($include_all) {
6583 foreach ($addon_callbacks as $function => $data) {
6584 // Skip placeholders for functions provided by active add-ons
6585 if (in_array($function, $addon_provided_functions)) {
6586 continue;
6587 }
6588
6589 // Skip excluded functions
6590 if (in_array($function, $excluded_functions)) {
6591 continue;
6592 }
6593
6594 // Add the placeholder
6595 $callbacks[$function] = $data;
6596 }
6597 }
6598
6599 // Add callbacks from active add-ons (will override placeholders)
6600 foreach ($active_addon_callbacks as $function => $data) {
6601 // Skip excluded functions
6602 if (in_array($function, $excluded_functions)) {
6603 continue;
6604 }
6605
6606 // Always include callbacks from add-ons
6607 $callbacks[$function] = $data;
6608
6609 // Ensure they have the proper add-on info
6610 if (isset($addon_function_mapping[$function])) {
6611 $addon_info = $addon_function_mapping[$function];
6612 $callbacks[$function]['addon'] = $addon_info['addon'];
6613 $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6614 $callbacks[$function]['installed'] = $addon_info['is_installed'];
6615 $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6616 }
6617 }
6618
6619 // Just before returning callbacks, sort them to prioritize free features
6620 if (!$grouped) {
6621 // Create temporary arrays for sorting
6622 $free_callbacks = array();
6623 $pro_callbacks = array();
6624
6625 // Split callbacks into free and pro
6626 foreach ($callbacks as $key => $data) {
6627 if (isset($data['pro_only']) && $data['pro_only']) {
6628 $pro_callbacks[$key] = $data;
6629 } else {
6630 $free_callbacks[$key] = $data;
6631 }
6632 }
6633
6634 // Merge with free callbacks first
6635 $callbacks = array_merge($free_callbacks, $pro_callbacks);
6636 }
6637
6638 // Return grouped structure if requested
6639 if ($grouped) {
6640 $grouped_callbacks = array();
6641 foreach ($callbacks as $key => $data) {
6642 $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
6643
6644 // Ensure we carry forward all the new fields in grouped mode
6645 $callback_data = array(
6646 'label' => $data['label'],
6647 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
6648 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
6649 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
6650 'addon' => isset($data['addon']) ? $data['addon'] : false,
6651 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
6652 'installed' => isset($data['installed']) ? $data['installed'] : true
6653 );
6654
6655 $grouped_callbacks[$group_label][$key] = $callback_data;
6656 }
6657
6658 // Sort within each group to prioritize free features
6659 foreach ($grouped_callbacks as $group => $items) {
6660 $free_items = array();
6661 $pro_items = array();
6662
6663 foreach ($items as $key => $data) {
6664 if (isset($data['pro_only']) && $data['pro_only']) {
6665 $pro_items[$key] = $data;
6666 } else {
6667 $free_items[$key] = $data;
6668 }
6669 }
6670
6671 $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
6672 }
6673
6674 return $grouped_callbacks;
6675 }
6676
6677 return $callbacks;
6678 }
6679
6680 public function mxchat_page_init() {
6681 register_setting(
6682 'mxchat_option_group',
6683 'mxchat_options',
6684 array($this, 'mxchat_sanitize')
6685 );
6686
6687 register_setting(
6688 'mxchat_option_group',
6689 'mxchat_similarity_threshold',
6690 array(
6691 'type' => 'number',
6692 'sanitize_callback' => function($value) {
6693 $value = absint($value);
6694 return min(max($value, 20), 95);
6695 },
6696 'default' => 80,
6697 )
6698 );
6699
6700 // Chatbot Settings Section
6701 add_settings_section(
6702 'mxchat_chatbot_section',
6703 esc_html__('Chatbot Settings', 'mxchat'),
6704 null,
6705 'mxchat-chatbot'
6706 );
6707
6708 // API Keys Settings Section
6709 add_settings_section(
6710 'mxchat_api_keys_section',
6711 esc_html__('API Keys', 'mxchat'),
6712 array($this, 'mxchat_api_keys_section_callback'),
6713 'mxchat-api-keys'
6714 );
6715
6716 // OpenAI API Key
6717 add_settings_field(
6718 'api_key',
6719 esc_html__('OpenAI API Key', 'mxchat'),
6720 array($this, 'api_key_callback'),
6721 'mxchat-api-keys',
6722 'mxchat_api_keys_section'
6723 );
6724
6725 // X.AI API Key
6726 add_settings_field(
6727 'xai_api_key',
6728 esc_html__('X.AI API Key', 'mxchat'),
6729 array($this, 'xai_api_key_callback'),
6730 'mxchat-api-keys',
6731 'mxchat_api_keys_section'
6732 );
6733
6734 // Claude API Key
6735 add_settings_field(
6736 'claude_api_key',
6737 esc_html__('Claude API Key', 'mxchat'),
6738 array($this, 'claude_api_key_callback'),
6739 'mxchat-api-keys',
6740 'mxchat_api_keys_section'
6741 );
6742
6743 // DeepSeek API Key
6744 add_settings_field(
6745 'deepseek_api_key',
6746 esc_html__('DeepSeek API Key', 'mxchat'),
6747 array($this, 'deepseek_api_key_callback'),
6748 'mxchat-api-keys',
6749 'mxchat_api_keys_section'
6750 );
6751
6752 // Google Gemini API Key
6753 add_settings_field(
6754 'gemini_api_key',
6755 esc_html__('Google Gemini API Key', 'mxchat'),
6756 array($this, 'gemini_api_key_callback'),
6757 'mxchat-api-keys',
6758 'mxchat_api_keys_section'
6759 );
6760
6761 // Voyage AI API Key
6762 add_settings_field(
6763 'voyage_api_key',
6764 esc_html__('Voyage AI API Key', 'mxchat'),
6765 array($this, 'voyage_api_key_callback'),
6766 'mxchat-api-keys',
6767 'mxchat_api_keys_section'
6768 );
6769
6770 // OpenRouter API Key
6771 add_settings_field(
6772 'openrouter_api_key',
6773 esc_html__('OpenRouter API Key', 'mxchat'),
6774 array($this, 'openrouter_api_key_callback'),
6775 'mxchat-api-keys',
6776 'mxchat_api_keys_section'
6777 );
6778
6779 // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6780 add_settings_field(
6781 'custom_provider',
6782 esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
6783 array($this, 'custom_provider_callback'),
6784 'mxchat-api-keys',
6785 'mxchat_api_keys_section'
6786 );
6787
6788 // Loops API Key
6789 add_settings_field(
6790 'loops_api_key',
6791 esc_html__('Loops API Key', 'mxchat'),
6792 array($this, 'mxchat_loops_api_key_callback'),
6793 'mxchat-api-keys',
6794 'mxchat_api_keys_section'
6795 );
6796
6797 // Brave Search API Key
6798 add_settings_field(
6799 'brave_api_key',
6800 __('Brave API Key', 'mxchat'),
6801 array($this, 'mxchat_brave_api_key_callback'),
6802 'mxchat-api-keys',
6803 'mxchat_api_keys_section'
6804 );
6805
6806 // Similarity Threshold Slider
6807 add_settings_field(
6808 'similarity_threshold', // Field ID
6809 esc_html__('Similarity Threshold', 'mxchat'), // Field title
6810 array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6811 'mxchat-chatbot', // Page
6812 'mxchat_chatbot_section' // Section
6813 );
6814
6815 // RAG Sources Limit Slider
6816 add_settings_field(
6817 'rag_sources_limit', // Field ID
6818 esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6819 array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6820 'mxchat-chatbot', // Page
6821 'mxchat_chatbot_section' // Section
6822 );
6823
6824 // RAG Chunks Limit Slider
6825 add_settings_field(
6826 'rag_chunks_limit', // Field ID
6827 esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6828 array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6829 'mxchat-chatbot', // Page
6830 'mxchat_chatbot_section' // Section
6831 );
6832
6833 add_settings_field(
6834 'append_to_body',
6835 esc_html__('Auto-Display Chatbot', 'mxchat'),
6836 array($this, 'mxchat_append_to_body_callback'),
6837 'mxchat-chatbot',
6838 'mxchat_chatbot_section'
6839 );
6840
6841 add_settings_field(
6842 'contextual_awareness_toggle',
6843 esc_html__('Contextual Awareness', 'mxchat'),
6844 array($this, 'mxchat_contextual_awareness_callback'),
6845 'mxchat-chatbot',
6846 'mxchat_chatbot_section'
6847 );
6848
6849 add_settings_field(
6850 'citation_links_toggle',
6851 esc_html__('Citation Links', 'mxchat'),
6852 array($this, 'mxchat_citation_links_toggle_callback'),
6853 'mxchat-chatbot',
6854 'mxchat_chatbot_section'
6855 );
6856
6857 // Strip unapproved links (plan 58f8b4) — the enforcement half of the old
6858 // Citation Links conflation, now its own control.
6859 add_settings_field(
6860 'strip_unapproved_links_toggle',
6861 esc_html__('Strip Unapproved Links', 'mxchat'),
6862 array($this, 'mxchat_strip_unapproved_links_toggle_callback'),
6863 'mxchat-chatbot',
6864 'mxchat_chatbot_section'
6865 );
6866
6867 // Satisfaction rating toggle (plan-a5b006).
6868 add_settings_field(
6869 'satisfaction_rating_enabled',
6870 esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6871 array($this, 'mxchat_satisfaction_rating_toggle_callback'),
6872 'mxchat-chatbot',
6873 'mxchat_chatbot_section'
6874 );
6875
6876 // Satisfaction rating customization (plan-141a12, plan-29caac):
6877 // the 5 customization fields are now inline-rendered inside
6878 // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6879
6880 add_settings_field(
6881 'enable_streaming_toggle',
6882 esc_html__('Enable Streaming', 'mxchat'),
6883 array($this, 'enable_streaming_toggle_callback'),
6884 'mxchat-chatbot',
6885 'mxchat_chatbot_section', // Same section as your working toggle
6886 array(
6887 'class' => 'mxchat-setting-row streaming-setting',
6888 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6889 )
6890 );
6891
6892
6893 add_settings_field(
6894 'model',
6895 esc_html__('Chat Model', 'mxchat'),
6896 array($this, 'mxchat_model_callback'),
6897 'mxchat-chatbot',
6898 'mxchat_chatbot_section'
6899 );
6900
6901 add_settings_field(
6902 'embedding_model',
6903 esc_html__('Embedding Model', 'mxchat'),
6904 array($this, 'embedding_model_callback'),
6905 'mxchat-chatbot',
6906 'mxchat_chatbot_section'
6907 );
6908
6909 add_settings_field(
6910 'system_prompt_instructions',
6911 esc_html__('AI Instructions (Behavior)', 'mxchat'),
6912 array($this, 'system_prompt_instructions_callback'),
6913 'mxchat-chatbot',
6914 'mxchat_chatbot_section'
6915 );
6916
6917
6918 add_settings_field(
6919 'top_bar_title',
6920 esc_html__('Top Bar Title', 'mxchat'),
6921 array($this, 'mxchat_top_bar_title_callback'),
6922 'mxchat-chatbot',
6923 'mxchat_chatbot_section'
6924 );
6925
6926 add_settings_field(
6927 'ai_agent_text',
6928 esc_html__('AI Agent Text', 'mxchat'),
6929 array($this, 'mxchat_ai_agent_text_callback'),
6930 'mxchat-chatbot',
6931 'mxchat_chatbot_section'
6932 );
6933
6934 add_settings_field(
6935 'enable_email_block',
6936 esc_html__('Require Email To Chat', 'mxchat'),
6937 array($this, 'enable_email_block_callback'),
6938 'mxchat-chatbot',
6939 'mxchat_chatbot_section'
6940 );
6941
6942 add_settings_field(
6943 'email_blocker_header_content',
6944 esc_html__('Require Email Chat Content', 'mxchat'),
6945 array($this, 'email_blocker_header_content_callback'),
6946 'mxchat-chatbot',
6947 'mxchat_chatbot_section'
6948 );
6949
6950 add_settings_field(
6951 'email_blocker_button_text',
6952 esc_html__('Require Email Chat Button Text', 'mxchat'),
6953 [$this, 'email_blocker_button_text_callback'],
6954 'mxchat-chatbot',
6955 'mxchat_chatbot_section'
6956 );
6957
6958 add_settings_field(
6959 'enable_name_field',
6960 esc_html__('Require Name Field', 'mxchat'),
6961 array($this, 'enable_name_field_callback'),
6962 'mxchat-chatbot',
6963 'mxchat_chatbot_section'
6964 );
6965
6966 add_settings_field(
6967 'name_field_placeholder',
6968 esc_html__('Name Field Placeholder', 'mxchat'),
6969 array($this, 'name_field_placeholder_callback'),
6970 'mxchat-chatbot',
6971 'mxchat_chatbot_section'
6972 );
6973
6974 add_settings_field(
6975 'intro_message',
6976 esc_html__('Introductory Message', 'mxchat'),
6977 array($this, 'mxchat_intro_message_callback'),
6978 'mxchat-chatbot',
6979 'mxchat_chatbot_section'
6980 );
6981
6982 add_settings_field(
6983 'input_copy',
6984 esc_html__('Input Copy', 'mxchat'),
6985 array($this, 'mxchat_input_copy_callback'),
6986 'mxchat-chatbot',
6987 'mxchat_chatbot_section'
6988 );
6989
6990 add_settings_field(
6991 'pre_chat_message',
6992 esc_html__('Chat Teaser Pop-up', 'mxchat'),
6993 array($this, 'mxchat_pre_chat_message_callback'),
6994 'mxchat-chatbot',
6995 'mxchat_chatbot_section'
6996 );
6997
6998 add_settings_field(
6999 'privacy_toggle',
7000 esc_html__('Toggle Privacy Notice', 'mxchat'),
7001 array($this, 'mxchat_privacy_toggle_callback'),
7002 'mxchat-chatbot',
7003 'mxchat_chatbot_section'
7004 );
7005
7006 add_settings_field(
7007 'complianz_toggle',
7008 esc_html__('Enable Complianz', 'mxchat'),
7009 array($this, 'mxchat_complianz_toggle_callback'),
7010 'mxchat-chatbot',
7011 'mxchat_chatbot_section'
7012 );
7013
7014 add_settings_field(
7015 'link_target_toggle',
7016 esc_html__('Open Links in a New Tab', 'mxchat'),
7017 array($this, 'mxchat_link_target_toggle_callback'),
7018 'mxchat-chatbot',
7019 'mxchat_chatbot_section'
7020 );
7021
7022 add_settings_field(
7023 'chat_persistence_toggle',
7024 esc_html__('Enable Chat Persistence', 'mxchat'),
7025 array($this, 'mxchat_chat_persistence_toggle_callback'),
7026 'mxchat-chatbot',
7027 'mxchat_chatbot_section'
7028 );
7029
7030 add_settings_field(
7031 'print_button_enabled',
7032 esc_html__('Show Download Transcript Button', 'mxchat'),
7033 array($this, 'mxchat_print_button_toggle_callback'),
7034 'mxchat-chatbot',
7035 'mxchat_chatbot_section'
7036 );
7037
7038 add_settings_field(
7039 'reset_chat_enabled',
7040 esc_html__('Show Start-New-Chat Button', 'mxchat'),
7041 array($this, 'mxchat_reset_chat_toggle_callback'),
7042 'mxchat-chatbot',
7043 'mxchat_chatbot_section'
7044 );
7045
7046 add_settings_field(
7047 'reset_chat_label',
7048 esc_html__('Start-New-Chat Button Label', 'mxchat'),
7049 array($this, 'mxchat_reset_chat_label_callback'),
7050 'mxchat-chatbot',
7051 'mxchat_chatbot_section'
7052 );
7053
7054 add_settings_field(
7055 'popular_question_1',
7056 esc_html__('Quick Question 1', 'mxchat'),
7057 array($this, 'mxchat_popular_question_1_callback'),
7058 'mxchat-chatbot',
7059 'mxchat_chatbot_section'
7060 );
7061
7062 add_settings_field(
7063 'popular_question_2',
7064 esc_html__('Quick Question 2', 'mxchat'),
7065 array($this, 'mxchat_popular_question_2_callback'),
7066 'mxchat-chatbot',
7067 'mxchat_chatbot_section'
7068 );
7069
7070 add_settings_field(
7071 'popular_question_3',
7072 esc_html__('Quick Question 3', 'mxchat'),
7073 array($this, 'mxchat_popular_question_3_callback'),
7074 'mxchat-chatbot',
7075 'mxchat_chatbot_section'
7076 );
7077
7078 add_settings_field(
7079 'additional_popular_questions',
7080 esc_html__('Additional Quick Questions', 'mxchat'),
7081 array($this, 'mxchat_additional_popular_questions_callback'),
7082 'mxchat-chatbot',
7083 'mxchat_chatbot_section'
7084 );
7085
7086
7087 add_settings_field(
7088 'rate_limits',
7089 __('Rate Limits Settings', 'mxchat'),
7090 array($this, 'mxchat_rate_limits_callback'),
7091 'mxchat-chatbot',
7092 'mxchat_chatbot_section'
7093 );
7094
7095 // Loops Settings Section
7096 add_settings_section(
7097 'mxchat_loops_section',
7098 esc_html__('Loops Settings', 'mxchat'),
7099 null,
7100 'mxchat-embed'
7101 );
7102
7103 // Loops Settings Fields (API Key moved to API Keys tab)
7104 add_settings_field(
7105 'loops_mailing_list',
7106 esc_html__('Loops Mailing List', 'mxchat'),
7107 array($this, 'mxchat_loops_mailing_list_callback'),
7108 'mxchat-embed',
7109 'mxchat_loops_section'
7110 );
7111
7112 add_settings_field(
7113 'triggered_phrase_response',
7114 esc_html__('Triggered Phrase Response', 'mxchat'),
7115 array($this, 'mxchat_triggered_phrase_response_callback'),
7116 'mxchat-embed',
7117 'mxchat_loops_section'
7118 );
7119
7120 add_settings_field(
7121 'email_capture_response',
7122 esc_html__('Email Capture Response', 'mxchat'),
7123 array($this, 'mxchat_email_capture_response_callback'),
7124 'mxchat-embed',
7125 'mxchat_loops_section'
7126 );
7127
7128 // Brave Search Settings Fields
7129 add_settings_section(
7130 'mxchat_brave_section',
7131 __('Brave Search Settings', 'mxchat'),
7132 array($this, 'mxchat_brave_section_callback'),
7133 'mxchat-embed'
7134 );
7135
7136 // Brave API Key moved to API Keys tab
7137 add_settings_field(
7138 'brave_image_count',
7139 __('Number of Images to Return', 'mxchat'),
7140 array($this, 'mxchat_brave_image_count_callback'),
7141 'mxchat-embed',
7142 'mxchat_brave_section'
7143 );
7144
7145 add_settings_field(
7146 'brave_safe_search',
7147 __('Safe Search', 'mxchat'),
7148 array($this, 'mxchat_brave_safe_search_callback'),
7149 'mxchat-embed',
7150 'mxchat_brave_section'
7151 );
7152
7153 add_settings_field(
7154 'brave_news_count',
7155 __('Number of News Articles', 'mxchat'),
7156 array($this, 'mxchat_brave_news_count_callback'),
7157 'mxchat-embed',
7158 'mxchat_brave_section'
7159 );
7160
7161 add_settings_field(
7162 'brave_country',
7163 __('Country', 'mxchat'),
7164 array($this, 'mxchat_brave_country_callback'),
7165 'mxchat-embed',
7166 'mxchat_brave_section'
7167 );
7168
7169 add_settings_field(
7170 'brave_language',
7171 __('Language', 'mxchat'),
7172 array($this, 'mxchat_brave_language_callback'),
7173 'mxchat-embed',
7174 'mxchat_brave_section'
7175 );
7176
7177 // Chat with PDF Intent Settings Fields
7178 add_settings_section(
7179 'mxchat_pdf_intent_section',
7180 __('Toolbar Settings & Intents', 'mxchat'),
7181 array($this, 'mxchat_pdf_intent_section_callback'),
7182 'mxchat-embed'
7183 );
7184
7185 add_settings_field(
7186 'chat_toolbar_toggle',
7187 __('Show Chat Toolbar', 'mxchat'),
7188 array($this, 'mxchat_chat_toolbar_toggle_callback'),
7189 'mxchat-embed',
7190 'mxchat_pdf_intent_section'
7191 );
7192
7193 // PDF Upload Button Toggle
7194 add_settings_field(
7195 'show_pdf_upload_button',
7196 __('Show PDF Upload Button', 'mxchat'),
7197 array($this, 'mxchat_show_pdf_upload_button_callback'),
7198 'mxchat-embed',
7199 'mxchat_pdf_intent_section'
7200 );
7201
7202 // Word Upload Button Toggle
7203 add_settings_field(
7204 'show_word_upload_button',
7205 __('Show Word Upload Button', 'mxchat'),
7206 array($this, 'mxchat_show_word_upload_button_callback'),
7207 'mxchat-embed',
7208 'mxchat_pdf_intent_section'
7209 );
7210
7211 add_settings_field(
7212 'pdf_intent_trigger_text',
7213 __('Intent Trigger Text', 'mxchat'),
7214 array($this, 'mxchat_pdf_intent_trigger_text_callback'),
7215 'mxchat-embed',
7216 'mxchat_pdf_intent_section'
7217 );
7218
7219 add_settings_field(
7220 'pdf_intent_success_text',
7221 __('Success Text', 'mxchat'),
7222 array($this, 'mxchat_pdf_intent_success_text_callback'),
7223 'mxchat-embed',
7224 'mxchat_pdf_intent_section'
7225 );
7226
7227 add_settings_field(
7228 'pdf_intent_error_text',
7229 __('Error Text', 'mxchat'),
7230 array($this, 'mxchat_pdf_intent_error_text_callback'),
7231 'mxchat-embed',
7232 'mxchat_pdf_intent_section'
7233 );
7234
7235 // Add PDF Maximum Pages Field
7236 add_settings_field(
7237 'pdf_max_pages',
7238 __('Maximum Document Pages', 'mxchat'),
7239 array($this, 'mxchat_pdf_max_pages_callback'),
7240 'mxchat-embed',
7241 'mxchat_pdf_intent_section'
7242 );
7243
7244 // Live Agent Settings Fields
7245 add_settings_section(
7246 'mxchat_live_agent_section',
7247 __('Live Agent Settings', 'mxchat'),
7248 array($this, 'mxchat_live_agent_section_callback'),
7249 'mxchat-embed'
7250 );
7251
7252 // Live Agent Status Fields (add at top of live agent settings)
7253 add_settings_field(
7254 'live_agent_status',
7255 __('Live Agent Status', 'mxchat'),
7256 array($this, 'mxchat_live_agent_status_callback'),
7257 'mxchat-embed',
7258 'mxchat_live_agent_section'
7259 );
7260
7261 // Slack availability schedule (plans 8ccaa2 + 99d7a4). Each handoff channel
7262 // owns an independent schedule rendered under its own Integrations tab; this
7263 // one governs Slack only. Same callback as Telegram's, parameterized.
7264 add_settings_field(
7265 'live_agent_schedule_slack',
7266 __('Availability Schedule', 'mxchat'),
7267 array($this, 'mxchat_live_agent_schedule_callback'),
7268 'mxchat-embed',
7269 'mxchat_live_agent_section',
7270 array('channel' => 'slack')
7271 );
7272
7273 add_settings_field(
7274 'live_agent_notification_message',
7275 __('Notification Message', 'mxchat'),
7276 array($this, 'mxchat_live_agent_notification_message_callback'),
7277 'mxchat-embed',
7278 'mxchat_live_agent_section'
7279 );
7280
7281 add_settings_field(
7282 'live_agent_away_message',
7283 __('Away Message', 'mxchat'),
7284 array($this, 'mxchat_live_agent_away_message_callback'),
7285 'mxchat-embed',
7286 'mxchat_live_agent_section'
7287 );
7288
7289 add_settings_field(
7290 'live_agent_user_ids',
7291 __('Slack Agent User IDs', 'mxchat'),
7292 array($this, 'mxchat_live_agent_user_ids_callback'),
7293 'mxchat-embed',
7294 'mxchat_live_agent_section'
7295 );
7296
7297 // Shared handoff channel (plan 9f7756): route every handoff into one
7298 // pre-existing channel as threads instead of creating chat-* channels.
7299 add_settings_field(
7300 'live_agent_shared_channel',
7301 __('Shared Handoff Channel', 'mxchat'),
7302 array($this, 'mxchat_live_agent_shared_channel_callback'),
7303 'mxchat-embed',
7304 'mxchat_live_agent_section'
7305 );
7306
7307 // Auto-archive per-conversation chat- channels on !endchat (plan 7458a7).
7308 // Default OFF; never touches the shared handoff channel.
7309 add_settings_field(
7310 'live_agent_archive_on_end_toggle',
7311 __('Archive Channel When Chat Ends', 'mxchat'),
7312 array($this, 'mxchat_live_agent_archive_on_end_callback'),
7313 'mxchat-embed',
7314 'mxchat_live_agent_section'
7315 );
7316
7317 add_settings_field(
7318 'live_agent_webhook_url',
7319 __('Slack Webhook URL', 'mxchat'),
7320 array($this, 'mxchat_live_agent_webhook_url_callback'),
7321 'mxchat-embed',
7322 'mxchat_live_agent_section'
7323 );
7324
7325 add_settings_field(
7326 'live_agent_secret_key',
7327 __('Slack Secret Key', 'mxchat'),
7328 array($this, 'mxchat_live_agent_secret_key_callback'),
7329 'mxchat-embed',
7330 'mxchat_live_agent_section'
7331 );
7332
7333 // Live Agent Integration Fields
7334 add_settings_field(
7335 'live_agent_bot_token',
7336 __('Slack Bot OAuth Token', 'mxchat'),
7337 array($this, 'mxchat_live_agent_bot_token_callback'),
7338 'mxchat-embed',
7339 'mxchat_live_agent_section'
7340 );
7341
7342 // Telegram Integration Section
7343 add_settings_section(
7344 'mxchat_telegram_section',
7345 __('Telegram Settings', 'mxchat'),
7346 array($this, 'mxchat_telegram_section_callback'),
7347 'mxchat-embed'
7348 );
7349
7350 add_settings_field(
7351 'telegram_status',
7352 __('Live Agent Status', 'mxchat'),
7353 array($this, 'mxchat_telegram_status_callback'),
7354 'mxchat-embed',
7355 'mxchat_telegram_section'
7356 );
7357
7358 // Telegram availability schedule (plan 99d7a4) — independent of Slack's,
7359 // rendered right under the Telegram status toggle it extends.
7360 add_settings_field(
7361 'live_agent_schedule_telegram',
7362 __('Availability Schedule', 'mxchat'),
7363 array($this, 'mxchat_live_agent_schedule_callback'),
7364 'mxchat-embed',
7365 'mxchat_telegram_section',
7366 array('channel' => 'telegram')
7367 );
7368
7369 add_settings_field(
7370 'telegram_notification_message',
7371 __('Notification Message', 'mxchat'),
7372 array($this, 'mxchat_telegram_notification_message_callback'),
7373 'mxchat-embed',
7374 'mxchat_telegram_section'
7375 );
7376
7377 add_settings_field(
7378 'telegram_away_message',
7379 __('Away Message', 'mxchat'),
7380 array($this, 'mxchat_telegram_away_message_callback'),
7381 'mxchat-embed',
7382 'mxchat_telegram_section'
7383 );
7384
7385 add_settings_field(
7386 'telegram_bot_token',
7387 __('Telegram Bot Token', 'mxchat'),
7388 array($this, 'mxchat_telegram_bot_token_callback'),
7389 'mxchat-embed',
7390 'mxchat_telegram_section'
7391 );
7392
7393 add_settings_field(
7394 'telegram_group_id',
7395 __('Telegram Group ID', 'mxchat'),
7396 array($this, 'mxchat_telegram_group_id_callback'),
7397 'mxchat-embed',
7398 'mxchat_telegram_section'
7399 );
7400
7401 add_settings_field(
7402 'telegram_webhook_secret',
7403 __('Webhook Secret Token', 'mxchat'),
7404 array($this, 'mxchat_telegram_webhook_secret_callback'),
7405 'mxchat-embed',
7406 'mxchat_telegram_section'
7407 );
7408
7409 // Webhook Handoff Section (plan d88e22) — the third live-agent destination.
7410 // Outbound-only: handoffs POST to the owner's URL; the chat stays in AI mode.
7411 add_settings_section(
7412 'mxchat_webhook_handoff_section',
7413 __('Webhook Handoff Settings', 'mxchat'),
7414 array($this, 'mxchat_webhook_handoff_section_callback'),
7415 'mxchat-embed'
7416 );
7417
7418 add_settings_field(
7419 'webhook_handoff_status',
7420 __('Live Agent Status', 'mxchat'),
7421 array($this, 'mxchat_webhook_handoff_status_callback'),
7422 'mxchat-embed',
7423 'mxchat_webhook_handoff_section'
7424 );
7425
7426 // Webhook availability schedule — independent of Slack's and Telegram's,
7427 // same parameterized editor (plans 8ccaa2 + 99d7a4 + d88e22).
7428 add_settings_field(
7429 'live_agent_schedule_webhook',
7430 __('Availability Schedule', 'mxchat'),
7431 array($this, 'mxchat_live_agent_schedule_callback'),
7432 'mxchat-embed',
7433 'mxchat_webhook_handoff_section',
7434 array('channel' => 'webhook')
7435 );
7436
7437 add_settings_field(
7438 'webhook_handoff_notification_message',
7439 __('Notification Message', 'mxchat'),
7440 array($this, 'mxchat_webhook_handoff_notification_message_callback'),
7441 'mxchat-embed',
7442 'mxchat_webhook_handoff_section'
7443 );
7444
7445 add_settings_field(
7446 'webhook_handoff_away_message',
7447 __('Away Message', 'mxchat'),
7448 array($this, 'mxchat_webhook_handoff_away_message_callback'),
7449 'mxchat-embed',
7450 'mxchat_webhook_handoff_section'
7451 );
7452
7453 add_settings_field(
7454 'webhook_handoff_url',
7455 __('Webhook URL', 'mxchat'),
7456 array($this, 'mxchat_webhook_handoff_url_callback'),
7457 'mxchat-embed',
7458 'mxchat_webhook_handoff_section'
7459 );
7460
7461 add_settings_field(
7462 'webhook_handoff_secret',
7463 __('Signing Secret', 'mxchat'),
7464 array($this, 'mxchat_webhook_handoff_secret_callback'),
7465 'mxchat-embed',
7466 'mxchat_webhook_handoff_section'
7467 );
7468
7469 // General Settings Section
7470 add_settings_section(
7471 'mxchat_general_section',
7472 esc_html__('YouTube Tutorials', 'mxchat'),
7473 null,
7474 'mxchat-general'
7475 );
7476 }
7477
7478 public function mxchat_prompts_page_init() {
7479 register_setting(
7480 'mxchat_prompts_options',
7481 'mxchat_prompts_options',
7482 array(
7483 'type' => 'array',
7484 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
7485 'default' => array(
7486 'mxchat_auto_sync_posts' => 0,
7487 'mxchat_auto_sync_pages' => 0,
7488 'mxchat_use_pinecone' => 0,
7489 'mxchat_pinecone_api_key' => '',
7490 'mxchat_pinecone_environment' => '',
7491 'mxchat_pinecone_index' => '',
7492 'mxchat_pinecone_host' => '',
7493 ),
7494 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
7495 )
7496 );
7497
7498 add_action('admin_notices', array($this, 'sync_settings_notice'));
7499 }
7500
7501 public function mxchat_transcripts_page_init() {
7502 register_setting(
7503 'mxchat_transcripts_options',
7504 'mxchat_transcripts_options',
7505 array(
7506 'type' => 'array',
7507 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
7508 'default' => array(
7509 'mxchat_enable_notifications' => 0,
7510 'mxchat_notification_email' => get_option('admin_email'),
7511 'mxchat_auto_delete_transcripts' => 'never',
7512 ),
7513 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
7514 )
7515 );
7516
7517 add_settings_section(
7518 'mxchat_transcripts_notification_section',
7519 esc_html__('Chat Notification Settings', 'mxchat'),
7520 array($this, 'mxchat_transcripts_notification_section_callback'),
7521 'mxchat-transcripts'
7522 );
7523
7524 add_settings_field(
7525 'mxchat_enable_notifications',
7526 esc_html__('Enable Chat Notifications', 'mxchat'),
7527 array($this, 'mxchat_enable_notifications_callback'),
7528 'mxchat-transcripts',
7529 'mxchat_transcripts_notification_section'
7530 );
7531
7532 add_settings_field(
7533 'mxchat_notification_email',
7534 esc_html__('Notification Email Address', 'mxchat'),
7535 array($this, 'mxchat_notification_email_callback'),
7536 'mxchat-transcripts',
7537 'mxchat_transcripts_notification_section'
7538 );
7539
7540 add_settings_field(
7541 'mxchat_auto_delete_transcripts',
7542 esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
7543 array($this, 'mxchat_auto_delete_transcripts_callback'),
7544 'mxchat-transcripts',
7545 'mxchat_transcripts_notification_section'
7546 );
7547
7548 add_settings_field(
7549 'mxchat_retention_days',
7550 esc_html__('Custom Retention (Days)', 'mxchat'),
7551 array($this, 'mxchat_retention_days_callback'),
7552 'mxchat-transcripts',
7553 'mxchat_transcripts_notification_section'
7554 );
7555
7556 add_settings_field(
7557 'mxchat_auto_email_transcript',
7558 esc_html__('Auto-Email Full Transcript', 'mxchat'),
7559 array($this, 'mxchat_auto_email_transcript_callback'),
7560 'mxchat-transcripts',
7561 'mxchat_transcripts_notification_section'
7562 );
7563 }
7564
7565
7566 /**
7567 * Sanitize all prompts options
7568 *
7569 * @param array $input The unsanitized options array
7570 * @return array The sanitized options array
7571 */
7572 public function sanitize_prompts_options($input) {
7573 // Log the incoming input.
7574 //error_log('Sanitizing inputs: ' . print_r($input, true));
7575
7576 $sanitized = array();
7577
7578 // Boolean options
7579 $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
7580 $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
7581 $sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
7582
7583 // API Key: if less than 32 characters, flag as invalid.
7584 $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
7585 if (!empty($api_key) && strlen($api_key) < 32) {
7586 add_settings_error(
7587 'mxchat_prompts_options',
7588 'invalid_api_key',
7589 __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
7590 );
7591 $existing_options = get_option('mxchat_prompts_options', array());
7592 $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
7593 } else {
7594 $sanitized['mxchat_pinecone_api_key'] = $api_key;
7595 }
7596
7597 // Environment and Index Name
7598 $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
7599 $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
7600
7601 // Host: Remove protocol and validate format.
7602 $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
7603 $host = preg_replace('#^https?://#', '', $host);
7604 //error_log('Host after removing protocol: ' . $host);
7605 if (!empty($host)) {
7606 if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
7607 add_settings_error(
7608 'mxchat_prompts_options',
7609 'invalid_host',
7610 __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
7611 );
7612 $existing_options = get_option('mxchat_prompts_options', array());
7613 $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
7614 } else {
7615 $sanitized['mxchat_pinecone_host'] = $host;
7616 }
7617 } else {
7618 $sanitized['mxchat_pinecone_host'] = '';
7619 }
7620
7621 //error_log('Final sanitized array: ' . print_r($sanitized, true));
7622
7623 return $sanitized;
7624 }
7625
7626 public function sync_settings_notice() {
7627 // Only show notice on our plugin page
7628 if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
7629 return;
7630 }
7631
7632 // Check if settings were updated
7633 if (isset($_GET['settings-updated'])) {
7634
7635 ?>
7636 <div class="notice notice-success is-dismissible">
7637 <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
7638 <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
7639 </div>
7640 <?php
7641
7642 }
7643 }
7644 // Add this sanitization function to your class
7645 public function sanitize_sync_setting($input) {
7646 return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
7647 }
7648
7649 public function mxchat_rate_limits_callback() {
7650 $all_options = get_option('mxchat_options', []);
7651
7652 // Define available rate limits
7653 $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7654
7655 // Define available timeframes
7656 $timeframes = array(
7657 'hourly' => __('Per Hour', 'mxchat'),
7658 'daily' => __('Per Day', 'mxchat'),
7659 'weekly' => __('Per Week', 'mxchat'),
7660 'monthly' => __('Per Month', 'mxchat')
7661 );
7662
7663 // Get all roles plus a "logged_out" pseudo-role
7664 $roles = wp_roles()->get_names();
7665 $roles['logged_out'] = __('Logged Out Users', 'mxchat');
7666
7667 // Start the wrapper
7668 echo '<div class="pro-feature-wrapper active">';
7669 echo '<div class="mxchat-rate-limits-container">';
7670
7671 echo '<p class="description" style="margin-bottom: 20px;">' .
7672 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') .
7673 '</p>';
7674
7675 // Add markdown link documentation
7676 echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
7677 echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
7678 echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
7679 echo '<ul style="margin-left: 20px;">';
7680 echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
7681 echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
7682 echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
7683 echo '</ul>';
7684 echo '</div>';
7685
7686 // Output the controls for each role
7687 foreach ($roles as $role_id => $role_name) {
7688 // Get saved options or defaults
7689 $default_limit = ($role_id === 'logged_out') ? '10' : '100';
7690 $default_timeframe = 'daily';
7691 $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
7692
7693 $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
7694 ? $all_options['rate_limits'][$role_id]['limit']
7695 : $default_limit;
7696
7697 $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
7698 ? $all_options['rate_limits'][$role_id]['timeframe']
7699 : $default_timeframe;
7700
7701 $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
7702 ? $all_options['rate_limits'][$role_id]['message']
7703 : $default_message;
7704
7705 // Output the row
7706 echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
7707
7708 // Role label
7709 echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
7710
7711 // Controls section
7712 echo '<div class="mxchat-rate-limit-controls-wrapper">';
7713
7714 // Rate limit and timeframe controls
7715 echo '<div class="mxchat-rate-limit-controls">';
7716
7717 // Limit dropdown
7718 echo '<div>';
7719 echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
7720 echo '<select
7721 id="rate_limits_' . esc_attr($role_id) . '_limit"
7722 name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
7723 class="mxchat-autosave-field">';
7724 foreach ($rate_limits as $limit) {
7725 echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7726 }
7727 echo '</select>';
7728 echo '</div>';
7729
7730 // Timeframe dropdown
7731 echo '<div>';
7732 echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
7733 echo '<select
7734 id="rate_limits_' . esc_attr($role_id) . '_timeframe"
7735 name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
7736 class="mxchat-autosave-field">';
7737 foreach ($timeframes as $value => $label) {
7738 echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
7739 }
7740 echo '</select>';
7741 echo '</div>';
7742
7743 echo '</div>'; // End controls
7744
7745 // Custom message textarea
7746 echo '<div class="mxchat-rate-limit-message">';
7747 echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
7748 echo '<textarea
7749 id="rate_limits_' . esc_attr($role_id) . '_message"
7750 name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
7751 class="mxchat-autosave-field"
7752 placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
7753 esc_textarea($custom_message) .
7754 '</textarea>';
7755 echo '<p class="description">' .
7756 esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
7757 '</p>';
7758 echo '</div>'; // End message
7759
7760 echo '</div>'; // End controls wrapper
7761
7762 echo '</div>'; // End row
7763 }
7764
7765 echo '</div>'; // End container
7766
7767 echo '</div>'; // End pro-feature-wrapper
7768 }
7769
7770 private function mxchat_add_option_field($id, $title, $callback = '') {
7771 add_settings_field(
7772 $id,
7773 __($title, 'mxchat'),
7774 $callback ? array($this, $callback) : array($this, $id . '_callback'),
7775 'mxchat-max',
7776 'mxchat_setting_section_id',
7777 $id === 'model' ? ['label_for' => 'model'] : []
7778 );
7779 }
7780
7781 // API Keys Section Callback
7782 public function mxchat_api_keys_section_callback() {
7783 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>';
7784 }
7785
7786 // OpenAI API Key
7787 public function api_key_callback() {
7788 $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
7789 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7790
7791 echo '<div class="api-key-wrapper">';
7792 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 . '" />';
7793 echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7794 echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
7795 echo $this->mxchat_provider_key_test_button('openai', 'api_key');
7796 echo '</div>';
7797 }
7798
7799 // X.AI API Key
7800 public function xai_api_key_callback() {
7801 $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
7802 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7803
7804 echo '<div class="api-key-wrapper">';
7805 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 . '" />';
7806 echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7807 echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
7808 echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key');
7809 echo '</div>';
7810 }
7811 // Claude API Key
7812 public function claude_api_key_callback() {
7813 $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
7814 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7815
7816 echo '<div class="api-key-wrapper">';
7817 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 . '" />';
7818 echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7819 echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
7820 echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key');
7821 echo '</div>';
7822 }
7823
7824 // DeepSeek API Key
7825 public function deepseek_api_key_callback() {
7826 $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
7827 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7828
7829 echo '<div class="api-key-wrapper">';
7830 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 . '" />';
7831 echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7832 echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
7833 echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key');
7834 echo '</div>';
7835 }
7836
7837 // Gemini API Key
7838 public function gemini_api_key_callback() {
7839 $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
7840 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7841
7842 echo '<div class="api-key-wrapper">';
7843 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 . '" />';
7844 echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7845 echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
7846 echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key');
7847 echo '</div>';
7848 }
7849
7850
7851 // OpenRouter API Key
7852 public function openrouter_api_key_callback() {
7853 $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
7854 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7855
7856 echo '<div class="api-key-wrapper">';
7857 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 . '" />';
7858 echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7859 echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
7860 echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key');
7861 echo '</div>';
7862 }
7863
7864 /**
7865 * Renders a "Test key" button + result target next to a built-in provider key
7866 * field, and emits the shared delegated click handler ONCE (static guard). The
7867 * button carries data-target = the key field id so the owner can test the value
7868 * they just typed (test-before-save); the AJAX handler falls back to the saved
7869 * key when the field is empty. Styled with the WP `button` class to match the
7870 * adjacent Custom-provider "Test Connection" button on this same page.
7871 * plan-mxchat-20260623-c41f74.
7872 */
7873 public function mxchat_provider_key_test_button($provider, $target_id) {
7874 static $script_emitted = false;
7875 $nonce = wp_create_nonce('mxchat_test_provider_key');
7876 $html = '<div class="mxchat-key-test" style="margin-top:8px;">'
7877 . '<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>'
7878 . '<span class="mxchat-test-provider-key-result" style="margin-left:10px;font-size:13px;vertical-align:middle;"></span>'
7879 . '</div>';
7880 if (!$script_emitted) {
7881 $script_emitted = true;
7882 $html .= $this->mxchat_provider_key_test_script();
7883 }
7884 return $html;
7885 }
7886
7887 /**
7888 * One-time delegated click handler shared by every .mxchat-test-provider-key
7889 * button. Posts the typed key value + provider to mxchat_test_provider_key and
7890 * renders the success/error message inline. Mirrors the Custom-provider test.
7891 */
7892 private function mxchat_provider_key_test_script() {
7893 $t_testing = esc_js(__('Testing...', 'mxchat'));
7894 $t_valid = esc_js(__('Key is valid.', 'mxchat'));
7895 $t_failed = esc_js(__('Failed', 'mxchat'));
7896 $t_req = esc_js(__('Request failed', 'mxchat'));
7897 return '<script>(function(){'
7898 . 'if (window.__mxchatProviderKeyTestWired) { return; }'
7899 . 'window.__mxchatProviderKeyTestWired = true;'
7900 . 'document.addEventListener("click", function(e){'
7901 . 'var btn = e.target && e.target.closest ? e.target.closest(".mxchat-test-provider-key") : null;'
7902 . 'if (!btn) { return; }'
7903 . 'e.preventDefault();'
7904 . 'var field = btn.getAttribute("data-target") ? document.getElementById(btn.getAttribute("data-target")) : null;'
7905 . 'var out = btn.parentNode ? btn.parentNode.querySelector(".mxchat-test-provider-key-result") : null;'
7906 . 'if (out) { out.textContent = "' . $t_testing . '"; out.style.color = "#646970"; }'
7907 . 'btn.disabled = true;'
7908 . 'var fd = new FormData();'
7909 . 'fd.append("action", "mxchat_test_provider_key");'
7910 . 'fd.append("_wpnonce", btn.getAttribute("data-nonce"));'
7911 . 'fd.append("provider", btn.getAttribute("data-provider") || "");'
7912 . 'fd.append("key", field ? field.value : "");'
7913 . 'fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })'
7914 . '.then(function(r){ return r.json(); })'
7915 . '.then(function(j){'
7916 . 'if (out) {'
7917 . 'if (j && j.success) { out.textContent = "✓ " + ((j.data && j.data.message) ? j.data.message : "' . $t_valid . '"); out.style.color = "#00a32a"; }'
7918 . 'else { out.textContent = "⚠ " + ((j && j.data && j.data.message) ? j.data.message : "' . $t_failed . '"); out.style.color = "#d63638"; }'
7919 . '}'
7920 . 'btn.disabled = false;'
7921 . '})'
7922 . '.catch(function(){ if (out) { out.textContent = "⚠ ' . $t_req . '"; out.style.color = "#d63638"; } btn.disabled = false; });'
7923 . '});'
7924 . '})();</script>';
7925 }
7926
7927 // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
7928 public function custom_provider_callback() {
7929 $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
7930 $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
7931 $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
7932 $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
7933 $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
7934 $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
7935 $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
7936 $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
7937 $nonce = wp_create_nonce('mxchat_autosave_nonce');
7938 $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
7939
7940 echo '<style>
7941 .mxchat-cp { max-width: 680px; }
7942 .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
7943 .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
7944 .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
7945 .mxchat-cp .mxchat-cp-row > input[type="text"],
7946 .mxchat-cp .mxchat-cp-row > input[type="password"],
7947 .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
7948 .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
7949 .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
7950 .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
7951 .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; }
7952 .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; }
7953 .mxchat-cp .mxchat-cp-azure ol { margin: 0; padding: 0 0 0 18px; color: #50575e; font-size: 12px; line-height: 1.7; }
7954 .mxchat-cp .mxchat-cp-azure code { background: #eceefb; padding: 1px 5px; border-radius: 3px; font-size: 11px; }
7955 </style>';
7956
7957 echo '<div class="api-key-wrapper mxchat-cp">';
7958 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>';
7959
7960 // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout
7961 // so admins can configure Azure without piecing it together from each field's hint.
7962 echo '<div class="mxchat-cp-azure">';
7963 echo '<span class="mxchat-cp-azure-title">' . esc_html__('Azure OpenAI quick start', 'mxchat') . '</span>';
7964 echo '<ol>';
7965 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>';
7966 echo '<li>' . wp_kses(__('<strong>API Key</strong> → your Azure OpenAI key (required)', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7967 echo '<li>' . wp_kses(__('<strong>Auth Scheme</strong> → <code>api-key header (Azure OpenAI)</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7968 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>';
7969 echo '</ol>';
7970 echo '</div>';
7971
7972 echo '<div class="mxchat-cp-row">';
7973 echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
7974 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 . '" />';
7975 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>';
7976 echo '</div>';
7977
7978 echo '<div class="mxchat-cp-row">';
7979 echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
7980 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 . '" />';
7981 echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
7982 echo '</div>';
7983
7984 echo '<div class="mxchat-cp-row">';
7985 echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
7986 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 . '" />';
7987 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>';
7988 echo '</div>';
7989
7990 echo '<div class="mxchat-cp-row">';
7991 echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
7992 echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7993 echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
7994 echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
7995 echo '</select>';
7996 echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
7997 echo '</div>';
7998
7999 echo '<div class="mxchat-cp-row">';
8000 echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
8001 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 . '" />';
8002 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>';
8003 echo '</div>';
8004
8005 // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
8006 echo '<div class="mxchat-cp-row">';
8007 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>';
8008 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>';
8009 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>';
8010 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>';
8011 echo '</div>';
8012
8013 echo '<div class="mxchat-cp-row">';
8014 echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
8015 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 . '" />';
8016 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>';
8017 echo '</div>';
8018
8019 echo '<div class="mxchat-cp-test">';
8020 echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
8021 echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
8022 echo '</div>';
8023
8024 echo '<script>(function(){
8025 var btn = document.getElementById("mxchat-test-custom-provider");
8026 if (!btn || btn._wired) { return; } btn._wired = true;
8027 btn.addEventListener("click", function(){
8028 var out = document.getElementById("mxchat-test-custom-provider-result");
8029 out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
8030 out.style.color = "#646970";
8031 var fd = new FormData();
8032 fd.append("action", "mxchat_test_custom_provider");
8033 fd.append("_wpnonce", btn.getAttribute("data-nonce"));
8034 fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
8035 .then(function(r){ return r.json(); })
8036 .then(function(j){
8037 if (j && j.success) {
8038 out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
8039 out.style.color = "#00a32a";
8040 } else {
8041 out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
8042 out.style.color = "#d63638";
8043 }
8044 })
8045 .catch(function(){
8046 out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
8047 out.style.color = "#d63638";
8048 });
8049 });
8050 })();</script>';
8051
8052 echo '</div>';
8053 }
8054
8055 // Voyage API Key
8056 public function voyage_api_key_callback() {
8057 $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
8058 $nonce = wp_create_nonce('mxchat_autosave_nonce');
8059
8060 echo '<div class="api-key-wrapper">';
8061 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 . '" />';
8062 echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8063 echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
8064 echo '</div>';
8065 }
8066
8067 public function mxchat_loops_api_key_callback() {
8068 $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
8069 $nonce = wp_create_nonce('mxchat_autosave_nonce');
8070
8071 echo '<div class="api-key-wrapper">';
8072 echo sprintf(
8073 '<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" />',
8074 $loops_api_key,
8075 $nonce
8076 );
8077 echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8078 echo '</div>';
8079 // Cross-reference back to where the list is chosen, so the two screens point
8080 // at each other (plan-mxchat-20260802-907a63).
8081 echo '<p class="description">' . wp_kses(
8082 sprintf(
8083 /* translators: %s: link to the Loops integration tab. */
8084 __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'),
8085 '<a href="#integrations-loops">' . esc_html__('Integrations, Loops', 'mxchat') . '</a>'
8086 ),
8087 self::mxchat_loops_pointer_allowed_html()
8088 ) . '</p>';
8089 }
8090 public function mxchat_loops_mailing_list_callback() {
8091 // Add error handling and type checking
8092 $loops_api_key = '';
8093 $selected_list = '';
8094 $nonce = wp_create_nonce('mxchat_autosave_nonce');
8095
8096 // Safely get the API key
8097 if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
8098 $loops_api_key = $this->options['loops_api_key'];
8099 }
8100
8101 // Safely get the selected list
8102 if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
8103 $selected_list = $this->options['loops_mailing_list'];
8104 }
8105
8106 if (!empty($loops_api_key)) {
8107 $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
8108 if (is_array($lists) && !empty($lists)) {
8109 echo '<div class="mxchat-field-wrapper">';
8110 echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
8111
8112 // Add a default "Select a list" option
8113 echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
8114
8115 foreach ($lists as $list) {
8116 if (is_array($list) && isset($list['id']) && isset($list['name'])) {
8117 echo sprintf(
8118 '<option value="%s" %s>%s</option>',
8119 esc_attr($list['id']),
8120 selected($selected_list, $list['id'], false),
8121 esc_html($list['name'])
8122 );
8123 }
8124 }
8125 echo '</select>';
8126 echo '</div>';
8127 echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
8128 } else {
8129 echo '<p class="description">' . wp_kses(
8130 self::mxchat_loops_api_key_pointer(
8131 /* translators: %s: link to the API Keys tab. */
8132 __('No lists found. Please check your Loops API key under %s.', 'mxchat')
8133 ),
8134 self::mxchat_loops_pointer_allowed_html()
8135 ) . '</p>';
8136 }
8137 } else {
8138 echo '<p class="description">' . wp_kses(
8139 self::mxchat_loops_api_key_pointer(
8140 /* translators: %s: link to the API Keys tab. */
8141 __('Enter your Loops API key under %s to load mailing lists.', 'mxchat')
8142 ),
8143 self::mxchat_loops_pointer_allowed_html()
8144 ) . '</p>';
8145 }
8146 }
8147
8148 /**
8149 * Build the "API Keys" pointer used by the Loops mailing-list field.
8150 *
8151 * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API
8152 * Keys tab, but this field's copy still read as though the input were beside
8153 * it, so users had nowhere to go. Both live on the SAME screen
8154 * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this
8155 * dropdown under Integrations > Loops — so the pointer is an in-page tab
8156 * switch, not a cross-page link.
8157 *
8158 * A plain href="#api-keys" is all it takes: the shared admin shell
8159 * (js/admin-sidebar.js) honours section-naming hashes on load AND on
8160 * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old
8161 * data-target workaround on these pointer anchors is gone.
8162 *
8163 * @param string $template Translatable string containing one %s placeholder.
8164 * @return string
8165 */
8166 private static function mxchat_loops_api_key_pointer($template) {
8167 return sprintf(
8168 $template,
8169 '<a href="#api-keys">' . esc_html__('API Keys', 'mxchat') . '</a>'
8170 );
8171 }
8172
8173 /**
8174 * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook.
8175 */
8176 private static function mxchat_loops_pointer_allowed_html() {
8177 return array(
8178 'a' => array(
8179 'href' => array(),
8180 'data-target' => array(),
8181 ),
8182 );
8183 }
8184 public function mxchat_triggered_phrase_response_callback() {
8185 $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
8186 $triggered_response = isset($this->options['triggered_phrase_response'])
8187 ? $this->options['triggered_phrase_response']
8188 : $default_response;
8189 $nonce = wp_create_nonce('mxchat_autosave_nonce');
8190
8191 echo '<div class="mxchat-field-wrapper">';
8192 echo sprintf(
8193 '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
8194 $nonce,
8195 esc_textarea($triggered_response)
8196 );
8197 echo '</div>';
8198 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>';
8199 }
8200
8201 public function mxchat_email_capture_response_callback() {
8202 $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
8203 $email_capture_response = isset($this->options['email_capture_response'])
8204 ? $this->options['email_capture_response']
8205 : $default_response;
8206 $nonce = wp_create_nonce('mxchat_autosave_nonce');
8207
8208 echo '<div class="mxchat-field-wrapper">';
8209 echo sprintf(
8210 '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
8211 $nonce,
8212 esc_textarea($email_capture_response)
8213 );
8214 echo '</div>';
8215 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>';
8216 }
8217 public function mxchat_pre_chat_message_callback() {
8218 // Load the entire 'mxchat_options' array
8219 $all_options = get_option('mxchat_options', []);
8220
8221 // Retrieve the saved message or use the default value
8222 $default_message = __('Hey there! Ask me anything!', 'mxchat');
8223 $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
8224
8225 // Output the textarea
8226 printf(
8227 '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
8228 esc_textarea($pre_chat_message)
8229 );
8230 }
8231
8232 // Callback for AI Instructions textarea
8233 public function system_prompt_instructions_callback() {
8234 // Retrieve the current value of the system prompt instructions
8235 $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
8236 // Render the textarea field
8237 printf(
8238 '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
8239 $instructions
8240 );
8241 // Personalization hint
8242 echo '<p class="description" style="margin-top: 8px;">';
8243 echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
8244 echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
8245 echo '</p>';
8246 // Date awareness (plan cfcd80): the automatic line is the default; the
8247 // placeholders are for owners who want the date at a specific spot, with
8248 // the prompt-caching cost spelled out.
8249 echo '<p class="description" style="margin-top: 8px;">';
8250 echo esc_html__('The chatbot is told the current date and time in your site\'s timezone with every message, so it can tell past events from upcoming ones. You can also place {current_date} or {current_datetime} in the instructions above. Note: a placeholder changes the prompt once a day (date) or every minute (date and time), which reduces how much of it your AI provider can cache; the automatic line has no such cost, so most sites do not need one.', 'mxchat');
8251 echo '</p>';
8252 // Sample instructions button
8253 echo '<div class="mxchat-instructions-container">';
8254 echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
8255 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">';
8256 echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
8257 echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
8258 echo '</svg>';
8259 echo esc_html__('View Sample Instructions', 'mxchat');
8260 echo '</button>';
8261 echo '</div>';
8262
8263 // Add modal to WordPress admin footer instead of inline
8264 add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
8265 }
8266
8267 // New method to render modal in admin footer
8268 public function render_sample_instructions_modal() {
8269 static $modal_rendered = false;
8270 if ($modal_rendered) return; // Prevent duplicate modals
8271 $modal_rendered = true;
8272
8273 echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
8274 echo '<div class="mxchat-instructions-modal-content">';
8275 echo '<div class="mxchat-instructions-modal-header">';
8276 echo '<h3 class="mxchat-instructions-modal-title">';
8277 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">';
8278 echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
8279 echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
8280 echo '</svg>';
8281 echo esc_html__('Sample AI Instructions', 'mxchat');
8282 echo '</h3>';
8283 echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
8284 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">';
8285 echo '<line x1="18" y1="6" x2="6" y2="18"/>';
8286 echo '<line x1="6" y1="6" x2="18" y2="18"/>';
8287 echo '</svg>';
8288 echo '</button>';
8289 echo '</div>';
8290 echo '<div class="mxchat-instructions-modal-body">';
8291 echo '<div class="mxchat-instructions-content">';
8292 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:
8293
8294 # Response Style - CRITICALLY IMPORTANT
8295 - MAXIMUM LENGTH: 1-3 short sentences per response
8296 - Ultra-concise: Get straight to the answer with no filler
8297 - No introductions like "Sure!" or "I\'d be happy to help"
8298 - No phrases like "based on my knowledge" or "according to information"
8299 - No explanatory text before giving the answer
8300 - No summaries or repetition
8301 - Hyperlink all URLs
8302 - Respond in user\'s language
8303 - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
8304
8305 # Knowledge Base Requirements - PREVENT HALLUCINATIONS
8306 - ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
8307 - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
8308 - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
8309 - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
8310 - Better to admit insufficient information than provide inaccurate answers');
8311 echo '</div>';
8312 echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
8313 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">';
8314 echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
8315 echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
8316 echo '</svg>';
8317 echo esc_html__('Copy Instructions', 'mxchat');
8318 echo '</button>';
8319 echo '</div>';
8320 echo '<div class="mxchat-instructions-modal-footer">';
8321 echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
8322 echo '</div>';
8323 echo '</div>';
8324 echo '</div>';
8325 }
8326
8327
8328 public function mxchat_model_callback() {
8329 // Catalog refactor (plan-d14e89): single source of truth lives in
8330 // includes/class-mxchat-model-catalog.php. Dropdown groups are the
8331 // provider labels; each group maps model_id => "Label" strings.
8332 if (!class_exists('MxChat_Model_Catalog')) {
8333 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
8334 }
8335 // Retrieve the currently selected model from saved options
8336 $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.6-sol';
8337
8338 // Pass the saved model so a provider-retired id keeps rendering as the
8339 // current selection instead of a blank select (plan e46b8f).
8340 $models = MxChat_Model_Catalog::settings_dropdown_groups($selected_model);
8341
8342 // Begin the select dropdown
8343 echo '<select id="model" name="model">';
8344
8345 // Iterate over groups of models
8346 foreach ($models as $group_label => $group_models) {
8347 echo '<optgroup label="' . esc_attr($group_label) . '">';
8348
8349 foreach ($group_models as $model_value => $model_label) {
8350 echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
8351 }
8352
8353 echo '</optgroup>';
8354 }
8355
8356 echo '</select>';
8357
8358 // Add a note for OpenRouter
8359 echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
8360 echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
8361 echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
8362 echo '</p>';
8363
8364 // API Key Status Messages (hidden by default, shown by JS based on selected model)
8365 $has_openai_key = !empty($this->options['api_key']);
8366 $has_claude_key = !empty($this->options['claude_api_key']);
8367 $has_xai_key = !empty($this->options['xai_api_key']);
8368 $has_deepseek_key = !empty($this->options['deepseek_api_key']);
8369 $has_gemini_key = !empty($this->options['gemini_api_key']);
8370 $has_openrouter_key = !empty($this->options['openrouter_api_key']);
8371
8372 // OpenAI/GPT models
8373 echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
8374 if ($has_openai_key) {
8375 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8376 } else {
8377 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8378 }
8379 echo '</p>';
8380
8381 // Claude models
8382 echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
8383 if ($has_claude_key) {
8384 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
8385 } else {
8386 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8387 }
8388 echo '</p>';
8389
8390 // X.AI models
8391 echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
8392 if ($has_xai_key) {
8393 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
8394 } else {
8395 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>';
8396 }
8397 echo '</p>';
8398
8399 // DeepSeek models
8400 echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
8401 if ($has_deepseek_key) {
8402 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
8403 } else {
8404 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8405 }
8406 echo '</p>';
8407
8408 // Gemini models
8409 echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
8410 if ($has_gemini_key) {
8411 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8412 } else {
8413 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8414 }
8415 echo '</p>';
8416
8417 // OpenRouter models
8418 echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
8419 if ($has_openrouter_key) {
8420 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
8421 } else {
8422 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8423 }
8424 echo '</p>';
8425
8426 // ADD THESE HIDDEN FIELDS RIGHT HERE:
8427 $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
8428 $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
8429
8430 echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
8431 echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
8432 }
8433
8434 // Update your existing callback method
8435 public function enable_streaming_toggle_callback() {
8436 // Get value from options array, default to 'on'
8437 $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
8438 $checked = ($enabled === 'on') ? 'checked' : '';
8439
8440 echo '<label class="toggle-switch">';
8441 echo sprintf(
8442 '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
8443 esc_attr($checked)
8444 );
8445 echo '<span class="slider"></span>';
8446 echo '</label>';
8447
8448 // Test button — branded .mxch-btn with inline SVG (IDs preserved for AJAX binding)
8449 echo '<div class="mxch-streaming-test-row">';
8450 echo '<button type="button" id="mxchat-test-streaming-btn" class="mxch-btn mxch-btn-secondary">';
8451 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>';
8452 echo esc_html__('Test Streaming Compatibility', 'mxchat');
8453 echo '</button>';
8454 echo '<p id="mxchat-test-streaming-result" class="mxch-streaming-test-result"></p>';
8455 echo '</div>';
8456 }
8457
8458 // Web Search toggle callback
8459 public function enable_web_search_toggle_callback() {
8460 // Get value from options array, default to 'off'
8461 $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
8462 $checked = ($enabled === 'on') ? 'checked' : '';
8463
8464 // Get current model to determine if we should show/enable the toggle
8465 $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
8466
8467 // Models that DON'T support web search — OpenAI-docs-driven exception list.
8468 // Keep hardcoded; the catalog can't infer "supports web search" per-model, so any
8469 // future OpenAI model that lacks Responses-API web_search support is added here.
8470 $unsupported_models = array('gpt-4.1-nano');
8471
8472 // Web-search-capable chat-model allowlists, derived from the central model catalog
8473 // (class-mxchat-model-catalog.php). When a new OpenAI/Gemini chat model is added there,
8474 // the Web Search toggle picks it up automatically — no edit here.
8475 // OpenAI grounds via the Responses-API web_search tool; Gemini grounds natively via the
8476 // Google Search tool (plan 46b9ea wired the Gemini dispatch — every shipped Gemini chat
8477 // model is 2.x/3.x and grounds, matching that path's empty opt-out list, so all catalog
8478 // Gemini models are supported here).
8479 if (!class_exists('MxChat_Model_Catalog')) {
8480 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
8481 }
8482 $chat_catalog = MxChat_Model_Catalog::chat_models();
8483 $openai_models = (isset($chat_catalog['openai']['models']) && is_array($chat_catalog['openai']['models']))
8484 ? array_keys($chat_catalog['openai']['models'])
8485 : array();
8486 $gemini_models = (isset($chat_catalog['gemini']['models']) && is_array($chat_catalog['gemini']['models']))
8487 ? array_keys($chat_catalog['gemini']['models'])
8488 : array();
8489
8490 $is_capable = in_array($current_model, $openai_models) || in_array($current_model, $gemini_models);
8491 $is_supported = $is_capable && !in_array($current_model, $unsupported_models);
8492
8493 // Wrapper div with data attributes for JS to show/hide. data-openai-models is kept for
8494 // back-compat; data-gemini-models is the added second provider the JS now also honors.
8495 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;"' : '') . '>';
8496
8497 echo '<label class="toggle-switch">';
8498 echo sprintf(
8499 '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
8500 esc_attr($checked)
8501 );
8502 echo '<span class="slider"></span>';
8503 echo '</label>';
8504
8505 echo '</div>';
8506
8507 // Message shown when a model that can't ground (Claude, Grok, DeepSeek, OpenRouter, etc.) is selected
8508 echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
8509 echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
8510 echo esc_html__('Web search is only available for OpenAI and Gemini models.', 'mxchat');
8511 echo '</p>';
8512 }
8513
8514 // AJAX handler to fetch OpenRouter models
8515 public function fetch_openrouter_models() {
8516 check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
8517
8518 // plan-mxchat-20260731-c63fb6 — nonce is not authorization.
8519 if (!current_user_can('manage_options')) {
8520 wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')), 403);
8521 }
8522
8523 $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
8524
8525 if (empty($api_key)) {
8526 wp_send_json_error(array('message' => 'API key is required'));
8527 }
8528
8529 $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
8530 'headers' => array(
8531 'Authorization' => 'Bearer ' . $api_key,
8532 'Content-Type' => 'application/json',
8533 ),
8534 'timeout' => 15,
8535 ));
8536
8537 if (is_wp_error($response)) {
8538 wp_send_json_error(array('message' => $response->get_error_message()));
8539 }
8540
8541 $body = wp_remote_retrieve_body($response);
8542 $data = json_decode($body, true);
8543
8544 if (isset($data['data']) && is_array($data['data'])) {
8545 // Format the models for the frontend
8546 $models = array_map(function($model) {
8547 return array(
8548 'id' => $model['id'],
8549 'name' => $model['name'] ?? $model['id'],
8550 'description' => $model['description'] ?? '',
8551 'context_length' => $model['context_length'] ?? 0,
8552 'pricing' => array(
8553 'prompt' => $model['pricing']['prompt'] ?? 0,
8554 'completion' => $model['pricing']['completion'] ?? 0,
8555 ),
8556 );
8557 }, $data['data']);
8558
8559 wp_send_json_success(array('models' => $models));
8560 } else {
8561 wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
8562 }
8563 }
8564
8565 // Callback function for embedding model selection
8566 public function embedding_model_callback() {
8567 $models = array(
8568 esc_html__('OpenAI Embeddings', 'mxchat') => array(
8569 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
8570 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
8571 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
8572 ),
8573 esc_html__('Voyage AI Embeddings', 'mxchat') => array(
8574 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
8575 ),
8576 esc_html__('Google Gemini Embeddings', 'mxchat') => array(
8577 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
8578 )
8579 );
8580 $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
8581 // With custom-provider embeddings on, this picker is inert — the effective
8582 // model comes from the Custom Embedding Model field (plan ae02cb). Autosave
8583 // fires only on user change events, so the disabled attribute cannot cause
8584 // a missing-key save; JS keeps the state in sync with the toggle live.
8585 $custom_embeddings_on = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
8586 echo '<select id="embedding_model" name="embedding_model"' . ($custom_embeddings_on ? ' disabled' : '') . '>';
8587 foreach ($models as $group_label => $group_models) {
8588 echo '<optgroup label="' . esc_attr($group_label) . '">';
8589 foreach ($group_models as $model_value => $model_label) {
8590 echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
8591 }
8592 echo '</optgroup>';
8593 }
8594 echo '</select>';
8595 echo '<p class="mxch-field-description mxchat-embedding-custom-note" id="mxchat_embedding_custom_note"' . ($custom_embeddings_on ? '' : ' style="display:none;"') . '>';
8596 echo esc_html__('Custom provider embeddings are in use — the model is set in the Custom Embedding Model field under Custom Provider.', 'mxchat');
8597 echo '</p>';
8598
8599 // API Key Status Messages for Embedding Models
8600 $has_openai_key = !empty($this->options['api_key']);
8601 $has_voyage_key = !empty($this->options['voyage_api_key']);
8602 $has_gemini_key = !empty($this->options['gemini_api_key']);
8603
8604 // OpenAI Embeddings
8605 echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
8606 if ($has_openai_key) {
8607 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8608 } else {
8609 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8610 }
8611 echo '</p>';
8612
8613 // Voyage AI Embeddings
8614 echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
8615 if ($has_voyage_key) {
8616 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
8617 } else {
8618 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8619 }
8620 echo '</p>';
8621
8622 // Gemini Embeddings
8623 echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
8624 if ($has_gemini_key) {
8625 echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8626 } else {
8627 echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8628 }
8629 echo '</p>';
8630
8631 }
8632
8633
8634 public function mxchat_top_bar_title_callback() {
8635 // Retrieve the current value of the top bar title from saved options
8636 $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
8637
8638 // Render the input field
8639 echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
8640 }
8641 public function mxchat_ai_agent_text_callback() {
8642 // Retrieve the current value of the AI agent text from saved options
8643 $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
8644 // Render the input field
8645 echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
8646 }
8647
8648
8649 public function enable_email_block_callback() {
8650 // Load full plugin options array
8651 $all_options = get_option('mxchat_options', []);
8652
8653 // Get the value, default to 'off'
8654 $enable_email_block = isset($all_options['enable_email_block']) ? $all_options['enable_email_block'] : 'off';
8655
8656 // Check if it's 'on'
8657 $checked = ($enable_email_block === 'on') ? 'checked' : '';
8658
8659 echo '<label class="toggle-switch">';
8660 echo sprintf(
8661 '<input type="checkbox" id="enable_email_block" name="enable_email_block" value="on" %s />',
8662 esc_attr($checked)
8663 );
8664 echo '<span class="slider"></span>';
8665 echo '</label>';
8666 }
8667
8668 public function email_blocker_header_content_callback() {
8669 // Load the entire 'mxchat_options' array
8670 $all_options = get_option('mxchat_options', []);
8671
8672 // Retrieve the saved content or default to empty
8673 $content = isset($all_options['email_blocker_header_content'])
8674 ? $all_options['email_blocker_header_content']
8675 : '';
8676
8677 // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
8678 echo '<textarea
8679 id="email_blocker_header_content"
8680 name="email_blocker_header_content"
8681 rows="5"
8682 cols="70"
8683 data-setting="email_blocker_header_content"
8684 >' . esc_textarea($content) . '</textarea>';
8685 }
8686
8687 public function email_blocker_button_text_callback() {
8688 // Load the entire 'mxchat_options' array
8689 $all_options = get_option('mxchat_options', []);
8690
8691 // Retrieve the saved button text or default to empty
8692 $button_text = isset($all_options['email_blocker_button_text'])
8693 ? $all_options['email_blocker_button_text']
8694 : '';
8695
8696 // Use esc_attr to safely render the existing text
8697 echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
8698 }
8699
8700 //Enable name field callback
8701 public function enable_name_field_callback() {
8702 // Load full plugin options array
8703 $all_options = get_option('mxchat_options', []);
8704 // Get the value, default to 'off'
8705 $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
8706 // Check if it's 'on'
8707 $checked = ($enable_name_field === 'on') ? 'checked' : '';
8708 echo '<label class="toggle-switch">';
8709 echo sprintf(
8710 '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
8711 esc_attr($checked)
8712 );
8713 echo '<span class="slider"></span>';
8714 echo '</label>';
8715 }
8716 //Name field placeholder callback
8717 public function name_field_placeholder_callback() {
8718 $all_options = get_option('mxchat_options', []);
8719 $placeholder = isset($all_options['name_field_placeholder'])
8720 ? $all_options['name_field_placeholder']
8721 : esc_html__('Enter your name', 'mxchat');
8722
8723 echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
8724 }
8725
8726 // Consent checkbox toggle (b062c4)
8727 public function enable_consent_checkbox_callback() {
8728 $all_options = get_option('mxchat_options', []);
8729 $enabled = isset($all_options['enable_consent_checkbox']) ? $all_options['enable_consent_checkbox'] : 'off';
8730 $checked = ($enabled === 'on') ? 'checked' : '';
8731 echo '<label class="toggle-switch">';
8732 echo sprintf(
8733 '<input type="checkbox" id="enable_consent_checkbox" name="enable_consent_checkbox" value="on" %s />',
8734 esc_attr($checked)
8735 );
8736 echo '<span class="slider"></span>';
8737 echo '</label>';
8738 }
8739
8740 // Consent checkbox label (b062c4). Owner content; a safe HTML subset is
8741 // allowed (anchor + inline emphasis) so the Privacy Policy can be linked.
8742 public function consent_checkbox_label_callback() {
8743 $all_options = get_option('mxchat_options', []);
8744 $label = isset($all_options['consent_checkbox_label'])
8745 ? $all_options['consent_checkbox_label']
8746 : __('I agree to the Privacy Policy.', 'mxchat');
8747
8748 echo '<textarea
8749 id="consent_checkbox_label"
8750 name="consent_checkbox_label"
8751 rows="2"
8752 cols="70"
8753 data-setting="consent_checkbox_label"
8754 >' . esc_textarea($label) . '</textarea>';
8755 }
8756
8757 // Consent required toggle (b062c4)
8758 public function consent_checkbox_required_callback() {
8759 $all_options = get_option('mxchat_options', []);
8760 $required = isset($all_options['consent_checkbox_required']) ? $all_options['consent_checkbox_required'] : 'off';
8761 $checked = ($required === 'on') ? 'checked' : '';
8762 echo '<label class="toggle-switch">';
8763 echo sprintf(
8764 '<input type="checkbox" id="consent_checkbox_required" name="consent_checkbox_required" value="on" %s />',
8765 esc_attr($checked)
8766 );
8767 echo '<span class="slider"></span>';
8768 echo '</label>';
8769 }
8770
8771 // Show the pre-chat form to logged-in visitors too (c0cfaf). Default OFF —
8772 // today the form short-circuits on is_user_logged_in(), which means a
8773 // membership or LMS site where everyone is signed in never captures a lead
8774 // and never shows the consent checkbox.
8775 public function lead_capture_logged_in_toggle_callback() {
8776 $all_options = get_option('mxchat_options', []);
8777 $enabled = isset($all_options['lead_capture_logged_in_toggle']) ? $all_options['lead_capture_logged_in_toggle'] : 'off';
8778 $checked = ($enabled === 'on') ? 'checked' : '';
8779 echo '<label class="toggle-switch">';
8780 echo sprintf(
8781 '<input type="checkbox" id="lead_capture_logged_in_toggle" name="lead_capture_logged_in_toggle" value="on" %s />',
8782 esc_attr($checked)
8783 );
8784 echo '<span class="slider"></span>';
8785 echo '</label>';
8786 }
8787
8788 // Require an email address to submit the pre-chat form (c0cfaf). Default ON,
8789 // which is today's behaviour. Turning it off lets an owner collect a name
8790 // (and consent) without demanding an address.
8791 public function lead_capture_require_email_toggle_callback() {
8792 $all_options = get_option('mxchat_options', []);
8793 $required = isset($all_options['lead_capture_require_email_toggle']) ? $all_options['lead_capture_require_email_toggle'] : 'on';
8794 $checked = ($required === 'on') ? 'checked' : '';
8795 echo '<label class="toggle-switch">';
8796 echo sprintf(
8797 '<input type="checkbox" id="lead_capture_require_email_toggle" name="lead_capture_require_email_toggle" value="on" %s />',
8798 esc_attr($checked)
8799 );
8800 echo '<span class="slider"></span>';
8801 echo '</label>';
8802 }
8803
8804
8805
8806 public function mxchat_intro_message_callback() {
8807 // Load the entire 'mxchat_options' array
8808 $all_options = get_option('mxchat_options', []);
8809 // Retrieve the saved intro message or use the default
8810 $default_message = __('Hello! How can I assist you today?', 'mxchat');
8811 $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
8812 // Escape on output (esc_textarea) — neutralizes any payload already stored before the
8813 // Wordfence Stored-XSS fix (CWE-79, plan-3f8158) and prevents </textarea> context-breakout.
8814 ?>
8815 <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea( $saved_message ); ?></textarea>
8816 <p class="description" style="margin-top: 8px;">
8817 <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
8818 <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
8819 </p>
8820 <?php
8821 }
8822
8823 public function mxchat_input_copy_callback() {
8824 // Load the entire 'mxchat_options' array
8825 $all_options = get_option('mxchat_options', []);
8826
8827 // Retrieve the saved input copy or use the default value
8828 $default_copy = __('How can I assist?', 'mxchat');
8829 $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
8830
8831 // Output the input field with the saved value
8832 printf(
8833 '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
8834 esc_attr($input_copy),
8835 esc_attr__('How can I assist?', 'mxchat')
8836 );
8837 }
8838
8839
8840 public function mxchat_append_to_body_callback() {
8841 // Fetch fresh options to ensure we have the latest saved values
8842 $options = get_option('mxchat_options', array());
8843
8844 // Get value from options array, default to 'off'
8845 $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
8846 $checked = ($append_to_body === 'on') ? 'checked' : '';
8847
8848 // Get post type visibility settings
8849 $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
8850 $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
8851 if (!is_array($visibility_list)) {
8852 $visibility_list = array();
8853 }
8854
8855 echo '<div class="mxchat-autosave-section">';
8856
8857 // Main toggle
8858 echo '<label class="toggle-switch">';
8859 echo sprintf(
8860 '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
8861 esc_attr($checked)
8862 );
8863 echo '<span class="slider"></span>';
8864 echo '</label>';
8865
8866 // Post Type Visibility Options (only visible when auto-display is ON)
8867 $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
8868 echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8869
8870 echo '<div class="mxchat-post-type-visibility-header">';
8871 echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
8872 echo '</div>';
8873
8874 // Mode selector (radio buttons)
8875 echo '<div class="mxchat-visibility-mode">';
8876
8877 echo '<label class="mxchat-radio-label">';
8878 echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
8879 echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
8880 echo '</label>';
8881
8882 echo '<label class="mxchat-radio-label">';
8883 echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
8884 echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
8885 echo '</label>';
8886
8887 echo '<label class="mxchat-radio-label">';
8888 echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
8889 echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
8890 echo '</label>';
8891
8892 echo '</div>';
8893
8894 // Post type checkboxes (only visible when mode is include or exclude)
8895 $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
8896 echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
8897
8898 // Get all public post types
8899 $post_types = get_post_types(array('public' => true), 'objects');
8900
8901 foreach ($post_types as $post_type) {
8902 // Skip attachments
8903 if ($post_type->name === 'attachment') {
8904 continue;
8905 }
8906
8907 $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
8908
8909 echo '<label class="mxchat-checkbox-label">';
8910 echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
8911 echo '<span>' . esc_html($post_type->label) . '</span>';
8912 echo '</label>';
8913 }
8914
8915 echo '</div>'; // End post-type-list
8916 echo '</div>'; // End post-type-visibility-options
8917 echo '</div>'; // End mxchat-autosave-section
8918 }
8919
8920 public function mxchat_contextual_awareness_callback() {
8921 // Get value from options array, default to 'off'
8922 $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
8923 $checked = ($contextual_awareness === 'on') ? 'checked' : '';
8924 echo '<label class="toggle-switch">';
8925 echo sprintf(
8926 '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
8927 esc_attr($checked)
8928 );
8929 echo '<span class="slider"></span>';
8930 echo '</label>';
8931 }
8932
8933 public function mxchat_citation_links_toggle_callback() {
8934 // Get value from options array, default to 'on' (enabled by default)
8935 $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
8936 $checked = ($citation_links === 'on') ? 'checked' : '';
8937 echo '<label class="toggle-switch">';
8938 echo sprintf(
8939 '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
8940 esc_attr($checked)
8941 );
8942 echo '<span class="slider"></span>';
8943 echo '</label>';
8944 }
8945
8946 /**
8947 * "Strip unapproved links" toggle (plan 58f8b4). Until the site saves an
8948 * explicit value the rendered state is the install-stamp default — on for
8949 * installs born at 3.2.20+, off for upgrades — so what the admin sees here
8950 * always matches what the response URL guard is actually doing.
8951 */
8952 public function mxchat_strip_unapproved_links_toggle_callback() {
8953 if (isset($this->options['strip_unapproved_links_toggle'])) {
8954 $strip_links = $this->options['strip_unapproved_links_toggle'];
8955 } else {
8956 $strip_links = function_exists('mxchat_strip_unapproved_links_default')
8957 ? mxchat_strip_unapproved_links_default()
8958 : 'off';
8959 }
8960 $checked = ($strip_links === 'on') ? 'checked' : '';
8961 echo '<label class="toggle-switch">';
8962 echo sprintf(
8963 '<input type="checkbox" id="strip_unapproved_links_toggle" name="strip_unapproved_links_toggle" value="on" %s />',
8964 esc_attr($checked)
8965 );
8966 echo '<span class="slider"></span>';
8967 echo '</label>';
8968 }
8969
8970 /**
8971 * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
8972 * Default ON. The widget reads this through the localized object; the
8973 * mxchat_satisfaction_rating_enabled filter still lets developers force
8974 * the value site-wide.
8975 *
8976 * The 5 customization fields (idle/question/thanks/placeholder/saved) are
8977 * rendered inline here inside a single wrapper div whose initial display
8978 * is set server-side from the toggle value (plan-29caac). Mirrors the
8979 * auto-display chatbot pattern at mxchat_append_to_body_callback — no
8980 * DOMContentLoaded race because rows exist as direct children of this
8981 * callback's output, and the wrapper's display: none is inline at render
8982 * time so refresh shows the correct state with no flash.
8983 */
8984 public function mxchat_satisfaction_rating_toggle_callback() {
8985 $options = $this->options;
8986 $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
8987 $checked = ($value === 'on') ? 'checked' : '';
8988
8989 $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
8990 $idle = max(5, min(600, $idle));
8991 $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
8992 $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
8993 $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
8994 $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
8995
8996 echo '<div class="mxchat-autosave-section">';
8997
8998 echo '<label class="toggle-switch">';
8999 echo sprintf(
9000 '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
9001 esc_attr($checked)
9002 );
9003 echo '<span class="slider"></span>';
9004 echo '</label>';
9005
9006 ?>
9007 <style>
9008 .mxchat-sub-options-field { margin: 12px 0; }
9009 .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
9010 #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
9011 </style>
9012 <?php
9013
9014 $display_style = ($value === 'on') ? '' : 'display: none;';
9015 echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
9016
9017 echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
9018
9019 echo '<div class="mxchat-sub-options-field">';
9020 echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
9021 printf(
9022 '<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>',
9023 (int) $idle,
9024 esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
9025 );
9026 echo '</div>';
9027
9028 echo '<div class="mxchat-sub-options-field">';
9029 echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
9030 printf(
9031 '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
9032 esc_attr($question),
9033 esc_attr__('Was this helpful?', 'mxchat')
9034 );
9035 echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
9036 echo '</div>';
9037
9038 echo '<div class="mxchat-sub-options-field">';
9039 echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
9040 printf(
9041 '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
9042 esc_attr($thanks),
9043 esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
9044 );
9045 echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
9046 echo '</div>';
9047
9048 echo '<div class="mxchat-sub-options-field">';
9049 echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
9050 printf(
9051 '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
9052 esc_attr($placeholder),
9053 esc_attr__('Tell us what could be better…', 'mxchat')
9054 );
9055 echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
9056 echo '</div>';
9057
9058 echo '<div class="mxchat-sub-options-field">';
9059 echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
9060 printf(
9061 '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
9062 esc_attr($saved),
9063 esc_attr__('Thanks for the feedback.', 'mxchat')
9064 );
9065 echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
9066 echo '</div>';
9067
9068 echo '</div>'; // #satisfaction-rating-sub-options
9069 echo '</div>'; // .mxchat-autosave-section
9070
9071 ?>
9072 <script>
9073 (function() {
9074 document.addEventListener('DOMContentLoaded', function() {
9075 var toggle = document.getElementById('satisfaction_rating_enabled');
9076 var subOptions = document.getElementById('satisfaction-rating-sub-options');
9077 if (!toggle || !subOptions) return;
9078 toggle.addEventListener('change', function() {
9079 subOptions.style.display = toggle.checked ? '' : 'none';
9080 });
9081 });
9082 })();
9083 </script>
9084 <?php
9085 }
9086
9087 public function mxchat_privacy_toggle_callback() {
9088 // Load from mxchat_options array
9089 $options = get_option('mxchat_options', []);
9090
9091 // Get privacy toggle value with fallback
9092 $privacy_toggle = isset($options['privacy_toggle']) ? $options['privacy_toggle'] : 'off';
9093 $checked = ($privacy_toggle === 'on') ? 'checked' : '';
9094
9095 // Get privacy text with fallback
9096 $privacy_text = isset($options['privacy_text'])
9097 ? $options['privacy_text']
9098 : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
9099
9100 // Output the toggle switch
9101 echo '<label class="toggle-switch">';
9102 echo sprintf(
9103 '<input type="checkbox" id="privacy_toggle" name="privacy_toggle" value="on" %s />',
9104 esc_attr($checked)
9105 );
9106 echo '<span class="slider"></span>';
9107 echo '</label>';
9108
9109 // Output the custom text input field
9110 echo sprintf(
9111 '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
9112 esc_textarea($privacy_text)
9113 );
9114 }
9115
9116
9117 public function mxchat_complianz_toggle_callback() {
9118 // Load from mxchat_options array
9119 $options = get_option('mxchat_options', []);
9120
9121 // Get complianz toggle value with fallback
9122 $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
9123 $checked = ($complianz_toggle === 'on') ? 'checked' : '';
9124
9125 // Output the toggle switch
9126 echo '<label class="toggle-switch">';
9127 echo sprintf(
9128 '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
9129 esc_attr($checked)
9130 );
9131 echo '<span class="slider"></span>';
9132 echo '</label>';
9133 }
9134
9135 public function mxchat_link_target_toggle_callback() {
9136 // Load from mxchat_options array
9137 $options = get_option('mxchat_options', []);
9138
9139 // Get link target toggle value with fallback
9140 $link_target_toggle = isset($options['link_target_toggle']) ? $options['link_target_toggle'] : 'off';
9141 $checked = ($link_target_toggle === 'on') ? 'checked' : '';
9142
9143 // Output the toggle switch
9144 echo '<label class="toggle-switch">';
9145 echo sprintf(
9146 '<input type="checkbox" id="link_target_toggle" name="link_target_toggle" value="on" %s />',
9147 esc_attr($checked)
9148 );
9149 echo '<span class="slider"></span>';
9150 echo '</label>';
9151 }
9152
9153 public function mxchat_chat_persistence_toggle_callback() {
9154 // Load from mxchat_options array
9155 $options = get_option('mxchat_options', []);
9156
9157 // Get chat persistence toggle value with fallback
9158 $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
9159 $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
9160
9161 // Output the toggle switch
9162 echo '<label class="toggle-switch">';
9163 echo sprintf(
9164 '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
9165 esc_attr($checked)
9166 );
9167 echo '<span class="slider"></span>';
9168 echo '</label>';
9169 }
9170
9171 public function mxchat_print_button_toggle_callback() {
9172 // Load from mxchat_options array
9173 $options = get_option('mxchat_options', []);
9174
9175 // Default ON — the option was previously unexposed and the button always showed.
9176 $print_button_enabled = isset($options['print_button_enabled']) ? $options['print_button_enabled'] : 'on';
9177 $checked = ($print_button_enabled === 'on') ? 'checked' : '';
9178
9179 // Output the toggle switch
9180 echo '<label class="toggle-switch">';
9181 echo sprintf(
9182 '<input type="checkbox" id="print_button_enabled" name="print_button_enabled" value="on" %s />',
9183 esc_attr($checked)
9184 );
9185 echo '<span class="slider"></span>';
9186 echo '</label>';
9187 }
9188
9189 /**
9190 * Editor Assistant toggle (plan-8cb0cb). Standalone option, NOT in mxchat_options
9191 * (bypasses the mxchat_sanitize strip-trap + autosave normalization). Default OFF.
9192 * Saved by the mxchat_editor_assistant_enabled case in class-ajax-handler.php.
9193 * Renders on Content → Settings (moved there from Settings → Behavior, plan-f7df40).
9194 */
9195 public function mxchat_editor_assistant_toggle_callback() {
9196 $enabled = get_option('mxchat_editor_assistant_enabled', 'off');
9197 $checked = ($enabled === 'on') ? 'checked' : '';
9198
9199 echo '<label class="toggle-switch">';
9200 echo sprintf(
9201 '<input type="checkbox" id="mxchat_editor_assistant_enabled" name="mxchat_editor_assistant_enabled" value="on" %s />',
9202 esc_attr($checked)
9203 );
9204 echo '<span class="slider"></span>';
9205 echo '</label>';
9206 }
9207
9208 /**
9209 * Hybrid keyword boost toggle (plan-38ffa1; rebuilt on the house toggle pattern
9210 * in plan-64d34f — the hand-rolled .mxch-toggle markup matched neither selector
9211 * the autosave JS uses to place its save confirmation, so the control looked
9212 * dead). Standalone option, NOT in mxchat_options. Default OFF. Saved by the
9213 * mxchat_hybrid_keyword_toggle case in class-ajax-handler.php, which also runs
9214 * capability detection on enable.
9215 */
9216 public function mxchat_hybrid_keyword_toggle_callback() {
9217 $enabled = get_option('mxchat_hybrid_keyword_toggle', 'off');
9218 $checked = ($enabled === 'on') ? 'checked' : '';
9219
9220 echo '<label class="toggle-switch">';
9221 echo sprintf(
9222 '<input type="checkbox" id="mxchat_hybrid_keyword_toggle" name="mxchat_hybrid_keyword_toggle" value="on" %s />',
9223 esc_attr($checked)
9224 );
9225 echo '<span class="slider"></span>';
9226 echo '</label>';
9227 }
9228
9229 /**
9230 * Smart asset loading toggle (plan-915355; rebuilt on the house toggle pattern
9231 * in plan-64d34f, same dead-save-feedback defect as the hybrid keyword toggle).
9232 * Standalone option, NOT in mxchat_options. Default OFF. Saved by the
9233 * mxchat_smart_asset_loading case in class-ajax-handler.php.
9234 */
9235 public function mxchat_smart_asset_loading_toggle_callback() {
9236 $enabled = get_option('mxchat_smart_asset_loading', 'off');
9237 $checked = ($enabled === 'on') ? 'checked' : '';
9238
9239 echo '<label class="toggle-switch">';
9240 echo sprintf(
9241 '<input type="checkbox" id="mxchat_smart_asset_loading" name="mxchat_smart_asset_loading" value="on" %s />',
9242 esc_attr($checked)
9243 );
9244 echo '<span class="slider"></span>';
9245 echo '</label>';
9246 }
9247
9248 public function mxchat_reset_chat_toggle_callback() {
9249 // Load from mxchat_options array. plan ac2e81 — default OFF (new, opt-in).
9250 $options = get_option('mxchat_options', []);
9251 $reset_chat_enabled = isset($options['reset_chat_enabled']) ? $options['reset_chat_enabled'] : 'off';
9252 $checked = ($reset_chat_enabled === 'on') ? 'checked' : '';
9253
9254 echo '<label class="toggle-switch">';
9255 echo sprintf(
9256 '<input type="checkbox" id="reset_chat_enabled" name="reset_chat_enabled" value="on" %s />',
9257 esc_attr($checked)
9258 );
9259 echo '<span class="slider"></span>';
9260 echo '</label>';
9261 }
9262
9263 public function mxchat_reset_chat_label_callback() {
9264 // Editable label for the "Start new chat" menu item. plan ac2e81.
9265 $options = get_option('mxchat_options', []);
9266 $reset_chat_label = isset($options['reset_chat_label']) ? $options['reset_chat_label'] : '';
9267
9268 printf(
9269 '<input type="text" id="reset_chat_label" name="reset_chat_label" value="%s" placeholder="%s" class="regular-text" />',
9270 esc_attr($reset_chat_label),
9271 esc_attr__('Start new chat', 'mxchat')
9272 );
9273 }
9274
9275 public function mxchat_popular_question_1_callback() {
9276 // Load the full plugin options array
9277 $all_options = get_option('mxchat_options', []);
9278
9279 // Retrieve the specific option for popular_question_1
9280 $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
9281
9282 // Render the input field
9283 printf(
9284 '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
9285 esc_attr($popular_question_1),
9286 esc_attr__('Enter Quick Question 1', 'mxchat')
9287 );
9288 }
9289
9290
9291 public function mxchat_popular_question_2_callback() {
9292 // Load the full plugin options array
9293 $all_options = get_option('mxchat_options', []);
9294
9295 // Retrieve the specific option for popular_question_2
9296 $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
9297
9298 // Render the input field
9299 printf(
9300 '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
9301 esc_attr($popular_question_2),
9302 esc_attr__('Enter Quick Question 2', 'mxchat')
9303 );
9304 }
9305
9306
9307 public function mxchat_popular_question_3_callback() {
9308 // Load the full plugin options array
9309 $all_options = get_option('mxchat_options', []);
9310
9311 // Retrieve the specific option for popular_question_3
9312 $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
9313
9314 // Render the input field
9315 printf(
9316 '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
9317 esc_attr($popular_question_3),
9318 esc_attr(__('Enter Quick Question 3', 'mxchat'))
9319 );
9320 }
9321
9322 public function mxchat_additional_popular_questions_callback() {
9323 $options = get_option('mxchat_options', []);
9324 $additional_questions = isset($options['additional_popular_questions'])
9325 ? $options['additional_popular_questions']
9326 : get_option('additional_popular_questions', array());
9327
9328 echo '<div id="mxchat-additional-questions-container">';
9329 if (!empty($additional_questions)) {
9330 foreach ($additional_questions as $index => $question) {
9331 printf(
9332 '<div class="mxchat-question-row">
9333 <input type="text" name="additional_popular_questions[]"
9334 value="%s"
9335 placeholder="%s"
9336 class="regular-text mxchat-question-input"
9337 data-question-index="%d" />
9338 <button type="button" class="button mxchat-remove-question"
9339 aria-label="%s">%s</button>
9340 </div>',
9341 esc_attr($question),
9342 esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
9343 $index,
9344 esc_attr(__('Remove question', 'mxchat')),
9345 esc_html__('Remove', 'mxchat')
9346 );
9347 }
9348 } else {
9349 printf(
9350 '<div class="mxchat-question-row">
9351 <input type="text" name="additional_popular_questions[]"
9352 value=""
9353 placeholder="%s"
9354 class="regular-text mxchat-question-input"
9355 data-question-index="0" />
9356 <button type="button" class="button mxchat-remove-question"
9357 aria-label="%s">%s</button>
9358 </div>',
9359 esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
9360 esc_attr(__('Remove question', 'mxchat')),
9361 esc_html__('Remove', 'mxchat')
9362 );
9363 }
9364 echo '</div>';
9365 printf(
9366 '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
9367 esc_attr(__('Add question', 'mxchat')),
9368 esc_html__('Add Question', 'mxchat')
9369 );
9370 }
9371
9372 public function mxchat_brave_api_key_callback() {
9373 $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
9374 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9375
9376 echo '<div class="api-key-wrapper">';
9377 echo sprintf(
9378 '<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" />',
9379 $brave_api_key,
9380 $nonce
9381 );
9382 echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9383 echo '</div>';
9384 echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
9385 }
9386
9387 public function mxchat_brave_image_count_callback() {
9388 $brave_image_count = isset($this->options['brave_image_count'])
9389 ? intval($this->options['brave_image_count'])
9390 : 4;
9391 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9392
9393 echo '<div class="mxchat-field-wrapper">';
9394 echo sprintf(
9395 '<input type="number" id="brave_image_count" name="brave_image_count"
9396 value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9397 $brave_image_count,
9398 $nonce
9399 );
9400 echo '</div>';
9401 echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
9402 }
9403
9404 public function mxchat_brave_safe_search_callback() {
9405 $brave_safe_search = isset($this->options['brave_safe_search'])
9406 ? esc_attr($this->options['brave_safe_search'])
9407 : 'strict';
9408 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9409
9410 echo '<div class="mxchat-field-wrapper">';
9411 echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
9412 echo sprintf(
9413 '<option value="strict" %s>%s</option>',
9414 selected($brave_safe_search, 'strict', false),
9415 __('Strict', 'mxchat')
9416 );
9417 echo sprintf(
9418 '<option value="off" %s>%s</option>',
9419 selected($brave_safe_search, 'off', false),
9420 __('Off', 'mxchat')
9421 );
9422 echo '</select>';
9423 echo '</div>';
9424 echo '<p class="description">' .
9425 esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
9426 '</p>';
9427 }
9428
9429 public function mxchat_brave_news_count_callback() {
9430 $brave_news_count = isset($this->options['brave_news_count'])
9431 ? intval($this->options['brave_news_count'])
9432 : 3;
9433 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9434
9435 echo '<div class="mxchat-field-wrapper">';
9436 echo sprintf(
9437 '<input type="number" id="brave_news_count" name="brave_news_count"
9438 value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9439 $brave_news_count,
9440 $nonce
9441 );
9442 echo '</div>';
9443 echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
9444 }
9445
9446 public function mxchat_brave_country_callback() {
9447 $brave_country = isset($this->options['brave_country'])
9448 ? esc_attr($this->options['brave_country'])
9449 : 'us';
9450 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9451
9452 echo '<div class="mxchat-field-wrapper">';
9453 echo sprintf(
9454 '<input type="text" id="brave_country" name="brave_country"
9455 value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9456 $brave_country,
9457 $nonce
9458 );
9459 echo '</div>';
9460 echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
9461 }
9462
9463 public function mxchat_brave_language_callback() {
9464 $brave_language = isset($this->options['brave_language'])
9465 ? esc_attr($this->options['brave_language'])
9466 : 'en';
9467 $nonce = wp_create_nonce('mxchat_autosave_nonce');
9468
9469 echo '<div class="mxchat-field-wrapper">';
9470 echo sprintf(
9471 '<input type="text" id="brave_language" name="brave_language"
9472 value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9473 $brave_language,
9474 $nonce
9475 );
9476 echo '</div>';
9477 echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
9478 }
9479
9480
9481
9482
9483
9484 // Section Callback
9485 public function mxchat_pdf_intent_section_callback() {
9486 echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
9487 }
9488
9489 public function mxchat_chat_toolbar_toggle_callback() {
9490 // Get chat toolbar toggle value with fallback
9491 $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
9492 $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
9493
9494 // Output the toggle switch
9495 echo '<label class="toggle-switch">';
9496 echo sprintf(
9497 '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
9498 esc_attr($checked)
9499 );
9500 echo '<span class="slider"></span>';
9501 echo '</label>';
9502
9503 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>';
9504 }
9505
9506 /**
9507 * Callback for PDF upload button toggle setting
9508 */
9509 public function mxchat_show_pdf_upload_button_callback() {
9510 // Get toggle value with fallback
9511 $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
9512 $checked = ($show_pdf_button === 'on') ? 'checked' : '';
9513
9514 // Output the toggle switch
9515 echo '<label class="toggle-switch">';
9516 echo sprintf(
9517 '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
9518 esc_attr($checked)
9519 );
9520 echo '<span class="slider"></span>';
9521 echo '</label>';
9522
9523 echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
9524 }
9525
9526 /**
9527 * Callback for Word upload button toggle setting
9528 */
9529 public function mxchat_show_word_upload_button_callback() {
9530 // Get toggle value with fallback
9531 $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
9532 $checked = ($show_word_button === 'on') ? 'checked' : '';
9533
9534 // Output the toggle switch
9535 echo '<label class="toggle-switch">';
9536 echo sprintf(
9537 '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
9538 esc_attr($checked)
9539 );
9540 echo '<span class="slider"></span>';
9541 echo '</label>';
9542
9543 echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
9544 }
9545
9546 public function mxchat_pdf_intent_trigger_text_callback() {
9547 $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
9548
9549 echo sprintf(
9550 '<textarea id="pdf_intent_trigger_text"
9551 name="pdf_intent_trigger_text"
9552 rows="3"
9553 cols="50"
9554 placeholder="%s">%s</textarea>',
9555 esc_attr__('Enter trigger text', 'mxchat'),
9556 isset($this->options['pdf_intent_trigger_text'])
9557 ? esc_textarea($this->options['pdf_intent_trigger_text'])
9558 : esc_textarea($default_text)
9559 );
9560 echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
9561 }
9562
9563 public function mxchat_pdf_intent_success_text_callback() {
9564 $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
9565
9566 echo sprintf(
9567 '<textarea id="pdf_intent_success_text"
9568 name="pdf_intent_success_text"
9569 rows="3"
9570 cols="50"
9571 placeholder="%s">%s</textarea>',
9572 esc_attr__('Enter success text', 'mxchat'),
9573 isset($this->options['pdf_intent_success_text'])
9574 ? esc_textarea($this->options['pdf_intent_success_text'])
9575 : esc_textarea($default_text)
9576 );
9577 echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
9578 }
9579
9580 public function mxchat_pdf_intent_error_text_callback() {
9581 $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
9582
9583 echo sprintf(
9584 '<textarea id="pdf_intent_error_text"
9585 name="pdf_intent_error_text"
9586 rows="3"
9587 cols="50"
9588 placeholder="%s">%s</textarea>',
9589 esc_attr__('Enter error text', 'mxchat'),
9590 isset($this->options['pdf_intent_error_text'])
9591 ? esc_textarea($this->options['pdf_intent_error_text'])
9592 : esc_textarea($default_text)
9593 );
9594 echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
9595 }
9596
9597 public function mxchat_pdf_max_pages_callback() {
9598 $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
9599
9600 echo sprintf(
9601 '<input type="range"
9602 id="pdf_max_pages"
9603 name="pdf_max_pages"
9604 min="1"
9605 max="69"
9606 value="%d"
9607 class="range-slider" />',
9608 esc_attr($max_pages)
9609 );
9610 echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
9611 echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
9612 }
9613
9614 public function mxchat_live_agent_status_callback() {
9615 // Always get fresh options instead of using cached $this->options
9616 $fresh_options = get_option('mxchat_options');
9617 $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
9618
9619 echo '<label class="toggle-switch">';
9620 echo sprintf(
9621 '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
9622 checked($status, 'on', false)
9623 );
9624 echo '<span class="slider"></span>';
9625 echo '</label>';
9626 echo '<label for="live_agent_status" class="mxchat-status-label">';
9627 echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9628 echo '</label>';
9629 }
9630
9631 /**
9632 * Availability-schedule editor (plans 8ccaa2 + 99d7a4).
9633 *
9634 * ONE callback, parameterized by channel ('slack' | 'telegram' via the
9635 * add_settings_field $args) — the markup and CSS are shared, only the bound
9636 * option and the helper text differ. Each channel's editor renders under its
9637 * own Integrations tab and governs ONLY that channel's handoff. While the
9638 * master toggle is off the day grid is inert and handoff availability stays
9639 * governed solely by that channel's manual status toggle.
9640 *
9641 * The day inputs carry NO name attribute and are marked .mxchat-la-field so the
9642 * generic autosave skips them; the editor JS folds them into the channel's
9643 * hidden live_agent_schedule_<channel> input and fires one change, reusing the
9644 * existing autosave transport rather than growing a second one. All hooks the
9645 * JS needs are CLASSES scoped inside .mxchat-la-schedule, never ids — the
9646 * markup exists twice on the page.
9647 */
9648 public function mxchat_live_agent_schedule_callback($args = array()) {
9649 if (!class_exists('MxChat_Live_Agent_Schedule')) {
9650 return;
9651 }
9652 $channel = (isset($args['channel']) && in_array($args['channel'], MxChat_Live_Agent_Schedule::channels(), true))
9653 ? $args['channel']
9654 : 'slack';
9655 $field = 'live_agent_schedule_' . $channel;
9656 $sched = MxChat_Live_Agent_Schedule::get($channel);
9657 $labels = MxChat_Live_Agent_Schedule::day_labels();
9658 $tz = MxChat_Live_Agent_Schedule::timezone_label();
9659 $enabled = !empty($sched['enabled']);
9660 $channel_labels = array(
9661 'slack' => __('Slack', 'mxchat'),
9662 'telegram' => __('Telegram', 'mxchat'),
9663 'webhook' => __('Webhook', 'mxchat'),
9664 );
9665 $channel_label = $channel_labels[$channel];
9666 ?>
9667 <div class="mxchat-la-schedule<?php echo $enabled ? ' is-active' : ''; ?>"
9668 id="mxchat-la-schedule-<?php echo esc_attr($channel); ?>"
9669 data-channel="<?php echo esc_attr($channel); ?>">
9670 <label class="toggle-switch">
9671 <input type="checkbox" id="<?php echo esc_attr($field); ?>_enabled"
9672 class="mxchat-la-field mxchat-la-enabled" <?php checked($enabled); ?> />
9673 <span class="slider"></span>
9674 </label>
9675 <label for="<?php echo esc_attr($field); ?>_enabled" class="mxchat-status-label">
9676 <span class="status-text mxchat-la-status-text">
9677 <?php echo $enabled
9678 ? esc_html__('Scheduled hours', 'mxchat')
9679 : esc_html__('Always available', 'mxchat'); ?>
9680 </span>
9681 </label>
9682
9683 <div class="mxchat-la-days" aria-hidden="<?php echo $enabled ? 'false' : 'true'; ?>">
9684 <?php foreach ($labels as $n => $label) :
9685 $day = $sched['days'][$n];
9686 $on = !empty($day['enabled']);
9687 ?>
9688 <div class="mxchat-la-day<?php echo $on ? ' is-on' : ''; ?>" data-day="<?php echo esc_attr($n); ?>">
9689 <label class="mxchat-la-day-label">
9690 <input type="checkbox" class="mxchat-la-field mxchat-la-day-enabled"
9691 data-day="<?php echo esc_attr($n); ?>" <?php checked($on); ?> />
9692 <span class="mxchat-la-day-name"><?php echo esc_html($label); ?></span>
9693 </label>
9694 <div class="mxchat-la-times">
9695 <input type="time" class="mxchat-la-field mxchat-la-start"
9696 data-day="<?php echo esc_attr($n); ?>"
9697 value="<?php echo esc_attr($day['start']); ?>"
9698 aria-label="<?php echo esc_attr(sprintf(__('%s start time', 'mxchat'), $label)); ?>" />
9699 <span class="mxchat-la-dash">&ndash;</span>
9700 <input type="time" class="mxchat-la-field mxchat-la-end"
9701 data-day="<?php echo esc_attr($n); ?>"
9702 value="<?php echo esc_attr($day['end']); ?>"
9703 aria-label="<?php echo esc_attr(sprintf(__('%s end time', 'mxchat'), $label)); ?>" />
9704 </div>
9705 </div>
9706 <?php endforeach; ?>
9707 </div>
9708
9709 <input type="hidden" name="<?php echo esc_attr($field); ?>" id="<?php echo esc_attr($field); ?>"
9710 class="mxchat-la-hidden" value="<?php echo esc_attr(wp_json_encode($sched)); ?>" />
9711 </div>
9712 <p class="description">
9713 <?php printf(
9714 /* translators: 1: the handoff channel, e.g. Slack or Telegram; 2: the site's timezone, e.g. America/New_York */
9715 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'),
9716 '<strong>' . esc_html($channel_label) . '</strong>',
9717 '<strong>' . esc_html($tz) . '</strong>'
9718 ); ?>
9719 </p>
9720 <?php
9721 }
9722
9723 public function mxchat_live_agent_away_message_callback() {
9724 $message = isset($this->options['live_agent_away_message'])
9725 ? $this->options['live_agent_away_message']
9726 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9727
9728 printf(
9729 '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
9730 esc_textarea($message)
9731 );
9732 echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9733 }
9734
9735 public function mxchat_live_agent_notification_message_callback() {
9736 $message = isset($this->options['live_agent_notification_message'])
9737 ? $this->options['live_agent_notification_message']
9738 : __('Live agent has been notified.', 'mxchat');
9739
9740 printf(
9741 '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
9742 esc_textarea($message)
9743 );
9744 echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9745 }
9746
9747 public function mxchat_live_agent_webhook_url_callback() {
9748 $webhook_url = isset($this->options['live_agent_webhook_url'])
9749 ? esc_url($this->options['live_agent_webhook_url'])
9750 : esc_url(get_option('live_agent_webhook_url', ''));
9751
9752 printf(
9753 '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
9754 $webhook_url
9755 );
9756 echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9757 echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
9758 }
9759
9760 public function mxchat_live_agent_secret_key_callback() {
9761 printf(
9762 '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
9763 isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
9764 );
9765 echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9766 echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
9767 }
9768
9769 public function mxchat_live_agent_bot_token_callback() {
9770 printf(
9771 '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
9772 isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
9773 );
9774 echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9775 echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
9776
9777 // Surface the last live-agent post Slack refused (plan 2a4ab7). Slack
9778 // answers a refused post with HTTP 200, so before this existed a deleted
9779 // or archived channel or a revoked token failed with no trace anywhere.
9780 // The next successful post clears it.
9781 $slack_error = get_option('mxchat_slack_last_error');
9782 if (is_array($slack_error) && !empty($slack_error['error'])) {
9783 $slack_error_time = !empty($slack_error['time'])
9784 ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $slack_error['time'])
9785 : __('unknown time', 'mxchat');
9786 if (!empty($slack_error['channel'])) {
9787 $slack_error_text = sprintf(
9788 /* translators: 1: Slack API error code, 2: Slack channel ID, 3: local date and time of the failure */
9789 __('Slack said "%1$s" for channel %2$s (%3$s). The visitor was told the message could not be delivered. Check that the channel still exists and is not archived, that the bot is in it, and that the token above is still valid.', 'mxchat'),
9790 $slack_error['error'],
9791 $slack_error['channel'],
9792 $slack_error_time
9793 );
9794 } else {
9795 $slack_error_text = sprintf(
9796 /* translators: 1: Slack API error code, 2: local date and time of the failure */
9797 __('Slack said "%1$s" (%2$s). The visitor was told the message could not be delivered. Check that the token above is still valid.', 'mxchat'),
9798 $slack_error['error'],
9799 $slack_error_time
9800 );
9801 }
9802 echo '<p class="description"><strong>' . esc_html__('⚠ Last delivery error', 'mxchat') . '</strong> — ' . esc_html($slack_error_text) . '</p>';
9803 }
9804 }
9805
9806 public function mxchat_live_agent_user_ids_callback() {
9807 $user_ids = isset($this->options['live_agent_user_ids'])
9808 ? esc_textarea($this->options['live_agent_user_ids'])
9809 : '';
9810
9811 printf(
9812 '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
9813 $user_ids
9814 );
9815 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>';
9816 }
9817
9818 public function mxchat_live_agent_shared_channel_callback() {
9819 $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : '';
9820 printf(
9821 '<input type="text" id="live_agent_shared_channel" name="live_agent_shared_channel" value="%s" class="regular-text" placeholder="#support or C0123456789" />',
9822 esc_attr($value)
9823 );
9824 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>';
9825
9826 // Surface the last failed handoff so a wrong name / missing invite is
9827 // visible right where it gets fixed. A successful handoff clears this.
9828 $shared_error = get_option('mxchat_slack_shared_channel_error');
9829 if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) {
9830 echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . '</strong> — '
9831 . esc_html(sprintf(
9832 /* translators: %s: Slack API error code */
9833 __('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'),
9834 $shared_error['error']
9835 )) . '</p>';
9836 }
9837
9838 // Private-channel warning (plan 1a2666), recorded by the privacy probe at
9839 // configuration time or when the channel id first resolves. Posting INTO
9840 // a private channel works once the bot is a member, so everything looks
9841 // configured — but Slack delivers inbound replies from private channels
9842 // as message.groups events, which the documented app setup never
9843 // subscribes to, and agent replies silently never reach the visitor.
9844 $shared_privacy = get_option('mxchat_slack_shared_channel_privacy');
9845 if (!empty($shared_privacy['is_private']) && trim((string) $value) !== '' && ($shared_privacy['configured'] ?? '') === trim((string) $value)) {
9846 echo '<p class="description"><strong>' . esc_html__('⚠ This is a private channel', 'mxchat') . '</strong> — '
9847 . esc_html__('Slack sends replies from private channels as message.groups events. In your Slack app, add the groups:history scope and subscribe to the message.groups bot event (alongside message.channels), then reinstall the app — otherwise agent replies posted here never reach your visitors.', 'mxchat') . '</p>';
9848 }
9849 }
9850
9851 public function mxchat_live_agent_archive_on_end_callback() {
9852 $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off';
9853 printf(
9854 '<input type="checkbox" id="live_agent_archive_on_end_toggle" name="live_agent_archive_on_end_toggle" value="on" %s />',
9855 checked('on', $value, false)
9856 );
9857 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>';
9858 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>';
9859 }
9860
9861 /**
9862 * Telegram Integration Callbacks
9863 */
9864 public function mxchat_telegram_section_callback() {
9865 echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
9866 }
9867
9868 public function mxchat_telegram_status_callback() {
9869 $fresh_options = get_option('mxchat_options');
9870 $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
9871
9872 echo '<label class="toggle-switch">';
9873 echo sprintf(
9874 '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
9875 checked($status, 'on', false)
9876 );
9877 echo '<span class="slider"></span>';
9878 echo '</label>';
9879 echo '<label for="telegram_status" class="mxchat-status-label">';
9880 echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9881 echo '</label>';
9882 }
9883
9884 public function mxchat_telegram_notification_message_callback() {
9885 $message = isset($this->options['telegram_notification_message'])
9886 ? $this->options['telegram_notification_message']
9887 : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
9888
9889 printf(
9890 '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
9891 esc_textarea($message)
9892 );
9893 echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9894 }
9895
9896 public function mxchat_telegram_away_message_callback() {
9897 $message = isset($this->options['telegram_away_message'])
9898 ? $this->options['telegram_away_message']
9899 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9900
9901 printf(
9902 '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
9903 esc_textarea($message)
9904 );
9905 echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9906 }
9907
9908 public function mxchat_telegram_bot_token_callback() {
9909 printf(
9910 '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
9911 isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
9912 );
9913 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>';
9914 echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
9915 }
9916
9917 public function mxchat_telegram_group_id_callback() {
9918 printf(
9919 '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
9920 isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
9921 );
9922 echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
9923
9924 // Surface the last failed Telegram API call right where it gets fixed
9925 // (plan 1aeee3). Before this existed every Telegram response was
9926 // discarded — a wrong group id, a closed topic, or an oversized handoff
9927 // all failed with no trace anywhere. Kept until the next failure
9928 // overwrites it; the timestamp shows how stale it is.
9929 $tg_error = get_option('mxchat_telegram_last_error');
9930 if (!empty($tg_error['error'])) {
9931 echo '<p class="description"><strong>' . esc_html__('⚠ Last Telegram API failure', 'mxchat') . '</strong> — '
9932 . esc_html(sprintf(
9933 /* translators: 1: Telegram API method name, 2: Telegram's error description, 3: local date and time of the failure */
9934 __('%1$s failed with "%2$s" (%3$s). If live agent chat is working now, this may be from an earlier misconfiguration.', 'mxchat'),
9935 $tg_error['method'] ?? 'sendMessage',
9936 $tg_error['error'],
9937 !empty($tg_error['time']) ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $tg_error['time']) : __('unknown time', 'mxchat')
9938 )) . '</p>';
9939 }
9940
9941 // The inbound counterpart of the line above (plan 30398e): outbound tells you
9942 // MxChat could not reach Telegram, this one tells you Telegram reached MxChat
9943 // and was turned away. That failure previously left nothing behind but a
9944 // single error_log() line, so a Cloudflare-fronted install with no secret set
9945 // dropped every agent reply with no admin-side trace at all. Cleared
9946 // automatically by the first accepted request.
9947 $tg_rejects = get_option('mxchat_telegram_webhook_rejects');
9948 if (is_array($tg_rejects) && !empty($tg_rejects['count'])) {
9949 $reject_count = (int) $tg_rejects['count'];
9950 echo '<p class="description" style="color:#b32d2e;"><strong>' . esc_html__('⚠ Incoming Telegram webhook requests are being rejected', 'mxchat') . '</strong> — '
9951 . esc_html(sprintf(
9952 /* translators: 1: number of rejected requests, 2: local date and time of the most recent rejection */
9953 _n(
9954 '%1$s request rejected, most recently %2$s. Agent replies are not reaching visitors.',
9955 '%1$s requests rejected, most recently %2$s. Agent replies are not reaching visitors.',
9956 $reject_count,
9957 'mxchat'
9958 ),
9959 number_format_i18n($reject_count),
9960 !empty($tg_rejects['last_ts']) ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $tg_rejects['last_ts']) : __('unknown time', 'mxchat')
9961 ))
9962 . ' ' . esc_html($this->mxchat_telegram_reject_advice($tg_rejects['last_reason'] ?? ''))
9963 . '</p>';
9964 }
9965 }
9966
9967 public function mxchat_telegram_webhook_secret_callback() {
9968 $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
9969
9970 // Auto-generate secret if empty
9971 if (empty($secret)) {
9972 $secret = wp_generate_password(64, false, false);
9973 $options = get_option('mxchat_options', []);
9974 $options['telegram_webhook_secret'] = $secret;
9975 update_option('mxchat_options', $options);
9976 $this->options['telegram_webhook_secret'] = $secret;
9977 }
9978
9979 printf(
9980 '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
9981 esc_attr($secret)
9982 );
9983 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>';
9984 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>';
9985 }
9986
9987 /**
9988 * Webhook Handoff Callbacks (plan d88e22)
9989 */
9990 public function mxchat_webhook_handoff_section_callback() {
9991 echo '<p>' . esc_html__('Send live-agent handoffs to any URL you choose — your helpdesk, an automation flow, a CRM.', 'mxchat') . '</p>';
9992 }
9993
9994 public function mxchat_webhook_handoff_status_callback() {
9995 $fresh_options = get_option('mxchat_options');
9996 $status = isset($fresh_options['webhook_handoff_status']) ? $fresh_options['webhook_handoff_status'] : 'off';
9997
9998 echo '<label class="toggle-switch">';
9999 echo sprintf(
10000 '<input type="checkbox" id="webhook_handoff_status" name="webhook_handoff_status" value="on" %s />',
10001 checked($status, 'on', false)
10002 );
10003 echo '<span class="slider"></span>';
10004 echo '</label>';
10005 echo '<label for="webhook_handoff_status" class="mxchat-status-label">';
10006 echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
10007 echo '</label>';
10008 }
10009
10010 public function mxchat_webhook_handoff_notification_message_callback() {
10011 $message = isset($this->options['webhook_handoff_notification_message'])
10012 ? $this->options['webhook_handoff_notification_message']
10013 : __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat');
10014
10015 printf(
10016 '<textarea id="webhook_handoff_notification_message" name="webhook_handoff_notification_message" rows="3" cols="50">%s</textarea>',
10017 esc_textarea($message)
10018 );
10019 echo '<p class="description">' . esc_html__('Message shown after the handoff is delivered. The chat stays in AI mode — your team follows up separately, so let the visitor know what to expect.', 'mxchat') . '</p>';
10020 }
10021
10022 public function mxchat_webhook_handoff_away_message_callback() {
10023 $message = isset($this->options['webhook_handoff_away_message'])
10024 ? $this->options['webhook_handoff_away_message']
10025 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
10026
10027 printf(
10028 '<textarea id="webhook_handoff_away_message" name="webhook_handoff_away_message" rows="3" cols="50">%s</textarea>',
10029 esc_textarea($message)
10030 );
10031 echo '<p class="description">' . esc_html__('Message shown when this destination is offline or outside its scheduled hours.', 'mxchat') . '</p>';
10032 }
10033
10034 public function mxchat_webhook_handoff_url_callback() {
10035 $value = isset($this->options['webhook_handoff_url']) ? $this->options['webhook_handoff_url'] : '';
10036 printf(
10037 '<input type="url" id="webhook_handoff_url" name="webhook_handoff_url" value="%s" class="regular-text" placeholder="https://example.com/hooks/mxchat" />',
10038 esc_attr($value)
10039 );
10040 echo '<p class="description">' . esc_html__('Where handoffs are sent as a JSON POST. Must be https and publicly reachable (localhost and private-network hosts are rejected).', 'mxchat') . '</p>';
10041
10042 // Surface the last failed delivery right where it gets fixed — a handoff
10043 // that silently 404s is worse than no handoff. A successful one clears this.
10044 $webhook_error = get_option('mxchat_webhook_handoff_error');
10045 if (!empty($webhook_error['error']) && trim((string) $value) !== '' && ($webhook_error['configured'] ?? '') === trim((string) $value)) {
10046 echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this URL', 'mxchat') . '</strong> — '
10047 . esc_html(sprintf(
10048 /* translators: %s: the delivery failure, e.g. an HTTP status or a transport error */
10049 __('the request failed with "%s". Until this is fixed, the chatbot answers these conversations itself instead of telling visitors a human was notified.', 'mxchat'),
10050 $webhook_error['error']
10051 )) . '</p>';
10052 }
10053 }
10054
10055 public function mxchat_webhook_handoff_secret_callback() {
10056 printf(
10057 '<input type="password" id="webhook_handoff_secret" name="webhook_handoff_secret" value="%s" class="regular-text" />',
10058 isset($this->options['webhook_handoff_secret']) ? esc_attr($this->options['webhook_handoff_secret']) : ''
10059 );
10060 echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'webhook_handoff_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>';
10061 echo '<p class="description">' . esc_html__('Optional. When set, each POST carries an X-MxChat-Signature header (sha256 HMAC of the body) so your endpoint can verify the sender. The secret itself is never sent.', 'mxchat') . '</p>';
10062 }
10063
10064 public function mxchat_similarity_threshold_callback() {
10065 // Load from mxchat_options array
10066 $options = get_option('mxchat_options', []);
10067
10068 // Get value from options array with default of 35
10069 $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
10070
10071 echo '<div class="slider-container">';
10072 echo sprintf(
10073 '<input type="range"
10074 id="similarity_threshold"
10075 name="similarity_threshold"
10076 min="20"
10077 max="85"
10078 step="1"
10079 value="%s"
10080 class="range-slider" />',
10081 esc_attr($threshold)
10082 );
10083 echo sprintf(
10084 '<span id="threshold_value" class="range-value">%s</span>',
10085 esc_html($threshold)
10086 );
10087 echo '</div>';
10088 }
10089
10090 public function mxchat_max_input_length_callback() {
10091 // Load from mxchat_options array (plan a3fae2 part C).
10092 $options = get_option('mxchat_options', []);
10093
10094 // 0 = unlimited (default — preserves current behavior, no cap).
10095 $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0;
10096
10097 echo sprintf(
10098 '<input type="number"
10099 id="max_input_length"
10100 name="max_input_length"
10101 min="0"
10102 max="100000"
10103 step="1"
10104 value="%s"
10105 placeholder="0"
10106 class="mxch-input mxch-input-sm" />',
10107 esc_attr($max_input_length)
10108 );
10109 }
10110
10111 public function mxchat_rag_sources_limit_callback() {
10112 // Load from mxchat_options array
10113 $options = get_option('mxchat_options', []);
10114
10115 // Get value from options array with default of 3
10116 $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
10117
10118 echo '<div class="slider-container">';
10119 echo sprintf(
10120 '<input type="range"
10121 id="rag_sources_limit"
10122 name="rag_sources_limit"
10123 min="3"
10124 max="10"
10125 step="1"
10126 value="%s"
10127 class="range-slider" />',
10128 esc_attr($rag_sources_limit)
10129 );
10130 echo sprintf(
10131 '<span id="rag_sources_limit_value" class="range-value">%s</span>',
10132 esc_html($rag_sources_limit)
10133 );
10134 echo '</div>';
10135 }
10136
10137 public function mxchat_rag_chunks_limit_callback() {
10138 // Load from mxchat_options array
10139 $options = get_option('mxchat_options', []);
10140
10141 // Get value from options array with default of 15
10142 $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
10143
10144 echo '<div class="slider-container">';
10145 echo sprintf(
10146 '<input type="range"
10147 id="rag_chunks_limit"
10148 name="rag_chunks_limit"
10149 min="8"
10150 max="20"
10151 step="1"
10152 value="%s"
10153 class="range-slider" />',
10154 esc_attr($rag_chunks_limit)
10155 );
10156 echo sprintf(
10157 '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
10158 esc_html($rag_chunks_limit)
10159 );
10160 echo '</div>';
10161 }
10162
10163 /**
10164 * Add body class on the Onboarding wizard page so CSS-only chrome surgery
10165 * (collapsing the WP admin sidebar) only applies on this page.
10166 * Plan: plan-mxchat-20260527-905439.
10167 */
10168 public function mxchat_add_onboarding_body_class($classes) {
10169 if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') {
10170 $classes .= ' mxchat-onboarding-focused';
10171 }
10172 return $classes;
10173 }
10174
10175 public function mxchat_enqueue_admin_assets($hook_suffix = '') {
10176 // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY
10177 // guard here was the strpos() on $_GET['page'] below — which is
10178 // attacker-controlled — so ANY logged-in user (Subscriber included) could
10179 // load a page they are legitimately allowed to see, e.g.
10180 // /wp-admin/profile.php?page=mxchat, and receive every nonce this method
10181 // localizes. Three of the handlers behind those nonces verified the nonce
10182 // but checked no capability. Every MxChat menu page is registered
10183 // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for
10184 // legitimate users.
10185 if (!current_user_can('manage_options')) {
10186 return;
10187 }
10188
10189 // Get plugin version
10190 $version = MXCHAT_VERSION;
10191
10192 // Use file modification time for development (remove in production)
10193 if (defined('WP_DEBUG') && WP_DEBUG) {
10194 $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
10195 }
10196
10197 $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
10198 $plugin_url = plugin_dir_url(__FILE__) . '../';
10199
10200 // Only load on MxChat pages. Prefer the server-derived $hook_suffix that
10201 // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be
10202 // forged onto a screen MxChat does not own. Falls back to the legacy
10203 // $_GET check only when the hook is unavailable (direct/legacy callers).
10204 if ($hook_suffix !== '') {
10205 if (strpos($hook_suffix, 'mxchat') === false) {
10206 return;
10207 }
10208 } elseif (strpos($current_page, 'mxchat') === false) {
10209 return;
10210 }
10211
10212 // Always load these on all MxChat pages
10213 $this->enqueue_core_admin_assets($plugin_url, $version);
10214 $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
10215 $this->localize_admin_scripts($current_page);
10216 }
10217 private function enqueue_core_admin_assets($plugin_url, $version) {
10218 // Core admin styles
10219 wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
10220 wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
10221
10222 // New sidebar navigation styles (for main settings page)
10223 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10224
10225 // Core admin scripts
10226 wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
10227 }
10228 private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
10229 switch ($current_page) {
10230 case 'mxchat-prompts':
10231 // Shared shell JS: tab switching, deep-linking and the mobile menu
10232 // for this page's flat nav (inline copies removed by plan c192a4).
10233 wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
10234 wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
10235 'copied' => __('Copied', 'mxchat'),
10236 ));
10237 // Knowledge processing page assets
10238 wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
10239 wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
10240 // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
10241 wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
10242 // "Re-import affected entries" card (plan 89739b)
10243 wp_enqueue_script('mxchat-kb-reimport', $plugin_url . 'js/knowledge-reimport.js', array(), $version, true);
10244 wp_localize_script('mxchat-kb-reimport', 'mxchatKbReimport', array(
10245 'ajaxUrl' => admin_url('admin-ajax.php'),
10246 'requestFailed' => __('The request did not go through. Nothing is lost: try again.', 'mxchat'),
10247 /* translators: %s: number of entries checked so far */
10248 'checking' => __('Checking, %s entries so far', 'mxchat'),
10249 /* translators: 1: entries rewritten so far, 2: entries to rewrite */
10250 'rewriting' => __('Rewriting, %1$s of %2$s', 'mxchat'),
10251 /* translators: %s: number of entries */
10252 'countRepair' => __('%s to rewrite', 'mxchat'),
10253 /* translators: %s: number of entries */
10254 'countCorrect' => __('%s already correct', 'mxchat'),
10255 /* translators: %s: number of entries */
10256 'countChanged' => __('%s left alone', 'mxchat'),
10257 /* translators: %s: number of entries */
10258 'countSkipped' => __('%s skipped', 'mxchat'),
10259 /* translators: %s: number of entries */
10260 'countRewritten' => __('%s rewritten', 'mxchat'),
10261 /* translators: %s: number of entries */
10262 'countFailed' => __('%s not rewritten', 'mxchat'),
10263 /* translators: %s: number of further entries not shown in the list */
10264 'andMore' => __('and %s more', 'mxchat'),
10265 /* translators: %s: number of entries */
10266 'othersTitle' => __('Left alone or skipped (%s)', 'mxchat'),
10267 'leftAlone' => __('Left alone', 'mxchat'),
10268 'skipped' => __('Skipped', 'mxchat'),
10269 'rewritten' => __('Rewritten', 'mxchat'),
10270 'notRewritten' => __('Not rewritten', 'mxchat'),
10271 'noLongerNeeded' => __('No longer needed', 'mxchat'),
10272 /* translators: %s: number of entries */
10273 'apply' => __('Rewrite %s entries', 'mxchat'),
10274 /* translators: %s: number of entries still to rewrite */
10275 'resume' => __('Continue, %s left', 'mxchat'),
10276 /* translators: %s: number of entries */
10277 'done' => __('%s entries rewritten and embedded again.', 'mxchat'),
10278 /* translators: 1: entries rewritten, 2: entries that could not be rewritten */
10279 'doneWithFailures' => __('%1$s entries rewritten. %2$s could not be rewritten and were left as they were.', 'mxchat'),
10280 'nothingToDo' => __('Every entry checked is already correct. Nothing to rewrite.', 'mxchat'),
10281 /* translators: %s: the reason the check stopped */
10282 'scanStopped' => __('The check stopped early: %s', 'mxchat'),
10283 'reasons' => array(
10284 'entities' => __('HTML character codes', 'mxchat'),
10285 'currency' => __('Currency signs', 'mxchat'),
10286 'combining marks' => __('Accents and marks', 'mxchat'),
10287 'symbols' => __('Symbols', 'mxchat'),
10288 'joiners' => __('Joined letters', 'mxchat'),
10289 'RTL' => __('Right-to-left order', 'mxchat'),
10290 ),
10291 ));
10292 // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the
10293 // Testing tab's match-card / chunk-detail components, which are scoped
10294 // under .mxch-testing-results. Load that stylesheet here so the inspector
10295 // modal renders identically to the Testing tab.
10296 wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version);
10297 break;
10298
10299 case 'mxchat-transcripts':
10300 // Load admin sidebar CSS first (shared styles for sidebar navigation)
10301 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10302 // Load transcripts-specific styles
10303 wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
10304 wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
10305 break;
10306
10307 case 'mxchat-actions':
10308 // Load admin sidebar CSS first (shared styles for sidebar navigation)
10309 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10310 // Load actions-specific styles
10311 wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
10312 wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
10313
10314 // Localize script data for actions page
10315 $is_activated = get_option('mxchat_pro_license_status') === 'active';
10316 wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
10317 'ajaxUrl' => admin_url('admin-ajax.php'),
10318 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
10319 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
10320 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
10321 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
10322 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
10323 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
10324 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
10325 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
10326 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
10327 'isActivated' => $is_activated,
10328 'i18n' => array(
10329 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'),
10330 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'),
10331 'saving' => __('Saving...', 'mxchat'),
10332 'saved' => __('Saved successfully!', 'mxchat'),
10333 'error' => __('An error occurred. Please try again.', 'mxchat'),
10334 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
10335 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
10336 )
10337 ));
10338 break;
10339
10340 case 'mxchat-activation':
10341 // Load admin sidebar CSS first (shared styles for sidebar navigation)
10342 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10343 // Load pro page-specific styles
10344 wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
10345 // Load pro page JavaScript
10346 wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
10347 // Load activation script for license activation/deactivation
10348 wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
10349 break;
10350
10351 case 'mxchat-content':
10352 // Load admin sidebar CSS (shared styles for sidebar navigation)
10353 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10354 // Load content page-specific styles
10355 wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
10356 // Load content page JavaScript
10357 wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
10358 break;
10359
10360 case 'mxchat-api-access':
10361 // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
10362 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10363 wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
10364 wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
10365 'copied' => __('Copied', 'mxchat'),
10366 ));
10367 break;
10368
10369 case 'mxchat-max':
10370 case 'mxchat-onboarding':
10371 // Onboarding page — uses the shared admin shell PLUS the wizard
10372 // overlay (plan-905439). admin-onboarding-wizard.css scopes the
10373 // WP-chrome surgery to body.mxchat-onboarding-focused so it only
10374 // applies on THIS page. The body class is added below via the
10375 // admin_body_class filter.
10376 wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
10377 wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
10378 wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
10379 'copied' => __('Copied', 'mxchat'),
10380 ));
10381 // admin-style.css provides the .mxchat-instructions-modal-* classes
10382 // the new Behavior step's "View Sample Instructions" modal needs.
10383 // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay
10384 // so the wizard's own rules win where they collide. plan-a2e4d6.
10385 wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version);
10386 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);
10387 wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true);
10388 break;
10389 default:
10390 // Settings page: load the shared shell JS for #hash deep-linking
10391 // to tabs (plan 4ede16). The page's own inline nav script owns
10392 // clicks/accordion behaviour; the shell script adds load +
10393 // hashchange activation and replaceState so plain href="#tab"
10394 // anchors and shared URLs land on the right tab. Kept inside the
10395 // default case because the settings page also needs everything
10396 // below (Testing tab chatbot + streaming assets).
10397 if ($current_page === 'mxchat-settings') {
10398 wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
10399 wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
10400 'copied' => __('Copied', 'mxchat'),
10401 ));
10402 }
10403
10404 wp_enqueue_script(
10405 'mxchat-test-streaming-js',
10406 $plugin_url . 'js/mxchat-test-streaming.js',
10407 ['jquery'],
10408 $version,
10409 true
10410 );
10411
10412 wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
10413 'ajax_url' => admin_url('admin-ajax.php'),
10414 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
10415 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
10416 ]);
10417
10418 // Testing Tab: Load chatbot assets for the embedded testing chatbot
10419 wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
10420 wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
10421
10422 wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
10423 wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
10424
10425 // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
10426 do_action('mxchat_enqueue_testing_tab_assets');
10427
10428 // Localize mxchatChat for the chatbot JS (same settings as frontend)
10429 $options = get_option('mxchat_options', array());
10430 $prompts_options = get_option('mxchat_prompts_options', array());
10431 $theme_options = get_option('mxchat_theme_options', array());
10432 $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
10433 $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
10434 $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
10435
10436 wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
10437 'ajax_url' => admin_url('admin-ajax.php'),
10438 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
10439 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
10440 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
10441 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
10442 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
10443 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
10444 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
10445 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
10446 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
10447 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
10448 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
10449 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
10450 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
10451 'close_button_color' => $options['close_button_color'] ?? '#fff',
10452 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
10453 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
10454 'icon_color' => $options['icon_color'] ?? '#fff',
10455 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
10456 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
10457 'appendWidgetToBody' => 'off',
10458 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
10459 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
10460 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
10461 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
10462 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
10463 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
10464 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
10465 'email_collection_enabled' => 'off', // No email collection in testing
10466 'initial_email_state' => null,
10467 'skip_email_check' => true,
10468 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
10469 'skip_inline_colors' => $skip_inline_colors,
10470 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
10471 ));
10472
10473 // Localize testing tab script data
10474 wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
10475 'ajaxUrl' => admin_url('admin-ajax.php'),
10476 'nonce' => wp_create_nonce('mxchat_test_nonce'),
10477 'isAdmin' => true,
10478 'testingEnabled' => true
10479 ));
10480
10481 // Add testing enabled flag for the chatbot to return debug data
10482 add_action('admin_footer', function() {
10483 echo '<script>window.mxchatTestingEnabled = true;</script>';
10484 });
10485
10486 break;
10487 }
10488 }
10489 /**
10490 * The base mxchatAdmin payload shared by every MxChat admin page.
10491 *
10492 * Extracted (plan c192a4) so page-specific re-localizations of the SAME
10493 * global — the knowledge page prints a second `var mxchatAdmin` via the
10494 * mxchat-knowledge-processing handle, and last-printed wins — can merge
10495 * their extra keys on top of this instead of silently narrowing the object
10496 * that mxchat-admin.js also reads on that page.
10497 */
10498 private function mxchat_get_admin_base_localization() {
10499 return array(
10500 'ajax_url' => admin_url('admin-ajax.php'),
10501 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
10502 'admin_url' => admin_url(),
10503 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
10504 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
10505 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10506 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
10507 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
10508 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
10509 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
10510 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
10511 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
10512 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
10513 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
10514 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
10515 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
10516 'is_activated' => $this->is_activated ? '1' : '0',
10517 'status_refresh_interval' => 5000,
10518 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'),
10519 'unsaved_label' => __('Unsaved', 'mxchat'),
10520 // Live-agent schedule status text (plan 8ccaa2).
10521 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'),
10522 'i18n_always_available' => __('Always available', 'mxchat'),
10523 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10524 'ajaxurl' => admin_url('admin-ajax.php')
10525 );
10526 }
10527 private function localize_admin_scripts($current_page) {
10528 // Base localization data for main admin script
10529 $base_data = $this->mxchat_get_admin_base_localization();
10530
10531 // Localize main admin script with base data
10532 wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
10533
10534 // Canonical chat-model catalog for the modal picker grid
10535 // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php
10536 // automatically appears here.
10537 if (!class_exists('MxChat_Model_Catalog')) {
10538 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
10539 }
10540 wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape());
10541
10542 // Page-specific localizations
10543 $this->localize_page_specific_scripts($current_page);
10544 }
10545 private function localize_page_specific_scripts($current_page) {
10546 switch ($current_page) {
10547 case 'mxchat-prompts':
10548 // Status updater localization
10549 wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
10550 'ajax_url' => admin_url('admin-ajax.php'),
10551 'nonce' => wp_create_nonce('mxchat_status_nonce')
10552 ));
10553
10554 // Content selector localization
10555 wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
10556 'ajaxurl' => admin_url('admin-ajax.php'),
10557 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
10558 'i18n' => array(
10559 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
10560 'selectAll' => __('Select All', 'mxchat'),
10561 'process' => __('Process Selected', 'mxchat'),
10562 'cancel' => __('Cancel', 'mxchat'),
10563 'noResults' => __('No content found.', 'mxchat'),
10564 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
10565 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
10566 )
10567 ));
10568
10569 // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's
10570 // base one) and last-printed wins — so it must carry the FULL base
10571 // payload plus the knowledge-page extras, or every mxchatAdmin.*
10572 // key mxchat-admin.js reads on this page comes up undefined
10573 // (plan c192a4). Extras merge last: status_refresh_interval stays
10574 // at this page's faster 2000ms cadence.
10575 wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge(
10576 $this->mxchat_get_admin_base_localization(),
10577 array(
10578 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
10579 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
10580 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
10581 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10582 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
10583 'status_refresh_interval' => 2000,
10584 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
10585 )
10586 ));
10587 break;
10588
10589 case 'mxchat-activation':
10590 // Same last-printed-wins clobber as the knowledge page (plan c192a4,
10591 // fixed here by a5b297): this second `var mxchatAdmin` must carry
10592 // the full base payload plus the page extras.
10593 wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge(
10594 $this->mxchat_get_admin_base_localization(),
10595 array(
10596 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
10597 )
10598 ));
10599 break;
10600
10601 case 'mxchat-content':
10602 wp_localize_script('mxchat-content-js', 'mxchatContent', array(
10603 'ajaxUrl' => admin_url('admin-ajax.php'),
10604 'nonce' => wp_create_nonce('mxchat_content_nonce'),
10605 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10606 'previewUrl' => home_url('/?p='),
10607 'isActivated' => $this->is_activated(),
10608 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
10609 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
10610 // Whether Search Console is actually LINKED — distinct from hasGSC
10611 // (add-on active). Reads the same option the add-on's settings
10612 // card keys off; harmless false when the add-on is absent.
10613 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false),
10614 'seoOptimize' => array(
10615 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
10616 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
10617 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
10618 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
10619 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
10620 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
10621 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
10622 ),
10623 'i18n' => array(
10624 'generating' => __('Generating...', 'mxchat'),
10625 'planning' => __('Planning content structure...', 'mxchat'),
10626 'images' => __('Generating images...', 'mxchat'),
10627 'writing' => __('Writing full content...', 'mxchat'),
10628 'creating' => __('Creating WordPress post...', 'mxchat'),
10629 'done' => __('Content generated successfully!', 'mxchat'),
10630 'error' => __('An error occurred. Please try again.', 'mxchat'),
10631 'editSuccess' => __('Content updated successfully.', 'mxchat'),
10632 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
10633 )
10634 ));
10635 break;
10636
10637 case 'mxchat-transcripts':
10638 // Get chart data for localization
10639 $chart_data = $this->get_transcripts_chart_data();
10640
10641 // Same last-printed-wins clobber as the knowledge page (plan c192a4,
10642 // fixed here by a5b297): merge the base payload under the page keys.
10643 // export_nonce/setting_nonce/ajax_url duplicate base values identically;
10644 // delete_nonce and translate_nonce are the page-specific adds.
10645 wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge(
10646 $this->mxchat_get_admin_base_localization(),
10647 array(
10648 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
10649 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
10650 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10651 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
10652 )
10653 ));
10654
10655 // Localize chart data separately - use array_values to ensure proper JSON array encoding
10656 wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
10657 'labels' => array_values($chart_data['labels']),
10658 'chats' => array_values($chart_data['chats']),
10659 'messages' => array_values($chart_data['messages'])
10660 ));
10661 break;
10662
10663 case 'mxchat-settings':
10664 default:
10665 // The 'mxchatStyleSettings' localize that used to live here was
10666 // REMOVED by plan-mxchat-20260731-c63fb6.
10667 //
10668 // It targeted the script handle 'mxchat-color-picker', which is
10669 // registered/enqueued NOWHERE in the plugin — so wp_localize_script()
10670 // returned false and printed nothing. That accident was the only
10671 // thing keeping it from being a live secret disclosure: the payload
10672 // carried loops_api_key, live_agent_secret_key and
10673 // live_agent_bot_token in full, and this whole method ran for any
10674 // logged-in user (see the capability gate added to
10675 // mxchat_enqueue_admin_assets). One future
10676 // wp_enqueue_script('mxchat-color-picker', ...) would have printed
10677 // three secrets into page HTML for Subscribers.
10678 //
10679 // Nothing consumed the object: a tree-wide grep for
10680 // 'mxchatStyleSettings' returns only this call site, and js/ names
10681 // loops_api_key only at mxchat-admin.js:572, as a field-NAME string
10682 // in an autosave allowlist — not a value read. Removed entirely
10683 // rather than deleting just the three secret keys, so there is no
10684 // dead payload left for someone to re-arm.
10685 break;
10686 }
10687
10688 // Additional localization that was in the original code
10689 wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
10690 'ajax_url' => admin_url('admin-ajax.php'),
10691 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10692 ));
10693 }
10694
10695 public function mxchat_sanitize($input) {
10696 $new_input = array();
10697
10698 if (isset($input['api_key'])) {
10699 $new_input['api_key'] = sanitize_text_field($input['api_key']);
10700 }
10701
10702 if (isset($input['similarity_threshold'])) {
10703 $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
10704 $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
10705 }
10706
10707 if (isset($input['rag_sources_limit'])) {
10708 $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
10709 $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
10710 }
10711
10712 if (isset($input['rag_chunks_limit'])) {
10713 $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
10714 $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
10715 }
10716
10717 if (isset($input['xai_api_key'])) {
10718 $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
10719 }
10720
10721 if (isset($input['claude_api_key'])) {
10722 $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
10723 }
10724
10725 if (isset($input['enable_streaming_toggle'])) {
10726 $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
10727 } else {
10728 // If checkbox not checked, it won't be in $input, so set to 'off'
10729 $new_input['enable_streaming_toggle'] = 'off';
10730 }
10731
10732 if (isset($input['enable_web_search'])) {
10733 $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
10734 } else {
10735 // If checkbox not checked, it won't be in $input, so set to 'off'
10736 $new_input['enable_web_search'] = 'off';
10737 }
10738
10739 if (isset($input['deepseek_api_key'])) {
10740 $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
10741 }
10742
10743 if (isset($input['gemini_api_key'])) {
10744 $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
10745 }
10746
10747 if (isset($input['enable_woocommerce_integration'])) {
10748 $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
10749 }
10750
10751 if (isset($input['privacy_toggle'])) {
10752 $new_input['privacy_toggle'] = $input['privacy_toggle'];
10753 }
10754
10755 if (isset($input['complianz_toggle'])) {
10756 $new_input['complianz_toggle'] = $input['complianz_toggle'];
10757 }
10758
10759 // Handle custom privacy text input
10760 if (isset($input['privacy_text'])) {
10761 // Allow basic HTML for links
10762 $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
10763 }
10764
10765 if (isset($input['system_prompt_instructions'])) {
10766 $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
10767 }
10768
10769 if (isset($input['mxchat_pro_email'])) {
10770 $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
10771 }
10772
10773 if (isset($input['mxchat_activation_key'])) {
10774 $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
10775 }
10776
10777 if (isset($input['append_to_body'])) {
10778 $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
10779 }
10780
10781 // Post type visibility settings
10782 if (isset($input['post_type_visibility_mode'])) {
10783 $allowed_modes = array('all', 'include', 'exclude');
10784 $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
10785 ? $input['post_type_visibility_mode']
10786 : 'all';
10787 }
10788
10789 if (isset($input['post_type_visibility_list'])) {
10790 if (is_array($input['post_type_visibility_list'])) {
10791 $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
10792 } else {
10793 $new_input['post_type_visibility_list'] = array();
10794 }
10795 }
10796
10797 if (isset($input['contextual_awareness_toggle'])) {
10798 $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
10799 }
10800
10801 if (isset($input['citation_links_toggle'])) {
10802 $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
10803 }
10804
10805 if (isset($input['strip_unapproved_links_toggle'])) {
10806 $new_input['strip_unapproved_links_toggle'] = $input['strip_unapproved_links_toggle'] === 'on' ? 'on' : 'off';
10807 }
10808
10809 // Satisfaction rating prompt — defaults ON when unchecked (so first save
10810 // doesn't accidentally disable it). The form posts 'on' when checked;
10811 // unchecked checkboxes don't post a value at all, so we infer 'off' only
10812 // when the autosave/PHP request explicitly clears it via empty string.
10813 if (array_key_exists('satisfaction_rating_enabled', $input)) {
10814 $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
10815 }
10816
10817 // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
10818 // the 4 text strings are sanitized + capped server-side. Blank values are
10819 // preserved so the integrator falls back to translated defaults.
10820 if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
10821 $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
10822 }
10823
10824 // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default,
10825 // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out
10826 // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist,
10827 // so without this isset-handler the key is stripped on the next save of ANY field
10828 // (the 2c02ea global-rate-limit footgun).
10829 if (array_key_exists('max_input_length', $input)) {
10830 $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length'])));
10831 }
10832 if (array_key_exists('satisfaction_rating_question', $input)) {
10833 $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
10834 }
10835 if (array_key_exists('satisfaction_rating_thanks', $input)) {
10836 $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
10837 }
10838 if (array_key_exists('satisfaction_rating_placeholder', $input)) {
10839 $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
10840 }
10841 if (array_key_exists('satisfaction_rating_saved', $input)) {
10842 $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
10843 }
10844
10845 if (isset($input['top_bar_title'])) {
10846 $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
10847 }
10848
10849 if (isset($input['ai_agent_text'])) {
10850 $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
10851 }
10852
10853 if (isset($input['enable_email_block'])) {
10854 $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
10855 }
10856
10857 if (isset($input['email_blocker_header_content'])) {
10858 // wp_kses_post() allows standard HTML tags permitted by WordPress
10859 $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
10860 }
10861 if (isset($input['email_blocker_button_text'])) {
10862 $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
10863 }
10864 // Sanitize name field toggle
10865 if (isset($input['enable_name_field'])) {
10866 $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
10867 } else {
10868 $new_input['enable_name_field'] = 'off';
10869 }
10870 // Sanitize name field placeholder
10871 if (isset($input['name_field_placeholder'])) {
10872 $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
10873 }
10874 // Consent checkbox (b062c4). Both toggles default off — an unchecked box
10875 // posts nothing, so the else-branch is what makes unticking stick.
10876 if (isset($input['enable_consent_checkbox'])) {
10877 $new_input['enable_consent_checkbox'] = ($input['enable_consent_checkbox'] === 'on') ? 'on' : 'off';
10878 } else {
10879 $new_input['enable_consent_checkbox'] = 'off';
10880 }
10881 if (isset($input['consent_checkbox_label'])) {
10882 // Shared allowlist with the render path — see MxChat_Utils::sanitize_consent_label().
10883 $new_input['consent_checkbox_label'] = MxChat_Utils::sanitize_consent_label($input['consent_checkbox_label']);
10884 }
10885 if (isset($input['consent_checkbox_required'])) {
10886 $new_input['consent_checkbox_required'] = ($input['consent_checkbox_required'] === 'on') ? 'on' : 'off';
10887 } else {
10888 $new_input['consent_checkbox_required'] = 'off';
10889 }
10890 // Lead capture options (c0cfaf). Default OFF gets the else-branch so
10891 // unticking sticks; default ON deliberately has NO else — an absent key
10892 // must stay absent so the reader's ?? 'on' default applies, otherwise
10893 // every autosave of an unrelated field would silently flip the setting
10894 // off on installs that never touched it (the 2c02ea bug class).
10895 if (isset($input['lead_capture_logged_in_toggle'])) {
10896 $new_input['lead_capture_logged_in_toggle'] = ($input['lead_capture_logged_in_toggle'] === 'on') ? 'on' : 'off';
10897 } else {
10898 $new_input['lead_capture_logged_in_toggle'] = 'off';
10899 }
10900 if (isset($input['lead_capture_require_email_toggle'])) {
10901 $new_input['lead_capture_require_email_toggle'] = ($input['lead_capture_require_email_toggle'] === 'on') ? 'on' : 'off';
10902 }
10903 if (isset($input['intro_message'])) {
10904 $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
10905 }
10906
10907 if (isset($input['input_copy'])) {
10908 $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10909 }
10910
10911 if (isset($input['rate_limit_message'])) {
10912 $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10913 }
10914
10915 // Handle the new rate limits format
10916 if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
10917 $new_input['rate_limits'] = array();
10918 $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10919 $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10920
10921 foreach ($input['rate_limits'] as $role_id => $settings) {
10922 $new_input['rate_limits'][$role_id] = array();
10923
10924 // Sanitize limit
10925 if (isset($settings['limit'])) {
10926 $limit = sanitize_text_field($settings['limit']);
10927 // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive
10928 // integer (custom value) — mirrors the global branch (plan-2c02ea). Without
10929 // the custom path the per-role custom input was dropped and reset to the role
10930 // default on every save (plan-7e23e7).
10931 if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10932 $new_input['rate_limits'][$role_id]['limit'] = $limit;
10933 } else {
10934 $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
10935 }
10936 }
10937
10938 // Preserve the per-role custom value (mirrors the global branch's limit_custom).
10939 if (isset($settings['limit_custom'])) {
10940 $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']);
10941 }
10942
10943 // Sanitize timeframe
10944 if (isset($settings['timeframe'])) {
10945 $timeframe = sanitize_text_field($settings['timeframe']);
10946 if (in_array($timeframe, $allowed_timeframes, true)) {
10947 $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
10948 } else {
10949 $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
10950 }
10951 }
10952
10953 // Sanitize message
10954 if (isset($settings['message'])) {
10955 $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
10956 }
10957 }
10958 }
10959
10960 // Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea).
10961 // Mirrors the per-role block above, adapted to the single global shape. Without
10962 // this branch the whitelist-rebuild dropped rate_limits_global entirely on every
10963 // save, so the global cap silently fell back to its 'unlimited' default.
10964 // MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed.
10965 if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) {
10966 $g = $input['rate_limits_global'];
10967 $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10968 $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10969 $global_out = array();
10970
10971 if (isset($g['limit'])) {
10972 $limit = sanitize_text_field($g['limit']);
10973 // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the
10974 // autosave handler / renderer), OR any positive integer (custom value).
10975 if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10976 $global_out['limit'] = $limit;
10977 } else {
10978 $global_out['limit'] = 'unlimited';
10979 }
10980 }
10981
10982 if (isset($g['limit_custom'])) {
10983 $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']);
10984 }
10985
10986 if (isset($g['timeframe'])) {
10987 $timeframe = sanitize_text_field($g['timeframe']);
10988 $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily';
10989 }
10990
10991 if (isset($g['message'])) {
10992 $global_out['message'] = sanitize_textarea_field($g['message']);
10993 }
10994
10995 $new_input['rate_limits_global'] = $global_out;
10996 }
10997
10998 if (isset($input['pre_chat_message'])) {
10999 $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
11000 }
11001
11002 if (isset($input['voyage_api_key'])) {
11003 $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
11004 }
11005
11006 // Add to your sanitize function
11007 if (isset($input['embedding_model'])) {
11008 // Catalog refactor (plan-d14e89): allowlist derived from the canonical
11009 // catalog in includes/class-mxchat-model-catalog.php.
11010 if (!class_exists('MxChat_Model_Catalog')) {
11011 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
11012 }
11013 $allowed_models = MxChat_Model_Catalog::embedding_model_ids();
11014 if (in_array($input['embedding_model'], $allowed_models)) {
11015 $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
11016 }
11017 }
11018
11019 if (isset($input['model'])) {
11020 if ($input['model'] === 'openrouter') {
11021 $new_input['model'] = 'openrouter';
11022 } else {
11023 if (!class_exists('MxChat_Model_Catalog')) {
11024 require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
11025 }
11026 $allowed_models = MxChat_Model_Catalog::chat_model_ids();
11027
11028 if (in_array($input['model'], $allowed_models)) {
11029 $new_input['model'] = sanitize_text_field($input['model']);
11030 } else {
11031 // Fallback for any deprecated model
11032 $new_input['model'] = 'gpt-5.6-sol';
11033 }
11034 }
11035 }
11036
11037 if (isset($input['openrouter_selected_model'])) {
11038 // Just sanitize it, don't validate against a whitelist
11039 $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
11040 }
11041
11042 // ADD THIS:
11043 if (isset($input['openrouter_selected_model_name'])) {
11044 $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
11045 }
11046
11047 if (isset($input['openrouter_api_key'])) {
11048 $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
11049 }
11050
11051 // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
11052 if (isset($input['custom_provider_base_url'])) {
11053 $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
11054 }
11055 if (isset($input['custom_provider_api_key'])) {
11056 $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
11057 }
11058 if (isset($input['custom_provider_model'])) {
11059 $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
11060 }
11061 if (isset($input['custom_provider_auth_scheme'])) {
11062 $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
11063 $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
11064 }
11065 if (isset($input['custom_provider_for_embeddings'])) {
11066 $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
11067 }
11068 if (isset($input['custom_provider_for_images'])) {
11069 $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
11070 }
11071 if (isset($input['custom_provider_embedding_model'])) {
11072 $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
11073 }
11074 if (isset($input['custom_provider_api_version'])) {
11075 $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
11076 }
11077
11078
11079
11080 if (isset($input['woocommerce_consumer_key'])) {
11081 $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
11082 }
11083
11084 if (isset($input['woocommerce_consumer_secret'])) {
11085 $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
11086 }
11087
11088
11089 // Sanitize link_target_toggle
11090 if (isset($input['link_target_toggle'])) {
11091 $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
11092 }
11093
11094 // Sanitize Loops API Key
11095 if (isset($input['loops_api_key'])) {
11096 $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
11097 }
11098
11099 if (isset($input['chat_persistence_toggle'])) {
11100 $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
11101 }
11102
11103 // No else clause: an absent key stays absent, so the front-end default ('on') applies
11104 // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here).
11105 if (isset($input['print_button_enabled'])) {
11106 $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off';
11107 }
11108
11109 // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label.
11110 // No else on the toggle: an absent key stays absent so the front-end '?? off'
11111 // default applies, and the full-array autosave rebuild preserves a saved value.
11112 if (isset($input['reset_chat_enabled'])) {
11113 $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off';
11114 }
11115
11116 if (isset($input['reset_chat_label'])) {
11117 $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']);
11118 }
11119
11120 if (isset($input['popular_question_1'])) {
11121 $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
11122 }
11123
11124 if (isset($input['popular_question_2'])) {
11125 $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']);
11126 }
11127
11128 if (isset($input['popular_question_3'])) {
11129 $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']);
11130 }
11131
11132 if (isset($input['additional_popular_questions']) && is_array($input['additional_popular_questions'])) {
11133 $new_input['additional_popular_questions'] = array_map('sanitize_text_field', $input['additional_popular_questions']);
11134 }
11135
11136 // Sanitize Loops Mailing List
11137 if (isset($input['loops_mailing_list'])) {
11138 $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
11139 }
11140
11141 // Sanitize Triggered Phrase Response
11142 if (isset($input['triggered_phrase_response'])) {
11143 $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
11144 }
11145 if (isset($input['email_capture_response'])) {
11146 $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
11147 }
11148
11149 // Sanitize Brave Search Settings
11150 if (isset($input['brave_api_key'])) {
11151 $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
11152 }
11153
11154 if (isset($input['brave_image_count'])) {
11155 $image_count = intval($input['brave_image_count']);
11156 $new_input['brave_image_count'] = ($image_count >=1 && $image_count <=6) ? $image_count : 4;
11157 }
11158
11159 if (isset($input['brave_safe_search'])) {
11160 $allowed = array('strict', 'off');
11161 $new_input['brave_safe_search'] = in_array($input['brave_safe_search'], $allowed, true) ? $input['brave_safe_search'] : 'strict';
11162 }
11163
11164 if (isset($input['brave_news_count'])) {
11165 $news_count = intval($input['brave_news_count']);
11166 $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
11167 }
11168
11169 if (isset($input['brave_country'])) {
11170 $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
11171 }
11172
11173 if (isset($input['brave_language'])) {
11174 $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
11175 }
11176
11177 if (isset($input['chat_toolbar_toggle'])) {
11178 $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
11179 }
11180
11181 // Sanitize PDF upload button toggle
11182 if (isset($input['show_pdf_upload_button'])) {
11183 $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
11184 } else {
11185 $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
11186 }
11187
11188 // Sanitize Word upload button toggle
11189 if (isset($input['show_word_upload_button'])) {
11190 $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
11191 } else {
11192 $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
11193 }
11194
11195 if (isset($input['pdf_intent_trigger_text'])) {
11196 $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
11197 }
11198
11199 if (isset($input['pdf_intent_success_text'])) {
11200 $new_input['pdf_intent_success_text'] = sanitize_text_field($input['pdf_intent_success_text']);
11201 }
11202
11203 if (isset($input['pdf_intent_error_text'])) {
11204 $new_input['pdf_intent_error_text'] = sanitize_text_field($input['pdf_intent_error_text']);
11205 }
11206
11207 if (isset($input['pdf_max_pages'])) {
11208 $new_input['pdf_max_pages'] = intval($input['pdf_max_pages']);
11209 if ($new_input['pdf_max_pages'] < 1 || $new_input['pdf_max_pages'] > 69) {
11210 $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
11211 }
11212 }
11213
11214 if (isset($input['live_agent_webhook_url'])) {
11215 $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
11216 }
11217 if (isset($input['live_agent_secret_key'])) {
11218 $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
11219 }
11220
11221 // Live Agent Integration
11222 if (isset($input['live_agent_bot_token'])) {
11223 $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
11224 }
11225
11226 if (isset($input['live_agent_shared_channel'])) {
11227 $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']);
11228 }
11229
11230 // Default-OFF toggle: absent key stays absent (unchecked box = off).
11231 if (isset($input['live_agent_archive_on_end_toggle'])) {
11232 $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off';
11233 }
11234
11235 if (isset($input['live_agent_user_ids'])) {
11236 $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
11237 }
11238
11239 if (isset($input['live_agent_status'])) {
11240 $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
11241 }
11242 if (isset($input['live_agent_away_message'])) {
11243 $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
11244 }
11245 if (isset($input['live_agent_notification_message'])) {
11246 $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
11247 }
11248
11249 // Telegram Integration
11250 if (isset($input['telegram_status'])) {
11251 $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
11252 }
11253 if (isset($input['telegram_bot_token'])) {
11254 $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
11255 }
11256 if (isset($input['telegram_group_id'])) {
11257 $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
11258 }
11259 if (isset($input['telegram_webhook_secret'])) {
11260 $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
11261 }
11262 if (isset($input['telegram_notification_message'])) {
11263 $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
11264 }
11265 if (isset($input['telegram_away_message'])) {
11266 $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
11267 }
11268
11269 // Webhook Handoff (plan d88e22)
11270 if (isset($input['webhook_handoff_status'])) {
11271 $new_input['webhook_handoff_status'] = ($input['webhook_handoff_status'] === 'on') ? 'on' : 'off';
11272 }
11273 if (isset($input['webhook_handoff_url'])) {
11274 // https only — esc_url_raw with an https-only protocol list stores ''
11275 // for anything else, so a non-https URL can never persist.
11276 $new_input['webhook_handoff_url'] = esc_url_raw(trim((string) $input['webhook_handoff_url']), array('https'));
11277 }
11278 if (isset($input['webhook_handoff_secret'])) {
11279 $new_input['webhook_handoff_secret'] = sanitize_text_field($input['webhook_handoff_secret']);
11280 }
11281 if (isset($input['webhook_handoff_notification_message'])) {
11282 $new_input['webhook_handoff_notification_message'] = sanitize_textarea_field($input['webhook_handoff_notification_message']);
11283 }
11284 if (isset($input['webhook_handoff_away_message'])) {
11285 $new_input['webhook_handoff_away_message'] = sanitize_textarea_field($input['webhook_handoff_away_message']);
11286 }
11287
11288 // Sanitize script loading strategy
11289 if (isset($input['script_loading_strategy'])) {
11290 $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
11291 $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
11292 ? $input['script_loading_strategy']
11293 : 'default';
11294 }
11295
11296 // Sanitize debug mode
11297 if (isset($input['debug_mode'])) {
11298 $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
11299 }
11300
11301 // Content Generator Settings
11302 if (isset($input['content_model'])) {
11303 $new_input['content_model'] = sanitize_text_field($input['content_model']);
11304 }
11305 if (isset($input['content_image_model'])) {
11306 $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
11307 }
11308 if (isset($input['content_image_quality'])) {
11309 $q = sanitize_text_field($input['content_image_quality']);
11310 $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
11311 }
11312 if (isset($input['content_enable_images'])) {
11313 $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
11314 }
11315 if (isset($input['content_use_placeholders'])) {
11316 $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
11317 }
11318 if (isset($input['content_internal_linking'])) {
11319 $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
11320 }
11321 if (isset($input['content_tool_use'])) {
11322 $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
11323 }
11324 if (isset($input['content_image_count'])) {
11325 $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count']));
11326 }
11327
11328 // SEO Optimize toggle fields
11329 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) {
11330 if (isset($input[$seo_key])) {
11331 $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
11332 }
11333 }
11334
11335 // Preserve content generator settings when saving from main settings page
11336 // (where content fields are not in the form submission)
11337 $existing = get_option('mxchat_options', array());
11338 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) {
11339 if (!isset($new_input[$key]) && isset($existing[$key])) {
11340 $new_input[$key] = $existing[$key];
11341 }
11342 }
11343
11344 return $new_input;
11345 }
11346
11347 /**
11348 * Log a debug message if debug mode is enabled
11349 *
11350 * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
11351 * @param string $message The log message
11352 * @param array $data Optional additional data to log
11353 * @return bool Whether the message was logged
11354 */
11355 public static function mxchat_log_debug( $type, $message, $data = array() ) {
11356 $options = get_option( 'mxchat_options', array() );
11357
11358 // Check if debug mode is enabled
11359 if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
11360 return false;
11361 }
11362
11363 // Get current log
11364 $log = get_option( 'mxchat_debug_log', array() );
11365 if ( ! is_array( $log ) ) {
11366 $log = array();
11367 }
11368
11369 // Add new entry
11370 $entry = array(
11371 'time' => current_time( 'Y-m-d H:i:s' ),
11372 'type' => sanitize_key( $type ),
11373 'message' => sanitize_text_field( $message ),
11374 );
11375
11376 if ( ! empty( $data ) ) {
11377 $entry['data'] = $data;
11378 }
11379
11380 // Add to beginning of array (newest first)
11381 array_unshift( $log, $entry );
11382
11383 // Keep only last 100 entries
11384 if ( count( $log ) > 100 ) {
11385 $log = array_slice( $log, 0, 100 );
11386 }
11387
11388 // Save log
11389 update_option( 'mxchat_debug_log', $log, false );
11390
11391 return true;
11392 }
11393
11394 /**
11395 * Get the debug log entries
11396 *
11397 * @return array The debug log entries
11398 */
11399 public static function mxchat_get_debug_log() {
11400 $log = get_option( 'mxchat_debug_log', array() );
11401 return is_array( $log ) ? $log : array();
11402 }
11403
11404 /**
11405 * Clear the debug log
11406 *
11407 * @return bool Whether the log was cleared
11408 */
11409 public static function mxchat_clear_debug_log() {
11410 return delete_option( 'mxchat_debug_log' );
11411 }
11412
11413 /**
11414 * Export settings as JSON with masked API keys
11415 *
11416 * @return array The sanitized settings array
11417 */
11418 public static function mxchat_export_settings() {
11419 $options = get_option( 'mxchat_options', array() );
11420
11421 if ( ! is_array( $options ) ) {
11422 return array();
11423 }
11424
11425 // List of API key fields to mask
11426 $api_key_fields = array(
11427 'api_key',
11428 'xai_api_key',
11429 'claude_api_key',
11430 'deepseek_api_key',
11431 'voyage_api_key',
11432 'gemini_api_key',
11433 'openrouter_api_key',
11434 'loops_api_key',
11435 'brave_api_key',
11436 'live_agent_secret_key',
11437 'live_agent_bot_token',
11438 'telegram_bot_token',
11439 'telegram_webhook_secret',
11440 'woocommerce_consumer_key',
11441 'woocommerce_consumer_secret',
11442 );
11443
11444 // Mask API keys (show only last 4 characters)
11445 foreach ( $api_key_fields as $field ) {
11446 if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
11447 $value = $options[ $field ];
11448 if ( strlen( $value ) > 4 ) {
11449 $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
11450 } else {
11451 $options[ $field ] = '****';
11452 }
11453 }
11454 }
11455
11456 // Add metadata
11457 $export = array(
11458 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
11459 'export_date' => current_time( 'Y-m-d H:i:s' ),
11460 'wordpress_version' => get_bloginfo( 'version' ),
11461 'php_version' => phpversion(),
11462 'settings' => $options,
11463 );
11464
11465 return $export;
11466 }
11467
11468 /**
11469 * Reset all settings to defaults
11470 *
11471 * @return bool Whether the reset was successful
11472 */
11473 public static function mxchat_reset_all_settings() {
11474 // Delete main options
11475 $deleted = delete_option( 'mxchat_options' );
11476
11477 // Also clear the debug log
11478 delete_option( 'mxchat_debug_log' );
11479
11480 // Log the reset (will create new log since we just cleared it)
11481 // We need to temporarily enable debug mode to log this
11482 $temp_options = array( 'debug_mode' => 'on' );
11483 update_option( 'mxchat_options', $temp_options );
11484
11485 self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
11486
11487 // Now delete again to trigger re-initialization
11488 delete_option( 'mxchat_options' );
11489
11490 return $deleted;
11491 }
11492
11493 // Method to append the chatbot to the body
11494 public function mxchat_append_chatbot_to_body() {
11495 $options = get_option('mxchat_options');
11496 if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
11497 echo do_shortcode('[mxchat_chatbot floating="yes"]');
11498 }
11499 }
11500
11501
11502
11503
11504
11505 private function mxchat_fetch_loops_mailing_lists($api_key) {
11506 $url = 'https://app.loops.so/api/v1/lists';
11507 $response = wp_remote_get($url, array(
11508 'headers' => array(
11509 'Authorization' => 'Bearer ' . $api_key,
11510 'Content-Type' => 'application/json'
11511 )
11512 ));
11513
11514 if (is_wp_error($response)) {
11515 return array();
11516 }
11517
11518 $body = wp_remote_retrieve_body($response);
11519 $lists = json_decode($body, true);
11520
11521 return isset($lists) && is_array($lists) ? $lists : array();
11522 }
11523
11524 function mxchat_calculate_cosine_similarity($vec1, $vec2) {
11525 if (empty($vec1) || empty($vec2)) {
11526 return 0.0;
11527 }
11528
11529 $dot_product = 0.0;
11530 $norm_a = 0.0;
11531 $norm_b = 0.0;
11532
11533 for ($i = 0; $i < count($vec1); $i++) {
11534 $dot_product += $vec1[$i] * $vec2[$i];
11535 $norm_a += pow($vec1[$i], 2);
11536 $norm_b += pow($vec2[$i], 2);
11537 }
11538
11539 if ($norm_a == 0.0 || $norm_b == 0.0) {
11540 return 0.0;
11541 } else {
11542 return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
11543 }
11544 }
11545
11546 /**
11547 * Validates nonce and deletes all chat prompts
11548 */
11549 public function mxchat_handle_delete_all_prompts() {
11550 //error_log('=== DELETE ALL DEBUG START ===');
11551
11552 // Verify nonce
11553 if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
11554 //error_log('DEBUG: Nonce verification failed');
11555 wp_die(__('Nonce verification failed.', 'mxchat'));
11556 }
11557
11558 // Check permissions
11559 if (!current_user_can('manage_options')) {
11560 //error_log('DEBUG: Permission check failed');
11561 wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
11562 }
11563
11564 // Get bot_id and content type filter from POST data
11565 $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
11566 $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
11567
11568 $success = true;
11569 $error_messages = array();
11570
11571 // Get bot-specific Pinecone configuration
11572 $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
11573 $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
11574
11575 $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
11576
11577 if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
11578 // Delete from Pinecone (with optional content type filter)
11579 $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
11580
11581 if (!$result['success']) {
11582 $success = false;
11583 $error_messages[] = $result['message'];
11584 }
11585
11586 } else {
11587 // Delete from WordPress database
11588 global $wpdb;
11589 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
11590
11591 // Build WHERE conditions
11592 $where_clauses = array();
11593 $where_values = array();
11594
11595 // Bot filter
11596 if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
11597 $where_clauses[] = 'bot_id = %s';
11598 $where_values[] = $bot_id;
11599 }
11600
11601 // Content type filter
11602 if (!empty($content_type_filter)) {
11603 $where_clauses[] = 'content_type = %s';
11604 $where_values[] = $content_type_filter;
11605 }
11606
11607 if (!empty($where_clauses)) {
11608 $where_sql = implode(' AND ', $where_clauses);
11609 $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
11610 } else {
11611 // No filters — delete all
11612 $result = $wpdb->query("DELETE FROM {$table_name}");
11613 }
11614
11615 if ($result === false) {
11616 $success = false;
11617 $error_messages[] = 'Failed to delete from WordPress database';
11618 }
11619 }
11620
11621 // Every media entry in scope is gone: their auto-sync signatures go too,
11622 // or each file is skipped as "unchanged" on its next save (b0ae54).
11623 if ($success && (empty($content_type_filter) || $content_type_filter === 'attachment')) {
11624 MxChat_Utils::forget_all_attachment_signatures($bot_id);
11625 }
11626
11627 // Redirect back with a success message and bot_id
11628 $redirect_url = add_query_arg(array(
11629 'page' => 'mxchat-prompts',
11630 'bot_id' => $bot_id,
11631 'all_deleted' => $success ? 'true' : 'false'
11632 ), admin_url('admin.php'));
11633
11634 wp_safe_redirect($redirect_url);
11635 exit;
11636 }
11637
11638
11639
11640 /**
11641 * Handles deletion prompt with nonce validation
11642 */
11643 public function mxchat_handle_delete_prompt() {
11644 // Sanitize and validate nonce
11645 $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
11646 if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
11647 wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
11648 }
11649
11650 // Check permissions
11651 if (!current_user_can('manage_options')) {
11652 wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
11653 }
11654
11655 // Get ID and source parameters
11656 $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
11657 $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
11658
11659 if (empty($id)) {
11660 wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
11661 }
11662
11663 $success = false;
11664 $error_message = '';
11665
11666 // Resolve per-bot Pinecone settings — the global option is the wrong
11667 // index entirely when the row belongs to a bot with its own host
11668 $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default';
11669 $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
11670 $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
11671 $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
11672
11673 // If source is not specified, determine based on Pinecone configuration
11674 if (empty($source)) {
11675 $source = $use_pinecone ? 'pinecone' : 'wordpress';
11676 }
11677
11678 if ($source === 'pinecone' || $use_pinecone) {
11679 //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
11680
11681 // Handle Pinecone deletion
11682 if (empty($pinecone_options['mxchat_pinecone_host']) ||
11683 empty($pinecone_options['mxchat_pinecone_api_key'])) {
11684 wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
11685 }
11686
11687 // Delete from Pinecone using the vector ID directly
11688 $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
11689 $id,
11690 $pinecone_options['mxchat_pinecone_api_key'],
11691 $pinecone_options['mxchat_pinecone_host'],
11692 $pinecone_options['mxchat_pinecone_namespace'] ?? ''
11693 );
11694 if ($result['success']) {
11695 $success = true;
11696
11697 // Remove from vector cache
11698 $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
11699 $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
11700
11701 set_transient('mxchat_admin_notice_success',
11702 esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
11703 } else {
11704 $error_message = $result['message'];
11705 set_transient('mxchat_admin_notice_error',
11706 esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
11707 }
11708 } else {
11709 //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
11710
11711 // Handle WordPress database deletion
11712 global $wpdb;
11713 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
11714
11715 // Clear cache and delete prompt
11716 wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
11717
11718 $result = $wpdb->delete(
11719 $table_name,
11720 array('id' => intval($id)),
11721 array('%d')
11722 );
11723
11724 if ($result !== false) {
11725 $success = true;
11726 set_transient('mxchat_admin_notice_success',
11727 esc_html__('Entry deleted successfully.', 'mxchat'), 30);
11728 } else {
11729 set_transient('mxchat_admin_notice_error',
11730 esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
11731 }
11732 }
11733
11734 // Redirect back to the prompts page
11735 wp_safe_redirect(add_query_arg(
11736 array(
11737 'page' => 'mxchat-prompts',
11738 'deleted' => $success ? 'true' : 'false'
11739 ),
11740 admin_url('admin.php')
11741 ));
11742 exit;
11743 }
11744
11745
11746
11747
11748 /**
11749 * Averages multiple vectors into a single vector
11750 */
11751 private function mxchat_average_vectors($vectors) {
11752 $vector_length = count($vectors[0]);
11753 $sum_vector = array_fill(0, $vector_length, 0);
11754
11755 foreach ($vectors as $vector) {
11756 for ($i = 0; $i < $vector_length; $i++) {
11757 $sum_vector[$i] += $vector[$i];
11758 }
11759 }
11760
11761 // Divide each component by the number of vectors to get the average
11762 $num_vectors = count($vectors);
11763 for ($i = 0; $i < $vector_length; $i++) {
11764 $sum_vector[$i] /= $num_vectors;
11765 }
11766
11767 return $sum_vector;
11768 }
11769
11770
11771
11772
11773 /**
11774 * Generates embeddings from input text for MXChat
11775 */
11776 public function mxchat_generate_embedding($text) {
11777 // Enable detailed logging for debugging
11778 //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
11779 //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
11780
11781 $options = get_option('mxchat_options');
11782
11783 // Custom Provider embeddings first, as the chat and the knowledge
11784 // importers do (plan 418afd): a phrase embedded with another model
11785 // can never match a question embedded with the custom one. Returns
11786 // the vector, or the error string this function returns on failure.
11787 if (is_array($options) && isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
11788 return MxChat_Utils::generate_embedding_custom($text, $options);
11789 }
11790
11791 $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
11792 //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
11793
11794 // Determine provider and endpoint
11795 if (strpos($selected_model, 'voyage') === 0) {
11796 $api_key = $options['voyage_api_key'] ?? '';
11797 $endpoint = 'https://api.voyageai.com/v1/embeddings';
11798 $provider_name = 'Voyage AI';
11799 //error_log('[MXCHAT-EMBED] Using Voyage AI API');
11800 } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
11801 $api_key = $options['gemini_api_key'] ?? '';
11802 $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
11803 $provider_name = 'Google Gemini';
11804 //error_log('[MXCHAT-EMBED] Using Google Gemini API');
11805 } else {
11806 $api_key = $options['api_key'] ?? '';
11807 $endpoint = 'https://api.openai.com/v1/embeddings';
11808 $provider_name = 'OpenAI';
11809 //error_log('[MXCHAT-EMBED] Using OpenAI API');
11810 }
11811
11812 //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
11813
11814 if (empty($api_key)) {
11815 $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
11816 //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
11817 return $error_message;
11818 }
11819
11820 // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
11821 $estimated_tokens = ceil(str_word_count($text) / 0.75);
11822 //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
11823
11824 if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
11825 //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
11826 // Consider truncating text here
11827 }
11828
11829 // Prepare request body based on provider
11830 if (strpos($selected_model, 'gemini-embedding') === 0) {
11831 // Gemini API format
11832 $request_body = array(
11833 'model' => 'models/' . $selected_model,
11834 'content' => array(
11835 'parts' => array(
11836 array('text' => $text)
11837 )
11838 )
11839 );
11840
11841 // Set output dimensionality to 1536 for consistency with other models
11842 $request_body['outputDimensionality'] = 1536;
11843 } else {
11844 // OpenAI/Voyage API format
11845 $request_body = array(
11846 'model' => $selected_model,
11847 'input' => $text
11848 );
11849
11850 // Add output_dimension for voyage-3-large model
11851 if ($selected_model === 'voyage-3-large') {
11852 $request_body['output_dimension'] = 2048;
11853 }
11854 }
11855
11856 //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
11857
11858 // Prepare headers based on provider
11859 if (strpos($selected_model, 'gemini-embedding') === 0) {
11860 // Gemini uses API key as query parameter
11861 $endpoint .= '?key=' . $api_key;
11862 $headers = array(
11863 'Content-Type' => 'application/json'
11864 );
11865 } else {
11866 // OpenAI/Voyage use Bearer token
11867 $headers = array(
11868 'Authorization' => 'Bearer ' . $api_key,
11869 'Content-Type' => 'application/json'
11870 );
11871 }
11872
11873 // Make API request
11874 //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
11875 $response = wp_remote_post($endpoint, array(
11876 'body' => wp_json_encode($request_body),
11877 'headers' => $headers,
11878 'timeout' => 60 // Increased timeout for large inputs
11879 ));
11880
11881 // Handle wp_remote_post errors
11882 if (is_wp_error($response)) {
11883 $error_message = $response->get_error_message();
11884 //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
11885 return 'Connection error: ' . $error_message;
11886 }
11887
11888 // Get and check HTTP response code
11889 $http_code = wp_remote_retrieve_response_code($response);
11890 //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
11891
11892 if ($http_code !== 200) {
11893 $error_body = wp_remote_retrieve_body($response);
11894 //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
11895
11896 // Try to parse error for more details
11897 $error_json = json_decode($error_body, true);
11898 if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
11899 $error_type = $error_json['error']['type'] ?? 'unknown';
11900 $error_message = $error_json['error']['message'] ?? 'No message';
11901 //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
11902 //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
11903
11904 // Customize error message for common API errors
11905 if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
11906 $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
11907 } elseif ($error_type === 'authentication_error') {
11908 $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
11909 }
11910
11911 //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11912 return $error_message;
11913 }
11914
11915 $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
11916 //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11917 return $error_message;
11918 }
11919
11920 // Parse response body
11921 $response_body = wp_remote_retrieve_body($response);
11922 //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
11923
11924 $response_data = json_decode($response_body, true);
11925
11926 if (json_last_error() !== JSON_ERROR_NONE) {
11927 $error = json_last_error_msg();
11928 //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
11929 //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
11930 return "Failed to parse API response: $error";
11931 }
11932
11933 // Handle different response formats based on provider
11934 if (strpos($selected_model, 'gemini-embedding') === 0) {
11935 // Gemini API response format
11936 if (isset($response_data['embedding']['values'])) {
11937 $embedding_dimensions = count($response_data['embedding']['values']);
11938 //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
11939
11940 // Check if embedding dimensions are as expected (should be 1536)
11941 if ($embedding_dimensions !== 1536) {
11942 //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
11943 }
11944
11945 MxChat_Utils::stamp_active_embedding_model($selected_model);
11946 return $response_data['embedding']['values'];
11947 } else {
11948 //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
11949 //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11950
11951 if (isset($response_data['error'])) {
11952 $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
11953 //error_log('[MXCHAT-EMBED] ' . $error_message);
11954 return $error_message;
11955 }
11956
11957 $error_message = "Invalid Gemini API response format: No embedding found";
11958 //error_log('[MXCHAT-EMBED] ' . $error_message);
11959 return $error_message;
11960 }
11961 } else {
11962 // OpenAI/Voyage API response format
11963 if (isset($response_data['data'][0]['embedding'])) {
11964 $embedding_dimensions = count($response_data['data'][0]['embedding']);
11965 //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
11966
11967 // Check if embedding dimensions are as expected
11968 if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
11969 ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
11970 //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
11971 }
11972
11973 MxChat_Utils::stamp_active_embedding_model($selected_model);
11974 return $response_data['data'][0]['embedding'];
11975 } else {
11976 //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
11977 //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11978
11979 if (isset($response_data['error'])) {
11980 $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
11981 //error_log('[MXCHAT-EMBED] ' . $error_message);
11982 return $error_message;
11983 }
11984
11985 $error_message = "Invalid API response format: No embedding found";
11986 //error_log('[MXCHAT-EMBED] ' . $error_message);
11987 return $error_message;
11988 }
11989 }
11990 }
11991
11992
11993
11994 }
11995 ?>
11996