PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.0.11
MxChat – AI Chatbot & Content Generation for WordPress v1.0.11
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-admin.php +1174 -10460 3.2.191.0.11 View file →
@@ -6,31 +6,13 @@
6 6 class MxChat_Admin {
7 7 private $options;
8 8 private $chat_count;
9 9 private $is_activated;
10 - private $knowledge_manager;
11 10
12 - /**
13 - * Get whether the license is activated
14 - * @return bool
15 - */
16 - public function is_activated() {
17 - return $this->is_activated;
18 - }
19 -
20 - /**
21 - * Get plugin options
22 - * @return array
23 - */
24 - public function get_options() {
25 - return $this->options;
26 - }
27 -
28 - public function __construct($knowledge_manager = null) {
11 + public function __construct() {
29 12 $this->options = get_option('mxchat_options');
30 13 $this->chat_count = get_option('mxchat_chat_count', 0);
31 14 $this->is_activated = $this->is_license_active();
32 - $this->knowledge_manager = $knowledge_manager;
33 15
34 16 // Initialize default options if they are not set
35 17 if (!$this->options) {
36 18 $this->initialize_default_options();
@@ -37,410 +19,66 @@
37 19 }
38 20
39 21 // Add admin menu and initialize settings
40 22 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
41 - // Pro & Extensions registers at priority 30 so it always lands last in
42 - // the sidebar — below API Access (priority 20) and below any other
43 - // submenu that hooks at default priority 10.
44 - add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
45 - // Onboarding visibility — runs LAST so it can remove the submenu after every
46 - // other add_submenu_page() call. The page stays reachable by direct URL.
47 - add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999);
48 23 add_action('admin_init', array($this, 'mxchat_page_init'));
49 - add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
50 24 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
51 - // Add body class for the Onboarding wizard (plan-905439) so the
52 - // chrome-surgery CSS in admin-onboarding-wizard.css can scope its
53 - // WP-sidebar collapse to this page only.
54 - add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class'));
55 25 add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
26 + add_action('admin_post_mxchat_submit_content', array($this, 'mxchat_handle_content_submission'));
56 27 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
57 28 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
58 29 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
59 - add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
30 + add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
60 31 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
61 32 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
62 33 add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
34 + add_action('wp_ajax_mxchat_activate_license', array($this, 'mxchat_handle_activate_license'));
63 35 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
64 - add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
65 - add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
66 - add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
67 - add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
68 - add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
69 36
70 - // Leads tab (inside Transcripts)
71 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
72 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
73 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
74 -
75 - add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
76 - add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
77 - add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
78 - add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
79 - // Self-heal: the cleanup event is otherwise only scheduled at activation or
80 - // when the retention setting CHANGES — if it is ever lost (deactivate cycle,
81 - // cron-option wipe, DB restore) nothing re-registers it and retention goes
82 - // silently inert while the UI still says it is on (plan-bc08a6).
83 - add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled'));
84 -
85 - add_action('admin_init', array($this, 'register_pinecone_settings'));
86 - add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
87 -
88 - add_action('admin_notices', array($this, 'display_admin_notices'));
89 -
90 - add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
91 - add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
92 - add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
93 -
94 - // wp_ajax_mxchat_save_selected_bot is registered (and handled) in
95 - // admin/class-ajax-handler.php — a duplicate registration here pointed
96 - // at a method this class never defined, a load-order-dependent fatal
97 - // waiting to fire (plan 52bcad).
98 - add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
99 - add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
100 -
101 - // Actions page AJAX handlers
102 - add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
103 - add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
104 - add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
105 - add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
106 - add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
107 - add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
108 - add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
109 - add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
110 - add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
111 - add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
112 -
113 - // Slack test connection
114 - add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
115 -
116 - // Translation handlers
117 - add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
118 - add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
119 -
120 - // 3.2.3: Embedding model switch protection
121 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
122 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
123 - add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax'));
124 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
125 - add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice'));
126 37 }
127 38
128 - /**
129 - * Nudge admins to configure a Telegram webhook secret (plan-0c17b5).
130 - *
131 - * Shown only when a Telegram bot token is configured (integration active)
132 - * AND no webhook secret is set. Without a secret the webhook falls back to a
133 - * Telegram source-IP check — safer than the old fail-open, but a real secret
134 - * is the recommended protection. Dismissible; does not block anything.
135 - */
136 - public function mxchat_telegram_secret_notice() {
137 - if (!current_user_can('manage_options')) {
138 - return;
139 - }
140 - $options = get_option('mxchat_options', array());
141 - $has_token = !empty($options['telegram_bot_token']);
142 - $has_secret = !empty($options['telegram_webhook_secret']);
143 - if (!$has_token || $has_secret) {
144 - return;
145 - }
146 - if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') {
147 - return;
148 - }
149 - $settings_url = admin_url('admin.php?page=mxchat-max');
150 - ?>
151 - <div class="notice notice-warning is-dismissible mxchat-telegram-secret-notice">
152 - <p><strong><?php esc_html_e('MxChat: Telegram webhook is running without a secret token', 'mxchat'); ?></strong></p>
153 - <p>
154 - <?php esc_html_e('Your Telegram integration is active but no webhook secret is configured. Requests are currently verified only by origin IP. For full protection, set a webhook secret token in the Telegram settings and re-register your webhook.', 'mxchat'); ?>
155 - </p>
156 - <p>
157 - <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
158 - </p>
159 - </div>
160 - <script>
161 - (function(){
162 - var n = document.querySelector('.mxchat-telegram-secret-notice');
163 - if (!n) return;
164 - n.addEventListener('click', function(e){
165 - if (e.target && e.target.classList.contains('notice-dismiss')) {
166 - var d = new FormData();
167 - d.append('action', 'mxchat_dismiss_telegram_secret_notice');
168 - d.append('nonce', '<?php echo esc_js(wp_create_nonce('mxchat_dismiss_telegram_secret')); ?>');
169 - fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', { method: 'POST', body: d, credentials: 'same-origin' });
170 - }
171 - });
172 - })();
173 - </script>
174 - <?php
39 + // Method to check if the license is active
40 + private function is_license_active() {
41 + $license_status = get_option('mxchat_license_status', 'inactive');
42 + return $license_status === 'active';
175 43 }
176 44
177 - /**
178 - * AJAX: persist dismissal of the Telegram-secret admin notice (plan-0c17b5).
179 - */
180 - public function mxchat_dismiss_telegram_secret_notice_ajax() {
181 - if (!current_user_can('manage_options')
182 - || !check_ajax_referer('mxchat_dismiss_telegram_secret', 'nonce', false)) {
183 - wp_send_json_error();
184 - }
185 - update_option('mxchat_dismissed_telegram_secret_notice', '1', 'no');
186 - wp_send_json_success();
187 - }
45 + // Initialize default options
46 + private function initialize_default_options() {
47 + $default_options = array(
48 + 'api_key' => '',
49 + 'system_prompt_instructions' => '[EXAMPLE INSTRUCTIONS] You are an AI Chatbot assistant for this website. The primary subject you should focus on is [insert proper subject here]. Your main goal is to assist visitors with questions related to this specific topic. Here are some key things to keep in mind:
50 + - Your name is [Chatbot Name]. Always introduce yourself as this name when appropriate.
51 + - Stay focused on topics related to [insert proper subject here]. If a visitor asks about an unrelated topic, politely redirect the conversation to how you can assist them with this subject. If there is an exception topic (e.g., "parking") that you should assist with, you may do so if instructed.
52 + - When appropriate, highlight the benefits of [insert proper subject here]. Offer to guide visitors to relevant pages or provide them with more information.
53 + - If a visitor asks for a purchase link or further information, provide them with this link: [Insert Purchase Link Here]. Always ensure that the link is relevant and directly related to the website\'s offerings.
54 + - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
55 + - If you reference specific content, provide a hyperlink to the relevant page using hypertext. Avoid including links that do not directly relate to the content or answer the visitor\'s query.
56 + - Provide answers based on the knowledge available to you. If you do not have an answer to a specific question, let the visitor know that you don’t have the information and suggest where they might find it or offer to help with something else.',
57 + 'model' => 'gpt-3.5-turbo',
58 + 'rate_limit' => '100',
59 + 'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
60 + 'top_bar_title' => 'MxChat',
61 + 'intro_message' => 'Hello! How can I assist you today?',
62 + 'input_copy' => 'How can I assist?',
63 + 'append_to_body' => 'on',
64 + 'close_button_color' => '#fff',
65 + 'chatbot_bg_color' => '#fff',
66 + 'user_message_bg_color' => '#fff',
67 + 'user_message_font_color' => '#212121',
68 + 'bot_message_bg_color' => '#212121',
69 + 'bot_message_font_color' => '#fff',
70 + 'top_bar_bg_color' => '#212121',
71 + 'send_button_font_color' => '#212121',
72 + 'chat_input_font_color' => '#212121',
73 + 'chatbot_background_color' => '#212121',
74 + 'icon_color' => '#fff',
75 + 'enable_woocommerce_integration' => '0',
76 + 'enable_woocommerce_order_access' => '0',
77 + 'link_target_toggle' => 'on',
78 + );
188 79
189 - /**
190 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
191 - * switch. Pure option comparison — no counts, no DB queries beyond the
192 - * cached options. The dialog is shown whenever the user has previously
193 - * embedded with a different model than the one they're switching to.
194 - */
195 - public function mxchat_check_embedding_switch_ajax() {
196 - check_ajax_referer('mxchat_admin_nonce', 'security');
197 - if (!current_user_can('manage_options')) {
198 - wp_send_json_error(__('Unauthorized', 'mxchat'));
199 - }
200 80
201 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
202 - $options = get_option('mxchat_options', array());
203 - if (isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
204 - // The standard dropdown is inert while custom embeddings are on —
205 - // whatever value it posts, the next embed uses the custom identity.
206 - $new_model = MxChat_Utils::get_selected_embedding_model($options);
207 - }
208 - $active_model = MxChat_Utils::get_active_embedding_model();
209 -
210 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
211 -
212 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
213 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
214 -
215 - wp_send_json_success(array(
216 - 'is_mismatch' => $is_mismatch,
217 - 'active_model' => $active_model,
218 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
219 - 'new_model' => $new_model,
220 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
221 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
222 - 'active_dims' => $active_dims,
223 - 'new_dims' => $new_dims,
224 - ));
225 - }
226 -
227 - /**
228 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
229 - * pair so the banner reappears on the next switch event.
230 - */
231 - public function mxchat_dismiss_embedding_mismatch_ajax() {
232 - check_ajax_referer('mxchat_admin_nonce', 'security');
233 - if (!current_user_can('manage_options')) {
234 - wp_send_json_error(__('Unauthorized', 'mxchat'));
235 - }
236 -
237 - $options = get_option('mxchat_options', array());
238 - $selected = MxChat_Utils::get_selected_embedding_model($options);
239 - $active = MxChat_Utils::get_active_embedding_model();
240 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
241 - wp_send_json_success();
242 - }
243 -
244 - /**
245 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
246 - * (last used to actually embed something) differs from the currently
247 - * selected model. Pure option comparison — no DB queries on every page
248 - * load. The banner auto-clears once both match again, i.e. after a delete
249 - * + re-embed cycle.
250 - */
251 - public function mxchat_embedding_mismatch_notice() {
252 - if (!current_user_can('manage_options')) {
253 - return;
254 - }
255 -
256 - $options = get_option('mxchat_options', array());
257 - $selected = MxChat_Utils::get_selected_embedding_model($options);
258 - $active = MxChat_Utils::get_active_embedding_model();
259 -
260 - if (empty($active) || empty($selected) || $active === $selected) {
261 - return;
262 - }
263 -
264 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
265 - if ($dismissed === $active . '|' . $selected) {
266 - return;
267 - }
268 -
269 - $active_label = MxChat_Utils::embedding_model_label($active);
270 - $selected_label = MxChat_Utils::embedding_model_label($selected);
271 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
272 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
273 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
274 -
275 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
276 - $actions_url = admin_url('admin.php?page=mxchat-actions');
277 -
278 - ?>
279 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
280 - data-active="<?php echo esc_attr($active); ?>"
281 - data-selected="<?php echo esc_attr($selected); ?>">
282 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
283 - <p>
284 - <?php
285 - printf(
286 - /* translators: 1: previously-used model name, 2: currently-selected model name */
287 - esc_html__('Your knowledge base and actions were embedded with %1$s, but %2$s is now selected. Similarity matching will return inaccurate or empty results until you delete all existing embeddings and re-embed your content with the new model.', 'mxchat'),
288 - '<code>' . esc_html($active_label) . '</code>',
289 - '<code>' . esc_html($selected_label) . '</code>'
290 - );
291 - ?>
292 - </p>
293 - <?php if ($dims_differ) : ?>
294 - <p>
295 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
296 - <?php
297 - printf(
298 - /* translators: 1: old dim count, 2: new dim count */
299 - esc_html__('Existing vectors are %1$d-dimensional but the new model produces %2$d-dimensional vectors. If you use Pinecone, your index will reject queries entirely until re-embedded.', 'mxchat'),
300 - (int) $active_dims,
301 - (int) $selected_dims
302 - );
303 - ?>
304 - </p>
305 - <?php endif; ?>
306 - <p>
307 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
308 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
309 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
310 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
311 - </p>
312 - </div>
313 - <script>
314 - (function($){
315 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
316 - $.post(ajaxurl, {
317 - action: 'mxchat_dismiss_embedding_mismatch',
318 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
319 - });
320 - });
321 - })(jQuery);
322 - </script>
323 - <?php
324 - }
325 -
326 -private function is_license_active() {
327 - $license_status = get_option('mxchat_license_status', 'inactive');
328 - return ($license_status === 'active');
329 -}
330 -
331 -private function initialize_default_options() {
332 - $default_options = array(
333 - 'api_key' => '',
334 - 'xai_api_key' => '',
335 - 'claude_api_key' => '',
336 - 'deepseek_api_key' => '',
337 - 'voyage_api_key' => '',
338 - 'gemini_api_key' => '',
339 - 'enable_streaming_toggle' => 'off',
340 - 'enable_web_search' => 'off',
341 - 'embedding_model' => 'text-embedding-ada-002',
342 - 'system_prompt_instructions' => 'You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
343 -
344 - # Response Style - CRITICALLY IMPORTANT
345 - - MAXIMUM LENGTH: 1-3 short sentences per response
346 - - Ultra-concise: Get straight to the answer with no filler
347 - - No introductions like "Sure!" or "I\'d be happy to help"
348 - - No phrases like "based on my knowledge" or "according to information"
349 - - No explanatory text before giving the answer
350 - - No summaries or repetition
351 - - Hyperlink all URLs
352 - - Respond in user\'s language
353 - - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
354 -
355 - # Knowledge Base Requirements - PREVENT HALLUCINATIONS
356 - - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
357 - - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
358 - - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
359 - - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
360 - - Better to admit insufficient information than provide inaccurate answers',
361 - 'model' => esc_html__('gpt-5.6-sol', 'mxchat'),
362 - 'rate_limit_logged_out' => esc_html__('100', 'mxchat'),
363 - 'role_rate_limits' => array(),
364 - 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
365 - 'enable_email_block' => '',
366 - 'email_blocker_header_content' => __("<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>", 'mxchat'),
367 - 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
368 - 'enable_name_field' => 'off', // NEW
369 - 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
370 - 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
371 - 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
372 - 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
373 - 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
374 - 'append_to_body' => esc_html__('off', 'mxchat'),
375 - 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
376 - 'post_type_visibility_list' => array(), // Array of post type slugs
377 - 'contextual_awareness_toggle' => 'off',
378 - 'citation_links_toggle' => 'on',
379 - 'satisfaction_rating_enabled' => 'off',
380 - 'satisfaction_rating_idle_seconds' => 60,
381 - 'satisfaction_rating_question' => '',
382 - 'satisfaction_rating_thanks' => '',
383 - 'satisfaction_rating_placeholder' => '',
384 - 'satisfaction_rating_saved' => '',
385 - 'close_button_color' => esc_html__('#fff', 'mxchat'),
386 - 'chatbot_bg_color' => esc_html__('#fff', 'mxchat'),
387 - 'user_message_bg_color' => esc_html__('#fff', 'mxchat'),
388 - 'user_message_font_color' => esc_html__('#212121', 'mxchat'),
389 - 'bot_message_bg_color' => esc_html__('#212121', 'mxchat'),
390 - 'bot_message_font_color' => esc_html__('#fff', 'mxchat'),
391 - 'top_bar_bg_color' => esc_html__('#212121', 'mxchat'),
392 - 'send_button_font_color' => esc_html__('#212121', 'mxchat'),
393 - 'chat_input_font_color' => esc_html__('#212121', 'mxchat'),
394 - 'chatbot_background_color' => esc_html__('#212121', 'mxchat'),
395 - 'icon_color' => esc_html__('#fff', 'mxchat'),
396 - 'enable_woocommerce_integration' => esc_html__('0', 'mxchat'),
397 - 'link_target_toggle' => esc_html__('off', 'mxchat'),
398 - 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
399 -
400 - // New fields for Loops Integration
401 - 'loops_api_key' => '',
402 - 'loops_mailing_list' => '',
403 - 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
404 - 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
405 - 'popular_question_1' => '',
406 - 'popular_question_2' => '',
407 - 'popular_question_3' => '',
408 - 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
409 - 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
410 - 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
411 - 'pdf_max_pages' => 69,
412 - 'show_pdf_upload_button' => 'on',
413 - 'show_word_upload_button' => 'on',
414 -
415 - // Live Agent Integration (Slack)
416 - 'live_agent_webhook_url' => '',
417 - 'live_agent_secret_key' => '',
418 - 'live_agent_bot_token' => '',
419 - 'live_agent_message_bg_color' => esc_html__('#ffffff', 'mxchat'),
420 - 'live_agent_message_font_color' => esc_html__('#333333', 'mxchat'),
421 -
422 - // Telegram Integration
423 - 'telegram_status' => 'off',
424 - 'telegram_bot_token' => '',
425 - 'telegram_group_id' => '',
426 - 'telegram_webhook_secret' => '',
427 - 'telegram_notification_message' => __("I've notified a support agent. Please allow a moment for them to respond. If you'd like to continue with AI, just type \"Switch to AI\" at any time.", 'mxchat'),
428 - 'telegram_away_message' => __("I just checked, and it looks like our support team isn't personally available at the moment. If you'd like, you can leave your email address, and they'll get back to you as soon as possible. In the meantime, you can keep chatting with me — just let me know how I can help!", 'mxchat'),
429 -
430 - 'chat_toolbar_toggle' => esc_html__('off', 'mxchat'),
431 - 'mode_indicator_bg_color' => esc_html__('#767676', 'mxchat'),
432 - 'mode_indicator_font_color' => esc_html__('#ffffff', 'mxchat'),
433 - 'toolbar_icon_color' => esc_html__('#212121', 'mxchat'),
434 -
435 - // Optimization settings
436 - 'script_loading_strategy' => 'default',
437 -
438 - // Debug settings
439 - 'debug_mode' => 'off',
440 - );
441 -
442 -
443 81 // Merge existing options with defaults
444 82 $existing_options = get_option('mxchat_options', array());
445 83 $merged_options = wp_parse_args($existing_options, $default_options);
446 84
@@ -448,5782 +86,603 @@
448 86 if ($existing_options !== $merged_options) {
449 87 update_option('mxchat_options', $merged_options);
450 88 }
451 89
452 - // Add default limits for each role
453 - $roles = wp_roles()->get_names();
454 - foreach ($roles as $role_id => $role_name) {
455 - $default_options['role_rate_limits'][$role_id] = esc_html__('100', 'mxchat');
456 - }
457 -
458 - return $default_options;
459 -
460 90 // Update the $this->options property
461 91 $this->options = $merged_options;
462 92 }
463 93
464 -public function mxchat_add_plugin_page() {
465 - // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file).
466 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
94 + public function mxchat_add_plugin_page() {
95 + // Main menu page
96 + add_menu_page(
97 + 'MxChat Settings',
98 + 'MxChat',
99 + 'manage_options',
100 + 'mxchat-max',
101 + array($this, 'mxchat_create_admin_page'),
102 + 'dashicons-testimonial',
103 + 6
104 + );
467 105
468 - // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu
469 - // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now
470 - // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding).
471 - add_menu_page(
472 - esc_html__('MxChat', 'mxchat'),
473 - esc_html__('MxChat', 'mxchat'),
474 - 'manage_options',
475 - 'mxchat-max',
476 - array($this, 'mxchat_create_dashboard_page'),
477 - 'dashicons-testimonial',
478 - 6
479 - );
106 + // Submenu page for Knowledge
107 + add_submenu_page(
108 + 'mxchat-max',
109 + 'Prompts',
110 + 'Knowledge',
111 + 'manage_options',
112 + 'mxchat-prompts',
113 + array($this, 'mxchat_create_prompts_page')
114 + );
480 115
481 - // Onboarding submenu — first child under MxChat (plan-d14e89).
482 - // First registration uses menu_slug === parent slug 'mxchat-max' →
483 - // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the
484 - // first child shows as "Onboarding" instead of a redundant pair.
485 - add_submenu_page(
486 - 'mxchat-max',
487 - esc_html__('MxChat Onboarding', 'mxchat'),
488 - esc_html__('Onboarding', 'mxchat'),
489 - 'manage_options',
490 - 'mxchat-max',
491 - array($this, 'mxchat_create_dashboard_page')
492 - );
493 - // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link
494 - // + legacy redirects still target this slug). Parent === null keeps it
495 - // out of the menu while remaining accessible by URL.
496 - add_submenu_page(
497 - null,
498 - esc_html__('MxChat Onboarding', 'mxchat'),
499 - esc_html__('Onboarding', 'mxchat'),
500 - 'manage_options',
501 - 'mxchat-onboarding',
502 - array($this, 'mxchat_create_dashboard_page')
503 - );
116 + // Submenu page for Chat Transcripts
117 + add_submenu_page(
118 + 'mxchat-max', // Corrected parent slug to match the main menu
119 + 'Chat Transcripts',
120 + 'Transcripts',
121 + 'manage_options',
122 + 'mxchat-transcripts',
123 + array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
124 + );
504 125
505 - // Settings submenu — same callback as before, just at a new slug.
506 - add_submenu_page(
507 - 'mxchat-max',
508 - esc_html__('MxChat Settings', 'mxchat'),
509 - esc_html__('Settings', 'mxchat'),
510 - 'manage_options',
511 - 'mxchat-settings',
512 - array($this, 'mxchat_create_admin_page')
513 - );
514 -
515 - // Submenu page for Knowledge
516 - add_submenu_page(
517 - 'mxchat-max',
518 - esc_html__('Prompts', 'mxchat'),
519 - esc_html__('Knowledge', 'mxchat'),
520 - 'manage_options',
521 - 'mxchat-prompts',
522 - array($this, 'mxchat_create_prompts_page')
523 - );
524 -
525 - add_submenu_page(
526 - 'mxchat-max',
527 - esc_html__('Chat Transcripts', 'mxchat'),
528 - esc_html__('Transcripts', 'mxchat'),
529 - 'manage_options',
530 - 'mxchat-transcripts',
531 - array($this, 'mxchat_create_transcripts_page')
532 - );
533 -
534 - add_submenu_page(
535 - 'mxchat-max',
536 - esc_html__('MxChat Actions', 'mxchat'),
537 - esc_html__('Actions', 'mxchat'),
538 - 'manage_options',
539 - 'mxchat-actions',
540 - array($this, 'mxchat_actions_page_html')
541 - );
542 -
543 - // Content Generator page
544 - add_submenu_page(
545 - 'mxchat-max',
546 - esc_html__('Content', 'mxchat'),
547 - esc_html__('Content', 'mxchat'),
548 - 'manage_options',
549 - 'mxchat-content',
550 - array($this, 'mxchat_create_content_page')
551 - );
552 -
553 -}
554 -
555 -/**
556 - * Register the Pro & Extensions submenu on a later admin_menu priority so it
557 - * always renders as the bottom-most item in the MxChat sidebar — below
558 - * configuration pages like API Access (priority 20).
559 - */
560 -public function mxchat_add_pro_extensions_page() {
561 - add_submenu_page(
562 - 'mxchat-max',
563 - esc_html__('Pro & Extensions', 'mxchat'),
564 - esc_html__('Pro & Extensions', 'mxchat'),
565 - 'manage_options',
566 - 'mxchat-activation',
567 - array($this, 'mxchat_create_activation_page')
568 - );
569 -}
570 -
571 -public function mxchat_create_addons_page() {
572 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
573 - $addons_page = new MxChat_Addons();
574 - $addons_page->render_page();
575 -}
576 -
577 -/**
578 - * Render the Content Generator admin page
579 - */
580 -public function mxchat_create_content_page() {
581 - require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
582 - // The Editor Assistant toggle on the Settings tab renders through
583 - // mxchat_render_field_wrapper(), which lives in admin-settings-page.php
584 - // (plan-f7df40 relocation) — load it the same way the settings page does.
585 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
586 - mxchat_render_content_page($this);
587 -}
588 -
589 -/**
590 - * Test actual streaming functionality in the WordPress environment
591 - */
592 -public function mxchat_handle_test_streaming_actual() {
593 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
594 -
595 - // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler
596 - // reads the site's provider keys and spends them on an outbound call, so it
597 - // is billable abuse for any logged-in user who obtained the nonce.
598 - if (!current_user_can('manage_options')) {
599 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
126 + // Submenu page for Activation Key
127 + add_submenu_page(
128 + 'mxchat-max',
129 + 'Pro Upgrade',
130 + 'Pro Upgrade',
131 + 'manage_options',
132 + 'mxchat-activation',
133 + array($this, 'mxchat_create_activation_page')
134 + );
600 135 }
601 136
602 - // Check if headers have already been sent
603 - if (headers_sent()) {
604 - wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
605 - return;
606 - }
607 137
608 - // Check for required functions
609 - if (!function_exists('curl_init')) {
610 - wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
138 +public function mxchat_handle_content_submission() {
139 + // Check if the form was submitted and the user has sufficient permissions
140 + if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
611 141 return;
612 142 }
613 143
614 - // Get user's selected model and API key
615 - $options = get_option('mxchat_options', []);
616 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
617 -
618 - // Get the provider from the model
619 - $model_parts = explode('-', $selected_model);
620 - $provider = strtolower($model_parts[0]);
621 -
622 - // Get the appropriate API key
623 - $api_key = '';
624 - switch ($provider) {
625 - case 'gpt':
626 - case 'o1':
627 - $api_key = $options['api_key'] ?? '';
628 - break;
629 - case 'claude':
630 - $api_key = $options['claude_api_key'] ?? '';
631 - break;
632 - case 'grok':
633 - $api_key = $options['xai_api_key'] ?? '';
634 - break;
635 - case 'deepseek':
636 - $api_key = $options['deepseek_api_key'] ?? '';
637 - break;
638 - case 'gemini':
639 - $api_key = $options['gemini_api_key'] ?? '';
640 - break;
641 - default:
642 - // Default to OpenAI for unknown models
643 - $api_key = $options['api_key'] ?? '';
644 - $provider = 'gpt';
645 - break;
144 + // Verify the nonce field for security
145 + $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
146 + if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
147 + wp_die('Nonce verification failed.');
646 148 }
647 149
648 - if (empty($api_key)) {
649 - wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
650 - return;
651 - }
150 + // Sanitize the content input
151 + $article_content = sanitize_textarea_field($_POST['article_content']);
652 152
653 - // Test streaming with the selected model and provider
654 - try {
655 - $this->perform_streaming_test($provider, $selected_model, $api_key);
656 - } catch (Exception $e) {
657 - wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
658 - }
659 -}
153 + // Generate the embedding vector for the content
154 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
660 155
661 -/**
662 - * Perform the actual streaming test
663 - */
664 -private function perform_streaming_test($provider, $model, $api_key) {
665 - // Set streaming headers
666 - header('Content-Type: text/event-stream');
667 - header('Cache-Control: no-cache');
668 - header('X-Accel-Buffering: no'); // Disable nginx buffering
156 + global $wpdb;
157 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
669 158
670 - // Prepare test message
671 - $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
672 -
673 - // Configure API request based on provider
674 - $url = '';
675 - $headers = [];
676 - $body = [];
677 -
678 - switch ($provider) {
679 - case 'gpt':
680 - case 'o1':
681 - $url = 'https://api.openai.com/v1/chat/completions';
682 - $headers = [
683 - 'Content-Type: application/json',
684 - 'Authorization: Bearer ' . $api_key
685 - ];
686 - $body = [
687 - 'model' => $model,
688 - 'messages' => [['role' => 'user', 'content' => $test_message]],
689 - 'max_tokens' => 50,
690 - 'temperature' => 0.3,
691 - 'stream' => true
692 - ];
693 - break;
694 -
695 - case 'claude':
696 - $url = 'https://api.anthropic.com/v1/messages';
697 - $headers = [
698 - 'Content-Type: application/json',
699 - 'x-api-key: ' . $api_key,
700 - 'anthropic-version: 2023-06-01'
701 - ];
702 - $body = [
703 - 'model' => $model,
704 - 'messages' => [['role' => 'user', 'content' => $test_message]],
705 - 'max_tokens' => 50,
706 - 'temperature' => 0.3,
707 - 'stream' => true
708 - ];
709 - // Claude flagships from Opus 4.7 onward reject the temperature
710 - // param outright (400). Reuse the catalog's decision — this path
711 - // previously sent temperature unconditionally, so the streaming
712 - // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5.
713 - if (class_exists('MxChat_Model_Catalog')
714 - && method_exists('MxChat_Model_Catalog', 'supports_temperature')
715 - && !MxChat_Model_Catalog::supports_temperature($model)) {
716 - unset($body['temperature']);
717 - }
718 - break;
719 -
720 - case 'grok':
721 - $url = 'https://api.x.ai/v1/chat/completions';
722 - $headers = [
723 - 'Content-Type: application/json',
724 - 'Authorization: Bearer ' . $api_key
725 - ];
726 - $body = [
727 - 'model' => $model,
728 - 'messages' => [['role' => 'user', 'content' => $test_message]],
729 - 'max_tokens' => 50,
730 - 'temperature' => 0.3,
731 - 'stream' => true
732 - ];
733 - break;
734 -
735 - case 'deepseek':
736 - $url = 'https://api.deepseek.com/v1/chat/completions';
737 - $headers = [
738 - 'Content-Type: application/json',
739 - 'Authorization: Bearer ' . $api_key
740 - ];
741 - $body = [
742 - 'model' => $model,
743 - 'messages' => [['role' => 'user', 'content' => $test_message]],
744 - 'max_tokens' => 50,
745 - 'temperature' => 0.3,
746 - 'stream' => true,
747 - // DeepSeek V4 defaults to thinking mode ON — reasoning would
748 - // consume the 50-token test budget and return no visible text.
749 - 'thinking' => ['type' => 'disabled']
750 - ];
751 - break;
752 -
753 - default:
754 - echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
755 - flush();
756 - return;
159 + // Check if the 'source_url' column exists in the table and add it if it doesn't
160 + if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
161 + // Use wpdb::query and a prepared statement to avoid SQL injection
162 + $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
757 163 }
758 164
759 - // Initialize cURL
760 - $ch = curl_init();
761 - curl_setopt($ch, CURLOPT_URL, $url);
762 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
763 - curl_setopt($ch, CURLOPT_POST, true);
764 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
765 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
766 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
767 - curl_setopt($ch, CURLOPT_TIMEOUT, 30);
768 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
769 - return $this->process_streaming_test_data($data, $provider);
770 - });
165 + if (is_array($embedding_vector)) {
166 + // Serialize the embedding vector before storing it
167 + $embedding_vector_serialized = serialize($embedding_vector);
771 168
772 - // Send initial test message
773 - echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
774 - flush();
169 + // Insert the content and embedding vector into the database, using a prepared statement
170 + $inserted = $wpdb->insert(
171 + $table_name,
172 + array(
173 + 'article_content' => $article_content,
174 + 'embedding_vector' => $embedding_vector_serialized,
175 + 'source_url' => '', // Empty string as a placeholder for now, or pass a valid URL if applicable
176 + ),
177 + array(
178 + '%s', // Format for article_content (string)
179 + '%s', // Format for embedding_vector (serialized string)
180 + '%s', // Format for source_url (string)
181 + )
182 + );
775 183
776 - $result = curl_exec($ch);
777 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
778 - $curl_error = curl_error($ch);
779 - curl_close($ch);
780 -
781 - if ($curl_error) {
782 - echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
783 - flush();
784 - return;
785 - }
786 -
787 - if ($http_code !== 200) {
788 - echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
789 - flush();
790 - return;
791 - }
792 -
793 - // Send completion signal
794 - echo "data: [DONE]\n\n";
795 - flush();
796 -}
797 -
798 -/**
799 - * Process streaming data for the test
800 - */
801 -private function process_streaming_test_data($data, $provider) {
802 - static $chunk_count = 0;
803 -
804 - $lines = explode("\n", $data);
805 -
806 - foreach ($lines as $line) {
807 - if (trim($line) === '') {
808 - continue;
809 - }
810 -
811 - // Handle different provider formats
812 - if ($provider === 'claude') {
813 - // Claude uses event: and data: format
814 - if (strpos($line, 'data: ') === 0) {
815 - $json_str = substr($line, 6);
816 - $json = json_decode($json_str, true);
817 -
818 - if (isset($json['type']) && $json['type'] === 'content_block_delta') {
819 - if (isset($json['delta']['text'])) {
820 - $chunk_count++;
821 - echo "data: " . json_encode([
822 - 'content' => $json['delta']['text'],
823 - 'test_chunk' => $chunk_count
824 - ]) . "\n\n";
825 - flush();
826 - }
827 - }
828 - }
184 + if ($inserted === false) {
185 + error_log('Error inserting content: ' . $wpdb->last_error);
186 + set_transient('mxchat_admin_notice', 'Error inserting content into the database. Please try again.', 30);
829 187 } else {
830 - // OpenAI, X.AI, DeepSeek format
831 - if (strpos($line, 'data: ') === 0) {
832 - $json_str = substr($line, 6);
833 -
834 - if ($json_str === '[DONE]') {
835 - // Don't echo [DONE] here, let the main function handle it
836 - continue;
837 - }
838 -
839 - $json = json_decode($json_str, true);
840 - if (isset($json['choices'][0]['delta']['content'])) {
841 - $chunk_count++;
842 - echo "data: " . json_encode([
843 - 'content' => $json['choices'][0]['delta']['content'],
844 - 'test_chunk' => $chunk_count
845 - ]) . "\n\n";
846 - flush();
847 - }
848 - }
188 + set_transient('mxchat_admin_notice', 'Content successfully submitted!', 30);
849 189 }
190 + } else {
191 + error_log('Embedding generation failed for article content: ' . $article_content);
192 + set_transient('mxchat_admin_notice', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
850 193 }
851 194
852 - return strlen($data);
195 + // Redirect after setting the transient
196 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
197 + exit;
853 198 }
854 199
855 -/**
856 - * Updated version of your existing test method (keep this as a fallback)
857 - */
858 -public function mxchat_handle_test_streaming() {
859 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
200 +public function mxchat_display_admin_notice() {
201 + // Get the message from the transient
202 + $message = get_transient('mxchat_admin_notice');
860 203
861 - // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but
862 - // fail here so the alias never becomes a bypass if that call is refactored.
863 - if (!current_user_can('manage_options')) {
864 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
865 - }
204 + if ($message) {
205 + echo '<div class="notice notice-error is-dismissible">';
206 + echo '<p>' . esc_html($message) . '</p>';
207 + echo '</div>';
866 208
867 - // Use the actual streaming test instead
868 - $this->mxchat_handle_test_streaming_actual();
869 -}
870 -
871 -
872 -public function register_pinecone_settings() {
873 - register_setting(
874 - 'mxchat_pinecone_addon_options',
875 - 'mxchat_pinecone_addon_options',
876 - array(
877 - 'type' => 'array',
878 - 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
879 - 'default' => array(
880 - 'mxchat_use_pinecone' => '0',
881 - 'mxchat_pinecone_api_key' => '',
882 - 'mxchat_pinecone_host' => '',
883 - 'mxchat_pinecone_index' => '',
884 - 'mxchat_pinecone_environment' => ''
885 - )
886 - )
887 - );
888 -}
889 -
890 -public function sanitize_pinecone_settings($input) {
891 - $sanitized = array();
892 -
893 - $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
894 - $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
895 - $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
896 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
897 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
898 -
899 - // Remove https:// from host if present
900 - $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
901 -
902 - return $sanitized;
903 -}
904 -
905 -public function register_openai_vectorstore_settings() {
906 - register_setting(
907 - 'mxchat_openai_vectorstore_options',
908 - 'mxchat_openai_vectorstore_options',
909 - array(
910 - 'type' => 'array',
911 - 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
912 - 'default' => array(
913 - 'mxchat_use_openai_vectorstore' => '0',
914 - 'mxchat_vectorstore_ids' => '',
915 - 'mxchat_vectorstore_max_results' => 5
916 - )
917 - )
918 - );
919 -}
920 -
921 -public function sanitize_openai_vectorstore_settings($input) {
922 - $sanitized = array();
923 -
924 - $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
925 - $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
926 - $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
927 -
928 - // Ensure max results is within reasonable range
929 - if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
930 - $sanitized['mxchat_vectorstore_max_results'] = 1;
209 + // Delete the transient after displaying the message
210 + delete_transient('mxchat_admin_notice');
931 211 }
932 - if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
933 - $sanitized['mxchat_vectorstore_max_results'] = 20;
934 - }
935 -
936 - return $sanitized;
937 212 }
938 213
939 -/**
940 - * AJAX handler to test OpenAI Vector Store connection
941 - */
942 -public function mxchat_test_vectorstore_connection() {
943 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
944 214
945 - if (!current_user_can('manage_options')) {
946 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
947 - return;
948 - }
215 + public function mxchat_handle_delete_prompt() {
216 + // Sanitize and validate nonce using wp_unslash and sanitize_text_field
217 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
218 + if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
219 + wp_die('Nonce verification failed.');
220 + }
949 221
950 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
951 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
952 - $mxchat_options = get_option('mxchat_options', array());
953 - $api_key = $mxchat_options['api_key'] ?? '';
222 + // Check user permissions
223 + if (!current_user_can('manage_options')) {
224 + wp_die('You do not have sufficient permissions to delete prompts.');
225 + }
954 226
955 - if (empty($api_key)) {
956 - wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
957 - return;
958 - }
227 + // Sanitize and validate the 'id' parameter
228 + $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
229 + if ($id <= 0) {
230 + wp_die('Invalid prompt ID.');
231 + }
959 232
960 - if (empty($vectorstore_ids)) {
961 - wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
962 - return;
963 - }
233 + global $wpdb;
234 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
964 235
965 - // Get the first Vector Store ID for testing
966 - $ids_array = array_map('trim', explode(',', $vectorstore_ids));
967 - $test_id = $ids_array[0];
236 + // Clear relevant cache before deletion
237 + $cache_key = 'prompt_' . $id;
238 + wp_cache_delete($cache_key, 'mxchat_prompts');
968 239
969 - // Test by retrieving the Vector Store info
970 - $response = wp_remote_get(
971 - 'https://api.openai.com/v1/vector_stores/' . $test_id,
972 - array(
973 - 'headers' => array(
974 - 'Authorization' => 'Bearer ' . $api_key,
975 - 'Content-Type' => 'application/json',
976 - 'OpenAI-Beta' => 'assistants=v2'
977 - ),
978 - 'timeout' => 30
979 - )
980 - );
240 + // Delete the record using a prepared statement
241 + $deleted = $wpdb->delete($table_name, array('id' => $id), array('%d'));
981 242
982 - if (is_wp_error($response)) {
983 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
984 - return;
985 - }
986 -
987 - $status_code = wp_remote_retrieve_response_code($response);
988 - $body = json_decode(wp_remote_retrieve_body($response), true);
989 -
990 - if ($status_code === 200 && isset($body['id'])) {
991 - $file_count = $body['file_counts']['completed'] ?? 0;
992 - $name = $body['name'] ?? $test_id;
993 - wp_send_json_success(array(
994 - 'message' => sprintf(
995 - __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
996 - esc_html($name),
997 - $file_count
998 - )
999 - ));
1000 - } elseif ($status_code === 404) {
1001 - wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
1002 - } elseif ($status_code === 401) {
1003 - wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
1004 - } else {
1005 - $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
1006 - wp_send_json_error(array('message' => $error_message));
1007 - }
1008 -}
1009 -
1010 -/**
1011 - * AJAX handler to test Slack connection and validate scopes
1012 - */
1013 -public function mxchat_test_slack_connection() {
1014 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
1015 -
1016 - if (!current_user_can('manage_options')) {
1017 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1018 - return;
1019 - }
1020 -
1021 - $bot_token = $this->options['live_agent_bot_token'] ?? '';
1022 -
1023 - if (empty($bot_token)) {
1024 - wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
1025 - return;
1026 - }
1027 -
1028 - // Test 1: Validate bot token with auth.test
1029 - $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
1030 - 'headers' => array(
1031 - 'Authorization' => 'Bearer ' . $bot_token,
1032 - 'Content-Type' => 'application/json'
1033 - ),
1034 - 'timeout' => 15
1035 - ));
1036 -
1037 - if (is_wp_error($auth_response)) {
1038 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
1039 - return;
1040 - }
1041 -
1042 - $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
1043 -
1044 - if (!isset($auth_body['ok']) || !$auth_body['ok']) {
1045 - $error = $auth_body['error'] ?? 'unknown_error';
1046 - $error_messages = array(
1047 - 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
1048 - 'not_authed' => __('No authentication token provided.', 'mxchat'),
1049 - 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
1050 - 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
1051 - );
1052 - $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
1053 - wp_send_json_error(array('message' => $message));
1054 - return;
1055 - }
1056 -
1057 - $team_name = $auth_body['team'] ?? 'Unknown Workspace';
1058 - $bot_name = $auth_body['user'] ?? 'Unknown Bot';
1059 -
1060 - // Test 2: Check if we can list channels (tests channels:read scope)
1061 - $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
1062 - 'headers' => array(
1063 - 'Authorization' => 'Bearer ' . $bot_token,
1064 - 'Content-Type' => 'application/json'
1065 - ),
1066 - 'body' => json_encode(array('limit' => 1)),
1067 - 'timeout' => 15
1068 - ));
1069 -
1070 - $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
1071 - $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
1072 -
1073 - // Test 3: Check if we can create channels (tests channels:manage scope)
1074 - // We'll just check the error message without actually creating
1075 - $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
1076 - 'headers' => array(
1077 - 'Authorization' => 'Bearer ' . $bot_token,
1078 - 'Content-Type' => 'application/json'
1079 - ),
1080 - 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
1081 - 'timeout' => 15
1082 - ));
1083 -
1084 - $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
1085 -
1086 - // If channel was created, delete it immediately
1087 - if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
1088 - wp_remote_post('https://slack.com/api/conversations.archive', array(
1089 - 'headers' => array(
1090 - 'Authorization' => 'Bearer ' . $bot_token,
1091 - 'Content-Type' => 'application/json'
1092 - ),
1093 - 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
1094 - 'timeout' => 15
1095 - ));
1096 - $can_create_channels = true;
1097 - } else {
1098 - $create_error = $create_body['error'] ?? '';
1099 - // name_taken means we have permission but channel exists
1100 - $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
1101 -
1102 - // Check for missing scope errors
1103 - if ($create_error === 'missing_scope') {
1104 - $can_create_channels = false;
243 + if ($deleted !== false) {
244 + // Optionally, clear a general cache if you have one
245 + wp_cache_delete('all_prompts', 'mxchat_prompts');
1105 246 }
1106 - }
1107 247
1108 - // Build result message
1109 - $results = array();
1110 - $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
1111 - $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
1112 - $results[] = '';
1113 - $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
1114 - $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
248 + // Redirect to the prompts page with a success message
249 + $redirect_url = add_query_arg(array(
250 + 'page' => 'mxchat-prompts',
251 + 'deleted' => 'true'
252 + ), admin_url('admin.php'));
1115 253
1116 - $missing_scopes = array();
1117 - if (!$can_read_channels) $missing_scopes[] = 'channels:read';
1118 - if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
1119 -
1120 - if (!empty($missing_scopes)) {
1121 - wp_send_json_error(array(
1122 - 'message' => implode("\n", $results),
1123 - 'missing_scopes' => $missing_scopes,
1124 - 'partial' => true
1125 - ));
1126 - } else {
1127 - wp_send_json_success(array(
1128 - 'message' => implode("\n", $results)
1129 - ));
254 + wp_safe_redirect($redirect_url);
255 + exit;
1130 256 }
1131 -}
1132 257
1133 -public function mxchat_display_admin_notice() {
1134 - // Success notice
1135 - if ($message = get_transient('mxchat_admin_notice_success')) {
1136 - ?>
1137 - <div class="notice notice-success is-dismissible">
1138 - <p><?php echo esc_html($message); ?></p>
1139 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
1140 - </div>
1141 - <?php
1142 - delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1143 - }
1144 258
1145 - // Error notice
1146 - if ($message = get_transient('mxchat_admin_notice_error')) {
1147 - ?>
1148 - <div class="notice notice-error is-dismissible">
1149 - <p><?php echo esc_html($message); ?></p>
1150 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
259 +public function mxchat_create_admin_page() {
260 + ?>
261 + <div class="wrap mxchat-admin">
262 + <?php if (!$this->is_activated): ?>
263 + <div class="mxchat-pro-banner">
264 + <p>
265 + Want even more features such as a fully customizable theme, WooCommerce integration, dedicated support, and much more?
266 + <a href="https://mxchat.ai/" target="_blank">Upgrade to MxChat Pro today and get a special launch lifetime license for only $49.97!</a>
267 + </p>
1151 268 </div>
1152 - <?php
1153 - delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1154 - }
1155 -}
1156 -
1157 -public function show_live_agent_disabled_banner() {
1158 - $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1159 -
1160 - if ($show_disabled_notice) {
1161 - ?>
1162 - <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1163 - <div class="mxchat-pro-notification">
1164 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1165 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1166 - <line x1="18" y1="6" x2="6" y2="18"></line>
1167 - <line x1="6" y1="6" x2="18" y2="18"></line>
1168 - </svg>
1169 - </button>
1170 - <div class="mxchat-live-agent-content">
1171 - <h3>🔧 Live Agent Integration Updated!</h3>
1172 - <p>We've temporarily disabled your Live Agent integration due to recent enhancements that have made it much better! You can easily turn it back on by going to <strong>Settings &rarr; Integrations &rarr; Toolbar</strong> and reviewing the new configuration options.</p>
269 + <?php endif; ?>
270 + <h2 class="admin-title">Mx<span class="admin-emphasis">Chat</span></h2>
271 + <h2 class="nav-tab-wrapper">
272 + <a href="#chatbot" class="nav-tab nav-tab-active" data-tab="chatbot">Chatbot</a>
273 + <a href="#embed" class="nav-tab" data-tab="embed">Embed</a>
274 + <a href="#theme" class="nav-tab" data-tab="theme">Theme</a>
275 + <a href="#general" class="nav-tab" data-tab="general">General</a>
276 + </h2>
277 + <form method="post" action="options.php">
278 + <?php settings_fields('mxchat_option_group'); ?>
279 + <div id="chatbot" class="tab-content active">
280 + <?php do_settings_sections('mxchat-chatbot'); ?>
281 + </div>
282 + <div id="embed" class="tab-content">
283 + <?php do_settings_sections('mxchat-embed'); ?>
284 + </div>
285 + <div id="theme" class="tab-content">
286 + <?php do_settings_sections('mxchat-theme'); ?>
287 + </div>
288 + <div id="general" class="tab-content">
289 + <?php do_settings_sections('mxchat-general'); ?>
290 + <div class="mxchat-general-notes">
291 + <h3>Important Notes</h3>
292 + <p>
293 + You can add the chatbot to your site using the <code>[mxchat_chatbot floating="yes"]</code> or <code>[mxchat_chatbot floating="no"]</code> shortcode. Additionally, you can automatically append the chatbot to your site’s body element from the settings page.
294 + </p>
295 + <p>
296 + Please note that you must have an OpenAI API key to use the chatbot. You can obtain an API key from the <a href="https://platform.openai.com/signup" target="_blank">OpenAI website</a>. It's easy to sign up, and you'll need to add credits to your account before using the chatbot. Generally, as little as $5 in credits is sufficient to get started.
297 + </p>
1173 298 </div>
1174 299 </div>
1175 - </div>
1176 - <?php
1177 - }
300 + <?php submit_button(); ?>
301 + </form>
302 + </div>
303 + <?php
1178 304 }
1179 -/**
1180 - * Render the Onboarding page. Delegates to the procedural renderer in
1181 - * includes/admin-onboarding-page.php. Wired to both `?page=mxchat-max`
1182 - * (legacy top-level URL) and `?page=mxchat-onboarding` (the canonical
1183 - * Onboarding submenu).
1184 - *
1185 - * When the user has dismissed onboarding and lands on `mxchat-max` (the
1186 - * legacy URL, since the Onboarding submenu has been removed), redirect to
1187 - * Settings instead — the page is "graduated" and we shouldn't dump them
1188 - * back onto it. They can still navigate here directly via the unhide link.
1189 - */
1190 -public function mxchat_create_dashboard_page() {
1191 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
1192 305
1193 - $current = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1194 - if ($current === 'mxchat-max' && function_exists('mxchat_onboarding_is_dismissed') && mxchat_onboarding_is_dismissed()) {
1195 - wp_safe_redirect(admin_url('admin.php?page=mxchat-settings'));
1196 - exit;
1197 - }
1198 306
1199 - if (function_exists('mxchat_render_onboarding_page')) {
1200 - mxchat_render_onboarding_page();
1201 - return;
1202 - }
1203 - // Defensive: if the include failed to load, fall back to the old Settings page
1204 - // so the top-level menu never lands on an empty screen.
1205 - $this->mxchat_create_admin_page();
1206 -}
1207 -
1208 -/**
1209 - * Hide the Onboarding submenu when the user has dismissed it (either
1210 - * manually or via auto-graduation). The page itself remains routable so
1211 - * the Settings "Show MxChat Onboarding again" link can navigate back to it.
1212 - */
1213 -public function mxchat_apply_onboarding_visibility() {
1214 - if (!function_exists('mxchat_onboarding_is_dismissed')) {
1215 - return;
1216 - }
1217 - if (mxchat_onboarding_is_dismissed()) {
1218 - // The first MxChat child is the same-slug-as-parent registration
1219 - // (slug 'mxchat-max', labelled "Onboarding") added in plan-d14e89.
1220 - // Remove it so the menu opens straight to Settings after dismiss.
1221 - remove_submenu_page('mxchat-max', 'mxchat-max');
1222 - }
1223 -}
1224 -
1225 -public function mxchat_create_admin_page() {
1226 - $this->add_live_agent_nonce();
1227 - $this->add_theme_migration_nonce();
1228 -
1229 - // Include and render the new sidebar-based settings page
1230 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1231 - mxchat_render_settings_page($this);
1232 -}
1233 -
1234 -public function dismiss_live_agent_notice() {
1235 - // Add debugging
1236 - //error_log('dismiss_live_agent_notice called');
1237 - //error_log('POST data: ' . print_r($_POST, true));
1238 -
1239 - // Verify nonce
1240 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1241 - //error_log('Nonce verification failed');
1242 - wp_die('Security check failed');
1243 - }
1244 -
1245 - // Remove the notice flag
1246 - $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1247 - //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
1248 -
1249 - wp_send_json_success();
1250 -}
1251 -public function add_live_agent_nonce() {
1252 - if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1253 - // Make sure your admin script is enqueued and localize the data
1254 - wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1255 - 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1256 - 'ajaxurl' => admin_url('admin-ajax.php')
1257 - ));
1258 - }
1259 -}
1260 -
1261 -/**
1262 - * Show theme migration notice for Pro users with AI-generated themes
1263 - * Only shown once - dismissible and stored in options
1264 - */
1265 -public function show_theme_migration_banner() {
1266 - // Only show if Pro is activated
1267 - if (!$this->is_activated) {
1268 - return;
1269 - }
1270 -
1271 - // Check if notice should be shown
1272 - $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1273 -
1274 - if ($show_notice) {
1275 - ?>
1276 - <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1277 - <div class="mxchat-pro-notification">
1278 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1279 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1280 - <line x1="18" y1="6" x2="6" y2="18"></line>
1281 - <line x1="6" y1="6" x2="18" y2="18"></line>
1282 - </svg>
1283 - </button>
1284 - <div class="mxchat-theme-migration-content">
1285 - <h3>🎨 AI Theme Migration Required</h3>
1286 - <p>If you're using an AI-generated chatbot theme, you'll need to migrate it to match the new CSS structure. Go to <strong>Theme Settings</strong>, select your theme from the sidebar, and click the <strong>Migrate</strong> button.</p>
1287 - </div>
307 + public function mxchat_create_transcripts_page() {
308 + ?>
309 + <div class="wrap mxchat-admin">
310 + <h2><?php esc_html_e('Chat Transcripts', 'mxchat'); ?></h2>
311 + <form id="mxchat-delete-form" method="post">
312 + <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
313 + <div class="mxchat-controls">
314 + <label for="mxchat-select-all-transcripts" class="mxchat-select-all-label">
315 + <input type="checkbox" id="mxchat-select-all-transcripts" /> <?php esc_html_e('Select All', 'mxchat'); ?>
316 + </label>
317 + <input type="submit" value="<?php esc_attr_e('Delete Selected', 'mxchat'); ?>" class="button button-primary delete-chats-button" />
318 + </div>
319 + <div id="mxchat-transcripts">
320 + <!-- Transcripts will be loaded here -->
321 + </div>
322 + </form>
1288 323 </div>
1289 - </div>
1290 - <?php
1291 - }
1292 -}
1293 -
1294 -/**
1295 - * Dismiss theme migration notice via AJAX
1296 - */
1297 -public function dismiss_theme_migration_notice() {
1298 - // Verify nonce
1299 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1300 - wp_die('Security check failed');
1301 - }
1302 -
1303 - // Remove the notice flag
1304 - delete_option('mxchat_show_theme_migration_notice');
1305 -
1306 - wp_send_json_success();
1307 -}
1308 -
1309 -/**
1310 - * Add nonce for theme migration notice dismiss
1311 - */
1312 -public function add_theme_migration_nonce() {
1313 - if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1314 - wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1315 - 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1316 - 'ajaxurl' => admin_url('admin-ajax.php')
1317 - ));
1318 - }
1319 -}
1320 -
1321 -public function mxchat_create_transcripts_page() {
1322 - global $wpdb;
1323 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1324 -
1325 - // Get basic stats
1326 - $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1327 - $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
1328 -
1329 - // Count unique users with detailed breakdown
1330 - $total_users = $wpdb->get_var("
1331 - SELECT COUNT(DISTINCT
1332 - CASE
1333 - WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1334 - WHEN user_id != 0 THEN CONCAT('user_', user_id)
1335 - WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1336 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1337 - AND user_identifier NOT LIKE 'Language Learner'
1338 - AND user_identifier NOT LIKE 'Casual Browser'
1339 - AND user_identifier NOT LIKE 'Policy Enforcer'
1340 - AND user_identifier NOT LIKE 'Researcher'
1341 - AND user_identifier NOT LIKE 'Loyalty Member'
1342 - AND user_identifier NOT LIKE 'Gift Buyer'
1343 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1344 - THEN user_identifier
1345 - ELSE session_id
1346 - END
1347 - )
1348 - FROM $table_name
1349 - WHERE role != 'assistant'
1350 - ");
1351 -
1352 - // Get user type breakdown
1353 - $registered_users = $wpdb->get_var("
1354 - SELECT COUNT(DISTINCT user_email)
1355 - FROM $table_name
1356 - WHERE user_email != '' AND user_email IS NOT NULL
1357 - ");
1358 -
1359 - $guest_users = $wpdb->get_var("
1360 - SELECT COUNT(DISTINCT user_identifier)
1361 - FROM $table_name
1362 - WHERE (user_email = '' OR user_email IS NULL)
1363 - AND role != 'assistant'
1364 - AND user_identifier NOT LIKE 'Tech-Savvy User'
1365 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1366 - AND user_identifier NOT LIKE 'Language Learner'
1367 - AND user_identifier NOT LIKE 'Casual Browser'
1368 - AND user_identifier NOT LIKE 'Policy Enforcer'
1369 - AND user_identifier NOT LIKE 'Researcher'
1370 - AND user_identifier NOT LIKE 'Loyalty Member'
1371 - AND user_identifier NOT LIKE 'Gift Buyer'
1372 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1373 - ");
1374 -
1375 - // Get agent test messages count
1376 - $agent_tests = $wpdb->get_var("
1377 - SELECT COUNT(DISTINCT session_id)
1378 - FROM $table_name
1379 - WHERE user_identifier IN (
1380 - 'Tech-Savvy User',
1381 - 'Detail-Oriented User',
1382 - 'Language Learner',
1383 - 'Casual Browser',
1384 - 'Policy Enforcer',
1385 - 'Researcher',
1386 - 'Loyalty Member',
1387 - 'Gift Buyer',
1388 - 'Parent or Caregiver'
1389 - )
1390 - ");
1391 - // Get activity metrics
1392 - $today_chats = $wpdb->get_var("
1393 - SELECT COUNT(DISTINCT session_id)
1394 - FROM $table_name
1395 - WHERE DATE(timestamp) = CURDATE()
1396 - ");
1397 -
1398 - $week_chats = $wpdb->get_var("
1399 - SELECT COUNT(DISTINCT session_id)
1400 - FROM $table_name
1401 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1402 - ");
1403 -
1404 - $month_chats = $wpdb->get_var("
1405 - SELECT COUNT(DISTINCT session_id)
1406 - FROM $table_name
1407 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1408 - ");
1409 -
1410 - // Get daily chat data for last 7 days
1411 - $daily_stats = $wpdb->get_results("
1412 - SELECT
1413 - DATE(timestamp) as date,
1414 - COUNT(DISTINCT session_id) as chats,
1415 - COUNT(*) as messages
1416 - FROM $table_name
1417 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1418 - GROUP BY DATE(timestamp)
1419 - ORDER BY date ASC
1420 - ");
1421 -
1422 - // Get average messages per chat
1423 - $avg_messages = $wpdb->get_var("
1424 - SELECT AVG(message_count)
1425 - FROM (
1426 - SELECT session_id, COUNT(*) as message_count
1427 - FROM $table_name
1428 - GROUP BY session_id
1429 - ) as chat_counts
1430 - ");
1431 - $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1432 -
1433 - // Get busiest hour
1434 - $busiest_hour = $wpdb->get_row("
1435 - SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1436 - FROM $table_name
1437 - GROUP BY HOUR(timestamp)
1438 - ORDER BY chat_count DESC
1439 - LIMIT 1
1440 - ");
1441 -
1442 - // Prepare chart data
1443 - $chart_labels = array();
1444 - $chart_chats = array();
1445 - $chart_messages = array();
1446 -
1447 - // Fill last 7 days with data
1448 - for ($i = 6; $i >= 0; $i--) {
1449 - $date = date('Y-m-d', strtotime("-$i days"));
1450 - $day_name = date('D', strtotime("-$i days"));
1451 - $chart_labels[] = $day_name;
1452 -
1453 - $found = false;
1454 - foreach ($daily_stats as $stat) {
1455 - if ($stat->date === $date) {
1456 - $chart_chats[] = (int)$stat->chats;
1457 - $chart_messages[] = (int)$stat->messages;
1458 - $found = true;
1459 - break;
1460 - }
324 + <?php
1461 325 }
1462 - if (!$found) {
1463 - $chart_chats[] = 0;
1464 - $chart_messages[] = 0;
1465 - }
1466 - }
1467 326
1468 - // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1469 - $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
1470 327
1471 - // Prepare page data for the template
1472 - $page_data = array(
1473 - 'total_chats' => $total_chats,
1474 - 'total_messages' => $total_messages,
1475 - 'total_users' => $total_users,
1476 - 'registered_users' => $registered_users,
1477 - 'guest_users' => $guest_users,
1478 - 'agent_tests' => $agent_tests,
1479 - 'today_chats' => $today_chats,
1480 - 'week_chats' => $week_chats,
1481 - 'month_chats' => $month_chats,
1482 - 'avg_messages' => $avg_messages,
1483 - 'busiest_hour' => $busiest_hour,
1484 - 'chart_labels' => $chart_labels,
1485 - 'chart_chats' => $chart_chats,
1486 - 'chart_messages' => $chart_messages,
1487 - 'satisfaction_stats' => $satisfaction_stats,
1488 - );
1489 328
1490 - // Include and render the new template
1491 - require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1492 - mxchat_render_transcripts_page($this, $page_data);
1493 -}
1494 329
1495 -/**
1496 - * Per-bot satisfaction rating rollup over the last $days days. Used by the
1497 - * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1498 - *
1499 - * @param int $days Window in days.
1500 - * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1501 - */
1502 -public function get_satisfaction_rating_stats($days = 30) {
1503 - global $wpdb;
1504 - $table = $wpdb->prefix . 'mxchat_session_ratings';
1505 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1506 - return array();
1507 - }
1508 - $days = max(1, (int) $days);
1509 - $rows = $wpdb->get_results($wpdb->prepare(
1510 - "SELECT bot_id,
1511 - COUNT(*) AS total,
1512 - SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1513 - SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1514 - FROM {$table}
1515 - WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1516 - GROUP BY bot_id
1517 - ORDER BY total DESC",
1518 - $days
1519 - ));
1520 - $out = array();
1521 - foreach ((array) $rows as $row) {
1522 - $total = (int) $row->total;
1523 - $positive = (int) $row->positive;
1524 - $negative = (int) $row->negative;
1525 - $out[] = array(
1526 - 'bot_id' => $row->bot_id ?: 'default',
1527 - 'total' => $total,
1528 - 'positive' => $positive,
1529 - 'negative' => $negative,
1530 - 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1531 - 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1532 - );
1533 - }
1534 - return $out;
1535 -}
330 + public function mxchat_create_prompts_page() {
331 + global $wpdb;
332 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1536 333
1537 -/**
1538 - * Get chart data for transcripts page
1539 - * Used by both page render and script localization
1540 - *
1541 - * @return array Chart data with labels, chats, and messages arrays
1542 - */
1543 -private function get_transcripts_chart_data() {
1544 - global $wpdb;
1545 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
334 + // Verify the nonce before processing the request
335 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
1546 336
1547 - // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1548 - $daily_stats = $wpdb->get_results("
1549 - SELECT
1550 - DATE(timestamp) as date,
1551 - COUNT(DISTINCT session_id) as chats,
1552 - COUNT(*) as messages
1553 - FROM $table_name
1554 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1555 - GROUP BY DATE(timestamp)
1556 - ORDER BY date ASC
1557 - ");
1558 -
1559 - // Prepare chart data
1560 - $chart_labels = array();
1561 - $chart_chats = array();
1562 - $chart_messages = array();
1563 -
1564 - // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1565 - for ($i = 6; $i >= 0; $i--) {
1566 - $date = date('Y-m-d', strtotime("-$i days"));
1567 - $day_name = date('D', strtotime("-$i days"));
1568 - $chart_labels[] = $day_name;
1569 -
1570 - $found = false;
1571 - if ($daily_stats) {
1572 - foreach ($daily_stats as $stat) {
1573 - if ($stat->date === $date) {
1574 - $chart_chats[] = (int)$stat->chats;
1575 - $chart_messages[] = (int)$stat->messages;
1576 - $found = true;
1577 - break;
1578 - }
1579 - }
1580 - }
1581 - if (!$found) {
1582 - $chart_chats[] = 0;
1583 - $chart_messages[] = 0;
1584 - }
1585 - }
1586 -
1587 - return array(
1588 - 'labels' => $chart_labels,
1589 - 'chats' => $chart_chats,
1590 - 'messages' => $chart_messages
1591 - );
1592 -}
1593 -
1594 -public function mxchat_transcripts_notification_section_callback() {
1595 - echo '<p>' . esc_html__('Configure email notifications for new chat transcripts. You will receive an email notification when a new chat session begins.', 'mxchat') . '</p>';
1596 -}
1597 -public function mxchat_enable_notifications_callback() {
1598 - $options = get_option('mxchat_transcripts_options', array());
1599 - $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1600 - ?>
1601 - <label for="mxchat_enable_notifications">
1602 - <input type="checkbox" id="mxchat_enable_notifications"
1603 - name="mxchat_transcripts_options[mxchat_enable_notifications]"
1604 - value="1" <?php checked(1, $enabled); ?>>
1605 - <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1606 - </label>
1607 - <p class="description">
1608 - <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
1609 - </p>
1610 - <?php
1611 -}
1612 -public function mxchat_notification_email_callback() {
1613 - $options = get_option('mxchat_transcripts_options', array());
1614 - $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1615 - ?>
1616 - <?php /* type="text", not "email": the browser rejects a comma-separated list outright (plan 2f131a). Validation is server-side in MxChat_Utils. */ ?>
1617 - <input type="text" id="mxchat_notification_email"
1618 - name="mxchat_transcripts_options[mxchat_notification_email]"
1619 - value="<?php echo esc_attr($email); ?>"
1620 - class="regular-text">
1621 - <p class="description">
1622 - <?php printf(esc_html__('Enter the email address where notifications should be sent. Separate up to %d addresses with commas. Defaults to the admin email address.', 'mxchat'), (int) MxChat_Utils::NOTIFICATION_EMAIL_MAX); ?>
1623 - </p>
1624 - <?php
1625 -}
1626 -
1627 -public function mxchat_auto_delete_transcripts_callback() {
1628 - $options = get_option('mxchat_transcripts_options', array());
1629 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1630 - ?>
1631 - <select id="mxchat_auto_delete_transcripts"
1632 - name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1633 - <option value="never" <?php selected($interval, 'never'); ?>>
1634 - <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1635 - </option>
1636 - <option value="1week" <?php selected($interval, '1week'); ?>>
1637 - <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1638 - </option>
1639 - <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1640 - <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1641 - </option>
1642 - <option value="1month" <?php selected($interval, '1month'); ?>>
1643 - <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1644 - </option>
1645 - </select>
1646 - <p class="description">
1647 - <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
1648 - </p>
1649 - <?php
1650 -}
1651 -
1652 -/**
1653 - * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1654 - * and deletes transcripts older than the given number of days. Set to 0 to fall
1655 - * back to the dropdown (or "Never" if the dropdown is also Never).
1656 - *
1657 - * Devs can override the final day count via the `mxchat_transcript_retention_days`
1658 - * filter — runs in `cleanup_old_transcripts()` after this option is read.
1659 - *
1660 - * (plan-mxchat-20260509-9b80b1)
1661 - */
1662 -public function mxchat_retention_days_callback() {
1663 - $options = get_option('mxchat_transcripts_options', array());
1664 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1665 - ?>
1666 - <input type="number"
1667 - id="mxchat_retention_days"
1668 - name="mxchat_transcripts_options[mxchat_retention_days]"
1669 - value="<?php echo esc_attr($days); ?>"
1670 - min="0"
1671 - max="3650"
1672 - step="1"
1673 - style="width: 90px;" />
1674 - <p class="description">
1675 - <?php esc_html_e('Number of days to retain transcripts. When set to a value greater than 0, this overrides the dropdown above. Set to 0 to use the dropdown. Maximum 3650 (10 years). A daily wp-cron task removes anything older, cascading to translations and click-tracking rows.', 'mxchat'); ?>
1676 - <br>
1677 - <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1678 - <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
1679 - </p>
1680 - <?php
1681 -}
1682 -
1683 -public function mxchat_auto_email_transcript_callback() {
1684 - $options = get_option('mxchat_transcripts_options', array());
1685 - $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1686 - $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1687 - $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1688 - ?>
1689 - <label>
1690 - <input type="checkbox"
1691 - id="mxchat_auto_email_transcript_enabled"
1692 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1693 - value="1"
1694 - <?php checked($enabled, 1); ?>>
1695 - <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1696 - </label>
1697 - <br><br>
1698 - <label for="mxchat_auto_email_transcript_delay">
1699 - <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1700 - </label>
1701 - <select id="mxchat_auto_email_transcript_delay"
1702 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1703 - <option value="15" <?php selected($delay, '15'); ?>>
1704 - <?php esc_html_e('15 minutes', 'mxchat'); ?>
1705 - </option>
1706 - <option value="30" <?php selected($delay, '30'); ?>>
1707 - <?php esc_html_e('30 minutes', 'mxchat'); ?>
1708 - </option>
1709 - <option value="60" <?php selected($delay, '60'); ?>>
1710 - <?php esc_html_e('1 hour', 'mxchat'); ?>
1711 - </option>
1712 - </select>
1713 - <br><br>
1714 - <label>
1715 - <input type="checkbox"
1716 - id="mxchat_auto_email_transcript_require_contact"
1717 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1718 - value="1"
1719 - <?php checked($require_contact, 1); ?>>
1720 - <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1721 - </label>
1722 - <p class="description">
1723 - <?php esc_html_e('Automatically email the full transcript as a .txt file after the specified time has passed since the last user message. The scheduled email will be cancelled if a new message is received.', 'mxchat'); ?>
1724 - <br>
1725 - <?php esc_html_e('When "Only send if visitor provided contact info" is enabled, transcripts will only be emailed if the visitor shared an email address or phone number (including WhatsApp) in the chat.', 'mxchat'); ?>
1726 - </p>
1727 - <?php
1728 -}
1729 -
1730 -
1731 -
1732 -public function sanitize_transcripts_options($input) {
1733 - $sanitized = array();
1734 -
1735 - $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
1736 -
1737 - if (isset($input['mxchat_notification_email'])) {
1738 - // Same list rule as the Transcripts autosave path (plan 2f131a). These two
1739 - // paths disagreeing is how the original bug survived: this one DID call
1740 - // is_email(), but on sanitize_email()'s output — which is valid even when
1741 - // the input was two addresses mashed into one. See MxChat_Utils.
1742 - $parsed = MxChat_Utils::parse_notification_emails($input['mxchat_notification_email']);
1743 - if ($parsed['error'] !== '') {
1744 - add_settings_error(
1745 - 'mxchat_transcripts_options',
1746 - 'invalid_email',
1747 - $parsed['error'],
1748 - 'error'
1749 - );
1750 - // Keep whatever was already stored. Do NOT fall back to admin_email:
1751 - // that fallback belongs to a genuinely EMPTY field, and using it here
1752 - // would quietly redirect notifications away from the address on screen.
1753 - $existing = get_option('mxchat_transcripts_options', array());
1754 - if (is_array($existing) && isset($existing['mxchat_notification_email'])) {
1755 - $sanitized['mxchat_notification_email'] = $existing['mxchat_notification_email'];
1756 - }
337 + if (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce')) {
338 + // Sanitize input data
339 + $search_query = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';
340 + $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
1757 341 } else {
1758 - $sanitized['mxchat_notification_email'] = implode(', ', $parsed['emails']);
342 + $search_query = '';
343 + $current_page = 1;
1759 344 }
1760 - }
1761 345
1762 - // Sanitize auto-delete setting
1763 - $valid_intervals = array('never', '1week', '2weeks', '1month');
1764 - if (isset($input['mxchat_auto_delete_transcripts'])) {
1765 - $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1766 - ? $input['mxchat_auto_delete_transcripts']
1767 - : 'never';
1768 - } else {
1769 - $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1770 - }
346 + $per_page = 10;
1771 347
1772 - // Sanitize custom retention-days override (plan-9b80b1).
1773 - if (isset($input['mxchat_retention_days'])) {
1774 - $days = (int) $input['mxchat_retention_days'];
1775 - $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1776 - } else {
1777 - $sanitized['mxchat_retention_days'] = 0;
1778 - }
348 + // Create cache keys
349 + $cache_key_total = 'total_prompts_' . md5($search_query);
350 + $cache_key_prompts = 'prompts_' . md5($search_query . '_' . $current_page);
1779 351
1780 - // Get old values to check if auto-delete or retention-days changed.
1781 - $old_options = get_option('mxchat_transcripts_options');
1782 - $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1783 - $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
1784 -
1785 - // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1786 - // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1787 - // reason to keep the daily cron registered.
1788 - $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1789 - $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1790 - if ($interval_changed || $retention_changed) {
1791 - $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1792 - $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1793 - }
1794 -
1795 - // Sanitize auto-email transcript settings
1796 - $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
1797 -
1798 - $valid_delays = array('15', '30', '60');
1799 - if (isset($input['mxchat_auto_email_transcript_delay'])) {
1800 - $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1801 - ? $input['mxchat_auto_email_transcript_delay']
1802 - : '30';
1803 - } else {
1804 - $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1805 - }
1806 -
1807 - // Sanitize require contact info setting
1808 - $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1809 -
1810 - return $sanitized;
1811 -}
1812 -
1813 -/**
1814 - * Schedule or unschedule the transcript cleanup cron job
1815 - */
1816 -public function schedule_transcript_cleanup($interval) {
1817 - // Clear any existing scheduled event
1818 - $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1819 - if ($timestamp) {
1820 - wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1821 - }
1822 -
1823 - // Schedule new event whenever retention is active. "active" is the canonical
1824 - // value passed by sanitize_transcripts_options when either the dropdown != never
1825 - // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1826 - // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1827 - if ($interval !== 'never') {
1828 - // Schedule to run daily at 3 AM
1829 - $next_run = strtotime('tomorrow 3:00 AM');
1830 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1831 - }
1832 -}
1833 -
1834 -/**
1835 - * Self-heal guard: keep the cleanup cron in sync with the retention setting.
1836 - *
1837 - * Runs on admin_init. Cost when nothing is wrong: one get_option() (cached) and
1838 - * one wp_next_scheduled() (reads the cached cron option) — no writes. It only
1839 - * schedules when retention is active but the event is missing, and only
1840 - * unschedules when retention is off but the event survived. Both directions
1841 - * reuse schedule_transcript_cleanup() so there is exactly one scheduling path.
1842 - * Legacy dropdown values (1week/2weeks/1month) count as active, matching the
1843 - * helper's own semantics. Deliberately not gated on DISABLE_WP_CRON: scheduling
1844 - * writes the cron option regardless of how cron is executed, so a server-side
1845 - * cron runner still picks the event up.
1846 - */
1847 -public function ensure_transcript_cleanup_scheduled() {
1848 - $options = get_option('mxchat_transcripts_options', array());
1849 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1850 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1851 - $active = ($interval !== 'never') || ($days > 0);
1852 - $scheduled = (bool) wp_next_scheduled('mxchat_cleanup_old_transcripts');
1853 -
1854 - if ($active && !$scheduled) {
1855 - $this->schedule_transcript_cleanup('active');
1856 - } elseif (!$active && $scheduled) {
1857 - $this->schedule_transcript_cleanup('never');
1858 - }
1859 -}
1860 -
1861 -/**
1862 - * Delete old transcripts based on the configured interval
1863 - */
1864 -public function cleanup_old_transcripts() {
1865 - $options = get_option('mxchat_transcripts_options', array());
1866 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1867 - $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1868 -
1869 - // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
1870 - $days = 0;
1871 - if ($custom_days > 0) {
1872 - $days = $custom_days;
1873 - } else {
1874 - switch ($interval) {
1875 - case '1week': $days = 7; break;
1876 - case '2weeks': $days = 14; break;
1877 - case '1month': $days = 30; break;
1878 - case 'never':
1879 - default:
1880 - $days = 0;
1881 - }
1882 - }
1883 -
1884 - // Devs can override the final day count programmatically.
1885 - $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
1886 -
1887 - if ($days <= 0) {
1888 - return; // Retention disabled — bail.
1889 - }
1890 -
1891 - global $wpdb;
1892 - $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1893 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1894 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
1895 -
1896 - // Defensive: if the main table doesn't exist (fresh-ish install), bail.
1897 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
1898 - return;
1899 - }
1900 -
1901 - $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
1902 -
1903 - // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
1904 - // the cron will pick up where it left off on the next tick (within hours).
1905 - $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
1906 -
1907 - $sessions_to_delete = $wpdb->get_col(
1908 - $wpdb->prepare(
1909 - "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
1910 - $cutoff_date,
1911 - $batch_cap
1912 - )
1913 - );
1914 -
1915 - if (empty($sessions_to_delete)) {
1916 - return;
1917 - }
1918 -
1919 - $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
1920 -
1921 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1922 - // $placeholders is a server-built list of literal "%s" tokens.
1923 - $deleted_transcripts = (int) $wpdb->query(
1924 - $wpdb->prepare(
1925 - "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
1926 - $sessions_to_delete
1927 - )
1928 - );
1929 -
1930 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
1931 - $wpdb->query(
1932 - $wpdb->prepare(
1933 - "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
1934 - $sessions_to_delete
1935 - )
1936 - );
1937 - }
1938 -
1939 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
1940 - $wpdb->query(
1941 - $wpdb->prepare(
1942 - "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
1943 - $sessions_to_delete
1944 - )
1945 - );
1946 - }
1947 - // phpcs:enable
1948 -
1949 - update_option('mxchat_retention_last_swept_at', time(), false);
1950 - update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
1951 -}
1952 -
1953 -public function export_chat_transcripts() {
1954 - if (!current_user_can('manage_options')) {
1955 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1956 - }
1957 -
1958 - check_ajax_referer('mxchat_export_transcripts', 'security');
1959 -
1960 - global $wpdb;
1961 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1962 -
1963 - // Get all transcripts ordered by session and timestamp
1964 - $results = $wpdb->get_results(
1965 - "SELECT session_id, user_email, user_identifier, role, message, timestamp
1966 - FROM {$table_name}
1967 - ORDER BY session_id, timestamp ASC"
1968 - );
1969 -
1970 - if (empty($results)) {
1971 - wp_send_json_error(array('message' => 'No transcripts found.'));
1972 - wp_die();
1973 - }
1974 -
1975 - // Set headers for CSV download
1976 - header('Content-Type: text/csv');
1977 - header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
1978 - header('Pragma: no-cache');
1979 - header('Expires: 0');
1980 -
1981 - // Create output stream
1982 - $output = fopen('php://output', 'w');
1983 -
1984 - // Add UTF-8 BOM for proper Excel encoding
1985 - fputs($output, "\xEF\xBB\xBF");
1986 -
1987 - // Add CSV headers
1988 - fputcsv($output, array(
1989 - 'Session ID',
1990 - 'Email',
1991 - 'User Identifier',
1992 - 'Role',
1993 - 'Message',
1994 - 'Timestamp'
1995 - ));
1996 -
1997 - // Add data rows
1998 - foreach ($results as $row) {
1999 - fputcsv($output, array(
2000 - $row->session_id,
2001 - $row->user_email,
2002 - $row->user_identifier,
2003 - $row->role,
2004 - $row->message,
2005 - $row->timestamp
2006 - ));
2007 - }
2008 -
2009 - fclose($output);
2010 - wp_die();
2011 -}
2012 -
2013 -// ============================================================================
2014 -// Leads tab (inside Transcripts)
2015 -//
2016 -// Leads are derived from existing data — no dedicated table. Primary source:
2017 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
2018 -// source: the mxchat_sessions table's visitor_email/visitor_name columns
2019 -// (plus any unmigrated legacy `mxchat_email_{sid}` wp_options rows) for
2020 -// "orphan" leads who submitted the pre-chat form but never chatted.
2021 -// ============================================================================
2022 -
2023 -/**
2024 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
2025 - */
2026 -public function mxchat_fetch_leads() {
2027 - if (!current_user_can('manage_options')) {
2028 - wp_send_json_error(['message' => 'Insufficient permissions']);
2029 - wp_die();
2030 - }
2031 -
2032 - global $wpdb;
2033 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2034 -
2035 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
2036 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
2037 - $offset = ($page - 1) * $per_page;
2038 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
2039 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
2040 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
2041 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
2042 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
2043 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
2044 -
2045 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
2046 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2047 -
2048 - // Base WHERE for transcripts leads.
2049 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
2050 - $where_params = [];
2051 -
2052 - if ($date_cutoff) {
2053 - $where_clauses[] = 'timestamp >= %s';
2054 - $where_params[] = $date_cutoff;
2055 - }
2056 - if ($page_filter && $has_page_url_column) {
2057 - $where_clauses[] = 'originating_page_url = %s';
2058 - $where_params[] = $page_filter;
2059 - }
2060 - if ($search !== '') {
2061 - $like = '%' . $wpdb->esc_like($search) . '%';
2062 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
2063 - $where_params[] = $like;
2064 - $where_params[] = $like;
2065 - }
2066 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
2067 -
2068 - // Aggregate query grouped by email.
2069 - $select_sql = $has_page_url_column
2070 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2071 - COUNT(DISTINCT session_id) AS conversation_count"
2072 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2073 - COUNT(DISTINCT session_id) AS conversation_count";
2074 -
2075 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
2076 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
2077 -
2078 - $transcripts_sql = $wpdb->prepare(
2079 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
2080 - array_merge($where_params, [$per_page, $offset])
2081 - );
2082 - $transcript_rows = $wpdb->get_results($transcripts_sql);
2083 -
2084 - // Count of unique transcript-based leads under the same filters.
2085 - $count_sql = $wpdb->prepare(
2086 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
2087 - $where_params
2088 - );
2089 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
2090 -
2091 - // Hydrate each row: name, latest_session_id, top page.
2092 - $leads = [];
2093 - foreach ($transcript_rows as $row) {
2094 - $detail = $has_page_url_column
2095 - ? $wpdb->get_row($wpdb->prepare(
2096 - "SELECT session_id, user_name, originating_page_url, originating_page_title
2097 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2098 - $row->user_email
2099 - ))
2100 - : $wpdb->get_row($wpdb->prepare(
2101 - "SELECT session_id, user_name FROM {$table}
2102 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2103 - $row->user_email
2104 - ));
2105 -
2106 - $leads[] = [
2107 - 'email' => $row->user_email,
2108 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2109 - 'conversation_count' => (int) $row->conversation_count,
2110 - 'last_seen' => $row->last_seen,
2111 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
2112 - 'first_seen' => $row->first_seen,
2113 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
2114 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2115 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
2116 - 'is_orphan' => false,
2117 - 'status' => 'active',
2118 - ];
2119 - }
2120 -
2121 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
2122 - // status filter below. Deduplication priority when the same email appears in multiple
2123 - // sources: transcripts > chat_deleted > orphan.
2124 - $transcripts_emails_seen = array_flip(array_map(
2125 - function ($r) { return strtolower($r['email']); },
2126 - $leads
2127 - ));
2128 -
2129 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
2130 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
2131 - $chat_deleted_leads_all = [];
2132 - if ($status === 'all' || $status === 'chat_deleted') {
2133 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
2134 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
2135 - $chat_deleted_leads_all = array_values(array_filter(
2136 - $chat_deleted_leads_all,
2137 - function ($row) use ($transcripts_emails_seen) {
2138 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
352 + // Retrieve total number of prompts from cache or database
353 + $total_prompts = wp_cache_get($cache_key_total, 'mxchat_prompts');
354 + if ($total_prompts === false) {
355 + if (!empty($search_query)) {
356 + $total_prompts = $wpdb->get_var(
357 + $wpdb->prepare(
358 + "SELECT COUNT(*) FROM {$table_name} WHERE article_content LIKE %s",
359 + '%' . $wpdb->esc_like($search_query) . '%'
360 + )
361 + );
362 + } else {
363 + $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
2139 364 }
2140 - ));
2141 - foreach ($chat_deleted_leads_all as $row) {
2142 - $transcripts_emails_seen[strtolower($row['email'])] = true;
365 + wp_cache_set($cache_key_total, $total_prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
2143 366 }
2144 - }
2145 367
2146 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
2147 - // when a date filter is active.
2148 - $orphan_leads_all = [];
2149 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
2150 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
2151 - $orphan_leads_all = array_values(array_filter(
2152 - $orphan_leads_all,
2153 - function ($row) use ($transcripts_emails_seen) {
2154 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2155 - }
2156 - ));
2157 - }
368 + $total_pages = ceil($total_prompts / $per_page);
369 + $offset = ($current_page - 1) * $per_page;
2158 370
2159 - // Apply status filter to the transcripts-derived list.
2160 - if ($status === 'orphan' || $status === 'chat_deleted') {
2161 - $leads = [];
2162 - $transcripts_lead_count = 0;
2163 - }
2164 -
2165 - // Stitch the current page from the three buckets in priority order.
2166 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
2167 - $remaining_slots = $per_page - count($leads);
2168 -
2169 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
2170 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
2171 - if ($start < count($chat_deleted_leads_all)) {
2172 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
2173 - $remaining_slots = $per_page - count($leads);
2174 - }
2175 - }
2176 -
2177 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
2178 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
2179 - $start = max(0, ($page - 1) * $per_page - $before);
2180 - if ($start < count($orphan_leads_all)) {
2181 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
2182 - }
2183 - }
2184 -
2185 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
2186 -
2187 - // Stats strip: always computed over full dataset, unaffected by filters.
2188 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
2189 -
2190 - // Top pages: top 5 by distinct emails captured.
2191 - $top_pages = [];
2192 - if ($has_page_url_column) {
2193 - $top_pages_rows = $wpdb->get_results(
2194 - "SELECT originating_page_url AS url,
2195 - MAX(originating_page_title) AS title,
2196 - COUNT(DISTINCT user_email) AS lead_count
2197 - FROM {$table}
2198 - WHERE user_email IS NOT NULL AND user_email != ''
2199 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
2200 - GROUP BY originating_page_url
2201 - ORDER BY lead_count DESC, url ASC
2202 - LIMIT 5"
2203 - );
2204 - foreach ($top_pages_rows as $p) {
2205 - $top_pages[] = [
2206 - 'url' => $p->url,
2207 - 'title' => $p->title ?: $p->url,
2208 - 'lead_count' => (int) $p->lead_count,
2209 - ];
2210 - }
2211 - }
2212 -
2213 - wp_send_json([
2214 - 'success' => true,
2215 - 'leads' => $leads,
2216 - 'page' => $page,
2217 - 'per_page' => $per_page,
2218 - 'total_count' => $total_count,
2219 - 'total_pages' => $total_pages,
2220 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
2221 - 'showing_end' => min($offset + $per_page, $total_count),
2222 - 'stats' => $stats,
2223 - 'top_pages' => $top_pages,
2224 - ]);
2225 - wp_die();
2226 -}
2227 -
2228 -/**
2229 - * Delete one or more leads by email. Removes every transcripts row for that
2230 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2231 - * mxchat_history_{sid}) and any orphan option entries matching the email.
2232 - */
2233 -public function mxchat_delete_leads() {
2234 - if (!current_user_can('manage_options')) {
2235 - wp_send_json_error(['message' => 'Insufficient permissions']);
2236 - wp_die();
2237 - }
2238 - check_ajax_referer('mxchat_delete_leads', 'security');
2239 -
2240 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2241 - $emails = [];
2242 - foreach ($emails_raw as $e) {
2243 - $clean = sanitize_email((string) $e);
2244 - if ($clean) {
2245 - $emails[] = $clean;
2246 - }
2247 - }
2248 - if (empty($emails)) {
2249 - wp_send_json_error(['message' => 'No emails provided']);
2250 - wp_die();
2251 - }
2252 -
2253 - $summary = self::mxchat_wipe_leads_by_email($emails);
2254 -
2255 - wp_send_json([
2256 - 'success' => true,
2257 - 'deleted_leads' => count($emails),
2258 - 'deleted_sessions' => $summary['deleted_sessions'],
2259 - 'deleted_rows' => $summary['deleted_rows'],
2260 - ]);
2261 - wp_die();
2262 -}
2263 -
2264 -/**
2265 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2266 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2267 - *
2268 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2269 - * Input emails must already be sanitized with sanitize_email().
2270 - */
2271 -private static function mxchat_wipe_leads_by_email(array $emails) {
2272 - global $wpdb;
2273 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2274 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2275 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
2276 -
2277 - $deleted_sessions = 0;
2278 - $deleted_rows = 0;
2279 - $emails_lc = array_map('strtolower', $emails);
2280 -
2281 - foreach ($emails as $email) {
2282 - $session_ids = $wpdb->get_col($wpdb->prepare(
2283 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2284 - $email
2285 - ));
2286 -
2287 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2288 - if ($rows_removed !== false) {
2289 - $deleted_rows += (int) $rows_removed;
2290 - }
2291 -
2292 - foreach ($session_ids as $sid) {
2293 - $deleted_sessions++;
2294 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2295 - delete_option('mxchat_history_' . $sid);
2296 - delete_option('mxchat_email_' . $sid);
2297 - delete_option('mxchat_name_' . $sid);
2298 - delete_option('mxchat_agent_name_' . $sid);
2299 - delete_option('mxchat_lead_del_email_' . $sid);
2300 - delete_option('mxchat_lead_del_name_' . $sid);
2301 - delete_option('mxchat_lead_del_ts_' . $sid);
2302 - if (class_exists('MxChat_Session_Store')) {
2303 - MxChat_Session_Store::delete_session($sid); // b64b77
371 + // Retrieve prompts from cache or database
372 + $prompts = wp_cache_get($cache_key_prompts, 'mxchat_prompts');
373 + if ($prompts === false) {
374 + if (!empty($search_query)) {
375 + $prompts = $wpdb->get_results(
376 + $wpdb->prepare(
377 + "SELECT * FROM {$table_name} WHERE article_content LIKE %s ORDER BY timestamp DESC LIMIT %d OFFSET %d",
378 + '%' . $wpdb->esc_like($search_query) . '%',
379 + $per_page,
380 + $offset
381 + )
382 + );
383 + } else {
384 + $prompts = $wpdb->get_results(
385 + $wpdb->prepare(
386 + "SELECT * FROM {$table_name} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
387 + $per_page,
388 + $offset
389 + )
390 + );
2304 391 }
2305 - if ($has_translations) {
2306 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2307 - }
392 + wp_cache_set($cache_key_prompts, $prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
2308 393 }
2309 - }
2310 394
2311 - // Table-side twin of the option sweep below (5658f2): orphan pre-chat
2312 - // captures now live in the sessions table's identity columns.
2313 - if (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'find_by_email')) {
2314 - foreach ($emails as $email) {
2315 - foreach (MxChat_Session_Store::find_by_email($email) as $sid) {
2316 - MxChat_Session_Store::delete_session($sid);
2317 - }
2318 - }
2319 - }
395 + ?>
2320 396
2321 - // Clean up any lingering option entries (unmigrated orphan pre-chat captures +
2322 - // chat_deleted preservations) whose stored value matches one of the emails being wiped.
2323 - $lingering = $wpdb->get_results(
2324 - "SELECT option_name, option_value FROM {$wpdb->options}
2325 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2326 - );
2327 - foreach ($lingering as $opt) {
2328 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2329 - continue;
2330 - }
2331 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2332 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2333 - delete_option('mxchat_lead_del_email_' . $sid);
2334 - delete_option('mxchat_lead_del_name_' . $sid);
2335 - delete_option('mxchat_lead_del_ts_' . $sid);
2336 - } else {
2337 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2338 - delete_option('mxchat_email_' . $sid);
2339 - delete_option('mxchat_name_' . $sid);
2340 - }
2341 - }
397 + <div class="wrap mxchat-admin">
398 + <div class="mxchat-grid-container">
2342 399
2343 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
400 + <!-- Submit Content -->
401 + <div class="mxchat-grid-item full-width">
402 + <h2>Submit Content</h2>
403 + <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
404 + <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
405 + <div class="mxchat-form-group">
406 + <label for="article_content">Article Content:</label>
407 + <textarea name="article_content" id="article_content" required></textarea>
408 + <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
409 + </div>
410 + </form>
411 + </div>
2344 412
2345 - return [
2346 - 'deleted_sessions' => $deleted_sessions,
2347 - 'deleted_rows' => $deleted_rows,
2348 - ];
2349 -}
413 + <!-- Submit Sitemap -->
414 + <div class="mxchat-grid-item">
415 + <h2>Submit Sitemap</h2>
416 + <form id="mxchat-sitemap-form" method="post" class="mxchat-sitemap-form" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_sitemap')); ?>">
417 + <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
418 + <div class="mxchat-search-group">
419 + <input type="url" name="sitemap_url" id="sitemap_url" placeholder="Sitemap URL" required />
420 + <input type="submit" name="submit_sitemap" value="Submit Sitemap" class="button button-primary" />
421 + </div>
422 + </form>
423 + <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"></div>
424 + <div id="mxchat-loading-text" style="display: none; margin-top: 10px; color: #333;">Loading sitemap content into database, please wait...</div>
425 + </div>
2350 426
2351 -/**
2352 - * Stream a leads CSV. scope=all exports every lead under current filters is not
2353 - * supported to keep semantics simple; caller either exports all leads or a
2354 - * specific set of selected emails.
2355 - */
2356 -public function mxchat_export_leads() {
2357 - if (!current_user_can('manage_options')) {
2358 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2359 - }
2360 - check_ajax_referer('mxchat_export_leads', 'security');
427 + <!-- Search Knowledge -->
428 + <div class="mxchat-grid-item">
429 + <h2>Search Knowledge</h2>
430 + <form method="get" id="knowledge-search">
431 + <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
432 + <input type="hidden" name="page" value="mxchat-prompts" />
433 + <div class="mxchat-search-group">
434 + <input type="text" name="search" placeholder="Search Knowledge" value="<?php echo esc_attr($search_query); ?>" />
435 + <input type="submit" value="Search" class="button button-primary" />
436 + </div>
437 + </form>
438 + </div>
439 + </div>
2361 440
2362 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2363 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2364 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
441 + <!-- Table below the forms -->
442 + <div class="tablenav">
443 + <div class="tablenav-pages">
444 + <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
445 + <?php
446 + $page_links = paginate_links(array(
447 + 'base' => add_query_arg('paged', '%#%', admin_url('admin.php?page=mxchat-prompts')),
448 + 'format' => '',
449 + 'prev_text' => __('&laquo; Previous'),
450 + 'next_text' => __('Next &raquo;'),
451 + 'total' => $total_pages,
452 + 'current' => $current_page,
453 + 'add_args' => array(
454 + 'search' => $search_query,
455 + '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')
456 + ),
457 + ));
2365 458
2366 - $emails_in_clean = [];
2367 - foreach ($emails_in as $e) {
2368 - $clean = sanitize_email((string) $e);
2369 - if ($clean) {
2370 - $emails_in_clean[] = $clean;
2371 - }
2372 - }
459 + if ($page_links) {
460 + echo '<div class="tablenav-pages">' . wp_kses_post($page_links) . '</div>';
461 + }
462 + ?>
463 + </div>
464 + </div>
465 + <table class="wp-list-table widefat fixed striped">
466 + <thead>
467 + <tr>
468 + <th>ID</th>
469 + <th>Article Content</th>
470 + <th>URL</th>
471 + <th>Actions</th>
472 + </tr>
473 + </thead>
474 + <tbody>
475 + <?php
476 + if ($prompts) {
477 + foreach ($prompts as $prompt) {
478 + ?>
479 + <tr>
480 + <td><?php echo esc_html($prompt->id); ?></td>
481 + <td class="mxchat_article_content_dashboard"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></td>
482 + <td class="mxchat_article_url_dashboard">
483 + <?php if (!empty($prompt->source_url)): ?>
484 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
485 + <?php else: ?>
486 + N/A
487 + <?php endif; ?>
488 + </td>
489 + <td>
490 + <a href="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_prompt&id=' . esc_attr($prompt->id) . '&_wpnonce=' . wp_create_nonce('mxchat_delete_prompt_nonce'))); ?>">Delete</a>
491 + </td>
492 + </tr>
493 + <?php
494 + }
495 + } else {
496 + ?>
497 + <tr>
498 + <td colspan="4">No prompts found.</td>
499 + </tr>
500 + <?php
501 + }
502 + ?>
503 + </tbody>
504 + </table>
505 + </div>
2373 506
2374 - global $wpdb;
2375 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2376 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2377 -
2378 - // Collect leads from transcripts.
2379 - $transcripts_sql = "SELECT user_email AS email,
2380 - MAX(timestamp) AS last_seen,
2381 - COUNT(DISTINCT session_id) AS conversation_count
2382 - FROM {$table}
2383 - WHERE user_email IS NOT NULL AND user_email != ''";
2384 - $params = [];
2385 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2386 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2387 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2388 - $params = $emails_in_clean;
507 + <?php
2389 508 }
2390 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
2391 509
2392 - $rows = !empty($params)
2393 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2394 - : $wpdb->get_results($transcripts_sql);
510 + public function mxchat_generate_embedding($text) {
511 + $options = get_option('mxchat_options');
512 + $api_key = $options['api_key'] ?? 'default_api_key';
2395 513
2396 - // Hydrate each row with name + top page.
2397 - $export_rows = [];
2398 - foreach ($rows as $row) {
2399 - $detail = $has_page_url_column
2400 - ? $wpdb->get_row($wpdb->prepare(
2401 - "SELECT user_name, originating_page_url FROM {$table}
2402 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2403 - $row->email
2404 - ))
2405 - : $wpdb->get_row($wpdb->prepare(
2406 - "SELECT user_name FROM {$table}
2407 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2408 - $row->email
2409 - ));
2410 - $export_rows[] = [
2411 - 'email' => $row->email,
2412 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2413 - 'conversation_count' => (int) $row->conversation_count,
2414 - 'last_seen' => $row->last_seen,
2415 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2416 - ];
2417 - }
2418 -
2419 - // Include orphan + chat_deleted leads when exporting all.
2420 - if ($scope === 'all') {
2421 - $transcripts_emails_lc = array_flip(array_map(
2422 - function ($r) { return strtolower($r['email']); },
2423 - $export_rows
514 + $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
515 + 'body' => wp_json_encode(array(
516 + 'model' => 'text-embedding-ada-002',
517 + 'input' => $text
518 + )),
519 + 'headers' => array(
520 + 'Authorization' => 'Bearer ' . $api_key,
521 + 'Content-Type' => 'application/json'
522 + ),
2424 523 ));
2425 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2426 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2427 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2428 - $export_rows[] = [
2429 - 'email' => $cd['email'],
2430 - 'name' => $cd['name'],
2431 - 'conversation_count' => 0,
2432 - 'last_seen' => $cd['last_seen'],
2433 - 'top_page_url' => '',
2434 - ];
2435 - }
2436 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2437 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2438 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2439 - $export_rows[] = [
2440 - 'email' => $orphan['email'],
2441 - 'name' => $orphan['name'],
2442 - 'conversation_count' => 0,
2443 - 'last_seen' => '',
2444 - 'top_page_url' => '',
2445 - ];
2446 - }
2447 - }
2448 524
2449 - if (empty($export_rows)) {
2450 - wp_send_json_error(['message' => 'No leads to export.']);
2451 - wp_die();
2452 - }
2453 -
2454 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2455 - header('Content-Type: text/csv');
2456 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2457 - header('Pragma: no-cache');
2458 - header('Expires: 0');
2459 -
2460 - $output = fopen('php://output', 'w');
2461 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2462 -
2463 - if ($fields_mode === 'email_only') {
2464 - fputcsv($output, ['Email']);
2465 - foreach ($export_rows as $r) {
2466 - fputcsv($output, [$r['email']]);
525 + if (is_wp_error($response)) {
526 + return null;
2467 527 }
2468 - } else {
2469 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page']);
2470 - foreach ($export_rows as $r) {
2471 - fputcsv($output, [
2472 - $r['email'],
2473 - $r['name'],
2474 - $r['conversation_count'],
2475 - $r['last_seen'],
2476 - $r['top_page_url'],
2477 - ]);
2478 - }
2479 - }
2480 528
2481 - fclose($output);
2482 - wp_die();
2483 -}
2484 -
2485 -/**
2486 - * Stats strip payload (independent of filters).
2487 - */
2488 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2489 - global $wpdb;
2490 -
2491 - $total_transcripts_emails = (int) $wpdb->get_var(
2492 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2493 - WHERE user_email IS NOT NULL AND user_email != ''"
2494 - );
2495 -
2496 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2497 - "SELECT COUNT(*) FROM (
2498 - SELECT user_email FROM {$table}
2499 - WHERE user_email IS NOT NULL AND user_email != ''
2500 - GROUP BY user_email
2501 - HAVING MIN(timestamp) >= %s
2502 - ) AS new_leads",
2503 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2504 - ));
2505 -
2506 - $total_convos = (int) $wpdb->get_var(
2507 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2508 - WHERE user_email IS NOT NULL AND user_email != ''"
2509 - );
2510 -
2511 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2512 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
2513 -
2514 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2515 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2516 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2517 -
2518 - $avg = $total_transcripts_emails > 0
2519 - ? round($total_convos / $total_transcripts_emails, 1)
2520 - : 0;
2521 -
2522 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2523 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2524 - // inflate this number.
2525 - $orphan_pct = $total_leads > 0
2526 - ? (int) round(($orphan_count / $total_leads) * 100)
2527 - : 0;
2528 -
2529 - return [
2530 - 'total_leads' => $total_leads,
2531 - 'new_this_week' => $new_this_week,
2532 - 'avg_convos' => $avg,
2533 - 'orphan_pct' => $orphan_pct,
2534 - 'orphan_count' => $orphan_count,
2535 - 'chat_deleted_count' => $chat_deleted_count,
2536 - ];
2537 -}
2538 -
2539 -/**
2540 - * Collect leads who had a conversation that an admin later deleted (preserved via
2541 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2542 - * original last-seen timestamp so they still sort and filter sensibly.
2543 - *
2544 - * @param string $search Optional email/name substring filter.
2545 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2546 - * @return array
2547 - */
2548 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2549 - global $wpdb;
2550 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2551 -
2552 - $rows = $wpdb->get_results(
2553 - "SELECT option_name, option_value FROM {$wpdb->options}
2554 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2555 - );
2556 - if (empty($rows)) {
2557 - return [];
529 + $response_data = json_decode(wp_remote_retrieve_body($response), true);
530 + return $response_data['data'][0]['embedding'] ?? null;
2558 531 }
2559 532
2560 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2561 - // they've come back and chatted, so they're active leads again.
2562 - $emails_in_transcripts = array_map(
2563 - 'strtolower',
2564 - (array) $wpdb->get_col(
2565 - "SELECT DISTINCT user_email FROM {$table}
2566 - WHERE user_email IS NOT NULL AND user_email != ''"
2567 - )
2568 - );
2569 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2570 -
2571 - $needle = strtolower(trim((string) $search));
2572 - $by_email = [];
2573 -
2574 - foreach ($rows as $opt) {
2575 - $email = sanitize_email(trim((string) $opt->option_value));
2576 - if (!$email) {
2577 - continue;
533 + public function mxchat_delete_chat_history() {
534 + if (!current_user_can('manage_options')) {
535 + echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
536 + wp_die();
2578 537 }
2579 - if (isset($emails_in_transcripts[strtolower($email)])) {
2580 - continue;
2581 - }
2582 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2583 - if (!$sid) {
2584 - continue;
2585 - }
2586 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2587 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2588 538
2589 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2590 - continue;
2591 - }
2592 - if ($needle !== '') {
2593 - $hay = strtolower($email . ' ' . $name);
2594 - if (strpos($hay, $needle) === false) {
2595 - continue;
2596 - }
2597 - }
539 + check_ajax_referer('mxchat_delete_chat_history', 'security');
2598 540
2599 - $key = strtolower($email);
2600 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2601 - $by_email[$key] = [
2602 - 'email' => $email,
2603 - 'name' => $name,
2604 - 'conversation_count' => 0,
2605 - 'last_seen' => $ts,
2606 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2607 - 'first_seen' => $ts,
2608 - 'latest_session_id' => '',
2609 - 'top_page_url' => '',
2610 - 'top_page_title' => '',
2611 - 'is_orphan' => false,
2612 - 'status' => 'chat_deleted',
2613 - ];
2614 - }
2615 - }
541 + global $wpdb;
542 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2616 543
2617 - // Newest chat_deleted first.
2618 - usort($by_email, function ($a, $b) {
2619 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2620 - });
2621 - return array_values($by_email);
2622 -}
544 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
545 + foreach ($_POST['delete_session_ids'] as $session_id) {
546 + $session_id_sanitized = sanitize_text_field($session_id);
2623 547
2624 -/**
2625 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2626 - */
2627 -private static function mxchat_count_chat_deleted_leads() {
2628 - global $wpdb;
2629 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
548 + // Clear relevant cache before deletion
549 + $cache_key = 'chat_session_' . $session_id_sanitized;
550 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
2630 551
2631 - $emails = $wpdb->get_col(
2632 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2633 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2634 - );
2635 - if (empty($emails)) {
2636 - return 0;
2637 - }
2638 -
2639 - $transcripts_emails = array_map(
2640 - 'strtolower',
2641 - (array) $wpdb->get_col(
2642 - "SELECT DISTINCT user_email FROM {$table}
2643 - WHERE user_email IS NOT NULL AND user_email != ''"
2644 - )
2645 - );
2646 - $transcripts_emails = array_flip($transcripts_emails);
2647 -
2648 - $count = 0;
2649 - $seen = [];
2650 - foreach ($emails as $raw) {
2651 - $email = strtolower(trim((string) $raw));
2652 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2653 - continue;
2654 - }
2655 - $seen[$email] = true;
2656 - $count++;
2657 - }
2658 - return $count;
2659 -}
2660 -
2661 -/**
2662 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2663 - * Returned rows have no conversation_count, no timestamp.
2664 - *
2665 - * @param string $search Optional email/name substring filter.
2666 - * @return array
2667 - */
2668 -private static function mxchat_collect_orphan_leads($search = '') {
2669 - global $wpdb;
2670 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2671 -
2672 - // Primary source since 5658f2: the sessions table's identity columns.
2673 - // The legacy option scan stays for installs still mid-migration.
2674 - $store_rows = (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'identity_rows'))
2675 - ? MxChat_Session_Store::identity_rows()
2676 - : [];
2677 -
2678 - $option_rows = $wpdb->get_results(
2679 - "SELECT option_name, option_value FROM {$wpdb->options}
2680 - WHERE option_name LIKE 'mxchat_email_%'"
2681 - );
2682 - if (empty($option_rows) && empty($store_rows)) {
2683 - return [];
2684 - }
2685 -
2686 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2687 - $session_ids_with_rows = $wpdb->get_col(
2688 - "SELECT DISTINCT session_id FROM {$table}
2689 - WHERE user_email IS NOT NULL AND user_email != ''"
2690 - );
2691 - $session_ids_with_rows = array_flip($session_ids_with_rows);
2692 -
2693 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2694 - $emails_in_transcripts = array_map(
2695 - 'strtolower',
2696 - (array) $wpdb->get_col(
2697 - "SELECT DISTINCT user_email FROM {$table}
2698 - WHERE user_email IS NOT NULL AND user_email != ''"
2699 - )
2700 - );
2701 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2702 -
2703 - $orphans_by_email = [];
2704 - $needle = strtolower(trim((string) $search));
2705 -
2706 - // Normalize both sources into [sid, email, name] candidates. Table rows
2707 - // first — a session can only live in one home, and dedup-by-email below
2708 - // handles any overlap either way.
2709 - $candidates = [];
2710 - foreach ($store_rows as $row) {
2711 - $candidates[] = [
2712 - 'sid' => (string) $row['session_id'],
2713 - 'email' => (string) $row['visitor_email'],
2714 - 'name' => is_string($row['visitor_name'] ?? null) ? $row['visitor_name'] : '',
2715 - ];
2716 - }
2717 - foreach ($option_rows as $opt) {
2718 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2719 - $name_option = $sid ? get_option('mxchat_name_' . $sid, '') : '';
2720 - $candidates[] = [
2721 - 'sid' => (string) $sid,
2722 - 'email' => (string) $opt->option_value,
2723 - 'name' => is_string($name_option) ? $name_option : '',
2724 - ];
2725 - }
2726 -
2727 - foreach ($candidates as $cand) {
2728 - $email = sanitize_email(trim($cand['email']));
2729 - if (!$email) {
2730 - continue;
2731 - }
2732 - $sid = $cand['sid'];
2733 - if (!$sid) {
2734 - continue;
2735 - }
2736 - // Exclude leads who have any transcripts rows (they appear in the main list).
2737 - if (isset($emails_in_transcripts[strtolower($email)])) {
2738 - continue;
2739 - }
2740 - if (isset($session_ids_with_rows[$sid])) {
2741 - continue;
2742 - }
2743 -
2744 - $name = trim($cand['name']);
2745 -
2746 - if ($needle !== '') {
2747 - $hay = strtolower($email . ' ' . $name);
2748 - if (strpos($hay, $needle) === false) {
2749 - continue;
552 + // Perform the deletion
553 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
2750 554 }
2751 - }
2752 555
2753 - $key = strtolower($email);
2754 - if (!isset($orphans_by_email[$key])) {
2755 - $orphans_by_email[$key] = [
2756 - 'email' => $email,
2757 - 'name' => $name,
2758 - 'conversation_count' => 0,
2759 - 'last_seen' => '',
2760 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2761 - 'first_seen' => '',
2762 - 'latest_session_id' => '',
2763 - 'top_page_url' => '',
2764 - 'top_page_title' => '',
2765 - 'is_orphan' => true,
2766 - 'status' => 'orphan',
2767 - ];
2768 - }
2769 - }
556 + // Optionally, clear a general cache if you have one
557 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2770 558
2771 - return array_values($orphans_by_email);
2772 -}
2773 -
2774 -/**
2775 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2776 - */
2777 -private static function mxchat_leads_date_cutoff($date_range) {
2778 - switch ($date_range) {
2779 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2780 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2781 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2782 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2783 - case 'all':
2784 - default: return '';
2785 - }
2786 -}
2787 -
2788 -/**
2789 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2790 - */
2791 -private static function mxchat_leads_format_relative($timestamp) {
2792 - if (!$timestamp) {
2793 - return '';
2794 - }
2795 - $ts = strtotime($timestamp . ' UTC');
2796 - if (!$ts) {
2797 - return '';
2798 - }
2799 - $diff = time() - $ts;
2800 - if ($diff < 60) return __('just now', 'mxchat');
2801 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2802 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2803 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2804 - return wp_date('M j', $ts);
2805 -}
2806 -
2807 -/**
2808 - * Handle translation of chat messages via AJAX
2809 - */
2810 -public function mxchat_translate_messages() {
2811 - if (!current_user_can('manage_options')) {
2812 - wp_send_json_error(['error' => 'Insufficient permissions']);
2813 - wp_die();
2814 - }
2815 -
2816 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2817 - $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
2818 - $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
2819 - $messages = json_decode($messages_json, true);
2820 -
2821 - if (empty($session_id)) {
2822 - wp_send_json_error(['error' => 'No session ID provided']);
2823 - wp_die();
2824 - }
2825 -
2826 - if (empty($messages) || !is_array($messages)) {
2827 - wp_send_json_error(['error' => 'No messages to translate']);
2828 - wp_die();
2829 - }
2830 -
2831 - // Language names for prompting
2832 - $languages = [
2833 - 'en' => 'English',
2834 - 'es' => 'Spanish',
2835 - 'fr' => 'French',
2836 - 'de' => 'German',
2837 - 'it' => 'Italian',
2838 - 'pt' => 'Portuguese',
2839 - 'nl' => 'Dutch',
2840 - 'ru' => 'Russian',
2841 - 'zh' => 'Chinese',
2842 - 'ja' => 'Japanese',
2843 - 'ko' => 'Korean',
2844 - 'ar' => 'Arabic',
2845 - 'hi' => 'Hindi',
2846 - 'tr' => 'Turkish',
2847 - 'pl' => 'Polish',
2848 - 'vi' => 'Vietnamese',
2849 - 'th' => 'Thai',
2850 - 'id' => 'Indonesian',
2851 - 'sv' => 'Swedish',
2852 - 'da' => 'Danish'
2853 - ];
2854 -
2855 - $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
2856 -
2857 - // Build combined text for translation (numbered for parsing)
2858 - $numbered_messages = [];
2859 - foreach ($messages as $i => $msg) {
2860 - $content = isset($msg['content']) ? trim($msg['content']) : '';
2861 - if (!empty($content)) {
2862 - $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
559 + echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
560 + } else {
561 + echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
2863 562 }
2864 - }
2865 563
2866 - if (empty($numbered_messages)) {
2867 - wp_send_json_error(['error' => 'No valid messages to translate']);
2868 564 wp_die();
2869 565 }
2870 566
2871 - $combined_text = implode("\n\n", $numbered_messages);
2872 567
2873 - // Prepare the translation prompt
2874 - $system_prompt = "You are a translator. Translate the following messages to {$target_lang_name}. Keep the [MSG#] and [/MSG#] tags exactly as they are - only translate the content between them. Maintain the original formatting, line breaks, and any HTML tags. Return ONLY the translated messages with the tags, no explanations.";
2875 568
2876 - // Get user's selected model and determine provider
2877 - $options = get_option('mxchat_options', []);
2878 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
2879 -
2880 - // Check if using OpenRouter
2881 - if ($selected_model === 'openrouter') {
2882 - $provider = 'openrouter';
2883 - $selected_model = $options['openrouter_selected_model'] ?? '';
2884 - $api_key = $options['openrouter_api_key'] ?? '';
2885 -
2886 - if (empty($selected_model)) {
2887 - wp_send_json_error(['error' => 'No OpenRouter model selected']);
2888 - wp_die();
2889 - }
2890 - } else {
2891 - // Determine provider from model name
2892 - $model_parts = explode('-', $selected_model);
2893 - $provider = strtolower($model_parts[0]);
2894 -
2895 - // Get the appropriate API key based on provider
2896 - $api_key = '';
2897 - switch ($provider) {
2898 - case 'gpt':
2899 - case 'o1':
2900 - $api_key = $options['api_key'] ?? '';
2901 - break;
2902 - case 'claude':
2903 - $api_key = $options['claude_api_key'] ?? '';
2904 - break;
2905 - case 'grok':
2906 - $api_key = $options['xai_api_key'] ?? '';
2907 - break;
2908 - case 'deepseek':
2909 - $api_key = $options['deepseek_api_key'] ?? '';
2910 - break;
2911 - case 'gemini':
2912 - $api_key = $options['gemini_api_key'] ?? '';
2913 - break;
2914 - default:
2915 - // Default to OpenAI
2916 - $api_key = $options['api_key'] ?? '';
2917 - $provider = 'gpt';
2918 - break;
2919 - }
2920 - }
2921 -
2922 - if (empty($api_key)) {
2923 - wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
2924 - wp_die();
2925 - }
2926 -
2927 - // Make API request based on provider
2928 - $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
2929 -
2930 - if (is_wp_error($response)) {
2931 - wp_send_json_error(['error' => $response->get_error_message()]);
2932 - wp_die();
2933 - }
2934 -
2935 - // Parse the response to extract translated messages
2936 - $translations = [];
2937 - foreach ($messages as $msg) {
2938 - $index = $msg['index'];
2939 - $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
2940 - if (preg_match($pattern, $response, $matches)) {
2941 - $translations[] = [
2942 - 'index' => $index,
2943 - 'translated' => trim($matches[1])
2944 - ];
2945 - }
2946 - }
2947 -
2948 - // Save translations to database
2949 - if (!empty($translations)) {
2950 - $this->save_transcript_translation($session_id, $target_lang, $translations);
2951 - }
2952 -
2953 - wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
2954 - wp_die();
2955 -}
2956 -
2957 -/**
2958 - * Save transcript translation to database
2959 - */
2960 -private function save_transcript_translation($session_id, $language_code, $translations) {
2961 - global $wpdb;
2962 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
2963 -
2964 - // Check if table exists, create if not
2965 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
2966 - mxchat_create_translations_table();
2967 - }
2968 -
2969 - $now = current_time('mysql');
2970 - $translations_json = wp_json_encode($translations);
2971 -
2972 - // Use REPLACE to insert or update
2973 - $wpdb->query($wpdb->prepare(
2974 - "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
2975 - VALUES (%s, %s, %s, %s, %s)",
2976 - $session_id,
2977 - $language_code,
2978 - $translations_json,
2979 - $now,
2980 - $now
2981 - ));
2982 -}
2983 -
2984 -/**
2985 - * Get saved translation for a session
2986 - */
2987 -public function mxchat_get_transcript_translation() {
2988 - if (!current_user_can('manage_options')) {
2989 - wp_send_json_error(['error' => 'Insufficient permissions']);
2990 - wp_die();
2991 - }
2992 -
2993 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2994 -
2995 - if (empty($session_id)) {
2996 - wp_send_json_error(['error' => 'No session ID provided']);
2997 - wp_die();
2998 - }
2999 -
3000 - global $wpdb;
3001 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
3002 -
3003 - // Check if table exists
3004 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3005 - wp_send_json(['success' => true, 'has_translation' => false]);
3006 - wp_die();
3007 - }
3008 -
3009 - // Get the most recent translation for this session
3010 - $result = $wpdb->get_row($wpdb->prepare(
3011 - "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
3012 - $session_id
3013 - ));
3014 -
3015 - if ($result) {
3016 - $translations = json_decode($result->translations, true);
3017 - wp_send_json([
3018 - 'success' => true,
3019 - 'has_translation' => true,
3020 - 'language' => $result->language_code,
3021 - 'translations' => $translations
3022 - ]);
3023 - } else {
3024 - wp_send_json(['success' => true, 'has_translation' => false]);
3025 - }
3026 - wp_die();
3027 -}
3028 -
3029 -/**
3030 - * Translate text using the user's selected provider and model
3031 - */
3032 -private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
3033 - switch ($provider) {
3034 - case 'claude':
3035 - return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
3036 - case 'grok':
3037 - return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
3038 - case 'deepseek':
3039 - return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
3040 - case 'gemini':
3041 - return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
3042 - case 'openrouter':
3043 - return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
3044 - case 'gpt':
3045 - case 'o1':
3046 - default:
3047 - return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
3048 - }
3049 -}
3050 -
3051 -/**
3052 - * Translate text using OpenAI API
3053 - */
3054 -private function translate_with_openai($api_key, $model, $system_prompt, $text) {
3055 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
3056 - 'timeout' => 60,
3057 - 'headers' => [
3058 - 'Authorization' => 'Bearer ' . $api_key,
3059 - 'Content-Type' => 'application/json'
3060 - ],
3061 - 'body' => wp_json_encode([
3062 - 'model' => $model,
3063 - 'messages' => [
3064 - ['role' => 'system', 'content' => $system_prompt],
3065 - ['role' => 'user', 'content' => $text]
3066 - ],
3067 - 'temperature' => 0.3
3068 - ])
3069 - ]);
3070 -
3071 - if (is_wp_error($response)) {
3072 - return $response;
3073 - }
3074 -
3075 - $body = json_decode(wp_remote_retrieve_body($response), true);
3076 -
3077 - if (isset($body['error'])) {
3078 - return new WP_Error('api_error', $body['error']['message']);
3079 - }
3080 -
3081 - if (isset($body['choices'][0]['message']['content'])) {
3082 - return $body['choices'][0]['message']['content'];
3083 - }
3084 -
3085 - return new WP_Error('api_error', 'Invalid API response');
3086 -}
3087 -
3088 -/**
3089 - * Translate text using Claude API
3090 - */
3091 -private function translate_with_claude($api_key, $model, $system_prompt, $text) {
3092 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3093 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3094 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3095 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3096 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
3097 - 'timeout' => 60,
3098 - 'headers' => [
3099 - 'x-api-key' => $api_key,
3100 - 'anthropic-version' => '2023-06-01',
3101 - 'Content-Type' => 'application/json'
3102 - ],
3103 - 'body' => wp_json_encode([
3104 - 'model' => $model,
3105 - 'max_tokens' => 4096,
3106 - // Prompt-cache breakpoint (plan 1ff43b): the translate instruction
3107 - // repeats across every message in a batch, so cache reads bill at
3108 - // 0.1x. Below the model's minimum prefix it silently no-ops.
3109 - 'system' => trim((string) $system_prompt) === '' ? $system_prompt : [
3110 - ['type' => 'text', 'text' => $system_prompt, 'cache_control' => ['type' => 'ephemeral']]
3111 - ],
3112 - 'messages' => [
3113 - ['role' => 'user', 'content' => $text]
3114 - ]
3115 - ])
3116 - ]);
3117 -
3118 - if (is_wp_error($response)) {
3119 - return $response;
3120 - }
3121 -
3122 - $body = json_decode(wp_remote_retrieve_body($response), true);
3123 -
3124 - if (isset($body['error'])) {
3125 - return new WP_Error('api_error', $body['error']['message']);
3126 - }
3127 -
3128 - if (isset($body['content'][0]['text'])) {
3129 - return $body['content'][0]['text'];
3130 - }
3131 -
3132 - return new WP_Error('api_error', 'Invalid API response');
3133 -}
3134 -
3135 -/**
3136 - * Translate text using xAI (Grok) API
3137 - */
3138 -private function translate_with_xai($api_key, $model, $system_prompt, $text) {
3139 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
3140 - 'timeout' => 60,
3141 - 'headers' => [
3142 - 'Authorization' => 'Bearer ' . $api_key,
3143 - 'Content-Type' => 'application/json'
3144 - ],
3145 - 'body' => wp_json_encode([
3146 - 'model' => $model,
3147 - 'messages' => [
3148 - ['role' => 'system', 'content' => $system_prompt],
3149 - ['role' => 'user', 'content' => $text]
3150 - ],
3151 - 'temperature' => 0.3
3152 - ])
3153 - ]);
3154 -
3155 - if (is_wp_error($response)) {
3156 - return $response;
3157 - }
3158 -
3159 - $body = json_decode(wp_remote_retrieve_body($response), true);
3160 -
3161 - if (isset($body['error'])) {
3162 - return new WP_Error('api_error', $body['error']['message']);
3163 - }
3164 -
3165 - if (isset($body['choices'][0]['message']['content'])) {
3166 - return $body['choices'][0]['message']['content'];
3167 - }
3168 -
3169 - return new WP_Error('api_error', 'Invalid API response');
3170 -}
3171 -
3172 -/**
3173 - * Translate text using DeepSeek API
3174 - */
3175 -private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
3176 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
3177 - 'timeout' => 60,
3178 - 'headers' => [
3179 - 'Authorization' => 'Bearer ' . $api_key,
3180 - 'Content-Type' => 'application/json'
3181 - ],
3182 - 'body' => wp_json_encode([
3183 - 'model' => $model,
3184 - 'messages' => [
3185 - ['role' => 'system', 'content' => $system_prompt],
3186 - ['role' => 'user', 'content' => $text]
3187 - ],
3188 - 'temperature' => 0.3,
3189 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
3190 - // slow responses); translation wants non-thinking.
3191 - 'thinking' => ['type' => 'disabled']
3192 - ])
3193 - ]);
3194 -
3195 - if (is_wp_error($response)) {
3196 - return $response;
3197 - }
3198 -
3199 - $body = json_decode(wp_remote_retrieve_body($response), true);
3200 -
3201 - if (isset($body['error'])) {
3202 - return new WP_Error('api_error', $body['error']['message']);
3203 - }
3204 -
3205 - if (isset($body['choices'][0]['message']['content'])) {
3206 - return $body['choices'][0]['message']['content'];
3207 - }
3208 -
3209 - return new WP_Error('api_error', 'Invalid API response');
3210 -}
3211 -
3212 -/**
3213 - * Translate text using Google Gemini API
3214 - */
3215 -private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
3216 - if ($model === 'gemini-3-pro-preview') {
3217 - $model = 'gemini-3.1-pro-preview';
3218 - }
3219 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
3220 -
3221 - $response = wp_remote_post($url, [
3222 - 'timeout' => 60,
3223 - 'headers' => [
3224 - 'Content-Type' => 'application/json'
3225 - ],
3226 - 'body' => wp_json_encode([
3227 - 'contents' => [
3228 - [
3229 - 'parts' => [
3230 - ['text' => $system_prompt . "\n\n" . $text]
3231 - ]
3232 - ]
3233 - ],
3234 - 'generationConfig' => [
3235 - 'temperature' => 0.3
3236 - ]
3237 - ])
3238 - ]);
3239 -
3240 - if (is_wp_error($response)) {
3241 - return $response;
3242 - }
3243 -
3244 - $body = json_decode(wp_remote_retrieve_body($response), true);
3245 -
3246 - if (isset($body['error'])) {
3247 - return new WP_Error('api_error', $body['error']['message']);
3248 - }
3249 -
3250 - if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
3251 - return $body['candidates'][0]['content']['parts'][0]['text'];
3252 - }
3253 -
3254 - return new WP_Error('api_error', 'Invalid API response');
3255 -}
3256 -
3257 -/**
3258 - * Translate text using OpenRouter API
3259 - */
3260 -private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
3261 - $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
3262 - 'timeout' => 60,
3263 - 'headers' => [
3264 - 'Authorization' => 'Bearer ' . $api_key,
3265 - 'Content-Type' => 'application/json',
3266 - 'HTTP-Referer' => home_url(),
3267 - 'X-Title' => 'MxChat Translation'
3268 - ],
3269 - 'body' => wp_json_encode([
3270 - 'model' => $model,
3271 - 'messages' => [
3272 - ['role' => 'system', 'content' => $system_prompt],
3273 - ['role' => 'user', 'content' => $text]
3274 - ],
3275 - 'temperature' => 0.3
3276 - ])
3277 - ]);
3278 -
3279 - if (is_wp_error($response)) {
3280 - return $response;
3281 - }
3282 -
3283 - $body = json_decode(wp_remote_retrieve_body($response), true);
3284 -
3285 - if (isset($body['error'])) {
3286 - return new WP_Error('api_error', $body['error']['message']);
3287 - }
3288 -
3289 - if (isset($body['choices'][0]['message']['content'])) {
3290 - return $body['choices'][0]['message']['content'];
3291 - }
3292 -
3293 - return new WP_Error('api_error', 'Invalid API response');
3294 -}
3295 -
3296 569 public function mxchat_fetch_chat_history() {
3297 570 global $wpdb;
3298 571 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3299 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3300 572
573 + // Check if the current user has sufficient permissions
3301 574 if (!current_user_can('manage_options')) {
3302 - wp_send_json_error(['message' => 'Insufficient permissions']);
575 + echo esc_html__('You do not have sufficient permissions to view this page.', 'mxchat');
3303 576 wp_die();
3304 577 }
3305 578
3306 - $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3307 - $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3308 - $offset = ($page - 1) * $per_page;
3309 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3310 - $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3311 - $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3312 - if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3313 - $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3314 - $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3315 - $ratings_join = '';
3316 - $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3317 - if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3318 - // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3319 - $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3320 - $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3321 - }
579 + // Fetch chat transcripts from the database, ordered by timestamp
580 + $chat_transcripts = $wpdb->get_results(
581 + $wpdb->prepare("SELECT * FROM {$table_name} ORDER BY timestamp ASC")
582 + );
3322 583
3323 - // Build search condition
3324 - $search_condition = '';
3325 - $search_params = [];
3326 - if (!empty($search)) {
3327 - $search_condition = "WHERE (
3328 - session_id LIKE %s
3329 - OR user_email LIKE %s
3330 - OR user_name LIKE %s
3331 - OR user_identifier LIKE %s
3332 - OR message LIKE %s
3333 - )";
3334 - $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3335 - }
3336 -
3337 - // Get total count
3338 - $count_query = !empty($search)
3339 - ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3340 - : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3341 - $total_sessions = (int) $wpdb->get_var($count_query);
3342 -
3343 - // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3344 - // and order by rating value (NULLs last) with recency as tiebreaker.
3345 - if ($ratings_join) {
3346 - $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3347 - } else {
3348 - $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3349 - }
3350 - $session_query = !empty($search)
3351 - ? $wpdb->prepare(
3352 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3353 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3354 - array_merge($search_params, [$per_page, $offset])
3355 - )
3356 - : $wpdb->prepare(
3357 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3358 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3359 - $per_page, $offset
3360 - );
3361 - $session_ids = $wpdb->get_col($session_query);
3362 -
3363 - $total_pages = ceil($total_sessions / $per_page);
3364 -
3365 - if (empty($session_ids)) {
3366 - wp_send_json([
3367 - 'success' => true,
3368 - 'sessions' => [],
3369 - 'page' => $page,
3370 - 'total_pages' => 0,
3371 - 'total_sessions' => 0,
3372 - 'showing_start' => 0,
3373 - 'showing_end' => 0
3374 - ]);
584 + // If no transcripts are available, display a message
585 + if (empty($chat_transcripts)) {
586 + echo esc_html__('No chat history available.', 'mxchat');
3375 587 wp_die();
3376 588 }
3377 589
3378 - // Check for optional columns/tables
3379 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3380 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
590 + ob_start();
591 + $current_session_id = '';
3381 592
3382 - // Batch-fetch session ratings for this page (plan-a5b006).
3383 - $ratings_map = array();
3384 - if ($rating_table_exists && !empty($session_ids)) {
3385 - $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3386 - $rating_rows = $wpdb->get_results($wpdb->prepare(
3387 - "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3388 - $session_ids
3389 - ));
3390 - foreach ($rating_rows as $row) {
3391 - $ratings_map[$row->session_id] = array(
3392 - 'value' => (int) $row->rating_value,
3393 - 'feedback' => (string) $row->rating_feedback,
3394 - );
3395 - }
3396 - }
3397 -
3398 - // Build session list data
3399 - $sessions = [];
3400 - foreach ($session_ids as $session_id) {
3401 - // Get session metadata
3402 - $session_data = $originating_columns_exist
3403 - ? $wpdb->get_row($wpdb->prepare(
3404 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3405 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3406 - $session_id
3407 - ))
3408 - : $wpdb->get_row($wpdb->prepare(
3409 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3410 - WHERE session_id = %s LIMIT 1",
3411 - $session_id
3412 - ));
3413 -
3414 - // Get message count and latest timestamp
3415 - $message_stats = $wpdb->get_row($wpdb->prepare(
3416 - "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3417 - $session_id
3418 - ));
3419 -
3420 - // Get first user message as preview
3421 - $first_user_msg = $wpdb->get_var($wpdb->prepare(
3422 - "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3423 - $session_id
3424 - ));
3425 - $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3426 -
3427 - // Build display name
3428 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3429 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3430 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3431 -
3432 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3433 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3434 -
3435 - // Format time - show relative for recent, date for older
3436 - $timestamp = strtotime($message_stats->latest . ' UTC');
3437 - $now = time();
3438 - $diff = $now - $timestamp;
3439 - if ($diff < 3600) {
3440 - $time_display = floor($diff / 60) . 'm ago';
3441 - } elseif ($diff < 86400) {
3442 - $time_display = floor($diff / 3600) . 'h ago';
3443 - } elseif ($diff < 604800) {
3444 - $time_display = floor($diff / 86400) . 'd ago';
3445 - } else {
3446 - $time_display = wp_date('M j', $timestamp);
3447 - }
3448 -
3449 - // Get initials for avatar
3450 - $initials = strtoupper(substr($display_name, 0, 2));
3451 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3452 - $parts = explode(' ', $display_name);
3453 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3454 - }
3455 -
3456 - $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3457 - $rating_value = $rating_entry ? $rating_entry['value'] : null;
3458 - $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3459 -
3460 - $sessions[] = [
3461 - 'session_id' => $session_id,
3462 - 'display_name' => $display_name,
3463 - 'display_sub' => $display_sub,
3464 - 'initials' => $initials,
3465 - 'preview' => $preview,
3466 - 'message_count' => (int) $message_stats->count,
3467 - 'time_display' => $time_display,
3468 - 'timestamp' => $message_stats->latest,
3469 - 'rating_value' => $rating_value,
3470 - 'rating_feedback' => $rating_feedback,
3471 - ];
3472 - }
3473 -
3474 - wp_send_json([
3475 - 'success' => true,
3476 - 'sessions' => $sessions,
3477 - 'page' => $page,
3478 - 'total_pages' => $total_pages,
3479 - 'total_sessions' => $total_sessions,
3480 - 'showing_start' => $offset + 1,
3481 - 'showing_end' => min($offset + $per_page, $total_sessions)
3482 - ]);
3483 - wp_die();
3484 -}
3485 -
3486 -/**
3487 - * Fetch single conversation details for split-panel view
3488 - */
3489 -public function mxchat_fetch_conversation() {
3490 - global $wpdb;
3491 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3492 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3493 -
3494 - if (!current_user_can('manage_options')) {
3495 - wp_send_json_error(['message' => 'Insufficient permissions']);
3496 - wp_die();
3497 - }
3498 -
3499 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3500 - if (empty($session_id)) {
3501 - wp_send_json_error(['message' => 'No session ID provided']);
3502 - wp_die();
3503 - }
3504 -
3505 - // Check for optional columns/tables
3506 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3507 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3508 -
3509 - // Get session metadata
3510 - $session_data = $originating_columns_exist
3511 - ? $wpdb->get_row($wpdb->prepare(
3512 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3513 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3514 - $session_id
3515 - ))
3516 - : $wpdb->get_row($wpdb->prepare(
3517 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3518 - WHERE session_id = %s LIMIT 1",
3519 - $session_id
3520 - ));
3521 -
3522 - if (!$session_data) {
3523 - wp_send_json_error(['message' => 'Session not found']);
3524 - wp_die();
3525 - }
3526 -
3527 - // Get clicked URLs
3528 - $clicked_urls = [];
3529 - if ($url_table_exists) {
3530 - $url_clicks = $wpdb->get_results($wpdb->prepare(
3531 - "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3532 - WHERE session_id = %s ORDER BY click_timestamp ASC",
3533 - $session_id
3534 - ));
3535 - foreach ($url_clicks as $click) {
3536 - $clicked_urls[] = $click->clicked_url;
3537 - }
3538 - }
3539 -
3540 - // Get all messages
3541 - $messages = $wpdb->get_results($wpdb->prepare(
3542 - "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3543 - $session_id
3544 - ));
3545 -
3546 - // Build user info
3547 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3548 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3549 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3550 -
3551 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3552 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3553 -
3554 - // Get initials
3555 - $initials = strtoupper(substr($display_name, 0, 2));
3556 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3557 - $parts = explode(' ', $display_name);
3558 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3559 - }
3560 -
3561 - // Page info
3562 - $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3563 - $page_title = '';
3564 - if ($page_url) {
3565 - $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3566 - }
3567 -
3568 - // Format messages for output
3569 - $formatted_messages = [];
3570 - foreach ($messages as $msg) {
3571 - $is_user = ($msg->role === 'user');
3572 - // Live-agent replies (Slack/Telegram handoff) persist with role 'agent'.
3573 - // Kept OUT of $is_bot so the RAG Sources link below stays bot-only.
3574 - $is_agent = ($msg->role === 'agent');
3575 - $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3576 -
3577 - $content = wp_kses(
3578 - stripslashes($msg->message),
3579 - [
3580 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3581 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3582 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3583 - 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3584 - 'img' => ['src' => [], 'alt' => [], 'class' => []],
3585 - 'h3' => ['class' => []],
3586 - 'h4' => ['class' => []],
3587 - 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
3588 - 'select' => ['class' => [], 'data-attribute' => []],
3589 - 'option' => ['value' => []],
3590 - 'span' => ['class' => []],
3591 - 'del' => [], 'ins' => [],
3592 - ]
3593 - );
3594 - $formatted_content = $this->format_transcript_message($content);
3595 -
3596 - $has_rag = $is_bot && !empty($msg->rag_context);
3597 -
3598 - $formatted_messages[] = [
3599 - 'id' => $msg->id,
3600 - 'role' => $msg->role,
3601 - 'is_user' => $is_user,
3602 - 'is_agent' => $is_agent,
3603 - 'is_bot' => $is_bot,
3604 - 'content' => $formatted_content,
3605 - 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
3606 - 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
3607 - 'has_rag' => $has_rag
3608 - ];
3609 - }
3610 -
3611 - // First message timestamp for "started" display
3612 - $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
3613 -
3614 - // Pull rating_feedback for this session (if any) so the details drawer can show it.
3615 - $rating_feedback = '';
3616 - $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
3617 - if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
3618 - $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
3619 - "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
3620 - $session_id
3621 - ));
3622 - }
3623 -
3624 - wp_send_json([
3625 - 'success' => true,
3626 - 'session_id' => $session_id,
3627 - 'user' => [
3628 - 'name' => $display_name,
3629 - 'sub' => $display_sub,
3630 - 'initials' => $initials,
3631 - 'email' => $user_email,
3632 - 'identifier' => $user_identifier
3633 - ],
3634 - 'page' => [
3635 - 'url' => $page_url,
3636 - 'title' => $page_title
3637 - ],
3638 - 'clicked_urls' => $clicked_urls,
3639 - 'messages' => $formatted_messages,
3640 - 'message_count' => count($messages),
3641 - 'started' => $started,
3642 - 'rating_feedback' => $rating_feedback
3643 - ]);
3644 - wp_die();
3645 -}
3646 -
3647 -
3648 -/**
3649 - * ALTERNATIVE: Simpler helper method using string replacement
3650 - */
3651 -private function highlight_clicked_links($message_content, $clicked_urls) {
3652 - if (empty($clicked_urls)) {
3653 - return wp_kses(
3654 - $message_content,
3655 - [
3656 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3657 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3658 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3659 - ]
3660 - );
3661 - }
3662 -
3663 - // First apply standard sanitization
3664 - $message_content = wp_kses(
3665 - $message_content,
3666 - [
3667 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3668 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3669 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3670 - ]
3671 - );
3672 -
3673 - // Process each clicked URL
3674 - foreach ($clicked_urls as $clicked_url) {
3675 - // Try multiple patterns to catch different link formats
3676 - $patterns = [
3677 - // Standard link format
3678 - '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
3679 - // Link with trailing slash
3680 - '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
3681 - // Encoded entities version
3682 - '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
3683 - ];
3684 -
3685 - foreach ($patterns as $pattern) {
3686 - if (preg_match($pattern, $message_content)) {
3687 - $message_content = preg_replace_callback(
3688 - $pattern,
3689 - function($matches) {
3690 - $full_match = $matches[0];
3691 - $attributes = $matches[1];
3692 -
3693 - // Check if it already has the class
3694 - if (strpos($full_match, 'mxchat-clicked-link') !== false) {
3695 - return $full_match;
3696 - }
3697 -
3698 - // Check if class attribute exists
3699 - if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
3700 - // Add to existing class
3701 - $new_attributes = preg_replace(
3702 - '/class=["\']([^"\']*)["\']/',
3703 - 'class="$1 mxchat-clicked-link"',
3704 - $attributes
3705 - );
3706 - } else {
3707 - // Add new class attribute
3708 - $new_attributes = $attributes . ' class="mxchat-clicked-link"';
3709 - }
3710 -
3711 - // Add title if not present
3712 - if (strpos($new_attributes, 'title=') === false) {
3713 - $new_attributes .= ' title="User clicked this link"';
3714 - }
3715 -
3716 - return '<a' . $new_attributes . '>';
3717 - },
3718 - $message_content
3719 - );
3720 -
3721 - // If we found and replaced, break out of the patterns loop
3722 - break;
593 + foreach ($chat_transcripts as $transcript) {
594 + // Start a new session block if session ID changes
595 + if ($current_session_id !== $transcript->session_id) {
596 + if ($current_session_id !== '') {
597 + echo '</div>'; // Close the previous session block
3723 598 }
599 + $current_session_id = sanitize_text_field($transcript->session_id);
600 + echo '<div class="chat-session">';
601 + echo '<h4><input type="checkbox" name="delete_session_ids[]" value="' . esc_attr($transcript->session_id) . '"> ' . esc_html__('Session ID:', 'mxchat') . ' ' . esc_html($current_session_id) . '</h4>';
3724 602 }
3725 - }
3726 603
3727 - return $message_content;
3728 -}
604 + // Format the timestamp for display
605 + $formatted_timestamp = date_i18n('F j, Y g:i a', strtotime($transcript->timestamp));
3729 606
3730 -public function mxchat_create_prompts_page() {
3731 - //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
3732 -
3733 - global $wpdb;
3734 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3735 -
3736 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3737 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
3738 -
3739 - // Display success message if all prompts were deleted
3740 - if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
3741 - echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button></div>';
3742 - }
3743 -
3744 - // Set up pagination, search query, and content type filter
3745 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
3746 - $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
3747 - $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
3748 - $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
3749 - $per_page = 25;
3750 -
3751 - //error_log('DEBUG: Search query: ' . $search_query);
3752 - //error_log('DEBUG: Content type filter: ' . $content_type_filter);
3753 - //error_log('DEBUG: Current page: ' . $current_page);
3754 - //error_log('DEBUG: Per page: ' . $per_page);
3755 -
3756 - // ================================
3757 - // MULTI-BOT CONFIGURATION
3758 - // ================================
3759 -
3760 - // Check for multi-bot and set up bot selection
3761 - if (class_exists('MxChat_Multi_Bot_Manager')) {
3762 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
3763 - $available_bots = $multi_bot_manager->get_available_bots();
3764 -
3765 - // Get saved bot selection (user-specific first, then site-wide default)
3766 - $user_id = get_current_user_id();
3767 - $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
3768 - if (empty($saved_bot_id)) {
3769 - $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
3770 - }
3771 -
3772 - // Allow URL override but default to saved selection
3773 - $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
3774 - $multibot_active = true;
3775 - } else {
3776 - $current_bot_id = 'default';
3777 - $multibot_active = false;
3778 - }
3779 -
3780 - // ================================
3781 - // DATA SOURCE CONFIGURATION
3782 - // ================================
3783 -
3784 - // Get bot-specific Pinecone settings
3785 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
3786 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3787 - $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
3788 -
3789 - // Get OpenAI Vector Store settings
3790 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
3791 - $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
3792 -
3793 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3794 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
3795 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
3796 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
3797 -
3798 - if ($use_pinecone && !empty($pinecone_api_key)) {
3799 - //error_log('DEBUG: Using PINECONE data source with bot-specific config');
3800 - // PINECONE DATA SOURCE
3801 - $data_source = 'pinecone';
3802 -
3803 - // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
3804 - // UPDATED 2.5.6: Added content_type_filter parameter
3805 - $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
3806 -
3807 - // TEMPORARY DEBUG - Add this right after the fetch call
3808 - //error_log('=== DEBUG: Bot switching issue ===');
3809 - //error_log('Current bot ID: ' . $current_bot_id);
3810 - //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3811 - //error_log('Records returned: ' . count($records['data'] ?? []));
3812 - //error_log('Total records: ' . ($records['total'] ?? 0));
3813 -
3814 - // Check first few records to see their bot_id
3815 - if (!empty($records['data'])) {
3816 - foreach (array_slice($records['data'], 0, 3) as $i => $record) {
3817 - $record_bot_id = $record->bot_id ?? 'NOT_SET';
3818 - //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
3819 - }
3820 - }
3821 - //error_log('=== END DEBUG ===');
3822 -
3823 - $total_records = $records['total'] ?? 0;
3824 - $prompts = $records['data'] ?? array();
3825 - $total_in_database = $records['total_in_database'] ?? 0;
3826 - $showing_recent_only = $records['showing_recent_only'] ?? false;
3827 -
3828 - $total_pages = ceil($total_records / $per_page);
3829 -
3830 - } else {
3831 - //error_log('DEBUG: Using WORDPRESS DB data source');
3832 - // WORDPRESS DB DATA SOURCE (your existing logic)
3833 - $data_source = 'wordpress';
3834 -
3835 - // Initialize these variables for WordPress DB
3836 - $total_in_database = 0;
3837 - $showing_recent_only = false;
3838 -
3839 - $offset = ($current_page - 1) * $per_page;
3840 -
3841 - // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
3842 - $where_clauses = array();
3843 - $where_values = array();
3844 -
3845 - if ($search_query) {
3846 - $where_clauses[] = "article_content LIKE %s";
3847 - $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
3848 - }
3849 -
3850 - if ($content_type_filter) {
3851 - $where_clauses[] = "content_type = %s";
3852 - $where_values[] = $content_type_filter;
3853 - }
3854 -
3855 - $sql_where = "";
3856 - if (!empty($where_clauses)) {
3857 - $sql_where = "WHERE " . implode(" AND ", $where_clauses);
3858 - }
3859 -
3860 - // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
3861 - // This ensures pagination shows X entries per page, not X chunks
3862 - // Entries with empty source_url are counted individually
3863 - if (!empty($where_values)) {
3864 - // Count unique source_urls + count of rows with empty source_url
3865 - $count_query = $wpdb->prepare(
3866 - "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
3867 - (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
3868 - array_merge($where_values, $where_values)
3869 - );
3870 - } else {
3871 - $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
3872 - (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
3873 - }
3874 - $total_records = $wpdb->get_var($count_query);
3875 - $total_pages = ceil($total_records / $per_page);
3876 -
3877 - // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
3878 - // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
3879 - if (!empty($where_values)) {
3880 - $urls_query = $wpdb->prepare(
3881 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
3882 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3883 - array_merge($where_values, array($per_page, $offset))
3884 - );
3885 - } else {
3886 - $urls_query = $wpdb->prepare(
3887 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
3888 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3889 - $per_page, $offset
3890 - );
3891 - }
3892 - $page_urls = $wpdb->get_results($urls_query);
3893 -
3894 - // Step 2: Fetch all rows for these source_urls
3895 - $prompts = array();
3896 - if (!empty($page_urls)) {
3897 - // Build URL order map to preserve newest-first ordering from step 1
3898 - $url_order_map = array();
3899 - $url_list = array();
3900 - $has_empty_url = false;
3901 - $order_index = 0;
3902 - foreach ($page_urls as $url_row) {
3903 - if (empty($url_row->source_url)) {
3904 - $has_empty_url = true;
3905 - $url_order_map['__empty__'] = $order_index++;
607 + // Determine the role to display (user identifier or email for users, bot for the AI)
608 + $role = $transcript->role;
609 + if ($role === 'user') {
610 + // Sanitize email if available
611 + if (!empty($transcript->user_email)) {
612 + $role = sanitize_email($transcript->user_email);
613 + } else {
614 + // Sanitize user identifier, anonymize if it's an IP address
615 + $user_identifier = sanitize_text_field($transcript->user_identifier);
616 +
617 + // Check if the user identifier is an IP address and anonymize it
618 + if (filter_var($user_identifier, FILTER_VALIDATE_IP)) {
619 + $role = preg_replace('/\.\d+$/', '.xxx', $user_identifier); // Mask the last octet
3906 620 } else {
3907 - $url_list[] = $url_row->source_url;
3908 - $url_order_map[$url_row->source_url] = $order_index++;
621 + $role = $user_identifier; // If it's not an IP, just display the identifier
3909 622 }
3910 623 }
3911 -
3912 - // Build query to fetch all rows for these URLs
3913 - $url_conditions = array();
3914 - $url_values = array();
3915 -
3916 - if (!empty($url_list)) {
3917 - $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
3918 - $url_conditions[] = "source_url IN ($placeholders)";
3919 - $url_values = array_merge($url_values, $url_list);
3920 - }
3921 -
3922 - if ($has_empty_url) {
3923 - $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
3924 - }
3925 -
3926 - if (!empty($url_conditions)) {
3927 - $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
3928 -
3929 - // Add original filters back
3930 - if (!empty($where_clauses)) {
3931 - $url_where .= " AND " . implode(" AND ", $where_clauses);
3932 - $url_values = array_merge($url_values, $where_values);
3933 - }
3934 -
3935 - if (!empty($url_values)) {
3936 - $prompts_query = $wpdb->prepare(
3937 - "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
3938 - $url_values
3939 - );
3940 - } else {
3941 - $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
3942 - }
3943 -
3944 - $prompts = $wpdb->get_results($prompts_query);
3945 -
3946 - // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
3947 - usort($prompts, function($a, $b) use ($url_order_map) {
3948 - $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
3949 - $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
3950 - $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
3951 - $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
3952 -
3953 - // First sort by URL order (newest URLs first)
3954 - if ($order_a !== $order_b) {
3955 - return $order_a - $order_b;
3956 - }
3957 -
3958 - // Within same URL, sort by timestamp DESC (newest chunks first)
3959 - return strtotime($b->timestamp) - strtotime($a->timestamp);
3960 - });
3961 - }
3962 624 }
3963 - }
3964 625
3965 - // ================================
3966 - // PAGINATION GENERATION
3967 - // ================================
3968 -
3969 - // Generate pagination links
3970 - if ($total_pages > 1) {
3971 - // Build a clean base URL with only necessary parameters
3972 - $pagination_args = array('page' => 'mxchat-prompts');
3973 -
3974 - // Preserve bot_id parameter if multi-bot is active
3975 - if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
3976 - $pagination_args['bot_id'] = $current_bot_id;
3977 - }
3978 -
3979 - // Preserve search query and nonce if present
3980 - if ($search_query) {
3981 - $pagination_args['search'] = $search_query;
3982 - if (!empty($nonce)) {
3983 - $pagination_args['_wpnonce'] = $nonce;
3984 - }
3985 - }
3986 -
3987 - // Preserve content type filter if present
3988 - if ($content_type_filter) {
3989 - $pagination_args['content_type'] = $content_type_filter;
3990 - }
3991 -
3992 - // Build clean base URL
3993 - $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
3994 -
3995 - $page_links = paginate_links(array(
3996 - 'base' => $base_url . '%_%',
3997 - 'format' => '&paged=%#%',
3998 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
3999 - 'next_text' => __('Next &raquo;', 'mxchat'),
4000 - 'total' => $total_pages,
4001 - 'current' => $current_page,
4002 - 'type' => 'plain',
4003 - ));
4004 - } else {
4005 - $page_links = '';
626 + // Output the chat message
627 + echo '<div class="chat-message">';
628 + echo '<strong>' . esc_html($role) . ' (' . esc_html($formatted_timestamp) . '):</strong> ';
629 + echo wp_kses_post($transcript->message);
630 + echo '</div>';
4006 631 }
4007 632
4008 - // ================================
4009 - // PROCESSING STATUS RETRIEVAL
4010 - // ================================
633 + // Close the final session block
634 + echo '</div>';
4011 635
4012 - // Retrieve processing statuses using queue-based method
4013 - $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
4014 - $pdf_status = $processing_statuses['pdf_status'];
4015 - $sitemap_status = $processing_statuses['sitemap_status'];
4016 - $is_processing = $processing_statuses['is_processing'];
636 + $output = ob_get_clean();
4017 637
4018 - //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
4019 -
4020 - // ================================
4021 - // RENDER PAGE WITH NEW SIDEBAR LAYOUT
4022 - // ================================
4023 -
4024 - // Include the new knowledge page template
4025 - require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
4026 -
4027 - // Package all page data for the render function
4028 - $page_data = array(
4029 - 'prompts' => $prompts,
4030 - 'total_records' => $total_records,
4031 - 'total_pages' => $total_pages,
4032 - 'current_page' => $current_page,
4033 - 'per_page' => $per_page,
4034 - 'page_links' => $page_links,
4035 - 'search_query' => $search_query,
4036 - 'content_type_filter' => $content_type_filter,
4037 - 'data_source' => $data_source,
4038 - 'use_pinecone' => $use_pinecone,
4039 - 'use_vectorstore' => $use_vectorstore,
4040 - 'multibot_active' => $multibot_active,
4041 - 'current_bot_id' => $current_bot_id,
4042 - 'pdf_status' => $pdf_status,
4043 - 'sitemap_status' => $sitemap_status,
4044 - 'is_processing' => $is_processing,
4045 - 'total_in_database' => $total_in_database ?? 0,
4046 - 'showing_recent_only' => $showing_recent_only ?? false,
4047 - );
4048 -
4049 - // Render the new sidebar-based page
4050 - mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
4051 -}
4052 -
4053 -/**
4054 - * Get bot-specific Pinecone configuration
4055 - * Used in the knowledge retrieval functions
4056 - */
4057 -private function get_bot_pinecone_config($bot_id = 'default') {
4058 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
4059 -
4060 - // If default bot or multi-bot add-on not active, use default Pinecone config
4061 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
4062 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
4063 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
4064 - $config = array(
4065 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
4066 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
4067 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
4068 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
4069 - );
4070 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
4071 - return $config;
4072 - }
4073 -
4074 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
4075 -
4076 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
4077 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
4078 -
4079 - if (!empty($bot_pinecone_config)) {
4080 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
4081 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
4082 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
4083 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
4084 - } else {
4085 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
4086 - }
4087 -
4088 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
4089 -}
4090 -
4091 -public function mxchat_delete_chat_history() {
4092 - if (!current_user_can('manage_options')) {
4093 - echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4094 - wp_die();
4095 - }
4096 - check_ajax_referer('mxchat_delete_chat_history', 'security');
4097 -
4098 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
4099 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
4100 - wp_die();
4101 - }
4102 -
4103 - global $wpdb;
4104 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4105 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
4106 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
4107 -
4108 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
4109 - // across the whole table). Default false: the chat rows go away but the lead is
4110 - // preserved as a separate "chat deleted" lead in the Leads tab.
4111 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
4112 -
4113 - $deleted_count = 0;
4114 - $preserved_as_deleted_leads = 0;
4115 - $emails_to_fully_wipe = [];
4116 -
4117 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
4118 - $session_id_sanitized = MxChat_Utils::sanitize_session_id($session_id);
4119 - if ($session_id_sanitized === '') {
4120 - continue;
4121 - }
4122 -
4123 - // Capture the lead info attached to this session *before* we delete the rows.
4124 - $lead_row = $wpdb->get_row($wpdb->prepare(
4125 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
4126 - FROM {$table_name}
4127 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
4128 - GROUP BY user_email, user_name
4129 - ORDER BY last_ts DESC LIMIT 1",
4130 - $session_id_sanitized
4131 - ));
4132 -
4133 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
4134 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
4135 -
4136 - if ($has_translations) {
4137 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
4138 - }
4139 -
4140 - delete_option('mxchat_history_' . $session_id_sanitized);
4141 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
4142 - if (class_exists('MxChat_Session_Store')) {
4143 - MxChat_Session_Store::delete_session($session_id_sanitized); // b64b77
4144 - }
4145 -
4146 - if ($lead_row && !empty($lead_row->user_email)) {
4147 - if ($also_delete_lead) {
4148 - // Full-wipe requested — queue the email so that all their sessions and
4149 - // related options get swept below. Also clear this session's pre-chat
4150 - // capture options (they're no longer meaningful).
4151 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
4152 - delete_option('mxchat_email_' . $session_id_sanitized);
4153 - delete_option('mxchat_name_' . $session_id_sanitized);
4154 - } else {
4155 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
4156 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
4157 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
4158 - if (!empty($lead_row->user_name)) {
4159 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
4160 - }
4161 - if (!empty($lead_row->last_ts)) {
4162 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
4163 - }
4164 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
4165 - delete_option('mxchat_email_' . $session_id_sanitized);
4166 - delete_option('mxchat_name_' . $session_id_sanitized);
4167 - $preserved_as_deleted_leads++;
4168 - }
4169 - } else {
4170 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
4171 - delete_option('mxchat_email_' . $session_id_sanitized);
4172 - delete_option('mxchat_name_' . $session_id_sanitized);
4173 - }
4174 -
4175 - $deleted_count++;
4176 - }
4177 -
4178 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
4179 - // chat_deleted preservation) for each affected email. Reuses the same internal
4180 - // helper as the Leads-tab Delete button for consistency.
4181 - if (!empty($emails_to_fully_wipe)) {
4182 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
4183 - }
4184 -
4185 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
4186 -
4187 - echo wp_json_encode([
4188 - 'success' => sprintf(
4189 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
4190 - $deleted_count
4191 - ),
4192 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
4193 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
4194 - ]);
638 + echo $output;
4195 639 wp_die();
4196 640 }
4197 641
4198 -/**
4199 - * Format transcript message content with markdown processing
4200 - * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
4201 - */
4202 -private function format_transcript_message($text) {
4203 - if (empty($text)) {
4204 - return '';
4205 - }
4206 642
4207 - // Normalize line endings and clean up excessive whitespace
4208 - $text = str_replace("\r\n", "\n", $text);
4209 - $text = str_replace("\r", "\n", $text);
4210 -
4211 - // Clean up existing <br> tags that may have been saved (legacy data)
4212 - // Convert <br>, <br/>, <br /> back to newlines for consistent processing
4213 - $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
4214 -
4215 - // Collapse 3+ consecutive newlines to just 2 (paragraph break)
4216 - $text = preg_replace('/\n{3,}/', "\n\n", $text);
4217 -
4218 - // Process markdown headers (# Header)
4219 - $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
4220 - $level = strlen($matches[1]);
4221 - $content = esc_html(trim($matches[2]));
4222 - return "<h{$level}>{$content}</h{$level}>";
4223 - }, $text);
4224 -
4225 - // Process code blocks with triple backticks
4226 - $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
4227 - $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
4228 - $code = esc_html($matches[2]);
4229 - return "<pre><code{$language}>{$code}</code></pre>";
4230 - }, $text);
4231 -
4232 - // Process inline code with single backticks
4233 - $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
4234 -
4235 - // Process bold text **text** or __text__
4236 - $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
4237 - $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
4238 -
4239 - // Process italic text *text* or _text_ (but not if part of URL)
4240 - $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
4241 - $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
4242 -
4243 - // Process markdown links [text](url)
4244 - $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
4245 - $link_text = esc_html($matches[1]);
4246 - $url = esc_url($matches[2]);
4247 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
4248 - }, $text);
4249 -
4250 - // Process citation-style brackets [URL]
4251 - $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
4252 - $url = esc_url($matches[1]);
4253 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
4254 - }, $text);
4255 -
4256 - // Process standalone URLs (not already in links or img src)
4257 - $text = preg_replace_callback(
4258 - '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
4259 - function($matches) {
4260 - $url = esc_url($matches[1]);
4261 - // Truncate display URL if too long
4262 - $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
4263 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
4264 - },
4265 - $text
4266 - );
4267 -
4268 - // Process mailto links
4269 - $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
4270 - $link_text = esc_html($matches[1]);
4271 - $mailto = esc_url($matches[2]);
4272 - return "<a href=\"{$mailto}\">{$link_text}</a>";
4273 - }, $text);
4274 -
4275 - // Convert paragraphs: split by double newlines, wrap in <p> tags
4276 - // This creates proper paragraph structure instead of excessive <br> tags
4277 - $paragraphs = preg_split('/\n\n+/', $text);
4278 -
4279 - // Filter out empty paragraphs but preserve content like "0"
4280 - $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
4281 - return $p !== '';
4282 - }));
4283 -
4284 - if (empty($paragraphs)) {
4285 - // No content after filtering
4286 - return '';
4287 - } elseif (count($paragraphs) > 1) {
4288 - // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
4289 - $formatted_paragraphs = array_map(function($p) {
4290 - return nl2br($p);
4291 - }, $paragraphs);
4292 - $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4293 - } else {
4294 - // Single paragraph - just convert newlines to <br>
4295 - $text = nl2br($paragraphs[0]);
4296 - }
4297 -
4298 - return $text;
4299 -}
4300 -
4301 -/**
4302 - * AJAX handler to fetch RAG context for a specific message
4303 - * Used by the transcript viewer to show retrieved documents
4304 - */
4305 -public function mxchat_get_rag_context() {
4306 - // Check permissions
4307 - if (!current_user_can('manage_options')) {
4308 - wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4309 - wp_die();
4310 - }
4311 -
4312 - // Validate message ID
4313 - if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4314 - wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4315 - wp_die();
4316 - }
4317 -
4318 - $message_id = absint($_POST['message_id']);
4319 -
4320 - global $wpdb;
4321 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4322 -
4323 - // Fetch the RAG context for this message
4324 - $result = $wpdb->get_row($wpdb->prepare(
4325 - "SELECT rag_context FROM {$table_name} WHERE id = %d",
4326 - $message_id
4327 - ));
4328 -
4329 - if (!$result || empty($result->rag_context)) {
4330 - wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4331 - wp_die();
4332 - }
4333 -
4334 - // Decode the JSON data
4335 - $rag_context = json_decode($result->rag_context, true);
4336 -
4337 - if (json_last_error() !== JSON_ERROR_NONE) {
4338 - wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4339 - wp_die();
4340 - }
4341 -
4342 - wp_send_json_success($rag_context);
4343 - wp_die();
4344 -}
4345 -
4346 -public function display_admin_notices() {
4347 - // Check if we're on a MXChat admin page
4348 - $screen = get_current_screen();
4349 - if (!$screen || strpos($screen->base, 'mxchat') === false) {
4350 - return;
4351 - }
4352 -
4353 - $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4354 -
4355 - // Check for error notices
4356 - $error_notice = get_transient('mxchat_admin_notice_error');
4357 - if ($error_notice) {
4358 - echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4359 - delete_transient('mxchat_admin_notice_error');
4360 - }
4361 -
4362 - // Check for success notices
4363 - $success_notice = get_transient('mxchat_admin_notice_success');
4364 - if ($success_notice) {
4365 - echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4366 - delete_transient('mxchat_admin_notice_success');
4367 - }
4368 -
4369 - // Check for info notices
4370 - $info_notice = get_transient('mxchat_admin_notice_info');
4371 - if ($info_notice) {
4372 - echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4373 - delete_transient('mxchat_admin_notice_info');
4374 - }
4375 -}
4376 -
4377 -
4378 643 public function mxchat_create_activation_page() {
4379 - // Include the new Pro & Extensions page template
4380 - require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
644 + $license_status = get_option('mxchat_license_status', 'inactive');
645 + $license_error = get_option('mxchat_license_error', '');
4381 646
4382 - // Get addons configuration from the MxChat_Addons class
4383 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4384 - $addons_instance = new MxChat_Addons();
4385 - $addons_config = $addons_instance->get_addons_config();
4386 -
4387 - // Render the consolidated Pro & Extensions page
4388 - mxchat_render_pro_page($this, $addons_config);
4389 -}
4390 -
4391 -/**
4392 - * Check if current activation is linked to a domain
4393 - * This checks YOUR website's database, not the user's local database
4394 - */
4395 -public function is_current_activation_linked($domain) {
4396 - $license_key = get_option('mxchat_activation_key');
4397 - $email = get_option('mxchat_pro_email');
4398 -
4399 - if (empty($license_key) || empty($email)) {
4400 - return false;
4401 - }
4402 -
4403 - // Check with YOUR website's API
4404 - $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4405 - 'body' => array(
4406 - 'license_key' => $license_key,
4407 - 'email' => $email,
4408 - 'domain' => $domain
4409 - ),
4410 - 'timeout' => 10,
4411 - 'sslverify' => false
4412 - ));
4413 -
4414 - if (is_wp_error($response)) {
4415 - return false;
4416 - }
4417 -
4418 - $body = json_decode(wp_remote_retrieve_body($response), true);
4419 - return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
4420 -}
4421 -
4422 -
4423 -public function mxchat_actions_page_html() {
4424 - if (!current_user_can('manage_options')) {
4425 - return;
4426 - }
4427 -
4428 - global $wpdb;
4429 - $table_name = $wpdb->prefix . 'mxchat_intents';
4430 -
4431 - // Get stats for dashboard
4432 - $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4433 - $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4434 - $disabled_actions = $total_actions - $enabled_actions;
4435 -
4436 - // Get unique action types count
4437 - $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
4438 -
4439 - // Get action type distribution
4440 - $type_distribution_raw = $wpdb->get_results("SELECT callback_function, COUNT(*) as count FROM $table_name GROUP BY callback_function ORDER BY count DESC LIMIT 10");
4441 - $available_callbacks = $this->mxchat_get_available_callbacks();
4442 - $callback_groups = $this->mxchat_get_available_callbacks(true, true);
4443 -
4444 - $action_type_distribution = array();
4445 - foreach ($type_distribution_raw as $row) {
4446 - $label = isset($available_callbacks[$row->callback_function]['label'])
4447 - ? $available_callbacks[$row->callback_function]['label']
4448 - : $row->callback_function;
4449 - $action_type_distribution[$label] = $row->count;
4450 - }
4451 -
4452 - // Native function-calling (AI Tools) data — plan-mxchat-20260617-a41dee.
4453 - // The AI Tools checklist reads from MxChat_Tool_Registry, the SAME single
4454 - // source the chat-time function-calling loop reads, so the two never drift.
4455 - if (!class_exists('MxChat_Tool_Registry')) {
4456 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-tool-registry.php';
4457 - }
4458 - if (!class_exists('MxChat_Model_Catalog')) {
4459 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
4460 - }
4461 - $fc_options = get_option('mxchat_options', array());
4462 - $fc_current_model = isset($fc_options['model']) ? $fc_options['model'] : 'gpt-5.6-sol';
4463 - $fc_model_capable = class_exists('MxChat_Model_Catalog')
4464 - ? MxChat_Model_Catalog::supports_tools($fc_current_model) : true;
4465 - $active_tab = (isset($_GET['tab']) && $_GET['tab'] === 'ai-tools') ? 'ai-tools' : 'dashboard';
4466 -
4467 - // Enrich each AI Tool with the dashicon its callback already uses on the
4468 - // Trigger Phrases "Choose what it does" grid, so the AI Tools cards/modal
4469 - // share the same iconography (plan 8bbf98 part 4). View-layer only — the
4470 - // registry's model-facing data is untouched. Default admin-generic.
4471 - $fc_tools = MxChat_Tool_Registry::available_tools();
4472 - foreach ($fc_tools as &$fc_tool_ref) {
4473 - $fc_cb_ref = $fc_tool_ref['callback'];
4474 - $fc_tool_ref['icon'] = isset($available_callbacks[$fc_cb_ref]['icon'])
4475 - ? $available_callbacks[$fc_cb_ref]['icon']
4476 - : 'admin-generic';
4477 - }
4478 - unset($fc_tool_ref);
4479 -
4480 - // Count of ACTIVE tools — drives the AI Tools sidebar nav badge, mirroring
4481 - // $total_actions for Trigger Phrases. A tool in the list = active (plan
4482 - // d450a7), so the badge shows the same number the list pane shows (plan 5f7409).
4483 - $total_tools = count(array_filter($fc_tools, function ($t) {
4484 - return !empty($t['enabled']);
4485 - }));
4486 -
4487 - // Brave-key dependency check (plan 183856): Web Search + Image Search run on
4488 - // the Brave Search API. If either is enabled as a tool but no brave_api_key is
4489 - // configured, surface a graceful "key not set" notice so the admin isn't met
4490 - // with a silently no-firing tool.
4491 - $fc_brave_missing = false;
4492 - $brave_key = isset($fc_options['brave_api_key']) ? trim($fc_options['brave_api_key']) : '';
4493 - if ($brave_key === '') {
4494 - foreach ($fc_tools as $fc_t) {
4495 - if (!empty($fc_t['enabled']) && isset($fc_t['requires_key']) && $fc_t['requires_key'] === 'brave_api_key') {
4496 - $fc_brave_missing = true;
4497 - break;
4498 - }
4499 - }
4500 - }
4501 -
4502 - // Prepare page data
4503 - $page_data = array(
4504 - 'total_actions' => $total_actions,
4505 - 'enabled_actions' => $enabled_actions,
4506 - 'disabled_actions' => $disabled_actions,
4507 - 'action_types_count' => $action_types_count,
4508 - 'action_type_distribution' => $action_type_distribution,
4509 - 'available_callbacks' => $available_callbacks,
4510 - 'callback_groups' => $callback_groups,
4511 - // AI Tools section
4512 - 'active_tab' => $active_tab,
4513 - 'fc_enabled' => MxChat_Tool_Registry::is_enabled(),
4514 - 'total_tools' => $total_tools,
4515 - 'fc_tools' => $fc_tools,
4516 - 'fc_current_model' => $fc_current_model,
4517 - 'fc_model_capable' => $fc_model_capable,
4518 - 'fc_brave_missing' => $fc_brave_missing,
4519 - 'fc_saved' => isset($_GET['mxchat_fc_saved']),
4520 - );
4521 -
4522 - // Include and render the new template
4523 - require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4524 - mxchat_render_actions_page($this, $page_data);
4525 -}
4526 -
4527 -/**
4528 - * LEGACY HTML - Preserved below for reference, to be removed in future update
4529 - */
4530 -function mxchat_actions_page_legacy_html() {
4531 - // This function is deprecated and no longer used
4532 - // The new template is in includes/admin-actions-page.php
4533 647 ?>
4534 - <div class="wrap mxchat-wrapper">
4535 - <!-- Hero Section -->
4536 - <div class="mxchat-hero">
4537 - <h1 class="mxchat-main-title">
4538 - <span class="mxchat-gradient-text">Actions</span> Manager
4539 - </h1>
4540 - <p class="mxchat-hero-subtitle">
4541 - <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
4542 - </p>
4543 - </div>
4544 -
4545 - <!-- Actions Header with Search and Filter -->
4546 - <div class="mxchat-actions-header">
4547 - <div class="mxchat-actions-filters">
4548 - <form method="get" class="mxchat-search-form">
4549 - <input type="hidden" name="page" value="mxchat-actions">
4550 - <div class="mxchat-search-group">
4551 - <span class="dashicons dashicons-search"></span>
4552 - <input type="text" name="s" class="mxchat-search-input"
4553 - placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
4554 - value="<?php echo esc_attr($search_term); ?>">
4555 - </div>
4556 - <select name="callback_filter" class="mxchat-action-filter">
4557 - <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
4558 - <?php foreach ($available_callbacks as $function => $callback_data) :
4559 - $label = $callback_data['label']; ?>
4560 - <option value="<?php echo esc_attr($function); ?>"
4561 - <?php selected($callback_filter, $function); ?>>
4562 - <?php echo esc_html($label); ?>
4563 - </option>
4564 - <?php endforeach; ?>
4565 - </select>
4566 - <button type="submit" class="mxchat-button-secondary">
4567 - <?php esc_html_e('Filter', 'mxchat'); ?>
4568 - </button>
4569 - </form>
648 + <div class="wrap mxchat-admin">
649 + <h2>MxChat Pro: Activation</h2>
650 + <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
651 + <div class="error notice">
652 + <p><?php echo esc_html($license_error); ?></p>
4570 653 </div>
4571 - <div class="mxchat-actions-controls">
4572 - <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
4573 - <span class="dashicons dashicons-plus-alt"></span>
4574 - <?php esc_html_e('Add New Action', 'mxchat'); ?>
4575 - </button>
4576 - </div>
4577 - </div>
4578 -
4579 - <!-- Actions Grid Layout - All actions in a single grid -->
4580 - <div class="mxchat-actions-grid">
4581 - <div class="mxchat-cards-container">
4582 - <?php if (!empty($actions)) : ?>
4583 - <?php foreach ($actions as $action) :
4584 - $callback_function = $action->callback_function;
4585 - $callback_label = isset($available_callbacks[$callback_function]['label'])
4586 - ? $available_callbacks[$callback_function]['label']
4587 - : $callback_function;
4588 - $threshold_value = isset($action->similarity_threshold)
4589 - ? round($action->similarity_threshold * 100)
4590 - : 85;
4591 -
4592 - // Check if this is a form action
4593 - $is_form_action = strpos($action->intent_label, 'Form ') === 0;
4594 -
4595 - // Get action status (enabled/disabled) - default to true if column doesn't exist
4596 - $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
4597 -
4598 - // Get enabled bots for display
4599 - $enabled_bots = [];
4600 - if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
4601 - $enabled_bots = json_decode($action->enabled_bots, true);
4602 - if (!is_array($enabled_bots)) {
4603 - $enabled_bots = ['default'];
4604 - }
4605 - } else {
4606 - $enabled_bots = ['default']; // Backward compatibility
4607 - }
4608 - ?>
4609 - <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
4610 - <div class="mxchat-card-header">
4611 - <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
4612 - <div class="mxchat-card-toggle">
4613 - <label class="mxchat-switch">
4614 - <input type="checkbox" class="mxchat-action-toggle"
4615 - data-action-id="<?php echo esc_attr($action->id); ?>"
4616 - <?php checked($is_enabled); ?>>
4617 - <span class="mxchat-slider round"></span>
4618 - </label>
4619 - </div>
4620 - </div>
4621 -
4622 - <div class="mxchat-card-body">
4623 - <div class="mxchat-card-description">
4624 - <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
4625 - <?php echo esc_html($callback_label); ?>
4626 - </div>
4627 -
4628 - <div class="mxchat-card-phrases">
4629 - <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
4630 - <div class="mxchat-phrases-preview">
4631 - <?php
4632 - // Check if the helper function exists, otherwise use a simple substring
4633 - if (method_exists($this, 'get_trimmed_phrases')) {
4634 - echo esc_html($this->get_trimmed_phrases($action->phrases));
4635 - } else {
4636 - echo esc_html(strlen($action->phrases) > 100 ?
4637 - substr($action->phrases, 0, 97) . '...' :
4638 - $action->phrases);
4639 - }
4640 - ?>
4641 - </div>
4642 - </div>
4643 -
4644 - <div class="mxchat-threshold-control">
4645 - <div class="mxchat-threshold-label">
4646 - <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
4647 - <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
4648 - </div>
4649 - </div>
4650 -
4651 - <!-- Bot Availability Display (Read-only) -->
4652 - <div class="mxchat-card-bots">
4653 - <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
4654 - <div class="mxchat-bot-badges">
4655 - <?php
4656 - foreach ($enabled_bots as $bot_id) {
4657 - if ($bot_id === 'default') {
4658 - echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
4659 - } else {
4660 - // Try to get bot name from multi-bot manager
4661 - if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
4662 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4663 - $available_bots = $multi_bot_manager->get_available_bots();
4664 - $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
4665 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
4666 - } else {
4667 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
4668 - }
4669 - }
4670 - }
4671 - ?>
4672 - </div>
4673 - </div>
4674 - </div>
4675 -
4676 - <div class="mxchat-card-footer">
4677 - <?php
4678 - // Check if it's a form action
4679 - $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
4680 -
4681 - // Check if it's a recommendation flow action
4682 - $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
4683 -
4684 - if ($is_form_action) {
4685 - $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
4686 - ?>
4687 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
4688 - class="mxchat-button-primary">
4689 - <span class="dashicons dashicons-feedback"></span>
4690 - <?php esc_html_e('Edit Form', 'mxchat'); ?>
4691 - </a>
4692 - <?php } elseif ($is_flow_action) {
4693 - ?>
4694 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
4695 - class="mxchat-button-primary">
4696 - <span class="dashicons dashicons-list-view"></span>
4697 - <?php esc_html_e('Manage Flows', 'mxchat'); ?>
4698 - </a>
4699 - <?php } else { ?>
4700 - <button type="button"
4701 - class="mxchat-button-secondary mxchat-edit-button"
4702 - data-action-id="<?php echo esc_attr($action->id); ?>"
4703 - data-phrases="<?php echo esc_attr($action->phrases); ?>"
4704 - data-label="<?php echo esc_attr($action->intent_label); ?>"
4705 - data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
4706 - data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
4707 - data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
4708 - <span class="dashicons dashicons-edit"></span>
4709 - <?php esc_html_e('Edit', 'mxchat'); ?>
4710 - </button>
4711 - <form method="post"
4712 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
4713 - class="mxchat-delete-form"
4714 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
4715 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
4716 - <input type="hidden" name="action" value="mxchat_delete_intent">
4717 - <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
4718 - <button type="submit" class="mxchat-button-text mxchat-delete-button">
4719 - <span class="dashicons dashicons-trash"></span>
4720 - <?php esc_html_e('Delete', 'mxchat'); ?>
4721 - </button>
4722 - </form>
4723 - <?php } ?>
4724 - </div>
4725 - </div>
4726 - <?php endforeach; ?>
4727 - <?php else : ?>
4728 - <!-- If no actions found -->
4729 - <div class="mxchat-no-actions">
4730 - <div class="mxchat-empty-state">
4731 - <span class="dashicons dashicons-format-chat"></span>
4732 - <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4733 - <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4734 - <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4735 - <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4736 - </button>
4737 - </div>
4738 - </div>
4739 - <?php endif; ?>
4740 - </div>
4741 - </div>
4742 -
4743 - <?php if ($total_pages > 1) : ?>
4744 - <div class="mxchat-pagination">
4745 - <?php
4746 - echo paginate_links(array(
4747 - 'base' => add_query_arg('paged', '%#%'),
4748 - 'format' => '',
4749 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4750 - 'next_text' => __('Next &raquo;', 'mxchat'),
4751 - 'total' => $total_pages,
4752 - 'current' => $page
4753 - ));
4754 - ?>
4755 - </div>
4756 654 <?php endif; ?>
4757 -
4758 -<!-- Add/Edit Action Modal with Step-Based Approach -->
4759 -<!-- Complete Modal HTML with Defined Groups Variable -->
4760 -<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
4761 - <div class="mxchat-modal-content">
4762 - <span class="mxchat-modal-close">&times;</span>
4763 -
4764 - <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4765 - <!-- Dynamic nonce field -->
4766 - <div id="action-nonce-container">
4767 - <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
4768 - </div>
4769 - <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4770 - <input type="hidden" name="intent_id" id="edit_action_id" value="">
4771 - <input type="hidden" name="callback_function" id="callback_function" value="">
4772 -
4773 - <!-- Step 1: Action Type Selection -->
4774 - <div id="mxchat-action-step-1" class="mxchat-action-step active">
4775 - <div class="mxchat-step-indicator">
4776 - <div class="mxchat-step-number">1</div>
4777 - <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4778 - </div>
4779 -
4780 - <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4781 - <div class="mxchat-action-type-search">
4782 - <span class="dashicons dashicons-search"></span>
4783 - <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4784 - </div>
4785 -
4786 - <?php
4787 - // Get the callbacks - IMPORTANT: Define the $groups variable here
4788 - $groups = $this->mxchat_get_available_callbacks(true, true);
4789 - ?>
4790 -
4791 - <div class="mxchat-action-type-categories">
4792 - <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
4793 - <?php
4794 - // Get unique categories from the defined groups
4795 - foreach ($groups as $group_label => $group_callbacks) :
4796 - $category_slug = sanitize_title($group_label);
4797 - ?>
4798 - <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4799 - <?php endforeach; ?>
4800 - </div>
4801 -
4802 - <div class="mxchat-action-types-grid">
4803 - <?php
4804 - // Generate action cards from available callbacks
4805 - foreach ($groups as $group_label => $group_callbacks) :
4806 - $category_slug = sanitize_title($group_label);
4807 -
4808 - foreach ($group_callbacks as $function => $data) :
4809 - $label = $data['label'];
4810 - $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4811 - $description = isset($data['description']) ? $data['description'] : '';
4812 - $is_addon = isset($data['addon']) && $data['addon'] !== false;
4813 - $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4814 - $is_installed = isset($data['installed']) ? $data['installed'] : true;
4815 - $is_promo = !empty($data['addon_promo']) && !$is_installed;
4816 -
4817 - // Determine card status and styling
4818 - $card_class = 'mxchat-action-type-card';
4819 - $icon_class = 'mxchat-action-type-icon';
4820 - $status_badge = '';
4821 -
4822 - if ($is_promo) {
4823 - // Promotional card — not selectable, just informational
4824 - $card_class .= ' not-installed mxchat-promo-card';
4825 - $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4826 - } elseif ($is_addon && !$is_installed) {
4827 - // Add-on not installed
4828 - $card_class .= ' not-installed';
4829 - $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4830 - }
4831 -
4832 - // Default description if none provided
4833 - if (empty($description)) {
4834 - $description = sprintf(
4835 - esc_html__('Use the %s action in your chatbot', 'mxchat'),
4836 - $label
4837 - );
4838 - }
4839 - ?>
4840 - <div class="<?php echo esc_attr($card_class); ?>"
4841 - data-category="<?php echo esc_attr($category_slug); ?>"
4842 - <?php if (!$is_promo) : ?>
4843 - data-value="<?php echo esc_attr($function); ?>"
4844 - data-label="<?php echo esc_attr($label); ?>"
4845 - <?php endif; ?>
4846 - data-pro="false"
4847 - data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4848 - data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
4849 - <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
4850 - <div class="<?php echo esc_attr($icon_class); ?>">
4851 - <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4852 - </div>
4853 - <div class="mxchat-action-type-info">
4854 - <h4><?php echo esc_html($label); ?></h4>
4855 - <p><?php echo esc_html($description); ?></p>
4856 - <?php if (!empty($status_badge)) : ?>
4857 - <?php echo $status_badge; ?>
4858 - <?php endif; ?>
4859 -
4860 - <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
4861 - <div class="mxchat-addon-info">
4862 - <?php echo esc_html(sprintf(
4863 - __('Requires %s', 'mxchat'),
4864 - $addon_name
4865 - )); ?>
4866 - — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
4867 - </div>
4868 - <?php endif; ?>
4869 - </div>
4870 - </div>
4871 - <?php endforeach;
4872 - endforeach; ?>
4873 - </div>
4874 - </div>
4875 -
4876 - <div class="mxchat-modal-actions">
4877 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4878 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4879 - </button>
4880 - </div>
4881 - </div>
4882 -
4883 - <!-- Step 2: Action Configuration -->
4884 - <div id="mxchat-action-step-2" class="mxchat-action-step">
4885 - <div class="mxchat-step-indicator">
4886 - <div class="mxchat-step-number">2</div>
4887 - <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4888 - </div>
4889 -
4890 - <div class="mxchat-selected-action">
4891 - <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
4892 - <span class="dashicons dashicons-arrow-left-alt"></span>
4893 - <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
4894 - </button>
4895 - <div class="mxchat-selected-action-info">
4896 - <div id="selected-action-icon" class="mxchat-action-type-icon">
4897 - <span class="dashicons dashicons-admin-generic"></span>
4898 - </div>
4899 - <div class="mxchat-selected-action-details">
4900 - <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
4901 - <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
4902 - </div>
4903 - </div>
4904 - </div>
4905 -
4906 - <div class="mxchat-form-group">
4907 - <label for="intent_label">
4908 - <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
4909 - </label>
4910 - <input name="intent_label" type="text" id="intent_label" required
4911 - class="mxchat-intent-input"
4912 - placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
4913 - </div>
4914 -
4915 - <div class="mxchat-form-group">
4916 - <label for="phrases">
4917 - <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
4918 - </label>
4919 - <textarea name="phrases" id="action_phrases" rows="5" required
4920 - class="mxchat-intent-textarea"
4921 - placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
4922 - </div>
4923 -
4924 - <div class="mxchat-form-group">
4925 - <label for="similarity_threshold">
4926 - <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
4927 - <span class="mxchat-threshold-value-display">85%</span>
4928 - </label>
4929 - <div class="mxchat-slider-group modal-slider">
4930 - <input type="range"
4931 - name="similarity_threshold"
4932 - id="similarity_threshold"
4933 - min="10"
4934 - max="95"
4935 - value="85"
4936 - class="mxchat-intent-slider"
4937 - oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
4938 - </div>
4939 - <div class="mxchat-threshold-hint">
4940 - <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
4941 - </div>
4942 - </div>
4943 -
4944 - <!-- Bot Selection Section -->
4945 - <div class="mxchat-form-group">
4946 - <label for="enabled_bots">
4947 - <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
4948 - </label>
4949 - <div class="mxchat-bot-selector">
4950 - <div class="mxchat-bot-option">
4951 - <label class="mxchat-checkbox-label">
4952 - <input type="checkbox"
4953 - name="enabled_bots[]"
4954 - value="default"
4955 - id="bot_default"
4956 - checked="checked">
4957 - <span class="mxchat-checkmark"></span>
4958 - <?php esc_html_e('Default Bot', 'mxchat'); ?>
4959 - </label>
4960 - </div>
4961 -
4962 - <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
4963 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4964 - $available_bots = $multi_bot_manager->get_available_bots();
4965 -
4966 - foreach ($available_bots as $bot_id => $bot_name) :
4967 - if ($bot_id === 'default') continue; // Skip default, already shown above
4968 - ?>
4969 - <div class="mxchat-bot-option">
4970 - <label class="mxchat-checkbox-label">
4971 - <input type="checkbox"
4972 - name="enabled_bots[]"
4973 - value="<?php echo esc_attr($bot_id); ?>"
4974 - id="bot_<?php echo esc_attr($bot_id); ?>">
4975 - <span class="mxchat-checkmark"></span>
4976 - <?php echo esc_html($bot_name); ?>
4977 - </label>
4978 - </div>
4979 - <?php
4980 - endforeach;
4981 - endif; ?>
4982 - </div>
4983 - </div>
4984 -
4985 - <div class="mxchat-modal-actions">
4986 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4987 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4988 - </button>
4989 - <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
4990 - <?php esc_html_e('Save Action', 'mxchat'); ?>
4991 - </button>
4992 - </div>
4993 - </div>
655 + <form id="mxchat-activation-form">
656 + <table class="form-table">
657 + <tr valign="top">
658 + <th scope="row">Email Address</th>
659 + <td>
660 + <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" />
661 + </td>
662 + </tr>
663 + <tr valign="top">
664 + <th scope="row">Activation Key</th>
665 + <td>
666 + <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" />
667 + </td>
668 + </tr>
669 + </table>
670 + <?php if ($license_status !== 'active'): ?>
671 + <?php submit_button('Activate License', 'primary', 'activate_license'); ?>
672 + <?php else: ?>
673 + <h3>MxChat Pro</h3>
674 + <?php endif; ?>
4994 675 </form>
676 + <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
4995 677 </div>
4996 -</div>
4997 -
4998 -<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
4999 - <div class="mxchat-action-loading-spinner"></div>
5000 - <div class="mxchat-action-loading-text">
5001 - <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
5002 - </div>
5003 -</div>
5004 - </div><!-- .mxchat-wrapper -->
5005 678 <?php
5006 679 }
5007 -private function get_trimmed_phrases($phrases, $max_length = 100) {
5008 - if (strlen($phrases) <= $max_length) {
5009 - return $phrases;
5010 - }
5011 680
5012 - $trimmed = substr($phrases, 0, $max_length);
5013 - $last_comma = strrpos($trimmed, ',');
5014 681
5015 - if ($last_comma !== false) {
5016 - $trimmed = substr($trimmed, 0, $last_comma);
5017 - }
5018 682
5019 - return $trimmed . '...';
5020 -}
5021 -public function mxchat_add_enabled_column_to_intents() {
5022 - global $wpdb;
5023 - $table_name = $wpdb->prefix . 'mxchat_intents';
5024 -
5025 - // Check if the column already exists
5026 - $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
5027 -
5028 - if (empty($columns)) {
5029 - // Add the column with default value of 1 (enabled)
5030 - $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
5031 - }
5032 -}
5033 -
5034 -public function mxchat_handle_delete_intent() {
5035 - if ( ! current_user_can( 'manage_options' ) ) {
5036 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
5037 - }
5038 -
5039 - check_admin_referer('mxchat_delete_intent_nonce');
5040 -
5041 - if (isset($_POST['intent_id'])) {
5042 - global $wpdb;
5043 - $table_name = $wpdb->prefix . 'mxchat_intents';
5044 - $intent_id = intval($_POST['intent_id']);
5045 -
5046 - $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5047 - }
5048 -
5049 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5050 - exit;
5051 -}
5052 -public function mxchat_handle_edit_intent() {
5053 - // Security checks (nonce and permissions)
5054 - if (!current_user_can('manage_options')) {
5055 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5056 - }
5057 - check_admin_referer('mxchat_edit_intent');
5058 -
5059 - // Get POST data
5060 - $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
5061 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5062 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5063 - $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
5064 - $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
5065 -
5066 - // Handle enabled_bots
5067 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5068 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5069 -
5070 - // Ensure default is always included for backward compatibility
5071 - if (!in_array('default', $enabled_bots)) {
5072 - $enabled_bots[] = 'default';
5073 - }
5074 -
5075 - $enabled_bots_json = json_encode($enabled_bots);
5076 -
5077 - // Validate inputs
5078 - if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
5079 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5080 - return;
5081 - }
5082 -
5083 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5084 - if (empty($phrases_array)) {
5085 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5086 - return;
5087 - }
5088 -
5089 - // Generate embeddings with improved error handling
5090 - $vectors = [];
5091 - $failed_phrases = [];
5092 -
5093 - foreach ($phrases_array as $phrase) {
5094 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5095 - if (is_array($embedding_vector)) {
5096 - $vectors[] = $embedding_vector;
5097 - } else {
5098 - $failed_phrases[] = $phrase;
5099 - }
5100 - }
5101 -
5102 - if (!empty($failed_phrases)) {
5103 - $this->handle_embedding_error(
5104 - sprintf(
5105 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5106 - implode(', ', $failed_phrases)
5107 - )
5108 - );
5109 - return;
5110 - }
5111 -
5112 - if (empty($vectors)) {
5113 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5114 - return;
5115 - }
5116 -
5117 - $combined_vector = $this->mxchat_average_vectors($vectors);
5118 - $serialized_vector = maybe_serialize($combined_vector);
5119 -
5120 - // Update the database
5121 - global $wpdb;
5122 - $table_name = $wpdb->prefix . 'mxchat_intents';
5123 -
5124 - $result = $wpdb->update(
5125 - $table_name,
5126 - array(
5127 - 'intent_label' => $intent_label,
5128 - 'phrases' => implode(', ', $phrases_array),
5129 - 'embedding_vector' => $serialized_vector,
5130 - 'similarity_threshold' => $similarity_threshold,
5131 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
5132 - ),
5133 - array('id' => $intent_id),
5134 - array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
5135 - array('%d') // Where format: integer
5136 - );
5137 -
5138 - if (false === $result) {
5139 - $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
5140 - return;
5141 - }
5142 -
5143 - // Set success message and redirect
5144 - set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
5145 -
5146 - $redirect_url = add_query_arg(
5147 - array(
5148 - 'page' => 'mxchat-actions'
5149 - ),
5150 - admin_url('admin.php')
5151 - );
5152 - wp_safe_redirect($redirect_url);
5153 - exit;
5154 -}
5155 -public function mxchat_handle_add_intent() {
5156 - if (!current_user_can('manage_options')) {
5157 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5158 - }
5159 - check_admin_referer('mxchat_add_intent_nonce');
5160 - global $wpdb;
5161 - $table_name = $wpdb->prefix . 'mxchat_intents';
5162 -
5163 - // Sanitize and get form data
5164 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5165 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5166 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5167 -
5168 - // Get similarity threshold from form (convert percentage to decimal)
5169 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5170 -
5171 - // Handle enabled_bots
5172 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5173 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5174 -
5175 - // Ensure default is always included for backward compatibility with existing actions
5176 - if (!in_array('default', $enabled_bots)) {
5177 - $enabled_bots[] = 'default';
5178 - }
5179 -
5180 - $enabled_bots_json = json_encode($enabled_bots);
5181 -
5182 - // Validate required fields
5183 - if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
5184 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5185 - return;
5186 - }
5187 -
5188 - // Validate callback function
5189 - $available_callbacks = $this->mxchat_get_available_callbacks();
5190 - if (!array_key_exists($callback_function, $available_callbacks)) {
5191 - $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
5192 - return;
5193 - }
5194 -
5195 - // Check if this is an add-on promotional placeholder (not a real action)
5196 - if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
5197 - $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
5198 - $this->handle_embedding_error(sprintf(
5199 - __('This action requires the %s to be installed and activated.', 'mxchat'),
5200 - $addon_name
5201 - ));
5202 - return;
5203 - }
5204 -
5205 - // Process phrases
5206 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5207 - if (empty($phrases_array)) {
5208 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5209 - return;
5210 - }
5211 -
5212 - // Generate embeddings with improved error handling
5213 - $vectors = [];
5214 - $failed_phrases = [];
5215 - foreach ($phrases_array as $phrase) {
5216 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5217 - if (is_array($embedding_vector)) {
5218 - $vectors[] = $embedding_vector;
5219 - } else {
5220 - $failed_phrases[] = $phrase;
5221 - }
5222 - }
5223 -
5224 - // Check for embedding failures
5225 - if (!empty($failed_phrases)) {
5226 - $this->handle_embedding_error(
5227 - sprintf(
5228 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5229 - implode(', ', $failed_phrases)
5230 - )
5231 - );
5232 - return;
5233 - }
5234 -
5235 - if (empty($vectors)) {
5236 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5237 - return;
5238 - }
5239 -
5240 - // Create combined vector and insert into database
5241 - $combined_vector = $this->mxchat_average_vectors($vectors);
5242 - $serialized_vector = maybe_serialize($combined_vector);
5243 -
5244 - $result = $wpdb->insert($table_name, [
5245 - 'intent_label' => $intent_label,
5246 - 'phrases' => implode(', ', $phrases_array),
5247 - 'embedding_vector' => $serialized_vector,
5248 - 'callback_function' => $callback_function,
5249 - 'similarity_threshold' => $similarity_threshold,
5250 - 'enabled_bots' => $enabled_bots_json, // NEW field
5251 - ]);
5252 -
5253 - if ($result === false) {
5254 - $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
5255 - return;
5256 - }
5257 -
5258 - // Set success message and redirect
5259 - set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
5260 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5261 - exit;
5262 -}
5263 -
5264 -
5265 -
5266 -
5267 -private function handle_embedding_error($message, $redirect = true) {
5268 - // Store the error message in the existing transient
5269 - set_transient('mxchat_admin_notice_error', $message, 60);
5270 -
5271 - if ($redirect) {
5272 - // Redirect back to the actions page
5273 - $redirect_url = add_query_arg(
5274 - array(
5275 - 'page' => 'mxchat-actions'
5276 - ),
5277 - admin_url('admin.php')
5278 - );
5279 - wp_safe_redirect($redirect_url);
5280 - exit;
5281 - }
5282 -}
5283 -
5284 -/**
5285 - * AJAX handler to fetch actions list for the new split-panel UI
5286 - */
5287 -public function mxchat_fetch_actions_list() {
5288 - check_ajax_referer('mxchat_actions_nonce', 'security');
5289 -
5290 - if (!current_user_can('manage_options')) {
5291 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5292 - }
5293 -
5294 - global $wpdb;
5295 - $table_name = $wpdb->prefix . 'mxchat_intents';
5296 -
5297 - $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
5298 - $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
5299 - $offset = ($page - 1) * $per_page;
5300 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
5301 - $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
5302 - $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
5303 -
5304 - // Build WHERE clause
5305 - $where = '1=1';
5306 - $params = array();
5307 -
5308 - if ($search) {
5309 - $search_like = '%' . $wpdb->esc_like($search) . '%';
5310 - $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
5311 - $params[] = $search_like;
5312 - $params[] = $search_like;
5313 - }
5314 -
5315 - if ($callback_filter) {
5316 - $where .= ' AND callback_function = %s';
5317 - $params[] = $callback_filter;
5318 - }
5319 -
5320 - // Get total count
5321 - $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
5322 - if (!empty($params)) {
5323 - $count_query = $wpdb->prepare($count_query, $params);
5324 - }
5325 - $total_actions = $wpdb->get_var($count_query);
5326 -
5327 - // Get actions
5328 - $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
5329 - $all_params = array_merge($params, array($per_page, $offset));
5330 - $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
5331 -
5332 - // Get available callbacks for labels/icons
5333 - $available_callbacks = $this->mxchat_get_available_callbacks();
5334 -
5335 - // Prefetch individual phrase counts for all fetched actions
5336 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5337 - $phrase_counts = array();
5338 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5339 - $action_ids = wp_list_pluck($actions, 'id');
5340 - if (!empty($action_ids)) {
5341 - $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5342 - $count_results = $wpdb->get_results($wpdb->prepare(
5343 - "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
5344 - $action_ids
5345 - ));
5346 - foreach ($count_results as $row) {
5347 - $phrase_counts[$row->intent_id] = intval($row->cnt);
5348 - }
5349 - }
5350 - }
5351 -
5352 - // Format actions for response
5353 - $formatted_actions = array();
5354 - foreach ($actions as $action) {
5355 - $callback_data = isset($available_callbacks[$action->callback_function])
5356 - ? $available_callbacks[$action->callback_function]
5357 - : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5358 -
5359 - $enabled_bots = json_decode($action->enabled_bots, true);
5360 - if (!is_array($enabled_bots)) {
5361 - $enabled_bots = array('default');
5362 - }
5363 -
5364 - $formatted_actions[] = array(
5365 - 'id' => intval($action->id),
5366 - 'label' => $action->intent_label,
5367 - 'phrases' => $action->phrases,
5368 - 'callback_function' => $action->callback_function,
5369 - 'callback_label' => $callback_data['label'],
5370 - 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5371 - 'threshold' => round($action->similarity_threshold * 100),
5372 - 'enabled' => (bool) $action->enabled,
5373 - 'enabled_bots' => $enabled_bots,
5374 - 'has_legacy_vector' => !empty($action->embedding_vector),
5375 - 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5376 - );
5377 - }
5378 -
5379 - $total_pages = ceil($total_actions / $per_page);
5380 - $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5381 - $showing_end = min($offset + $per_page, $total_actions);
5382 -
5383 - wp_send_json_success(array(
5384 - 'actions' => $formatted_actions,
5385 - 'page' => $page,
5386 - 'per_page' => $per_page,
5387 - 'total_actions' => intval($total_actions),
5388 - 'total_pages' => $total_pages,
5389 - 'showing_start' => $showing_start,
5390 - 'showing_end' => $showing_end,
5391 - ));
5392 -}
5393 -
5394 -/**
5395 - * AJAX handler to toggle action enabled status
5396 - */
5397 -public function mxchat_toggle_action_status() {
5398 - check_ajax_referer('mxchat_actions_nonce', 'security');
5399 -
5400 - if (!current_user_can('manage_options')) {
5401 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5402 - }
5403 -
5404 - $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5405 - $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
5406 -
5407 - if (!$action_id) {
5408 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5409 - }
5410 -
5411 - global $wpdb;
5412 - $table_name = $wpdb->prefix . 'mxchat_intents';
5413 -
5414 - $result = $wpdb->update(
5415 - $table_name,
5416 - array('enabled' => $enabled ? 1 : 0),
5417 - array('id' => $action_id),
5418 - array('%d'),
5419 - array('%d')
5420 - );
5421 -
5422 - if ($result === false) {
5423 - wp_send_json_error(__('Failed to update action status', 'mxchat'));
5424 - }
5425 -
5426 - wp_send_json_success(array('enabled' => (bool) $enabled));
5427 -}
5428 -
5429 -/**
5430 - * AJAX handler to bulk delete actions
5431 - */
5432 -public function mxchat_bulk_delete_actions() {
5433 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5434 -
5435 - if (!current_user_can('manage_options')) {
5436 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5437 - }
5438 -
5439 - $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5440 -
5441 - if (empty($action_ids)) {
5442 - wp_send_json_error(__('No actions selected', 'mxchat'));
5443 - }
5444 -
5445 - global $wpdb;
5446 - $table_name = $wpdb->prefix . 'mxchat_intents';
5447 -
5448 - $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5449 - $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5450 - $result = $wpdb->query($query);
5451 -
5452 - if ($result === false) {
5453 - wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5454 - }
5455 -
5456 - // Also delete individual phrases for these intents
5457 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5458 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5459 - $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5460 - }
5461 -
5462 - wp_send_json_success(array('deleted' => $result));
5463 -}
5464 -
5465 -/**
5466 - * AJAX handler to add a new intent/action
5467 - */
5468 -public function mxchat_add_intent_ajax() {
5469 - check_ajax_referer('mxchat_add_intent_nonce', 'security');
5470 -
5471 - if (!current_user_can('manage_options')) {
5472 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5473 - }
5474 -
5475 - global $wpdb;
5476 - $table_name = $wpdb->prefix . 'mxchat_intents';
5477 -
5478 - // Sanitize input
5479 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5480 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5481 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5482 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5483 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5484 -
5485 - // Validate
5486 - // Check if using new individual phrases mode or legacy mode
5487 - $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5488 - $use_individual = !empty($individual_phrases);
5489 -
5490 - // Validate required fields (phrases not required when using individual mode)
5491 - if (empty($intent_label) || empty($callback_function)) {
5492 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5493 - }
5494 - if (!$use_individual && empty($phrases_input)) {
5495 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5496 - }
5497 -
5498 - // Ensure default bot is included
5499 - if (!in_array('default', $enabled_bots)) {
5500 - $enabled_bots[] = 'default';
5501 - }
5502 - $enabled_bots_json = json_encode($enabled_bots);
5503 -
5504 - if ($use_individual) {
5505 - // New mode: individual phrases each get their own vector
5506 - // Insert the intent row with empty legacy fields
5507 - $result = $wpdb->insert(
5508 - $table_name,
5509 - array(
5510 - 'intent_label' => $intent_label,
5511 - 'phrases' => '',
5512 - 'embedding_vector' => '',
5513 - 'similarity_threshold' => $similarity_threshold,
5514 - 'callback_function' => $callback_function,
5515 - 'enabled' => 1,
5516 - 'enabled_bots' => $enabled_bots_json,
5517 - )
5518 - );
5519 -
5520 - if ($result === false) {
5521 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5522 - }
5523 -
5524 - $intent_id = $wpdb->insert_id;
5525 -
5526 - // Insert each phrase individually with its own embedding
5527 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5528 - $failed_phrases = array();
5529 - foreach ($individual_phrases as $phrase) {
5530 - $phrase = trim($phrase);
5531 - if (empty($phrase)) continue;
5532 -
5533 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5534 - if (is_wp_error($embedding_vector)) {
5535 - $failed_phrases[] = $phrase;
5536 - continue;
5537 - }
5538 -
5539 - $wpdb->insert(
5540 - $phrases_table,
5541 - array(
5542 - 'intent_id' => $intent_id,
5543 - 'phrase' => $phrase,
5544 - 'embedding_vector' => maybe_serialize($embedding_vector),
5545 - )
5546 - );
5547 - }
5548 -
5549 - $response = array('id' => $intent_id);
5550 - if (!empty($failed_phrases)) {
5551 - $response['failed_phrases'] = $failed_phrases;
5552 - }
5553 - wp_send_json_success($response);
5554 -
5555 - } else {
5556 - // Legacy mode: combine all phrases into one embedding (backwards compatible)
5557 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5558 - if (empty($phrases_array)) {
5559 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5560 - }
5561 -
5562 - // Generate embedding (combine phrases into single string for embedding)
5563 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5564 - if (is_wp_error($embedding_vector)) {
5565 - // Fallback: store without embedding
5566 - $serialized_vector = null;
5567 - } else {
5568 - $serialized_vector = maybe_serialize($embedding_vector);
5569 - }
5570 -
5571 - // Insert
5572 - $result = $wpdb->insert(
5573 - $table_name,
5574 - array(
5575 - 'intent_label' => $intent_label,
5576 - 'phrases' => implode(', ', $phrases_array),
5577 - 'embedding_vector' => $serialized_vector,
5578 - 'similarity_threshold' => $similarity_threshold,
5579 - 'callback_function' => $callback_function,
5580 - 'enabled' => 1,
5581 - 'enabled_bots' => $enabled_bots_json,
5582 - )
5583 - );
5584 -
5585 - if ($result === false) {
5586 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5587 - }
5588 -
5589 - wp_send_json_success(array('id' => $wpdb->insert_id));
5590 - }
5591 -}
5592 -
5593 -/**
5594 - * AJAX handler to edit an existing intent/action
5595 - */
5596 -public function mxchat_edit_intent_ajax() {
5597 - check_ajax_referer('mxchat_edit_intent', 'security');
5598 -
5599 - if (!current_user_can('manage_options')) {
5600 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5601 - }
5602 -
5603 - global $wpdb;
5604 - $table_name = $wpdb->prefix . 'mxchat_intents';
5605 -
5606 - // Sanitize input
5607 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5608 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5609 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5610 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5611 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5612 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5613 -
5614 - // Validate
5615 - if (!$intent_id || empty($intent_label)) {
5616 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5617 - }
5618 -
5619 - // Check if phrases are managed individually (empty phrases_input means individual mode)
5620 - $uses_individual_phrases = empty($phrases_input);
5621 -
5622 - if ($uses_individual_phrases) {
5623 - // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
5624 - $update_data = array(
5625 - 'intent_label' => $intent_label,
5626 - 'similarity_threshold' => $similarity_threshold,
5627 - 'callback_function' => $callback_function,
5628 - 'enabled_bots' => json_encode($enabled_bots),
5629 - );
5630 - } else {
5631 - // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
5632 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5633 - if (empty($phrases_array)) {
5634 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5635 - }
5636 -
5637 - // Generate new embedding (combine phrases into single string for embedding)
5638 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5639 - if (is_wp_error($embedding_vector)) {
5640 - // Keep existing embedding
5641 - $update_data = array(
5642 - 'intent_label' => $intent_label,
5643 - 'phrases' => implode(', ', $phrases_array),
5644 - 'similarity_threshold' => $similarity_threshold,
5645 - 'callback_function' => $callback_function,
5646 - 'enabled_bots' => json_encode($enabled_bots),
5647 - );
5648 - } else {
5649 - $serialized_vector = maybe_serialize($embedding_vector);
5650 - $update_data = array(
5651 - 'intent_label' => $intent_label,
5652 - 'phrases' => implode(', ', $phrases_array),
5653 - 'embedding_vector' => $serialized_vector,
5654 - 'similarity_threshold' => $similarity_threshold,
5655 - 'callback_function' => $callback_function,
5656 - 'enabled_bots' => json_encode($enabled_bots),
5657 - );
5658 - }
5659 - }
5660 -
5661 - // Ensure default bot is included
5662 - if (!in_array('default', $enabled_bots)) {
5663 - $enabled_bots[] = 'default';
5664 - }
5665 - $update_data['enabled_bots'] = json_encode($enabled_bots);
5666 -
5667 - $result = $wpdb->update(
5668 - $table_name,
5669 - $update_data,
5670 - array('id' => $intent_id),
5671 - null,
5672 - array('%d')
5673 - );
5674 -
5675 - if ($result === false) {
5676 - wp_send_json_error(__('Failed to update action.', 'mxchat'));
5677 - }
5678 -
5679 - wp_send_json_success(array('updated' => true));
5680 -}
5681 -
5682 -/**
5683 - * AJAX handler to delete a single intent/action
5684 - */
5685 -public function mxchat_delete_intent_ajax() {
5686 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5687 -
5688 - if (!current_user_can('manage_options')) {
5689 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5690 - }
5691 -
5692 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5693 -
5694 - if (!$intent_id) {
5695 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5696 - }
5697 -
5698 - global $wpdb;
5699 - $table_name = $wpdb->prefix . 'mxchat_intents';
5700 -
5701 - $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
5702 -
5703 - if ($result === false) {
5704 - wp_send_json_error(__('Failed to delete action', 'mxchat'));
5705 - }
5706 -
5707 - // Also delete individual phrases for this intent
5708 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5709 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5710 - $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
5711 - }
5712 -
5713 - wp_send_json_success(array('deleted' => true));
5714 -}
5715 -
5716 -/**
5717 - * AJAX handler to add a single phrase with its own embedding to an intent
5718 - */
5719 -public function mxchat_add_phrase_ajax() {
5720 - check_ajax_referer('mxchat_add_phrase_nonce', 'security');
5721 -
5722 - if (!current_user_can('manage_options')) {
5723 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5724 - }
5725 -
5726 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5727 - $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
5728 -
5729 - if (!$intent_id || empty($phrase)) {
5730 - wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
5731 - }
5732 -
5733 - // Verify the intent exists
5734 - global $wpdb;
5735 - $intents_table = $wpdb->prefix . 'mxchat_intents';
5736 - $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
5737 - if (!$intent) {
5738 - wp_send_json_error(__('Action not found.', 'mxchat'));
5739 - }
5740 -
5741 - // Generate embedding for this single phrase
5742 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5743 - if (is_wp_error($embedding_vector)) {
5744 - wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
5745 - }
5746 -
5747 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5748 - $result = $wpdb->insert(
5749 - $phrases_table,
5750 - array(
5751 - 'intent_id' => $intent_id,
5752 - 'phrase' => $phrase,
5753 - 'embedding_vector' => maybe_serialize($embedding_vector),
5754 - )
5755 - );
5756 -
5757 - if ($result === false) {
5758 - wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
5759 - }
5760 -
5761 - wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
5762 -}
5763 -
5764 -/**
5765 - * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
5766 - */
5767 -public function mxchat_delete_phrase_ajax() {
5768 - check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
5769 -
5770 - if (!current_user_can('manage_options')) {
5771 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5772 - }
5773 -
5774 - $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
5775 - if (!$phrase_id) {
5776 - wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
5777 - }
5778 -
5779 - global $wpdb;
5780 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5781 - $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
5782 -
5783 - if ($result === false) {
5784 - wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
5785 - }
5786 -
5787 - wp_send_json_success(array('deleted' => true));
5788 -}
5789 -
5790 -/**
5791 - * AJAX handler to fetch individual phrases for an intent
5792 - */
5793 -public function mxchat_get_phrases_ajax() {
5794 - check_ajax_referer('mxchat_get_phrases_nonce', 'security');
5795 -
5796 - if (!current_user_can('manage_options')) {
5797 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5798 - }
5799 -
5800 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5801 - if (!$intent_id) {
5802 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5803 - }
5804 -
5805 - global $wpdb;
5806 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5807 -
5808 - $phrases = array();
5809 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5810 - $phrases = $wpdb->get_results($wpdb->prepare(
5811 - "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
5812 - $intent_id
5813 - ));
5814 - }
5815 -
5816 - wp_send_json_success(array('phrases' => $phrases));
5817 -}
5818 -
5819 -/**
5820 - * AJAX handler to clear legacy phrases and embedding from the main intents table
5821 - */
5822 -public function mxchat_delete_legacy_phrases_ajax() {
5823 - check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
5824 -
5825 - if (!current_user_can('manage_options')) {
5826 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5827 - }
5828 -
5829 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5830 - if (!$intent_id) {
5831 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5832 - }
5833 -
5834 - global $wpdb;
5835 - $table_name = $wpdb->prefix . 'mxchat_intents';
5836 -
5837 - $result = $wpdb->update(
5838 - $table_name,
5839 - array('phrases' => '', 'embedding_vector' => ''),
5840 - array('id' => $intent_id),
5841 - array('%s', '%s'),
5842 - array('%d')
5843 - );
5844 -
5845 - if ($result === false) {
5846 - wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
5847 - }
5848 -
5849 - wp_send_json_success(array('cleared' => true));
5850 -}
5851 -
5852 -/**
5853 - * Enhanced get_available_callbacks function with form action exclusion
5854 - *
5855 - * @param bool $grouped Whether to return callbacks grouped by category
5856 - * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
5857 - * @return array Callbacks data with icons, descriptions and availability status
5858 - */
5859 -private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
5860 - // Load WordPress plugin functions if needed
5861 - if (!function_exists('get_plugins')) {
5862 - require_once ABSPATH . 'wp-admin/includes/plugin.php';
5863 - }
5864 -
5865 - // Get active plugins
5866 - $active_plugins = get_option('active_plugins', array());
5867 -
5868 - // Functions to exclude from the action selector only if Pro is activated
5869 - // If user doesn't have Pro, show these so they can see what they're missing
5870 - $excluded_when_pro_active_functions = array(
5871 - 'mxchat_handle_form_collection' // Forms add-on action
5872 - );
5873 -
5874 - // Always excluded functions (regardless of Pro status)
5875 - $always_excluded_functions = array();
5876 -
5877 - // Combine exclusion lists based on Pro activation status
5878 - $excluded_functions = $always_excluded_functions;
5879 - if ($this->is_activated) {
5880 - // Only exclude add-on managed functions if Pro is active
5881 - $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
5882 - }
5883 -
5884 - // Define add-on plugin files and their corresponding action functions
5885 - $addon_plugins = array(
5886 - 'mxchat-woo/mxchat-woo.php' => array(
5887 - 'functions' => array(
5888 - 'mxchat_handle_product_recommendations',
5889 - 'mxchat_handle_order_history',
5890 - 'mxchat_show_product_card',
5891 - 'mxchat_add_to_cart',
5892 - 'mxchat_checkout_redirect',
5893 - 'mxchat_handle_featured_products'
5894 - ),
5895 - 'name' => __('WooCommerce Add-on', 'mxchat'),
5896 - 'pro_required' => true
5897 - ),
5898 - 'mxchat-perplexity/mxchat-perplexity.php' => array(
5899 - 'functions' => array('mxchat_perplexity_research'),
5900 - 'name' => __('Perplexity Add-on', 'mxchat'),
5901 - 'pro_required' => true
5902 - ),
5903 - 'mxchat-forms/mxchat-forms.php' => array(
5904 - 'functions' => array('mxchat_handle_form_collection'),
5905 - 'name' => __('Forms Add-on', 'mxchat'),
5906 - 'pro_required' => true
5907 - ),
5908 - // Add other add-ons and their functions here
5909 - );
5910 -
5911 - // Get the functions that are provided by active add-ons
5912 - $addon_provided_functions = array();
5913 - $addon_function_mapping = array(); // Maps functions to their add-on info
5914 -
5915 - // Check which add-ons are active
5916 - foreach ($addon_plugins as $plugin_file => $addon_info) {
5917 - $is_active = in_array($plugin_file, $active_plugins);
5918 -
5919 - // For each function in this addon
5920 - foreach ($addon_info['functions'] as $function) {
5921 - // Consider a function installed only if:
5922 - // 1. The add-on is active AND
5923 - // 2. Either it doesn't require Pro OR Pro is activated
5924 - $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
5925 -
5926 - // If the add-on is installed, mark this function as provided by an add-on
5927 - if ($is_installed) {
5928 - $addon_provided_functions[] = $function;
5929 - }
5930 -
5931 - // Store addon info for this function regardless of installation status
5932 - $addon_function_mapping[$function] = array(
5933 - 'addon' => basename(dirname($plugin_file)),
5934 - 'addon_name' => $addon_info['name'],
5935 - 'pro_required' => $addon_info['pro_required'],
5936 - 'is_active' => $is_active,
5937 - 'is_installed' => $is_installed
5938 - );
5939 - }
5940 - }
5941 -
5942 - // Core callbacks - always available in the base plugin
5943 - $core_callbacks = array(
5944 - 'mxchat_handle_email_capture' => array(
5945 - 'label' => __('Loops Email Capture', 'mxchat'),
5946 - 'pro_only' => false,
5947 - 'group' => __('Customer Engagement', 'mxchat'),
5948 - 'icon' => 'email-alt',
5949 - 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
5950 - 'addon' => false, // Not from an add-on
5951 - 'installed' => true // Always installed with base plugin
5952 - ),
5953 - 'mxchat_handle_search_request' => array(
5954 - 'label' => __('Brave Web Search', 'mxchat'),
5955 - 'pro_only' => false,
5956 - 'group' => __('Search Features', 'mxchat'),
5957 - 'icon' => 'search',
5958 - 'description' => __('Let users search the web directly from the chat (requires a Brave Search API key)', 'mxchat'),
5959 - 'addon' => false,
5960 - 'installed' => true
5961 - ),
5962 - 'mxchat_handle_image_search_request' => array(
5963 - 'label' => __('Brave Image Search', 'mxchat'),
5964 - 'pro_only' => false,
5965 - 'group' => __('Search Features', 'mxchat'),
5966 - 'icon' => 'format-image',
5967 - 'description' => __('Search and display images in the chat conversation (requires a Brave Search API key)', 'mxchat'),
5968 - 'addon' => false,
5969 - 'installed' => true
5970 - ),
5971 - // Pro core features - check is_activated property
5972 - 'mxchat_generate_image' => array(
5973 - 'label' => __('Generate Image (OpenAI)', 'mxchat'),
5974 - 'pro_only' => false,
5975 - 'group' => __('Other Features', 'mxchat'),
5976 - 'icon' => 'art',
5977 - 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
5978 - 'addon' => false,
5979 - 'installed' => true
5980 - ),
5981 - 'mxchat_generate_gemini_image' => array(
5982 - 'label' => __('Generate Image (Gemini)', 'mxchat'),
5983 - 'pro_only' => false,
5984 - 'group' => __('Other Features', 'mxchat'),
5985 - 'icon' => 'art',
5986 - 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
5987 - 'addon' => false,
5988 - 'installed' => true
5989 - ),
5990 - 'mxchat_handle_pdf_discussion' => array(
5991 - 'label' => __('Chat with PDF', 'mxchat'),
5992 - 'pro_only' => false,
5993 - 'group' => __('Other Features', 'mxchat'),
5994 - 'icon' => 'media-document',
5995 - 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
5996 - 'addon' => false,
5997 - 'installed' => true
5998 - ),
5999 - 'mxchat_live_agent_handover' => array(
6000 - 'label' => __('Slack Live Agent', 'mxchat'),
6001 - 'pro_only' => false,
6002 - 'group' => __('Customer Engagement', 'mxchat'),
6003 - 'icon' => 'admin-users',
6004 - 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
6005 - 'addon' => false,
6006 - 'installed' => true
6007 - ),
6008 - 'mxchat_telegram_live_agent_handover' => array(
6009 - 'label' => __('Telegram Live Agent', 'mxchat'),
6010 - 'pro_only' => false,
6011 - 'group' => __('Customer Engagement', 'mxchat'),
6012 - 'icon' => 'format-chat',
6013 - 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
6014 - 'addon' => false,
6015 - 'installed' => true
6016 - ),
6017 - 'mxchat_handle_switch_to_chatbot_intent' => array(
6018 - 'label' => __('Back to Chatbot', 'mxchat'),
6019 - 'pro_only' => false,
6020 - 'group' => __('Customer Engagement', 'mxchat'),
6021 - 'icon' => 'backup',
6022 - 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
6023 - 'addon' => false,
6024 - 'installed' => true
6025 - ),
6026 - );
6027 -
6028 - // Add-on callbacks with placeholders - only include if the add-on is NOT active
6029 - // These are promotional/informational only — not selectable as real actions
6030 - $addon_callbacks = array(
6031 - // WooCommerce Add-on
6032 - 'mxchat_handle_product_recommendations' => array(
6033 - 'label' => __('Product Recommendations', 'mxchat'),
6034 - 'pro_only' => false,
6035 - 'addon_promo' => true,
6036 - 'group' => __('WooCommerce Features', 'mxchat'),
6037 - 'icon' => 'cart',
6038 - 'description' => __('Suggest products based on customer preferences', 'mxchat'),
6039 - ),
6040 - 'mxchat_handle_order_history' => array(
6041 - 'label' => __('Order History', 'mxchat'),
6042 - 'pro_only' => false,
6043 - 'addon_promo' => true,
6044 - 'group' => __('WooCommerce Features', 'mxchat'),
6045 - 'icon' => 'clipboard',
6046 - 'description' => __('Allow customers to check their order status', 'mxchat'),
6047 - ),
6048 - 'mxchat_show_product_card' => array(
6049 - 'label' => __('Show Product Card', 'mxchat'),
6050 - 'pro_only' => false,
6051 - 'addon_promo' => true,
6052 - 'group' => __('WooCommerce Features', 'mxchat'),
6053 - 'icon' => 'products',
6054 - 'description' => __('Display product information in the chat', 'mxchat'),
6055 - ),
6056 - 'mxchat_add_to_cart' => array(
6057 - 'label' => __('Add to Cart', 'mxchat'),
6058 - 'pro_only' => false,
6059 - 'addon_promo' => true,
6060 - 'group' => __('WooCommerce Features', 'mxchat'),
6061 - 'icon' => 'plus-alt',
6062 - 'description' => __('Add products to cart directly from chat', 'mxchat'),
6063 - ),
6064 - 'mxchat_checkout_redirect' => array(
6065 - 'label' => __('Proceed to Checkout', 'mxchat'),
6066 - 'pro_only' => false,
6067 - 'addon_promo' => true,
6068 - 'group' => __('WooCommerce Features', 'mxchat'),
6069 - 'icon' => 'arrow-right-alt',
6070 - 'description' => __('Redirect customer to checkout page', 'mxchat'),
6071 - ),
6072 - 'mxchat_handle_featured_products' => array(
6073 - 'label' => __('Featured Products Showcase', 'mxchat'),
6074 - 'pro_only' => false,
6075 - 'addon_promo' => true,
6076 - 'group' => __('WooCommerce Features', 'mxchat'),
6077 - 'icon' => 'star-filled',
6078 - 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
6079 - ),
6080 -
6081 - // Perplexity Add-on
6082 - 'mxchat_perplexity_research' => array(
6083 - 'label' => __('Perplexity Research', 'mxchat'),
6084 - 'pro_only' => false,
6085 - 'addon_promo' => true,
6086 - 'group' => __('Search Features', 'mxchat'),
6087 - 'icon' => 'book-alt',
6088 - 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
6089 - ),
6090 -
6091 - // Forms Add-on
6092 - 'mxchat_handle_form_collection' => array(
6093 - 'label' => __('Form Collection', 'mxchat'),
6094 - 'pro_only' => false,
6095 - 'addon_promo' => true,
6096 - 'group' => __('Form Features', 'mxchat'),
6097 - 'icon' => 'feedback',
6098 - 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
6099 - ),
6100 - );
6101 -
6102 - // Enhance add-on callbacks with installation status and addon info
6103 - foreach ($addon_callbacks as $function => $data) {
6104 - if (isset($addon_function_mapping[$function])) {
6105 - $addon_info = $addon_function_mapping[$function];
6106 -
6107 - $addon_callbacks[$function]['addon'] = $addon_info['addon'];
6108 - $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6109 - $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
6110 -
6111 - // Set pro_only based on add-on configuration
6112 - $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6113 - } else {
6114 - $addon_callbacks[$function]['addon'] = 'unknown';
6115 - $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
6116 - $addon_callbacks[$function]['installed'] = false;
6117 - }
6118 - }
6119 -
6120 - // Initialize callbacks with core features
6121 - $callbacks = $core_callbacks;
6122 -
6123 - // Get callbacks from active add-ons
6124 - $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
6125 -
6126 - // Add placeholder callbacks only for add-ons that aren't active
6127 - if ($include_all) {
6128 - foreach ($addon_callbacks as $function => $data) {
6129 - // Skip placeholders for functions provided by active add-ons
6130 - if (in_array($function, $addon_provided_functions)) {
6131 - continue;
6132 - }
6133 -
6134 - // Skip excluded functions
6135 - if (in_array($function, $excluded_functions)) {
6136 - continue;
6137 - }
6138 -
6139 - // Add the placeholder
6140 - $callbacks[$function] = $data;
6141 - }
6142 - }
6143 -
6144 - // Add callbacks from active add-ons (will override placeholders)
6145 - foreach ($active_addon_callbacks as $function => $data) {
6146 - // Skip excluded functions
6147 - if (in_array($function, $excluded_functions)) {
6148 - continue;
6149 - }
6150 -
6151 - // Always include callbacks from add-ons
6152 - $callbacks[$function] = $data;
6153 -
6154 - // Ensure they have the proper add-on info
6155 - if (isset($addon_function_mapping[$function])) {
6156 - $addon_info = $addon_function_mapping[$function];
6157 - $callbacks[$function]['addon'] = $addon_info['addon'];
6158 - $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6159 - $callbacks[$function]['installed'] = $addon_info['is_installed'];
6160 - $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6161 - }
6162 - }
6163 -
6164 - // Just before returning callbacks, sort them to prioritize free features
6165 - if (!$grouped) {
6166 - // Create temporary arrays for sorting
6167 - $free_callbacks = array();
6168 - $pro_callbacks = array();
6169 -
6170 - // Split callbacks into free and pro
6171 - foreach ($callbacks as $key => $data) {
6172 - if (isset($data['pro_only']) && $data['pro_only']) {
6173 - $pro_callbacks[$key] = $data;
6174 - } else {
6175 - $free_callbacks[$key] = $data;
6176 - }
6177 - }
6178 -
6179 - // Merge with free callbacks first
6180 - $callbacks = array_merge($free_callbacks, $pro_callbacks);
6181 - }
6182 -
6183 - // Return grouped structure if requested
6184 - if ($grouped) {
6185 - $grouped_callbacks = array();
6186 - foreach ($callbacks as $key => $data) {
6187 - $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
6188 -
6189 - // Ensure we carry forward all the new fields in grouped mode
6190 - $callback_data = array(
6191 - 'label' => $data['label'],
6192 - 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
6193 - 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
6194 - 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
6195 - 'addon' => isset($data['addon']) ? $data['addon'] : false,
6196 - 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
6197 - 'installed' => isset($data['installed']) ? $data['installed'] : true
6198 - );
6199 -
6200 - $grouped_callbacks[$group_label][$key] = $callback_data;
6201 - }
6202 -
6203 - // Sort within each group to prioritize free features
6204 - foreach ($grouped_callbacks as $group => $items) {
6205 - $free_items = array();
6206 - $pro_items = array();
6207 -
6208 - foreach ($items as $key => $data) {
6209 - if (isset($data['pro_only']) && $data['pro_only']) {
6210 - $pro_items[$key] = $data;
6211 - } else {
6212 - $free_items[$key] = $data;
6213 - }
6214 - }
6215 -
6216 - $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
6217 - }
6218 -
6219 - return $grouped_callbacks;
6220 - }
6221 -
6222 - return $callbacks;
6223 -}
6224 -
6225 683 public function mxchat_page_init() {
684 + // Register settings
6226 685 register_setting(
6227 686 'mxchat_option_group',
6228 687 'mxchat_options',
6229 688 array($this, 'mxchat_sanitize')
@@ -6228,207 +687,36 @@
6228 687 'mxchat_options',
6229 688 array($this, 'mxchat_sanitize')
6230 689 );
6231 690
6232 - register_setting(
6233 - 'mxchat_option_group',
6234 - 'mxchat_similarity_threshold',
6235 - array(
6236 - 'type' => 'number',
6237 - 'sanitize_callback' => function($value) {
6238 - $value = absint($value);
6239 - return min(max($value, 20), 95);
6240 - },
6241 - 'default' => 80,
6242 - )
6243 - );
6244 -
6245 691 // Chatbot Settings Section
6246 692 add_settings_section(
6247 693 'mxchat_chatbot_section',
6248 - esc_html__('Chatbot Settings', 'mxchat'),
694 + 'Chatbot Settings',
6249 695 null,
6250 696 'mxchat-chatbot'
6251 697 );
6252 698
6253 - // API Keys Settings Section
6254 - add_settings_section(
6255 - 'mxchat_api_keys_section',
6256 - esc_html__('API Keys', 'mxchat'),
6257 - array($this, 'mxchat_api_keys_section_callback'),
6258 - 'mxchat-api-keys'
6259 - );
6260 -
6261 - // OpenAI API Key
699 + // Registering fields for the Chatbot Settings section
6262 700 add_settings_field(
6263 701 'api_key',
6264 - esc_html__('OpenAI API Key', 'mxchat'),
702 + 'API Key',
6265 703 array($this, 'api_key_callback'),
6266 - 'mxchat-api-keys',
6267 - 'mxchat_api_keys_section'
6268 - );
6269 -
6270 - // X.AI API Key
6271 - add_settings_field(
6272 - 'xai_api_key',
6273 - esc_html__('X.AI API Key', 'mxchat'),
6274 - array($this, 'xai_api_key_callback'),
6275 - 'mxchat-api-keys',
6276 - 'mxchat_api_keys_section'
6277 - );
6278 -
6279 - // Claude API Key
6280 - add_settings_field(
6281 - 'claude_api_key',
6282 - esc_html__('Claude API Key', 'mxchat'),
6283 - array($this, 'claude_api_key_callback'),
6284 - 'mxchat-api-keys',
6285 - 'mxchat_api_keys_section'
6286 - );
6287 -
6288 - // DeepSeek API Key
6289 - add_settings_field(
6290 - 'deepseek_api_key',
6291 - esc_html__('DeepSeek API Key', 'mxchat'),
6292 - array($this, 'deepseek_api_key_callback'),
6293 - 'mxchat-api-keys',
6294 - 'mxchat_api_keys_section'
6295 - );
6296 -
6297 - // Google Gemini API Key
6298 - add_settings_field(
6299 - 'gemini_api_key',
6300 - esc_html__('Google Gemini API Key', 'mxchat'),
6301 - array($this, 'gemini_api_key_callback'),
6302 - 'mxchat-api-keys',
6303 - 'mxchat_api_keys_section'
6304 - );
6305 -
6306 - // Voyage AI API Key
6307 - add_settings_field(
6308 - 'voyage_api_key',
6309 - esc_html__('Voyage AI API Key', 'mxchat'),
6310 - array($this, 'voyage_api_key_callback'),
6311 - 'mxchat-api-keys',
6312 - 'mxchat_api_keys_section'
6313 - );
6314 -
6315 - // OpenRouter API Key
6316 - add_settings_field(
6317 - 'openrouter_api_key',
6318 - esc_html__('OpenRouter API Key', 'mxchat'),
6319 - array($this, 'openrouter_api_key_callback'),
6320 - 'mxchat-api-keys',
6321 - 'mxchat_api_keys_section'
6322 - );
6323 -
6324 - // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6325 - add_settings_field(
6326 - 'custom_provider',
6327 - esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
6328 - array($this, 'custom_provider_callback'),
6329 - 'mxchat-api-keys',
6330 - 'mxchat_api_keys_section'
6331 - );
6332 -
6333 - // Loops API Key
6334 - add_settings_field(
6335 - 'loops_api_key',
6336 - esc_html__('Loops API Key', 'mxchat'),
6337 - array($this, 'mxchat_loops_api_key_callback'),
6338 - 'mxchat-api-keys',
6339 - 'mxchat_api_keys_section'
6340 - );
6341 -
6342 - // Brave Search API Key
6343 - add_settings_field(
6344 - 'brave_api_key',
6345 - __('Brave API Key', 'mxchat'),
6346 - array($this, 'mxchat_brave_api_key_callback'),
6347 - 'mxchat-api-keys',
6348 - 'mxchat_api_keys_section'
6349 - );
6350 -
6351 - // Similarity Threshold Slider
6352 - add_settings_field(
6353 - 'similarity_threshold', // Field ID
6354 - esc_html__('Similarity Threshold', 'mxchat'), // Field title
6355 - array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6356 - 'mxchat-chatbot', // Page
6357 - 'mxchat_chatbot_section' // Section
6358 - );
6359 -
6360 - // RAG Sources Limit Slider
6361 - add_settings_field(
6362 - 'rag_sources_limit', // Field ID
6363 - esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6364 - array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6365 - 'mxchat-chatbot', // Page
6366 - 'mxchat_chatbot_section' // Section
6367 - );
6368 -
6369 - // RAG Chunks Limit Slider
6370 - add_settings_field(
6371 - 'rag_chunks_limit', // Field ID
6372 - esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6373 - array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6374 - 'mxchat-chatbot', // Page
6375 - 'mxchat_chatbot_section' // Section
6376 - );
6377 -
6378 - add_settings_field(
6379 - 'append_to_body',
6380 - esc_html__('Auto-Display Chatbot', 'mxchat'),
6381 - array($this, 'mxchat_append_to_body_callback'),
6382 704 'mxchat-chatbot',
6383 705 'mxchat_chatbot_section'
6384 706 );
6385 707
6386 708 add_settings_field(
6387 - 'contextual_awareness_toggle',
6388 - esc_html__('Contextual Awareness', 'mxchat'),
6389 - array($this, 'mxchat_contextual_awareness_callback'),
709 + 'system_prompt_instructions',
710 + 'AI Instructions',
711 + array($this, 'system_prompt_instructions_callback'),
6390 712 'mxchat-chatbot',
6391 713 'mxchat_chatbot_section'
6392 714 );
6393 715
6394 716 add_settings_field(
6395 - 'citation_links_toggle',
6396 - esc_html__('Citation Links', 'mxchat'),
6397 - array($this, 'mxchat_citation_links_toggle_callback'),
6398 - 'mxchat-chatbot',
6399 - 'mxchat_chatbot_section'
6400 - );
6401 -
6402 - // Satisfaction rating toggle (plan-a5b006).
6403 - add_settings_field(
6404 - 'satisfaction_rating_enabled',
6405 - esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6406 - array($this, 'mxchat_satisfaction_rating_toggle_callback'),
6407 - 'mxchat-chatbot',
6408 - 'mxchat_chatbot_section'
6409 - );
6410 -
6411 - // Satisfaction rating customization (plan-141a12, plan-29caac):
6412 - // the 5 customization fields are now inline-rendered inside
6413 - // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6414 -
6415 - add_settings_field(
6416 - 'enable_streaming_toggle',
6417 - esc_html__('Enable Streaming', 'mxchat'),
6418 - array($this, 'enable_streaming_toggle_callback'),
6419 - 'mxchat-chatbot',
6420 - 'mxchat_chatbot_section', // Same section as your working toggle
6421 - array(
6422 - 'class' => 'mxchat-setting-row streaming-setting',
6423 - 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6424 - )
6425 - );
6426 -
6427 -
6428 - add_settings_field(
6429 717 'model',
6430 - esc_html__('Chat Model', 'mxchat'),
718 + 'Model',
6431 719 array($this, 'mxchat_model_callback'),
6432 720 'mxchat-chatbot',
6433 721 'mxchat_chatbot_section'
6434 722 );
@@ -6433,27 +721,10 @@
6433 721 'mxchat_chatbot_section'
6434 722 );
6435 723
6436 724 add_settings_field(
6437 - 'embedding_model',
6438 - esc_html__('Embedding Model', 'mxchat'),
6439 - array($this, 'embedding_model_callback'),
6440 - 'mxchat-chatbot',
6441 - 'mxchat_chatbot_section'
6442 - );
6443 -
6444 - add_settings_field(
6445 - 'system_prompt_instructions',
6446 - esc_html__('AI Instructions (Behavior)', 'mxchat'),
6447 - array($this, 'system_prompt_instructions_callback'),
6448 - 'mxchat-chatbot',
6449 - 'mxchat_chatbot_section'
6450 - );
6451 -
6452 -
6453 - add_settings_field(
6454 725 'top_bar_title',
6455 - esc_html__('Top Bar Title', 'mxchat'),
726 + 'Top Bar Title',
6456 727 array($this, 'mxchat_top_bar_title_callback'),
6457 728 'mxchat-chatbot',
6458 729 'mxchat_chatbot_section'
6459 730 );
@@ -6458,795 +729,344 @@
6458 729 'mxchat_chatbot_section'
6459 730 );
6460 731
6461 732 add_settings_field(
6462 - 'ai_agent_text',
6463 - esc_html__('AI Agent Text', 'mxchat'),
6464 - array($this, 'mxchat_ai_agent_text_callback'),
733 + 'intro_message',
734 + 'Introductory Message',
735 + array($this, 'mxchat_intro_message_callback'),
6465 736 'mxchat-chatbot',
6466 737 'mxchat_chatbot_section'
6467 738 );
6468 -
739 +
6469 740 add_settings_field(
6470 - 'enable_email_block',
6471 - esc_html__('Require Email To Chat', 'mxchat'),
6472 - array($this, 'enable_email_block_callback'),
741 + 'input_copy',
742 + 'Input Copy',
743 + array($this, 'mxchat_input_copy_callback'),
6473 744 'mxchat-chatbot',
6474 745 'mxchat_chatbot_section'
6475 746 );
6476 747
6477 748 add_settings_field(
6478 - 'email_blocker_header_content',
6479 - esc_html__('Require Email Chat Content', 'mxchat'),
6480 - array($this, 'email_blocker_header_content_callback'),
749 + 'rate_limit',
750 + 'Rate Limit',
751 + array($this, 'mxchat_rate_limit_callback'),
6481 752 'mxchat-chatbot',
6482 753 'mxchat_chatbot_section'
6483 754 );
6484 755
6485 756 add_settings_field(
6486 - 'email_blocker_button_text',
6487 - esc_html__('Require Email Chat Button Text', 'mxchat'),
6488 - [$this, 'email_blocker_button_text_callback'],
757 + 'rate_limit_message',
758 + 'Rate Limit Message',
759 + array($this, 'mxchat_rate_limit_message_callback'),
6489 760 'mxchat-chatbot',
6490 761 'mxchat_chatbot_section'
6491 762 );
6492 763
6493 764 add_settings_field(
6494 - 'enable_name_field',
6495 - esc_html__('Require Name Field', 'mxchat'),
6496 - array($this, 'enable_name_field_callback'),
765 + 'pre_chat_message',
766 + 'Pre-Chat Message',
767 + array($this, 'mxchat_pre_chat_message_callback'),
6497 768 'mxchat-chatbot',
6498 769 'mxchat_chatbot_section'
6499 770 );
6500 771
6501 - add_settings_field(
6502 - 'name_field_placeholder',
6503 - esc_html__('Name Field Placeholder', 'mxchat'),
6504 - array($this, 'name_field_placeholder_callback'),
772 + add_settings_field(
773 + 'append_to_body',
774 + 'Append Chat Widget to Body',
775 + array($this, 'mxchat_append_to_body_callback'),
6505 776 'mxchat-chatbot',
6506 777 'mxchat_chatbot_section'
6507 778 );
6508 -
6509 - add_settings_field(
6510 - 'intro_message',
6511 - esc_html__('Introductory Message', 'mxchat'),
6512 - array($this, 'mxchat_intro_message_callback'),
6513 - 'mxchat-chatbot',
6514 - 'mxchat_chatbot_section'
6515 - );
6516 -
6517 - add_settings_field(
6518 - 'input_copy',
6519 - esc_html__('Input Copy', 'mxchat'),
6520 - array($this, 'mxchat_input_copy_callback'),
6521 - 'mxchat-chatbot',
6522 - 'mxchat_chatbot_section'
6523 - );
6524 -
6525 - add_settings_field(
6526 - 'pre_chat_message',
6527 - esc_html__('Chat Teaser Pop-up', 'mxchat'),
6528 - array($this, 'mxchat_pre_chat_message_callback'),
6529 - 'mxchat-chatbot',
6530 - 'mxchat_chatbot_section'
6531 - );
6532 -
6533 - add_settings_field(
779 +
780 + add_settings_field(
6534 781 'privacy_toggle',
6535 - esc_html__('Toggle Privacy Notice', 'mxchat'),
782 + 'Toggle Privacy Notice',
6536 783 array($this, 'mxchat_privacy_toggle_callback'),
6537 784 'mxchat-chatbot',
6538 785 'mxchat_chatbot_section'
6539 786 );
6540 -
787 +
6541 788 add_settings_field(
6542 - 'complianz_toggle',
6543 - esc_html__('Enable Complianz', 'mxchat'),
6544 - array($this, 'mxchat_complianz_toggle_callback'),
6545 - 'mxchat-chatbot',
6546 - 'mxchat_chatbot_section'
6547 - );
6548 -
6549 - add_settings_field(
6550 789 'link_target_toggle',
6551 - esc_html__('Open Links in a New Tab', 'mxchat'),
790 + 'Open Links in a New Tab',
6552 791 array($this, 'mxchat_link_target_toggle_callback'),
6553 792 'mxchat-chatbot',
6554 793 'mxchat_chatbot_section'
6555 794 );
6556 795
6557 - add_settings_field(
6558 - 'chat_persistence_toggle',
6559 - esc_html__('Enable Chat Persistence', 'mxchat'),
6560 - array($this, 'mxchat_chat_persistence_toggle_callback'),
6561 - 'mxchat-chatbot',
6562 - 'mxchat_chatbot_section'
6563 - );
6564 -
6565 - add_settings_field(
6566 - 'print_button_enabled',
6567 - esc_html__('Show Download Transcript Button', 'mxchat'),
6568 - array($this, 'mxchat_print_button_toggle_callback'),
6569 - 'mxchat-chatbot',
6570 - 'mxchat_chatbot_section'
6571 - );
6572 -
6573 - add_settings_field(
6574 - 'reset_chat_enabled',
6575 - esc_html__('Show Start-New-Chat Button', 'mxchat'),
6576 - array($this, 'mxchat_reset_chat_toggle_callback'),
6577 - 'mxchat-chatbot',
6578 - 'mxchat_chatbot_section'
6579 - );
6580 -
6581 - add_settings_field(
6582 - 'reset_chat_label',
6583 - esc_html__('Start-New-Chat Button Label', 'mxchat'),
6584 - array($this, 'mxchat_reset_chat_label_callback'),
6585 - 'mxchat-chatbot',
6586 - 'mxchat_chatbot_section'
6587 - );
6588 -
6589 - add_settings_field(
6590 - 'popular_question_1',
6591 - esc_html__('Quick Question 1', 'mxchat'),
6592 - array($this, 'mxchat_popular_question_1_callback'),
6593 - 'mxchat-chatbot',
6594 - 'mxchat_chatbot_section'
6595 - );
6596 -
6597 - add_settings_field(
6598 - 'popular_question_2',
6599 - esc_html__('Quick Question 2', 'mxchat'),
6600 - array($this, 'mxchat_popular_question_2_callback'),
6601 - 'mxchat-chatbot',
6602 - 'mxchat_chatbot_section'
6603 - );
6604 -
6605 - add_settings_field(
6606 - 'popular_question_3',
6607 - esc_html__('Quick Question 3', 'mxchat'),
6608 - array($this, 'mxchat_popular_question_3_callback'),
6609 - 'mxchat-chatbot',
6610 - 'mxchat_chatbot_section'
6611 - );
6612 -
6613 - add_settings_field(
6614 - 'additional_popular_questions',
6615 - esc_html__('Additional Quick Questions', 'mxchat'),
6616 - array($this, 'mxchat_additional_popular_questions_callback'),
6617 - 'mxchat-chatbot',
6618 - 'mxchat_chatbot_section'
6619 - );
6620 -
6621 -
6622 - add_settings_field(
6623 - 'rate_limits',
6624 - __('Rate Limits Settings', 'mxchat'),
6625 - array($this, 'mxchat_rate_limits_callback'),
6626 - 'mxchat-chatbot',
6627 - 'mxchat_chatbot_section'
6628 - );
6629 -
6630 - // Loops Settings Section
796 + // Embed Settings Section
6631 797 add_settings_section(
6632 - 'mxchat_loops_section',
6633 - esc_html__('Loops Settings', 'mxchat'),
798 + 'mxchat_embed_section',
799 + 'Embed Settings',
6634 800 null,
6635 801 'mxchat-embed'
6636 802 );
6637 803
6638 - // Loops Settings Fields (API Key moved to API Keys tab)
6639 804 add_settings_field(
6640 - 'loops_mailing_list',
6641 - esc_html__('Loops Mailing List', 'mxchat'),
6642 - array($this, 'mxchat_loops_mailing_list_callback'),
805 + 'enable_woocommerce_integration',
806 + 'Automatically Embed Products',
807 + array($this, 'mxchat_enable_woocommerce_integration_callback'),
6643 808 'mxchat-embed',
6644 - 'mxchat_loops_section'
809 + 'mxchat_embed_section'
6645 810 );
6646 -
811 +
6647 812 add_settings_field(
6648 - 'triggered_phrase_response',
6649 - esc_html__('Triggered Phrase Response', 'mxchat'),
6650 - array($this, 'mxchat_triggered_phrase_response_callback'),
813 + 'enable_woocommerce_order_access',
814 + 'Order History Access',
815 + array($this, 'mxchat_enable_woocommerce_order_access_callback'),
6651 816 'mxchat-embed',
6652 - 'mxchat_loops_section'
817 + 'mxchat_embed_section'
6653 818 );
6654 819
6655 820 add_settings_field(
6656 - 'email_capture_response',
6657 - esc_html__('Email Capture Response', 'mxchat'),
6658 - array($this, 'mxchat_email_capture_response_callback'),
821 + 'woocommerce_consumer_key',
822 + 'WooCommerce Consumer Key',
823 + array($this, 'mxchat_woocommerce_consumer_key_callback'),
6659 824 'mxchat-embed',
6660 - 'mxchat_loops_section'
825 + 'mxchat_embed_section'
6661 826 );
6662 827
6663 - // Brave Search Settings Fields
6664 - add_settings_section(
6665 - 'mxchat_brave_section',
6666 - __('Brave Search Settings', 'mxchat'),
6667 - array($this, 'mxchat_brave_section_callback'),
6668 - 'mxchat-embed'
6669 - );
6670 -
6671 - // Brave API Key moved to API Keys tab
6672 828 add_settings_field(
6673 - 'brave_image_count',
6674 - __('Number of Images to Return', 'mxchat'),
6675 - array($this, 'mxchat_brave_image_count_callback'),
829 + 'woocommerce_consumer_secret',
830 + 'WooCommerce Consumer Secret',
831 + array($this, 'mxchat_woocommerce_consumer_secret_callback'),
6676 832 'mxchat-embed',
6677 - 'mxchat_brave_section'
833 + 'mxchat_embed_section'
6678 834 );
6679 835
6680 - add_settings_field(
6681 - 'brave_safe_search',
6682 - __('Safe Search', 'mxchat'),
6683 - array($this, 'mxchat_brave_safe_search_callback'),
6684 - 'mxchat-embed',
6685 - 'mxchat_brave_section'
6686 - );
6687 -
6688 - add_settings_field(
6689 - 'brave_news_count',
6690 - __('Number of News Articles', 'mxchat'),
6691 - array($this, 'mxchat_brave_news_count_callback'),
6692 - 'mxchat-embed',
6693 - 'mxchat_brave_section'
6694 - );
6695 -
6696 - add_settings_field(
6697 - 'brave_country',
6698 - __('Country', 'mxchat'),
6699 - array($this, 'mxchat_brave_country_callback'),
6700 - 'mxchat-embed',
6701 - 'mxchat_brave_section'
6702 - );
6703 -
6704 - add_settings_field(
6705 - 'brave_language',
6706 - __('Language', 'mxchat'),
6707 - array($this, 'mxchat_brave_language_callback'),
6708 - 'mxchat-embed',
6709 - 'mxchat_brave_section'
6710 - );
6711 -
6712 - // Chat with PDF Intent Settings Fields
836 + // Theme Settings Section
6713 837 add_settings_section(
6714 - 'mxchat_pdf_intent_section',
6715 - __('Toolbar Settings & Intents', 'mxchat'),
6716 - array($this, 'mxchat_pdf_intent_section_callback'),
6717 - 'mxchat-embed'
838 + 'mxchat_theme_section',
839 + 'Theme Settings',
840 + null,
841 + 'mxchat-theme'
6718 842 );
6719 843
6720 844 add_settings_field(
6721 - 'chat_toolbar_toggle',
6722 - __('Show Chat Toolbar', 'mxchat'),
6723 - array($this, 'mxchat_chat_toolbar_toggle_callback'),
6724 - 'mxchat-embed',
6725 - 'mxchat_pdf_intent_section'
845 + 'close_button_color',
846 + 'Close Button & Title Color',
847 + array($this, 'mxchat_close_button_color_callback'),
848 + 'mxchat-theme',
849 + 'mxchat_theme_section'
6726 850 );
6727 851
6728 - // PDF Upload Button Toggle
6729 852 add_settings_field(
6730 - 'show_pdf_upload_button',
6731 - __('Show PDF Upload Button', 'mxchat'),
6732 - array($this, 'mxchat_show_pdf_upload_button_callback'),
6733 - 'mxchat-embed',
6734 - 'mxchat_pdf_intent_section'
853 + 'chatbot_bg_color',
854 + 'Chatbot Background Color',
855 + array($this, 'mxchat_chatbot_bg_color_callback'),
856 + 'mxchat-theme',
857 + 'mxchat_theme_section'
6735 858 );
6736 859
6737 - // Word Upload Button Toggle
6738 860 add_settings_field(
6739 - 'show_word_upload_button',
6740 - __('Show Word Upload Button', 'mxchat'),
6741 - array($this, 'mxchat_show_word_upload_button_callback'),
6742 - 'mxchat-embed',
6743 - 'mxchat_pdf_intent_section'
861 + 'user_message_bg_color',
862 + 'User Message Background Color',
863 + array($this, 'mxchat_user_message_bg_color_callback'),
864 + 'mxchat-theme',
865 + 'mxchat_theme_section'
6744 866 );
6745 867
6746 868 add_settings_field(
6747 - 'pdf_intent_trigger_text',
6748 - __('Intent Trigger Text', 'mxchat'),
6749 - array($this, 'mxchat_pdf_intent_trigger_text_callback'),
6750 - 'mxchat-embed',
6751 - 'mxchat_pdf_intent_section'
869 + 'user_message_font_color',
870 + 'User Message Font Color',
871 + array($this, 'mxchat_user_message_font_color_callback'),
872 + 'mxchat-theme',
873 + 'mxchat_theme_section'
6752 874 );
6753 875
6754 876 add_settings_field(
6755 - 'pdf_intent_success_text',
6756 - __('Success Text', 'mxchat'),
6757 - array($this, 'mxchat_pdf_intent_success_text_callback'),
6758 - 'mxchat-embed',
6759 - 'mxchat_pdf_intent_section'
877 + 'bot_message_bg_color',
878 + 'Bot Message Background Color',
879 + array($this, 'mxchat_bot_message_bg_color_callback'),
880 + 'mxchat-theme',
881 + 'mxchat_theme_section'
6760 882 );
6761 883
6762 884 add_settings_field(
6763 - 'pdf_intent_error_text',
6764 - __('Error Text', 'mxchat'),
6765 - array($this, 'mxchat_pdf_intent_error_text_callback'),
6766 - 'mxchat-embed',
6767 - 'mxchat_pdf_intent_section'
885 + 'bot_message_font_color',
886 + 'Bot Message Font Color',
887 + array($this, 'mxchat_bot_message_font_color_callback'),
888 + 'mxchat-theme',
889 + 'mxchat_theme_section'
6768 890 );
6769 891
6770 - // Add PDF Maximum Pages Field
6771 892 add_settings_field(
6772 - 'pdf_max_pages',
6773 - __('Maximum Document Pages', 'mxchat'),
6774 - array($this, 'mxchat_pdf_max_pages_callback'),
6775 - 'mxchat-embed',
6776 - 'mxchat_pdf_intent_section'
893 + 'top_bar_bg_color',
894 + 'Top Bar Background Color',
895 + array($this, 'mxchat_top_bar_bg_color_callback'),
896 + 'mxchat-theme',
897 + 'mxchat_theme_section'
6777 898 );
6778 899
6779 - // Live Agent Settings Fields
6780 - add_settings_section(
6781 - 'mxchat_live_agent_section',
6782 - __('Live Agent Settings', 'mxchat'),
6783 - array($this, 'mxchat_live_agent_section_callback'),
6784 - 'mxchat-embed'
6785 - );
6786 -
6787 - // Live Agent Status Fields (add at top of live agent settings)
6788 900 add_settings_field(
6789 - 'live_agent_status',
6790 - __('Live Agent Status', 'mxchat'),
6791 - array($this, 'mxchat_live_agent_status_callback'),
6792 - 'mxchat-embed',
6793 - 'mxchat_live_agent_section'
901 + 'send_button_font_color',
902 + 'Send Button Color',
903 + array($this, 'mxchat_send_button_font_color_callback'),
904 + 'mxchat-theme',
905 + 'mxchat_theme_section'
6794 906 );
6795 907
6796 - // Slack availability schedule (plans 8ccaa2 + 99d7a4). Each handoff channel
6797 - // owns an independent schedule rendered under its own Integrations tab; this
6798 - // one governs Slack only. Same callback as Telegram's, parameterized.
6799 908 add_settings_field(
6800 - 'live_agent_schedule_slack',
6801 - __('Availability Schedule', 'mxchat'),
6802 - array($this, 'mxchat_live_agent_schedule_callback'),
6803 - 'mxchat-embed',
6804 - 'mxchat_live_agent_section',
6805 - array('channel' => 'slack')
909 + 'chat_input_font_color',
910 + 'Chat Input Font Color',
911 + array($this, 'mxchat_chat_input_font_color_callback'),
912 + 'mxchat-theme',
913 + 'mxchat_theme_section'
6806 914 );
6807 915
6808 916 add_settings_field(
6809 - 'live_agent_notification_message',
6810 - __('Notification Message', 'mxchat'),
6811 - array($this, 'mxchat_live_agent_notification_message_callback'),
6812 - 'mxchat-embed',
6813 - 'mxchat_live_agent_section'
917 + 'chatbot_background_color',
918 + 'Floating Widget Background Color',
919 + array($this, 'mxchat_chatbot_background_color_callback'),
920 + 'mxchat-theme',
921 + 'mxchat_theme_section'
6814 922 );
6815 923
6816 924 add_settings_field(
6817 - 'live_agent_away_message',
6818 - __('Away Message', 'mxchat'),
6819 - array($this, 'mxchat_live_agent_away_message_callback'),
6820 - 'mxchat-embed',
6821 - 'mxchat_live_agent_section'
925 + 'icon_color',
926 + 'Chatbot Icon Color',
927 + array($this, 'mxchat_icon_color_callback'),
928 + 'mxchat-theme',
929 + 'mxchat_theme_section'
6822 930 );
6823 931
6824 - add_settings_field(
6825 - 'live_agent_user_ids',
6826 - __('Slack Agent User IDs', 'mxchat'),
6827 - array($this, 'mxchat_live_agent_user_ids_callback'),
6828 - 'mxchat-embed',
6829 - 'mxchat_live_agent_section'
6830 - );
6831 -
6832 - // Shared handoff channel (plan 9f7756): route every handoff into one
6833 - // pre-existing channel as threads instead of creating chat-* channels.
6834 - add_settings_field(
6835 - 'live_agent_shared_channel',
6836 - __('Shared Handoff Channel', 'mxchat'),
6837 - array($this, 'mxchat_live_agent_shared_channel_callback'),
6838 - 'mxchat-embed',
6839 - 'mxchat_live_agent_section'
6840 - );
6841 -
6842 - // Auto-archive per-conversation chat- channels on !endchat (plan 7458a7).
6843 - // Default OFF; never touches the shared handoff channel.
6844 - add_settings_field(
6845 - 'live_agent_archive_on_end_toggle',
6846 - __('Archive Channel When Chat Ends', 'mxchat'),
6847 - array($this, 'mxchat_live_agent_archive_on_end_callback'),
6848 - 'mxchat-embed',
6849 - 'mxchat_live_agent_section'
6850 - );
6851 -
6852 - add_settings_field(
6853 - 'live_agent_webhook_url',
6854 - __('Slack Webhook URL', 'mxchat'),
6855 - array($this, 'mxchat_live_agent_webhook_url_callback'),
6856 - 'mxchat-embed',
6857 - 'mxchat_live_agent_section'
6858 - );
6859 -
6860 - add_settings_field(
6861 - 'live_agent_secret_key',
6862 - __('Slack Secret Key', 'mxchat'),
6863 - array($this, 'mxchat_live_agent_secret_key_callback'),
6864 - 'mxchat-embed',
6865 - 'mxchat_live_agent_section'
6866 - );
6867 -
6868 - // Live Agent Integration Fields
6869 - add_settings_field(
6870 - 'live_agent_bot_token',
6871 - __('Slack Bot OAuth Token', 'mxchat'),
6872 - array($this, 'mxchat_live_agent_bot_token_callback'),
6873 - 'mxchat-embed',
6874 - 'mxchat_live_agent_section'
6875 - );
6876 -
6877 - // Telegram Integration Section
6878 - add_settings_section(
6879 - 'mxchat_telegram_section',
6880 - __('Telegram Settings', 'mxchat'),
6881 - array($this, 'mxchat_telegram_section_callback'),
6882 - 'mxchat-embed'
6883 - );
6884 -
6885 - add_settings_field(
6886 - 'telegram_status',
6887 - __('Live Agent Status', 'mxchat'),
6888 - array($this, 'mxchat_telegram_status_callback'),
6889 - 'mxchat-embed',
6890 - 'mxchat_telegram_section'
6891 - );
6892 -
6893 - // Telegram availability schedule (plan 99d7a4) — independent of Slack's,
6894 - // rendered right under the Telegram status toggle it extends.
6895 - add_settings_field(
6896 - 'live_agent_schedule_telegram',
6897 - __('Availability Schedule', 'mxchat'),
6898 - array($this, 'mxchat_live_agent_schedule_callback'),
6899 - 'mxchat-embed',
6900 - 'mxchat_telegram_section',
6901 - array('channel' => 'telegram')
6902 - );
6903 -
6904 - add_settings_field(
6905 - 'telegram_notification_message',
6906 - __('Notification Message', 'mxchat'),
6907 - array($this, 'mxchat_telegram_notification_message_callback'),
6908 - 'mxchat-embed',
6909 - 'mxchat_telegram_section'
6910 - );
6911 -
6912 - add_settings_field(
6913 - 'telegram_away_message',
6914 - __('Away Message', 'mxchat'),
6915 - array($this, 'mxchat_telegram_away_message_callback'),
6916 - 'mxchat-embed',
6917 - 'mxchat_telegram_section'
6918 - );
6919 -
6920 - add_settings_field(
6921 - 'telegram_bot_token',
6922 - __('Telegram Bot Token', 'mxchat'),
6923 - array($this, 'mxchat_telegram_bot_token_callback'),
6924 - 'mxchat-embed',
6925 - 'mxchat_telegram_section'
6926 - );
6927 -
6928 - add_settings_field(
6929 - 'telegram_group_id',
6930 - __('Telegram Group ID', 'mxchat'),
6931 - array($this, 'mxchat_telegram_group_id_callback'),
6932 - 'mxchat-embed',
6933 - 'mxchat_telegram_section'
6934 - );
6935 -
6936 - add_settings_field(
6937 - 'telegram_webhook_secret',
6938 - __('Webhook Secret Token', 'mxchat'),
6939 - array($this, 'mxchat_telegram_webhook_secret_callback'),
6940 - 'mxchat-embed',
6941 - 'mxchat_telegram_section'
6942 - );
6943 -
6944 932 // General Settings Section
6945 933 add_settings_section(
6946 934 'mxchat_general_section',
6947 - esc_html__('YouTube Tutorials', 'mxchat'),
935 + 'General Information',
6948 936 null,
6949 937 'mxchat-general'
6950 938 );
6951 -}
6952 939
6953 -public function mxchat_prompts_page_init() {
6954 - register_setting(
6955 - 'mxchat_prompts_options',
6956 - 'mxchat_prompts_options',
6957 - array(
6958 - 'type' => 'array',
6959 - 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
6960 - 'default' => array(
6961 - 'mxchat_auto_sync_posts' => 0,
6962 - 'mxchat_auto_sync_pages' => 0,
6963 - 'mxchat_use_pinecone' => 0,
6964 - 'mxchat_pinecone_api_key' => '',
6965 - 'mxchat_pinecone_environment' => '',
6966 - 'mxchat_pinecone_index' => '',
6967 - 'mxchat_pinecone_host' => '',
6968 - ),
6969 - 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
6970 - )
6971 - );
6972 940
6973 - add_action('admin_notices', array($this, 'sync_settings_notice'));
6974 941 }
6975 942
6976 -public function mxchat_transcripts_page_init() {
6977 - register_setting(
6978 - 'mxchat_transcripts_options',
6979 - 'mxchat_transcripts_options',
6980 - array(
6981 - 'type' => 'array',
6982 - 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
6983 - 'default' => array(
6984 - 'mxchat_enable_notifications' => 0,
6985 - 'mxchat_notification_email' => get_option('admin_email'),
6986 - 'mxchat_auto_delete_transcripts' => 'never',
6987 - ),
6988 - 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
6989 - )
6990 - );
6991 943
6992 - add_settings_section(
6993 - 'mxchat_transcripts_notification_section',
6994 - esc_html__('Chat Notification Settings', 'mxchat'),
6995 - array($this, 'mxchat_transcripts_notification_section_callback'),
6996 - 'mxchat-transcripts'
6997 - );
6998 944
6999 - add_settings_field(
7000 - 'mxchat_enable_notifications',
7001 - esc_html__('Enable Chat Notifications', 'mxchat'),
7002 - array($this, 'mxchat_enable_notifications_callback'),
7003 - 'mxchat-transcripts',
7004 - 'mxchat_transcripts_notification_section'
7005 - );
7006 945
7007 - add_settings_field(
7008 - 'mxchat_notification_email',
7009 - esc_html__('Notification Email Address', 'mxchat'),
7010 - array($this, 'mxchat_notification_email_callback'),
7011 - 'mxchat-transcripts',
7012 - 'mxchat_transcripts_notification_section'
7013 - );
946 + public function mxchat_handle_activate_license() {
947 + check_ajax_referer('mxchat_activate_license_nonce', 'security');
7014 948
7015 - add_settings_field(
7016 - 'mxchat_auto_delete_transcripts',
7017 - esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
7018 - array($this, 'mxchat_auto_delete_transcripts_callback'),
7019 - 'mxchat-transcripts',
7020 - 'mxchat_transcripts_notification_section'
7021 - );
949 + $license_key = isset($_POST['key']) ? sanitize_text_field($_POST['key']) : '';
950 + $customer_email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
7022 951
7023 - add_settings_field(
7024 - 'mxchat_retention_days',
7025 - esc_html__('Custom Retention (Days)', 'mxchat'),
7026 - array($this, 'mxchat_retention_days_callback'),
7027 - 'mxchat-transcripts',
7028 - 'mxchat_transcripts_notification_section'
7029 - );
952 + if (empty($license_key) || empty($customer_email)) {
953 + wp_send_json_error('Email or License Key is missing');
954 + }
7030 955
7031 - add_settings_field(
7032 - 'mxchat_auto_email_transcript',
7033 - esc_html__('Auto-Email Full Transcript', 'mxchat'),
7034 - array($this, 'mxchat_auto_email_transcript_callback'),
7035 - 'mxchat-transcripts',
7036 - 'mxchat_transcripts_notification_section'
7037 - );
7038 -}
956 + $product_id = 'MxChatPRO';
7039 957
958 + $response = wp_remote_get("http://mxchat.ai/?wc-api=software-api&request=activation&email={$customer_email}&license_key={$license_key}&product_id={$product_id}");
7040 959
7041 -/**
7042 - * Sanitize all prompts options
7043 - *
7044 - * @param array $input The unsanitized options array
7045 - * @return array The sanitized options array
7046 - */
7047 -public function sanitize_prompts_options($input) {
7048 - // Log the incoming input.
7049 - //error_log('Sanitizing inputs: ' . print_r($input, true));
960 + if (is_wp_error($response)) {
961 + wp_send_json_error('Activation failed due to a server error');
962 + }
7050 963
7051 - $sanitized = array();
964 + $body = wp_remote_retrieve_body($response);
965 + $data = json_decode($body);
7052 966
7053 - // Boolean options
7054 - $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
7055 - $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
7056 -$sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
7057 -
7058 - // API Key: if less than 32 characters, flag as invalid.
7059 - $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
7060 - if (!empty($api_key) && strlen($api_key) < 32) {
7061 - add_settings_error(
7062 - 'mxchat_prompts_options',
7063 - 'invalid_api_key',
7064 - __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
7065 - );
7066 - $existing_options = get_option('mxchat_prompts_options', array());
7067 - $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
7068 - } else {
7069 - $sanitized['mxchat_pinecone_api_key'] = $api_key;
7070 - }
7071 -
7072 - // Environment and Index Name
7073 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
7074 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
7075 -
7076 - // Host: Remove protocol and validate format.
7077 - $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
7078 - $host = preg_replace('#^https?://#', '', $host);
7079 - //error_log('Host after removing protocol: ' . $host);
7080 - if (!empty($host)) {
7081 - if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
7082 - add_settings_error(
7083 - 'mxchat_prompts_options',
7084 - 'invalid_host',
7085 - __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
7086 - );
7087 - $existing_options = get_option('mxchat_prompts_options', array());
7088 - $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
967 + if ($data && isset($data->activated) && $data->activated) {
968 + update_option('mxchat_license_status', 'active');
969 + wp_send_json_success();
7089 970 } else {
7090 - $sanitized['mxchat_pinecone_host'] = $host;
971 + $error_message = isset($data->error) ? $data->error : 'Activation failed';
972 + update_option('mxchat_license_status', 'inactive');
973 + update_option('mxchat_license_error', $error_message);
974 + wp_send_json_error($error_message);
7091 975 }
7092 - } else {
7093 - $sanitized['mxchat_pinecone_host'] = '';
7094 976 }
7095 977
7096 - //error_log('Final sanitized array: ' . print_r($sanitized, true));
7097 978
7098 - return $sanitized;
7099 -}
979 +public function mxchat_rate_limit_callback() {
980 + $rate_limits = array('5', '10', '15', '20', '100');
981 + $selected_rate_limit = isset($this->options['rate_limit']) ? $this->options['rate_limit'] : '100';
7100 982
7101 -public function sync_settings_notice() {
7102 - // Only show notice on our plugin page
7103 - if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
7104 - return;
983 + $disabled = $this->is_activated ? '' : 'disabled';
984 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
985 +
986 + echo '<div class="' . esc_attr($class) . '">';
987 + echo '<select id="rate_limit" name="mxchat_options[rate_limit]" ' . $disabled . '>';
988 + foreach ($rate_limits as $limit) {
989 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7105 990 }
991 + echo '</select>';
7106 992
7107 - // Check if settings were updated
7108 - if (isset($_GET['settings-updated'])) {
993 + if (!$this->is_activated) {
994 + echo '<div class="pro-feature-overlay">';
995 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
996 + echo '</div>';
997 + }
7109 998
7110 - ?>
7111 - <div class="notice notice-success is-dismissible">
7112 - <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
7113 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
7114 - </div>
7115 - <?php
7116 -
7117 - }
999 + echo '</div>';
7118 1000 }
7119 -// Add this sanitization function to your class
7120 -public function sanitize_sync_setting($input) {
7121 - return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
7122 -}
7123 1001
7124 -public function mxchat_rate_limits_callback() {
7125 - $all_options = get_option('mxchat_options', []);
1002 +public function mxchat_rate_limit_message_callback() {
1003 + $disabled = $this->is_activated ? '' : 'disabled';
1004 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7126 1005
7127 - // Define available rate limits
7128 - $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7129 -
7130 - // Define available timeframes
7131 - $timeframes = array(
7132 - 'hourly' => __('Per Hour', 'mxchat'),
7133 - 'daily' => __('Per Day', 'mxchat'),
7134 - 'weekly' => __('Per Week', 'mxchat'),
7135 - 'monthly' => __('Per Month', 'mxchat')
1006 + echo '<div class="' . esc_attr($class) . '">';
1007 + printf(
1008 + '<textarea id="rate_limit_message" name="mxchat_options[rate_limit_message]" rows="3" cols="50" %s>%s</textarea>',
1009 + esc_attr($disabled),
1010 + isset($this->options['rate_limit_message']) ? esc_textarea($this->options['rate_limit_message']) : 'Rate limit exceeded. Please try again later.'
7136 1011 );
7137 1012
7138 - // Get all roles plus a "logged_out" pseudo-role
7139 - $roles = wp_roles()->get_names();
7140 - $roles['logged_out'] = __('Logged Out Users', 'mxchat');
1013 + if (!$this->is_activated) {
1014 + echo '<div class="pro-feature-overlay">';
1015 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1016 + echo '</div>';
1017 + }
7141 1018
7142 - // Start the wrapper
7143 - echo '<div class="pro-feature-wrapper active">';
7144 - echo '<div class="mxchat-rate-limits-container">';
7145 -
7146 - echo '<p class="description" style="margin-bottom: 20px;">' .
7147 - esc_html__('Set message limits for each user role and customize the experience when users reach those limits. You can use {limit}, {timeframe}, {count}, and {remaining} as placeholders.', 'mxchat') .
7148 - '</p>';
7149 -
7150 - // Add markdown link documentation
7151 - echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
7152 - echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
7153 - echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
7154 - echo '<ul style="margin-left: 20px;">';
7155 - echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
7156 - echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
7157 - echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
7158 - echo '</ul>';
7159 1019 echo '</div>';
1020 +}
7160 1021
7161 - // Output the controls for each role
7162 - foreach ($roles as $role_id => $role_name) {
7163 - // Get saved options or defaults
7164 - $default_limit = ($role_id === 'logged_out') ? '10' : '100';
7165 - $default_timeframe = 'daily';
7166 - $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
7167 1022
7168 - $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
7169 - ? $all_options['rate_limits'][$role_id]['limit']
7170 - : $default_limit;
1023 +public function mxchat_enable_woocommerce_integration_callback() {
1024 + $checked = isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1' ? 'checked' : '';
1025 + $disabled = $this->is_activated ? '' : 'disabled';
1026 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7171 1027
7172 - $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
7173 - ? $all_options['rate_limits'][$role_id]['timeframe']
7174 - : $default_timeframe;
1028 + echo '<div class="' . esc_attr($class) . '">';
1029 + echo '<label class="toggle-switch">';
1030 + echo '<input type="checkbox" id="enable_woocommerce_integration" name="mxchat_options[enable_woocommerce_integration]" value="1" ' . $checked . ' ' . $disabled . '>';
1031 + echo '<span class="slider"></span>';
1032 + echo '</label>';
7175 1033
7176 - $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
7177 - ? $all_options['rate_limits'][$role_id]['message']
7178 - : $default_message;
1034 + if (!$this->is_activated) {
1035 + echo '<div class="pro-feature-overlay">';
1036 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1037 + echo '</div>';
1038 + }
7179 1039
7180 - // Output the row
7181 - echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
1040 + echo '</div>';
1041 +}
7182 1042
7183 - // Role label
7184 - echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
7185 1043
7186 - // Controls section
7187 - echo '<div class="mxchat-rate-limit-controls-wrapper">';
1044 +public function mxchat_enable_woocommerce_order_access_callback() {
1045 + $checked = isset($this->options['enable_woocommerce_order_access']) && $this->options['enable_woocommerce_order_access'] === '1' ? 'checked' : '';
1046 + $disabled = $this->is_activated ? '' : 'disabled';
1047 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7188 1048
7189 - // Rate limit and timeframe controls
7190 - echo '<div class="mxchat-rate-limit-controls">';
1049 + echo '<div class="' . esc_attr($class) . '">';
1050 + echo '<label class="toggle-switch">';
1051 + echo '<input type="checkbox" id="enable_woocommerce_order_access" name="mxchat_options[enable_woocommerce_order_access]" value="1" ' . $checked . ' ' . $disabled . '>';
1052 + echo '<span class="slider"></span>';
1053 + echo '</label>';
7191 1054
7192 - // Limit dropdown
7193 - echo '<div>';
7194 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
7195 - echo '<select
7196 - id="rate_limits_' . esc_attr($role_id) . '_limit"
7197 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
7198 - class="mxchat-autosave-field">';
7199 - foreach ($rate_limits as $limit) {
7200 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7201 - }
7202 - echo '</select>';
1055 + if (!$this->is_activated) {
1056 + echo '<div class="pro-feature-overlay">';
1057 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
7203 1058 echo '</div>';
7204 -
7205 - // Timeframe dropdown
7206 - echo '<div>';
7207 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
7208 - echo '<select
7209 - id="rate_limits_' . esc_attr($role_id) . '_timeframe"
7210 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
7211 - class="mxchat-autosave-field">';
7212 - foreach ($timeframes as $value => $label) {
7213 - echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
7214 - }
7215 - echo '</select>';
7216 - echo '</div>';
7217 -
7218 - echo '</div>'; // End controls
7219 -
7220 - // Custom message textarea
7221 - echo '<div class="mxchat-rate-limit-message">';
7222 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
7223 - echo '<textarea
7224 - id="rate_limits_' . esc_attr($role_id) . '_message"
7225 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
7226 - class="mxchat-autosave-field"
7227 - placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
7228 - esc_textarea($custom_message) .
7229 - '</textarea>';
7230 - echo '<p class="description">' .
7231 - esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
7232 - '</p>';
7233 - echo '</div>'; // End message
7234 -
7235 - echo '</div>'; // End controls wrapper
7236 -
7237 - echo '</div>'; // End row
7238 1059 }
7239 1060
7240 - echo '</div>'; // End container
1061 + echo '</div>';
1062 +}
7241 1063
7242 - echo '</div>'; // End pro-feature-wrapper
7243 -}
7244 1064
7245 -private function mxchat_add_option_field($id, $title, $callback = '') {
1065 + private function mxchat_add_option_field($id, $title, $callback = '') {
7246 1066 add_settings_field(
7247 1067 $id,
7248 - __($title, 'mxchat'),
1068 + $title,
7249 1069 $callback ? array($this, $callback) : array($this, $id . '_callback'),
7250 1070 'mxchat-max',
7251 1071 'mxchat_setting_section_id',
7252 1072 $id === 'model' ? ['label_for' => 'model'] : []
@@ -7251,3345 +1071,605 @@
7251 1071 'mxchat_setting_section_id',
7252 1072 $id === 'model' ? ['label_for' => 'model'] : []
7253 1073 );
7254 1074 }
1075 +
1076 +
1077 + public function api_key_callback() {
1078 + $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
1079 + echo '<input type="password" id="api_key" name="mxchat_options[api_key]" value="' . $apiKey . '" class="regular-text" />';
1080 + echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
1081 + }
7255 1082
7256 -// API Keys Section Callback
7257 -public function mxchat_api_keys_section_callback() {
7258 - echo '<p>' . esc_html__('Manage all your API keys in one place. Add the API keys for the services you want to use with your chatbot.', 'mxchat') . '</p>';
7259 -}
7260 1083
7261 -// OpenAI API Key
7262 -public function api_key_callback() {
7263 - $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
7264 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7265 1084
7266 - echo '<div class="api-key-wrapper">';
7267 - echo '<input type="text" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7268 - echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7269 - echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
7270 - echo $this->mxchat_provider_key_test_button('openai', 'api_key');
7271 - echo '</div>';
7272 -}
1085 +public function mxchat_woocommerce_consumer_key_callback() {
1086 + $disabled = $this->is_activated ? '' : 'disabled';
1087 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7273 1088
7274 -// X.AI API Key
7275 -public function xai_api_key_callback() {
7276 - $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
7277 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1089 + echo '<div class="' . esc_attr($class) . '">';
1090 + printf(
1091 + '<input type="text" id="woocommerce_consumer_key" name="mxchat_options[woocommerce_consumer_key]" value="%s" class="regular-text" %s />',
1092 + isset($this->options['woocommerce_consumer_key']) ? esc_attr($this->options['woocommerce_consumer_key']) : '',
1093 + $disabled
1094 + );
7278 1095
7279 - echo '<div class="api-key-wrapper">';
7280 - echo '<input type="text" id="xai_api_key" name="xai_api_key" value="' . $xaiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7281 - echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7282 - echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
7283 - echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key');
7284 - echo '</div>';
7285 -}
7286 -// Claude API Key
7287 -public function claude_api_key_callback() {
7288 - $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
7289 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1096 + if (!$this->is_activated) {
1097 + echo '<div class="pro-feature-overlay">';
1098 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1099 + echo '</div>';
1100 + }
7290 1101
7291 - echo '<div class="api-key-wrapper">';
7292 - echo '<input type="text" id="claude_api_key" name="claude_api_key" value="' . $claudeApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7293 - echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7294 - echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
7295 - echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key');
7296 1102 echo '</div>';
7297 1103 }
7298 1104
7299 -// DeepSeek API Key
7300 -public function deepseek_api_key_callback() {
7301 - $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
7302 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1105 +public function mxchat_woocommerce_consumer_secret_callback() {
1106 + $disabled = $this->is_activated ? '' : 'disabled';
1107 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7303 1108
7304 - echo '<div class="api-key-wrapper">';
7305 - echo '<input type="text" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7306 - echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7307 - echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
7308 - echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key');
7309 - echo '</div>';
7310 -}
1109 + echo '<div class="' . esc_attr($class) . '">';
1110 + printf(
1111 + '<input type="password" id="woocommerce_consumer_secret" name="mxchat_options[woocommerce_consumer_secret]" value="%s" class="regular-text" %s />',
1112 + isset($this->options['woocommerce_consumer_secret']) ? esc_attr($this->options['woocommerce_consumer_secret']) : '',
1113 + $disabled
1114 + );
1115 + echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';
7311 1116
7312 -// Gemini API Key
7313 -public function gemini_api_key_callback() {
7314 - $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
7315 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1117 + if (!$this->is_activated) {
1118 + echo '<div class="pro-feature-overlay">';
1119 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1120 + echo '</div>';
1121 + }
7316 1122
7317 - echo '<div class="api-key-wrapper">';
7318 - echo '<input type="text" id="gemini_api_key" name="gemini_api_key" value="' . $geminiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7319 - echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7320 - echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
7321 - echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key');
7322 1123 echo '</div>';
7323 1124 }
7324 1125
7325 1126
7326 -// OpenRouter API Key
7327 -public function openrouter_api_key_callback() {
7328 - $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
7329 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7330 1127
7331 - echo '<div class="api-key-wrapper">';
7332 - echo '<input type="text" id="openrouter_api_key" name="openrouter_api_key" value="' . $openrouterApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7333 - echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7334 - echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
7335 - echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key');
7336 - echo '</div>';
7337 -}
1128 + public function mxchat_pre_chat_message_callback() {
1129 + printf(
1130 + '<textarea id="pre_chat_message" name="mxchat_options[pre_chat_message]" rows="5" cols="50">%s</textarea>',
1131 + isset($this->options['pre_chat_message']) ? esc_textarea($this->options['pre_chat_message']) : ''
1132 + );
1133 + }
7338 1134
7339 -/**
7340 - * Renders a "Test key" button + result target next to a built-in provider key
7341 - * field, and emits the shared delegated click handler ONCE (static guard). The
7342 - * button carries data-target = the key field id so the owner can test the value
7343 - * they just typed (test-before-save); the AJAX handler falls back to the saved
7344 - * key when the field is empty. Styled with the WP `button` class to match the
7345 - * adjacent Custom-provider "Test Connection" button on this same page.
7346 - * plan-mxchat-20260623-c41f74.
7347 - */
7348 -public function mxchat_provider_key_test_button($provider, $target_id) {
7349 - static $script_emitted = false;
7350 - $nonce = wp_create_nonce('mxchat_test_provider_key');
7351 - $html = '<div class="mxchat-key-test" style="margin-top:8px;">'
7352 - . '<button type="button" class="button mxchat-test-provider-key" data-provider="' . esc_attr($provider) . '" data-target="' . esc_attr($target_id) . '" data-nonce="' . esc_attr($nonce) . '">' . esc_html__('Test key', 'mxchat') . '</button>'
7353 - . '<span class="mxchat-test-provider-key-result" style="margin-left:10px;font-size:13px;vertical-align:middle;"></span>'
7354 - . '</div>';
7355 - if (!$script_emitted) {
7356 - $script_emitted = true;
7357 - $html .= $this->mxchat_provider_key_test_script();
1135 + // Callback for AI Instructions textarea
1136 + public function system_prompt_instructions_callback() {
1137 + printf(
1138 + '<textarea id="system_prompt_instructions" name="mxchat_options[system_prompt_instructions]" rows="5" cols="50">%s</textarea>',
1139 + isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''
1140 + );
7358 1141 }
7359 - return $html;
7360 -}
7361 1142
7362 -/**
7363 - * One-time delegated click handler shared by every .mxchat-test-provider-key
7364 - * button. Posts the typed key value + provider to mxchat_test_provider_key and
7365 - * renders the success/error message inline. Mirrors the Custom-provider test.
7366 - */
7367 -private function mxchat_provider_key_test_script() {
7368 - $t_testing = esc_js(__('Testing...', 'mxchat'));
7369 - $t_valid = esc_js(__('Key is valid.', 'mxchat'));
7370 - $t_failed = esc_js(__('Failed', 'mxchat'));
7371 - $t_req = esc_js(__('Request failed', 'mxchat'));
7372 - return '<script>(function(){'
7373 - . 'if (window.__mxchatProviderKeyTestWired) { return; }'
7374 - . 'window.__mxchatProviderKeyTestWired = true;'
7375 - . 'document.addEventListener("click", function(e){'
7376 - . 'var btn = e.target && e.target.closest ? e.target.closest(".mxchat-test-provider-key") : null;'
7377 - . 'if (!btn) { return; }'
7378 - . 'e.preventDefault();'
7379 - . 'var field = btn.getAttribute("data-target") ? document.getElementById(btn.getAttribute("data-target")) : null;'
7380 - . 'var out = btn.parentNode ? btn.parentNode.querySelector(".mxchat-test-provider-key-result") : null;'
7381 - . 'if (out) { out.textContent = "' . $t_testing . '"; out.style.color = "#646970"; }'
7382 - . 'btn.disabled = true;'
7383 - . 'var fd = new FormData();'
7384 - . 'fd.append("action", "mxchat_test_provider_key");'
7385 - . 'fd.append("_wpnonce", btn.getAttribute("data-nonce"));'
7386 - . 'fd.append("provider", btn.getAttribute("data-provider") || "");'
7387 - . 'fd.append("key", field ? field.value : "");'
7388 - . 'fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })'
7389 - . '.then(function(r){ return r.json(); })'
7390 - . '.then(function(j){'
7391 - . 'if (out) {'
7392 - . 'if (j && j.success) { out.textContent = "✓ " + ((j.data && j.data.message) ? j.data.message : "' . $t_valid . '"); out.style.color = "#00a32a"; }'
7393 - . 'else { out.textContent = "⚠ " + ((j && j.data && j.data.message) ? j.data.message : "' . $t_failed . '"); out.style.color = "#d63638"; }'
7394 - . '}'
7395 - . 'btn.disabled = false;'
7396 - . '})'
7397 - . '.catch(function(){ if (out) { out.textContent = "⚠ ' . $t_req . '"; out.style.color = "#d63638"; } btn.disabled = false; });'
7398 - . '});'
7399 - . '})();</script>';
7400 -}
1143 + public function mxchat_model_callback() {
1144 + $models = array(
1145 + 'gpt-4o' => 'gpt-4o',
1146 + 'gpt-4o-mini' => 'gpt-4o-mini',
1147 + 'gpt-4-turbo' => 'gpt-4-turbo',
1148 + 'gpt-4' => 'gpt-4',
1149 + 'gpt-3.5-turbo' => 'gpt-3.5-turbo',
1150 + );
7401 1151
7402 -// Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
7403 -public function custom_provider_callback() {
7404 - $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
7405 - $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
7406 - $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
7407 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
7408 - $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
7409 - $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
7410 - $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
7411 - $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
7412 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7413 - $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
1152 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';
7414 1153
7415 - echo '<style>
7416 - .mxchat-cp { max-width: 680px; }
7417 - .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
7418 - .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
7419 - .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
7420 - .mxchat-cp .mxchat-cp-row > input[type="text"],
7421 - .mxchat-cp .mxchat-cp-row > input[type="password"],
7422 - .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
7423 - .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
7424 - .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
7425 - .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
7426 - .mxchat-cp .mxchat-cp-azure { margin: 0 0 18px; padding: 12px 14px; background: #f6f7ff; border: 1px solid #dfe1f5; border-left: 3px solid #7873f5; border-radius: 6px; max-width: 480px; }
7427 - .mxchat-cp .mxchat-cp-azure > .mxchat-cp-azure-title { display: block; font-weight: 600; color: #1d2327; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; margin: 0 0 8px; }
7428 - .mxchat-cp .mxchat-cp-azure ol { margin: 0; padding: 0 0 0 18px; color: #50575e; font-size: 12px; line-height: 1.7; }
7429 - .mxchat-cp .mxchat-cp-azure code { background: #eceefb; padding: 1px 5px; border-radius: 3px; font-size: 11px; }
7430 - </style>';
1154 + echo '<select id="model" name="mxchat_options[model]">';
1155 + foreach ($models as $model_value => $model_label) {
1156 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
1157 + }
1158 + echo '</select>';
1159 + }
7431 1160
7432 - echo '<div class="api-key-wrapper mxchat-cp">';
7433 - echo '<p class="mxchat-cp-intro">' . esc_html__('Point MxChat at any OpenAI-compatible /v1/chat/completions endpoint: Ollama, LM Studio, vLLM, llama.cpp, LocalAI, Azure OpenAI, etc. Then select "Custom (OpenAI-compatible)" in the model picker.', 'mxchat') . '</p>';
7434 -
7435 - // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout
7436 - // so admins can configure Azure without piecing it together from each field's hint.
7437 - echo '<div class="mxchat-cp-azure">';
7438 - echo '<span class="mxchat-cp-azure-title">' . esc_html__('Azure OpenAI quick start', 'mxchat') . '</span>';
7439 - echo '<ol>';
7440 - echo '<li>' . wp_kses(__('<strong>Base URL</strong> → <code>https://&lt;resource&gt;.openai.azure.com/openai/deployments/&lt;deployment&gt;</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7441 - echo '<li>' . wp_kses(__('<strong>API Key</strong> → your Azure OpenAI key (required)', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7442 - echo '<li>' . wp_kses(__('<strong>Auth Scheme</strong> → <code>api-key header (Azure OpenAI)</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7443 - echo '<li>' . wp_kses(__('<strong>API Version</strong> → required for Azure, e.g. <code>2024-08-01-preview</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7444 - echo '</ol>';
7445 - echo '</div>';
7446 -
7447 - echo '<div class="mxchat-cp-row">';
7448 - echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
7449 - echo '<input type="text" id="custom_provider_base_url" name="custom_provider_base_url" value="' . $base_url . '" class="regular-text mxchat-autosave-field" placeholder="http://localhost:11434/v1" autocomplete="off" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7450 - echo '<p class="description">' . esc_html__('Examples: Ollama http://localhost:11434/v1 · LM Studio http://localhost:1234/v1 · vLLM http://gpu:8000/v1 · Azure https://<resource>.openai.azure.com/openai/deployments/<deployment>', 'mxchat') . '</p>';
7451 - echo '</div>';
7452 -
7453 - echo '<div class="mxchat-cp-row">';
7454 - echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
7455 - echo '<input type="password" id="custom_provider_api_key" name="custom_provider_api_key" value="' . $api_key . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7456 - echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
7457 - echo '</div>';
7458 -
7459 - echo '<div class="mxchat-cp-row">';
7460 - echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
7461 - echo '<input type="text" id="custom_provider_model" name="custom_provider_model" value="' . $model_name . '" class="regular-text mxchat-autosave-field" placeholder="llama3.2" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7462 - echo '<p class="description">' . esc_html__('The model identifier the upstream server expects (e.g. llama3.2, mistral, gpt-oss). For Azure this is the deployment ID — leave empty if the Base URL already includes /deployments/<deployment>.', 'mxchat') . '</p>';
7463 - echo '</div>';
7464 -
7465 - echo '<div class="mxchat-cp-row">';
7466 - echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
7467 - echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7468 - echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
7469 - echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
7470 - echo '</select>';
7471 - echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
7472 - echo '</div>';
7473 -
7474 - echo '<div class="mxchat-cp-row">';
7475 - echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
7476 - echo '<input type="text" id="custom_provider_api_version" name="custom_provider_api_version" value="' . $api_version . '" class="regular-text mxchat-autosave-field" placeholder="2024-08-01-preview" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7477 - echo '<p class="description">' . esc_html__('Appended as ?api-version=... on the request URL. Required for Azure OpenAI; leave empty for non-Azure providers.', 'mxchat') . '</p>';
7478 - echo '</div>';
7479 -
7480 - // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
7481 - echo '<div class="mxchat-cp-row">';
7482 - echo '<label style="font-weight:600; display:block; margin:0 0 6px; color:#1d2327; font-size:13px;">' . esc_html__('Extended routing (opt-in)', 'mxchat') . '</label>';
7483 - echo '<label style="display:block; margin:0 0 6px; font-weight:400;"><input type="checkbox" id="custom_provider_for_embeddings" name="custom_provider_for_embeddings" value="on"' . checked($use_embed, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for embeddings', 'mxchat') . '</label>';
7484 - echo '<label style="display:block; margin:0 0 0; font-weight:400;"><input type="checkbox" id="custom_provider_for_images" name="custom_provider_for_images" value="on"' . checked($use_images, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for image generation', 'mxchat') . '</label>';
7485 - echo '<p class="description">' . esc_html__('When off, embeddings and image generation continue to use OpenAI (current behavior). Turn on only if your endpoint exposes OpenAI-compatible /embeddings or /images/generations routes (e.g. Ollama, vLLM, LocalAI).', 'mxchat') . '</p>';
7486 - echo '</div>';
7487 -
7488 - echo '<div class="mxchat-cp-row">';
7489 - echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
7490 - echo '<input type="text" id="custom_provider_embedding_model" name="custom_provider_embedding_model" value="' . $embed_model . '" class="regular-text mxchat-autosave-field" placeholder="nomic-embed-text" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7491 - echo '<p class="description">' . esc_html__('Only used when "Use custom provider for embeddings" is on. The embedding model name is separate from the chat model name above (e.g. Ollama embedding models: nomic-embed-text, mxbai-embed-large). Leave blank to fall back to the chat model name.', 'mxchat') . '</p>';
7492 - echo '</div>';
7493 -
7494 - echo '<div class="mxchat-cp-test">';
7495 - echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
7496 - echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
7497 - echo '</div>';
7498 -
7499 - echo '<script>(function(){
7500 - var btn = document.getElementById("mxchat-test-custom-provider");
7501 - if (!btn || btn._wired) { return; } btn._wired = true;
7502 - btn.addEventListener("click", function(){
7503 - var out = document.getElementById("mxchat-test-custom-provider-result");
7504 - out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
7505 - out.style.color = "#646970";
7506 - var fd = new FormData();
7507 - fd.append("action", "mxchat_test_custom_provider");
7508 - fd.append("_wpnonce", btn.getAttribute("data-nonce"));
7509 - fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
7510 - .then(function(r){ return r.json(); })
7511 - .then(function(j){
7512 - if (j && j.success) {
7513 - out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
7514 - out.style.color = "#00a32a";
7515 - } else {
7516 - out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
7517 - out.style.color = "#d63638";
7518 - }
7519 - })
7520 - .catch(function(){
7521 - out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
7522 - out.style.color = "#d63638";
7523 - });
7524 - });
7525 - })();</script>';
7526 -
7527 - echo '</div>';
7528 -}
7529 -
7530 -// Voyage API Key
7531 -public function voyage_api_key_callback() {
7532 - $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
7533 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7534 -
7535 - echo '<div class="api-key-wrapper">';
7536 - echo '<input type="text" id="voyage_api_key" name="voyage_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7537 - echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7538 - echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
7539 - echo '</div>';
7540 -}
7541 -
7542 -public function mxchat_loops_api_key_callback() {
7543 - $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7544 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7545 -
7546 - echo '<div class="api-key-wrapper">';
7547 - echo sprintf(
7548 - '<input type="text" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
7549 - $loops_api_key,
7550 - $nonce
7551 - );
7552 - echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7553 - echo '</div>';
7554 - // Cross-reference back to where the list is chosen, so the two screens point
7555 - // at each other (plan-mxchat-20260802-907a63).
7556 - echo '<p class="description">' . wp_kses(
7557 - sprintf(
7558 - /* translators: %s: link to the Loops integration tab. */
7559 - __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'),
7560 - '<a href="#integrations-loops">' . esc_html__('Integrations, Loops', 'mxchat') . '</a>'
7561 - ),
7562 - self::mxchat_loops_pointer_allowed_html()
7563 - ) . '</p>';
7564 -}
7565 -public function mxchat_loops_mailing_list_callback() {
7566 - // Add error handling and type checking
7567 - $loops_api_key = '';
7568 - $selected_list = '';
7569 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7570 -
7571 - // Safely get the API key
7572 - if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
7573 - $loops_api_key = $this->options['loops_api_key'];
1161 + public function mxchat_top_bar_title_callback() {
1162 + printf(
1163 + '<input type="text" id="top_bar_title" name="mxchat_options[top_bar_title]" value="%s" />',
1164 + isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : ''
1165 + );
7574 1166 }
7575 1167
7576 - // Safely get the selected list
7577 - if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
7578 - $selected_list = $this->options['loops_mailing_list'];
1168 + public function mxchat_intro_message_callback() {
1169 + printf(
1170 + '<textarea id="intro_message" name="mxchat_options[intro_message]" rows="5" cols="50">%s</textarea>',
1171 + isset($this->options['intro_message']) ? esc_textarea($this->options['intro_message']) : 'Hello! How can I assist you today?'
1172 + );
7579 1173 }
7580 -
7581 - if (!empty($loops_api_key)) {
7582 - $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7583 - if (is_array($lists) && !empty($lists)) {
7584 - echo '<div class="mxchat-field-wrapper">';
7585 - echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7586 -
7587 - // Add a default "Select a list" option
7588 - echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
7589 -
7590 - foreach ($lists as $list) {
7591 - if (is_array($list) && isset($list['id']) && isset($list['name'])) {
7592 - echo sprintf(
7593 - '<option value="%s" %s>%s</option>',
7594 - esc_attr($list['id']),
7595 - selected($selected_list, $list['id'], false),
7596 - esc_html($list['name'])
7597 - );
7598 - }
7599 - }
7600 - echo '</select>';
7601 - echo '</div>';
7602 - echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
7603 - } else {
7604 - echo '<p class="description">' . wp_kses(
7605 - self::mxchat_loops_api_key_pointer(
7606 - /* translators: %s: link to the API Keys tab. */
7607 - __('No lists found. Please check your Loops API key under %s.', 'mxchat')
7608 - ),
7609 - self::mxchat_loops_pointer_allowed_html()
7610 - ) . '</p>';
7611 - }
7612 - } else {
7613 - echo '<p class="description">' . wp_kses(
7614 - self::mxchat_loops_api_key_pointer(
7615 - /* translators: %s: link to the API Keys tab. */
7616 - __('Enter your Loops API key under %s to load mailing lists.', 'mxchat')
7617 - ),
7618 - self::mxchat_loops_pointer_allowed_html()
7619 - ) . '</p>';
1174 +
1175 + public function mxchat_input_copy_callback() {
1176 + printf(
1177 + '<input type="text" id="input_copy" name="mxchat_options[input_copy]" value="%s" placeholder="How can I assist?" />',
1178 + isset($this->options['input_copy']) ? esc_attr($this->options['input_copy']) : 'How can I assist?'
1179 + );
1180 + echo '<p class="description">This is the placeholder text for the chat input field.</p>';
7620 1181 }
7621 -}
7622 1182
7623 -/**
7624 - * Build the "API Keys" pointer used by the Loops mailing-list field.
7625 - *
7626 - * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API
7627 - * Keys tab, but this field's copy still read as though the input were beside
7628 - * it, so users had nowhere to go. Both live on the SAME screen
7629 - * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this
7630 - * dropdown under Integrations > Loops — so the pointer is an in-page tab
7631 - * switch, not a cross-page link.
7632 - *
7633 - * A plain href="#api-keys" is all it takes: the shared admin shell
7634 - * (js/admin-sidebar.js) honours section-naming hashes on load AND on
7635 - * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old
7636 - * data-target workaround on these pointer anchors is gone.
7637 - *
7638 - * @param string $template Translatable string containing one %s placeholder.
7639 - * @return string
7640 - */
7641 -private static function mxchat_loops_api_key_pointer($template) {
7642 - return sprintf(
7643 - $template,
7644 - '<a href="#api-keys">' . esc_html__('API Keys', 'mxchat') . '</a>'
7645 - );
7646 -}
7647 1183
7648 -/**
7649 - * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook.
7650 - */
7651 -private static function mxchat_loops_pointer_allowed_html() {
7652 - return array(
7653 - 'a' => array(
7654 - 'href' => array(),
7655 - 'data-target' => array(),
7656 - ),
7657 - );
7658 -}
7659 -public function mxchat_triggered_phrase_response_callback() {
7660 - $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
7661 - $triggered_response = isset($this->options['triggered_phrase_response'])
7662 - ? $this->options['triggered_phrase_response']
7663 - : $default_response;
7664 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7665 1184
7666 - echo '<div class="mxchat-field-wrapper">';
7667 - echo sprintf(
7668 - '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7669 - $nonce,
7670 - esc_textarea($triggered_response)
7671 - );
7672 - echo '</div>';
7673 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '</p>';
7674 -}
7675 1185
7676 -public function mxchat_email_capture_response_callback() {
7677 - $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
7678 - $email_capture_response = isset($this->options['email_capture_response'])
7679 - ? $this->options['email_capture_response']
7680 - : $default_response;
7681 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7682 1186
7683 - echo '<div class="mxchat-field-wrapper">';
7684 - echo sprintf(
7685 - '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7686 - $nonce,
7687 - esc_textarea($email_capture_response)
7688 - );
7689 - echo '</div>';
7690 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '</p>';
7691 -}
7692 -public function mxchat_pre_chat_message_callback() {
7693 - // Load the entire 'mxchat_options' array
7694 - $all_options = get_option('mxchat_options', []);
7695 1187
7696 - // Retrieve the saved message or use the default value
7697 - $default_message = __('Hey there! Ask me anything!', 'mxchat');
7698 - $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
1188 + public function mxchat_close_button_color_callback() {
1189 + $disabled = $this->is_activated ? '' : 'disabled';
7699 1190
7700 - // Output the textarea
1191 + echo '<div class="pro-feature-wrapper">';
7701 1192 printf(
7702 - '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
7703 - esc_textarea($pre_chat_message)
1193 + '<input type="text" id="close_button_color" name="mxchat_options[close_button_color]" value="%s" class="my-color-field" data-default-color="#4a4a4a" %s />',
1194 + isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '',
1195 + esc_attr($disabled)
7704 1196 );
7705 -}
7706 1197
7707 -// Callback for AI Instructions textarea
7708 -public function system_prompt_instructions_callback() {
7709 - // Retrieve the current value of the system prompt instructions
7710 - $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
7711 - // Render the textarea field
7712 - printf(
7713 - '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
7714 - $instructions
7715 - );
7716 - // Personalization hint
7717 - echo '<p class="description" style="margin-top: 8px;">';
7718 - echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
7719 - echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
7720 - echo '</p>';
7721 - // Sample instructions button
7722 - echo '<div class="mxchat-instructions-container">';
7723 - echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
7724 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7725 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7726 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7727 - echo '</svg>';
7728 - echo esc_html__('View Sample Instructions', 'mxchat');
7729 - echo '</button>';
7730 - echo '</div>';
1198 + if (!$this->is_activated) {
1199 + echo '<div class="pro-feature-overlay">';
1200 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1201 + echo '</div>';
1202 + }
7731 1203
7732 - // Add modal to WordPress admin footer instead of inline
7733 - add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
7734 -}
7735 -
7736 -// New method to render modal in admin footer
7737 -public function render_sample_instructions_modal() {
7738 - static $modal_rendered = false;
7739 - if ($modal_rendered) return; // Prevent duplicate modals
7740 - $modal_rendered = true;
7741 -
7742 - echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
7743 - echo '<div class="mxchat-instructions-modal-content">';
7744 - echo '<div class="mxchat-instructions-modal-header">';
7745 - echo '<h3 class="mxchat-instructions-modal-title">';
7746 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7747 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7748 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7749 - echo '</svg>';
7750 - echo esc_html__('Sample AI Instructions', 'mxchat');
7751 - echo '</h3>';
7752 - echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
7753 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7754 - echo '<line x1="18" y1="6" x2="6" y2="18"/>';
7755 - echo '<line x1="6" y1="6" x2="18" y2="18"/>';
7756 - echo '</svg>';
7757 - echo '</button>';
7758 1204 echo '</div>';
7759 - echo '<div class="mxchat-instructions-modal-body">';
7760 - echo '<div class="mxchat-instructions-content">';
7761 - echo esc_html('You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
1205 + }
7762 1206
7763 -# Response Style - CRITICALLY IMPORTANT
7764 -- MAXIMUM LENGTH: 1-3 short sentences per response
7765 -- Ultra-concise: Get straight to the answer with no filler
7766 -- No introductions like "Sure!" or "I\'d be happy to help"
7767 -- No phrases like "based on my knowledge" or "according to information"
7768 -- No explanatory text before giving the answer
7769 -- No summaries or repetition
7770 -- Hyperlink all URLs
7771 -- Respond in user\'s language
7772 -- Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
1207 + public function mxchat_chatbot_bg_color_callback() {
1208 + $disabled = $this->is_activated ? '' : 'disabled';
7773 1209
7774 -# Knowledge Base Requirements - PREVENT HALLUCINATIONS
7775 -- ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
7776 -- If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
7777 -- NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
7778 -- When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
7779 -- Better to admit insufficient information than provide inaccurate answers');
7780 - echo '</div>';
7781 - echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
7782 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7783 - echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
7784 - echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
7785 - echo '</svg>';
7786 - echo esc_html__('Copy Instructions', 'mxchat');
7787 - echo '</button>';
7788 - echo '</div>';
7789 - echo '<div class="mxchat-instructions-modal-footer">';
7790 - echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
7791 - echo '</div>';
7792 - echo '</div>';
7793 - echo '</div>';
7794 -}
1210 + echo '<div class="pro-feature-wrapper">';
1211 + printf(
1212 + '<input type="text" id="chatbot_bg_color" name="mxchat_options[chatbot_bg_color]" value="%s" class="my-color-field" data-default-color="#f9f9f9" %s />',
1213 + isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '',
1214 + esc_attr($disabled)
1215 + );
7795 1216
1217 + if (!$this->is_activated) {
1218 + echo '<div class="pro-feature-overlay">';
1219 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1220 + echo '</div>';
1221 + }
7796 1222
7797 -public function mxchat_model_callback() {
7798 - // Catalog refactor (plan-d14e89): single source of truth lives in
7799 - // includes/class-mxchat-model-catalog.php. Dropdown groups are the
7800 - // provider labels; each group maps model_id => "Label" strings.
7801 - if (!class_exists('MxChat_Model_Catalog')) {
7802 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1223 + echo '</div>';
7803 1224 }
7804 - // Retrieve the currently selected model from saved options
7805 - $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.6-sol';
7806 1225
7807 - // Pass the saved model so a provider-retired id keeps rendering as the
7808 - // current selection instead of a blank select (plan e46b8f).
7809 - $models = MxChat_Model_Catalog::settings_dropdown_groups($selected_model);
1226 + public function mxchat_user_message_bg_color_callback() {
1227 + $disabled = $this->is_activated ? '' : 'disabled';
7810 1228
7811 - // Begin the select dropdown
7812 - echo '<select id="model" name="model">';
1229 + echo '<div class="pro-feature-wrapper">';
1230 + printf(
1231 + '<input type="text" id="user_message_bg_color" name="mxchat_options[user_message_bg_color]" value="%s" class="my-color-field" data-default-color="#0078d7" %s />',
1232 + isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '',
1233 + esc_attr($disabled)
1234 + );
7813 1235
7814 - // Iterate over groups of models
7815 - foreach ($models as $group_label => $group_models) {
7816 - echo '<optgroup label="' . esc_attr($group_label) . '">';
7817 -
7818 - foreach ($group_models as $model_value => $model_label) {
7819 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
1236 + if (!$this->is_activated) {
1237 + echo '<div class="pro-feature-overlay">';
1238 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1239 + echo '</div>';
7820 1240 }
7821 1241
7822 - echo '</optgroup>';
1242 + echo '</div>';
7823 1243 }
7824 1244
7825 - echo '</select>';
1245 + public function mxchat_user_message_font_color_callback() {
1246 + $disabled = $this->is_activated ? '' : 'disabled';
7826 1247
7827 - // Add a note for OpenRouter
7828 - echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
7829 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
7830 - echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
7831 - echo '</p>';
1248 + echo '<div class="pro-feature-wrapper">';
1249 + printf(
1250 + '<input type="text" id="user_message_font_color" name="mxchat_options[user_message_font_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
1251 + isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '',
1252 + esc_attr($disabled)
1253 + );
7832 1254
7833 - // API Key Status Messages (hidden by default, shown by JS based on selected model)
7834 - $has_openai_key = !empty($this->options['api_key']);
7835 - $has_claude_key = !empty($this->options['claude_api_key']);
7836 - $has_xai_key = !empty($this->options['xai_api_key']);
7837 - $has_deepseek_key = !empty($this->options['deepseek_api_key']);
7838 - $has_gemini_key = !empty($this->options['gemini_api_key']);
7839 - $has_openrouter_key = !empty($this->options['openrouter_api_key']);
1255 + if (!$this->is_activated) {
1256 + echo '<div class="pro-feature-overlay">';
1257 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1258 + echo '</div>';
1259 + }
7840 1260
7841 - // OpenAI/GPT models
7842 - echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
7843 - if ($has_openai_key) {
7844 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
7845 - } else {
7846 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1261 + echo '</div>';
7847 1262 }
7848 - echo '</p>';
7849 1263
7850 - // Claude models
7851 - echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
7852 - if ($has_claude_key) {
7853 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
7854 - } else {
7855 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7856 - }
7857 - echo '</p>';
1264 + public function mxchat_bot_message_bg_color_callback() {
1265 + $disabled = $this->is_activated ? '' : 'disabled';
7858 1266
7859 - // X.AI models
7860 - echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
7861 - if ($has_xai_key) {
7862 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
7863 - } else {
7864 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for X.AI (Grok) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7865 - }
7866 - echo '</p>';
1267 + echo '<div class="pro-feature-wrapper">';
1268 + printf(
1269 + '<input type="text" id="bot_message_bg_color" name="mxchat_options[bot_message_bg_color]" value="%s" class="my-color-field" data-default-color="#e1e1e1" %s />',
1270 + isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '',
1271 + esc_attr($disabled)
1272 + );
7867 1273
7868 - // DeepSeek models
7869 - echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
7870 - if ($has_deepseek_key) {
7871 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
7872 - } else {
7873 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7874 - }
7875 - echo '</p>';
1274 + if (!$this->is_activated) {
1275 + echo '<div class="pro-feature-overlay">';
1276 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1277 + echo '</div>';
1278 + }
7876 1279
7877 - // Gemini models
7878 - echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
7879 - if ($has_gemini_key) {
7880 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
7881 - } else {
7882 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1280 + echo '</div>';
7883 1281 }
7884 - echo '</p>';
7885 1282
7886 - // OpenRouter models
7887 - echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
7888 - if ($has_openrouter_key) {
7889 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
7890 - } else {
7891 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7892 - }
7893 - echo '</p>';
1283 + public function mxchat_bot_message_font_color_callback() {
1284 + $disabled = $this->is_activated ? '' : 'disabled';
7894 1285
7895 - // ADD THESE HIDDEN FIELDS RIGHT HERE:
7896 - $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
7897 - $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
1286 + echo '<div class="pro-feature-wrapper">';
1287 + printf(
1288 + '<input type="text" id="bot_message_font_color" name="mxchat_options[bot_message_font_color]" value="%s" class="my-color-field" data-default-color="#333333" %s />',
1289 + isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '',
1290 + esc_attr($disabled)
1291 + );
7898 1292
7899 - echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
7900 - echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
7901 -}
1293 + if (!$this->is_activated) {
1294 + echo '<div class="pro-feature-overlay">';
1295 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1296 + echo '</div>';
1297 + }
7902 1298
7903 -// Update your existing callback method
7904 -public function enable_streaming_toggle_callback() {
7905 - // Get value from options array, default to 'on'
7906 - $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
7907 - $checked = ($enabled === 'on') ? 'checked' : '';
1299 + echo '</div>';
1300 + }
7908 1301
7909 - echo '<label class="toggle-switch">';
7910 - echo sprintf(
7911 - '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
7912 - esc_attr($checked)
7913 - );
7914 - echo '<span class="slider"></span>';
7915 - echo '</label>';
1302 + public function mxchat_top_bar_bg_color_callback() {
1303 + $disabled = $this->is_activated ? '' : 'disabled';
7916 1304
7917 - // Test button — branded .mxch-btn with inline SVG (IDs preserved for AJAX binding)
7918 - echo '<div class="mxch-streaming-test-row">';
7919 - echo '<button type="button" id="mxchat-test-streaming-btn" class="mxch-btn mxch-btn-secondary">';
7920 - echo '<svg class="mxch-streaming-test-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>';
7921 - echo esc_html__('Test Streaming Compatibility', 'mxchat');
7922 - echo '</button>';
7923 - echo '<p id="mxchat-test-streaming-result" class="mxch-streaming-test-result"></p>';
7924 - echo '</div>';
7925 -}
1305 + echo '<div class="pro-feature-wrapper">';
1306 + printf(
1307 + '<input type="text" id="top_bar_bg_color" name="mxchat_options[top_bar_bg_color]" value="%s" class="my-color-field" data-default-color="#00b294" %s />',
1308 + isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '',
1309 + esc_attr($disabled)
1310 + );
7926 1311
7927 -// Web Search toggle callback
7928 -public function enable_web_search_toggle_callback() {
7929 - // Get value from options array, default to 'off'
7930 - $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
7931 - $checked = ($enabled === 'on') ? 'checked' : '';
1312 + if (!$this->is_activated) {
1313 + echo '<div class="pro-feature-overlay">';
1314 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1315 + echo '</div>';
1316 + }
7932 1317
7933 - // Get current model to determine if we should show/enable the toggle
7934 - $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
7935 -
7936 - // Models that DON'T support web search — OpenAI-docs-driven exception list.
7937 - // Keep hardcoded; the catalog can't infer "supports web search" per-model, so any
7938 - // future OpenAI model that lacks Responses-API web_search support is added here.
7939 - $unsupported_models = array('gpt-4.1-nano');
7940 -
7941 - // Web-search-capable chat-model allowlists, derived from the central model catalog
7942 - // (class-mxchat-model-catalog.php). When a new OpenAI/Gemini chat model is added there,
7943 - // the Web Search toggle picks it up automatically — no edit here.
7944 - // OpenAI grounds via the Responses-API web_search tool; Gemini grounds natively via the
7945 - // Google Search tool (plan 46b9ea wired the Gemini dispatch — every shipped Gemini chat
7946 - // model is 2.x/3.x and grounds, matching that path's empty opt-out list, so all catalog
7947 - // Gemini models are supported here).
7948 - if (!class_exists('MxChat_Model_Catalog')) {
7949 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1318 + echo '</div>';
7950 1319 }
7951 - $chat_catalog = MxChat_Model_Catalog::chat_models();
7952 - $openai_models = (isset($chat_catalog['openai']['models']) && is_array($chat_catalog['openai']['models']))
7953 - ? array_keys($chat_catalog['openai']['models'])
7954 - : array();
7955 - $gemini_models = (isset($chat_catalog['gemini']['models']) && is_array($chat_catalog['gemini']['models']))
7956 - ? array_keys($chat_catalog['gemini']['models'])
7957 - : array();
7958 1320
7959 - $is_capable = in_array($current_model, $openai_models) || in_array($current_model, $gemini_models);
7960 - $is_supported = $is_capable && !in_array($current_model, $unsupported_models);
1321 + public function mxchat_send_button_font_color_callback() {
1322 + $disabled = $this->is_activated ? '' : 'disabled';
7961 1323
7962 - // Wrapper div with data attributes for JS to show/hide. data-openai-models is kept for
7963 - // back-compat; data-gemini-models is the added second provider the JS now also honors.
7964 - echo '<div id="web-search-toggle-wrapper" data-openai-models="' . esc_attr(implode(',', $openai_models)) . '" data-gemini-models="' . esc_attr(implode(',', $gemini_models)) . '" data-unsupported-models="' . esc_attr(implode(',', $unsupported_models)) . '"' . (!$is_supported ? ' style="display:none;"' : '') . '>';
1324 + echo '<div class="pro-feature-wrapper">';
1325 + printf(
1326 + '<input type="text" id="send_button_font_color" name="mxchat_options[send_button_font_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
1327 + isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '',
1328 + esc_attr($disabled)
1329 + );
7965 1330
7966 - echo '<label class="toggle-switch">';
7967 - echo sprintf(
7968 - '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
7969 - esc_attr($checked)
7970 - );
7971 - echo '<span class="slider"></span>';
7972 - echo '</label>';
1331 + if (!$this->is_activated) {
1332 + echo '<div class="pro-feature-overlay">';
1333 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1334 + echo '</div>';
1335 + }
7973 1336
7974 - echo '</div>';
1337 + echo '</div>';
1338 + }
7975 1339
7976 - // Message shown when a model that can't ground (Claude, Grok, DeepSeek, OpenRouter, etc.) is selected
7977 - echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
7978 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
7979 - echo esc_html__('Web search is only available for OpenAI and Gemini models.', 'mxchat');
7980 - echo '</p>';
7981 -}
1340 + public function mxchat_chatbot_background_color_callback() {
1341 + $disabled = $this->is_activated ? '' : 'disabled';
7982 1342
7983 -// AJAX handler to fetch OpenRouter models
7984 -public function fetch_openrouter_models() {
7985 - check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
1343 + echo '<div class="pro-feature-wrapper">';
1344 + printf(
1345 + '<input type="text" id="chatbot_background_color" name="mxchat_options[chatbot_background_color]" value="%s" class="my-color-field" data-default-color="#000000" %s />',
1346 + isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '',
1347 + esc_attr($disabled)
1348 + );
7986 1349
7987 - // plan-mxchat-20260731-c63fb6 — nonce is not authorization.
7988 - if (!current_user_can('manage_options')) {
7989 - wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')), 403);
7990 - }
7991 -
7992 - $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
7993 -
7994 - if (empty($api_key)) {
7995 - wp_send_json_error(array('message' => 'API key is required'));
7996 - }
7997 -
7998 - $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
7999 - 'headers' => array(
8000 - 'Authorization' => 'Bearer ' . $api_key,
8001 - 'Content-Type' => 'application/json',
8002 - ),
8003 - 'timeout' => 15,
8004 - ));
8005 -
8006 - if (is_wp_error($response)) {
8007 - wp_send_json_error(array('message' => $response->get_error_message()));
8008 - }
8009 -
8010 - $body = wp_remote_retrieve_body($response);
8011 - $data = json_decode($body, true);
8012 -
8013 - if (isset($data['data']) && is_array($data['data'])) {
8014 - // Format the models for the frontend
8015 - $models = array_map(function($model) {
8016 - return array(
8017 - 'id' => $model['id'],
8018 - 'name' => $model['name'] ?? $model['id'],
8019 - 'description' => $model['description'] ?? '',
8020 - 'context_length' => $model['context_length'] ?? 0,
8021 - 'pricing' => array(
8022 - 'prompt' => $model['pricing']['prompt'] ?? 0,
8023 - 'completion' => $model['pricing']['completion'] ?? 0,
8024 - ),
8025 - );
8026 - }, $data['data']);
8027 -
8028 - wp_send_json_success(array('models' => $models));
8029 - } else {
8030 - wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
8031 - }
8032 -}
8033 -
8034 -// Callback function for embedding model selection
8035 -public function embedding_model_callback() {
8036 - $models = array(
8037 - esc_html__('OpenAI Embeddings', 'mxchat') => array(
8038 - 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
8039 - 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
8040 - 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
8041 - ),
8042 - esc_html__('Voyage AI Embeddings', 'mxchat') => array(
8043 - 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
8044 - ),
8045 - esc_html__('Google Gemini Embeddings', 'mxchat') => array(
8046 - 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
8047 - )
8048 - );
8049 - $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
8050 - // With custom-provider embeddings on, this picker is inert — the effective
8051 - // model comes from the Custom Embedding Model field (plan ae02cb). Autosave
8052 - // fires only on user change events, so the disabled attribute cannot cause
8053 - // a missing-key save; JS keeps the state in sync with the toggle live.
8054 - $custom_embeddings_on = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
8055 - echo '<select id="embedding_model" name="embedding_model"' . ($custom_embeddings_on ? ' disabled' : '') . '>';
8056 - foreach ($models as $group_label => $group_models) {
8057 - echo '<optgroup label="' . esc_attr($group_label) . '">';
8058 - foreach ($group_models as $model_value => $model_label) {
8059 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
1350 + if (!$this->is_activated) {
1351 + echo '<div class="pro-feature-overlay">';
1352 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1353 + echo '</div>';
8060 1354 }
8061 - echo '</optgroup>';
8062 - }
8063 - echo '</select>';
8064 - echo '<p class="mxch-field-description mxchat-embedding-custom-note" id="mxchat_embedding_custom_note"' . ($custom_embeddings_on ? '' : ' style="display:none;"') . '>';
8065 - echo esc_html__('Custom provider embeddings are in use — the model is set in the Custom Embedding Model field under Custom Provider.', 'mxchat');
8066 - echo '</p>';
8067 1355
8068 - // API Key Status Messages for Embedding Models
8069 - $has_openai_key = !empty($this->options['api_key']);
8070 - $has_voyage_key = !empty($this->options['voyage_api_key']);
8071 - $has_gemini_key = !empty($this->options['gemini_api_key']);
8072 -
8073 - // OpenAI Embeddings
8074 - echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
8075 - if ($has_openai_key) {
8076 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8077 - } else {
8078 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1356 + echo '</div>';
8079 1357 }
8080 - echo '</p>';
8081 1358
8082 - // Voyage AI Embeddings
8083 - echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
8084 - if ($has_voyage_key) {
8085 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
8086 - } else {
8087 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8088 - }
8089 - echo '</p>';
1359 + public function mxchat_icon_color_callback() {
1360 + $disabled = $this->is_activated ? '' : 'disabled';
8090 1361
8091 - // Gemini Embeddings
8092 - echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
8093 - if ($has_gemini_key) {
8094 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8095 - } else {
8096 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8097 - }
8098 - echo '</p>';
1362 + echo '<div class="pro-feature-wrapper">';
1363 + printf(
1364 + '<input type="text" id="icon_color" name="mxchat_options[icon_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
1365 + isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '',
1366 + esc_attr($disabled)
1367 + );
8099 1368
8100 -}
1369 + if (!$this->is_activated) {
1370 + echo '<div class="pro-feature-overlay">';
1371 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1372 + echo '</div>';
1373 + }
8101 1374
8102 -
8103 -public function mxchat_top_bar_title_callback() {
8104 - // Retrieve the current value of the top bar title from saved options
8105 - $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
8106 -
8107 - // Render the input field
8108 - echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
8109 -}
8110 -public function mxchat_ai_agent_text_callback() {
8111 - // Retrieve the current value of the AI agent text from saved options
8112 - $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
8113 - // Render the input field
8114 - echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
8115 -}
8116 -
8117 -
8118 -public function enable_email_block_callback() {
8119 - // Load full plugin options array
8120 - $all_options = get_option('mxchat_options', []);
8121 -
8122 - // Get the value, default to 'off'
8123 - $enable_email_block = isset($all_options['enable_email_block']) ? $all_options['enable_email_block'] : 'off';
8124 -
8125 - // Check if it's 'on'
8126 - $checked = ($enable_email_block === 'on') ? 'checked' : '';
8127 -
8128 - echo '<label class="toggle-switch">';
8129 - echo sprintf(
8130 - '<input type="checkbox" id="enable_email_block" name="enable_email_block" value="on" %s />',
8131 - esc_attr($checked)
8132 - );
8133 - echo '<span class="slider"></span>';
8134 - echo '</label>';
8135 -}
8136 -
8137 -public function email_blocker_header_content_callback() {
8138 - // Load the entire 'mxchat_options' array
8139 - $all_options = get_option('mxchat_options', []);
8140 -
8141 - // Retrieve the saved content or default to empty
8142 - $content = isset($all_options['email_blocker_header_content'])
8143 - ? $all_options['email_blocker_header_content']
8144 - : '';
8145 -
8146 - // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
8147 - echo '<textarea
8148 - id="email_blocker_header_content"
8149 - name="email_blocker_header_content"
8150 - rows="5"
8151 - cols="70"
8152 - data-setting="email_blocker_header_content"
8153 - >' . esc_textarea($content) . '</textarea>';
8154 -}
8155 -
8156 -public function email_blocker_button_text_callback() {
8157 - // Load the entire 'mxchat_options' array
8158 - $all_options = get_option('mxchat_options', []);
8159 -
8160 - // Retrieve the saved button text or default to empty
8161 - $button_text = isset($all_options['email_blocker_button_text'])
8162 - ? $all_options['email_blocker_button_text']
8163 - : '';
8164 -
8165 - // Use esc_attr to safely render the existing text
8166 - echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
8167 -}
8168 -
8169 -//Enable name field callback
8170 -public function enable_name_field_callback() {
8171 - // Load full plugin options array
8172 - $all_options = get_option('mxchat_options', []);
8173 - // Get the value, default to 'off'
8174 - $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
8175 - // Check if it's 'on'
8176 - $checked = ($enable_name_field === 'on') ? 'checked' : '';
8177 - echo '<label class="toggle-switch">';
8178 - echo sprintf(
8179 - '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
8180 - esc_attr($checked)
8181 - );
8182 - echo '<span class="slider"></span>';
8183 - echo '</label>';
8184 -}
8185 -//Name field placeholder callback
8186 -public function name_field_placeholder_callback() {
8187 - $all_options = get_option('mxchat_options', []);
8188 - $placeholder = isset($all_options['name_field_placeholder'])
8189 - ? $all_options['name_field_placeholder']
8190 - : esc_html__('Enter your name', 'mxchat');
8191 -
8192 - echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
8193 -}
8194 -
8195 -
8196 -
8197 -public function mxchat_intro_message_callback() {
8198 - // Load the entire 'mxchat_options' array
8199 - $all_options = get_option('mxchat_options', []);
8200 - // Retrieve the saved intro message or use the default
8201 - $default_message = __('Hello! How can I assist you today?', 'mxchat');
8202 - $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
8203 - // Escape on output (esc_textarea) — neutralizes any payload already stored before the
8204 - // Wordfence Stored-XSS fix (CWE-79, plan-3f8158) and prevents </textarea> context-breakout.
8205 - ?>
8206 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea( $saved_message ); ?></textarea>
8207 - <p class="description" style="margin-top: 8px;">
8208 - <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
8209 - <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
8210 - </p>
8211 - <?php
8212 -}
8213 -
8214 -public function mxchat_input_copy_callback() {
8215 - // Load the entire 'mxchat_options' array
8216 - $all_options = get_option('mxchat_options', []);
8217 -
8218 - // Retrieve the saved input copy or use the default value
8219 - $default_copy = __('How can I assist?', 'mxchat');
8220 - $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
8221 -
8222 - // Output the input field with the saved value
8223 - printf(
8224 - '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
8225 - esc_attr($input_copy),
8226 - esc_attr__('How can I assist?', 'mxchat')
8227 - );
8228 -}
8229 -
8230 -
8231 -public function mxchat_append_to_body_callback() {
8232 - // Fetch fresh options to ensure we have the latest saved values
8233 - $options = get_option('mxchat_options', array());
8234 -
8235 - // Get value from options array, default to 'off'
8236 - $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
8237 - $checked = ($append_to_body === 'on') ? 'checked' : '';
8238 -
8239 - // Get post type visibility settings
8240 - $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
8241 - $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
8242 - if (!is_array($visibility_list)) {
8243 - $visibility_list = array();
1375 + echo '</div>';
8244 1376 }
8245 1377
8246 - echo '<div class="mxchat-autosave-section">';
1378 + public function mxchat_chat_input_font_color_callback() {
1379 + $disabled = $this->is_activated ? '' : 'disabled';
8247 1380
8248 - // Main toggle
8249 - echo '<label class="toggle-switch">';
8250 - echo sprintf(
8251 - '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
8252 - esc_attr($checked)
8253 - );
8254 - echo '<span class="slider"></span>';
8255 - echo '</label>';
1381 + echo '<div class="pro-feature-wrapper">';
1382 + printf(
1383 + '<input type="text" id="chat_input_font_color" name="mxchat_options[chat_input_font_color]" value="%s" class="my-color-field" data-default-color="#555555" %s />',
1384 + isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '',
1385 + esc_attr($disabled)
1386 + );
8256 1387
8257 - // Post Type Visibility Options (only visible when auto-display is ON)
8258 - $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
8259 - echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8260 -
8261 - echo '<div class="mxchat-post-type-visibility-header">';
8262 - echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
8263 - echo '</div>';
8264 -
8265 - // Mode selector (radio buttons)
8266 - echo '<div class="mxchat-visibility-mode">';
8267 -
8268 - echo '<label class="mxchat-radio-label">';
8269 - echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
8270 - echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
8271 - echo '</label>';
8272 -
8273 - echo '<label class="mxchat-radio-label">';
8274 - echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
8275 - echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
8276 - echo '</label>';
8277 -
8278 - echo '<label class="mxchat-radio-label">';
8279 - echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
8280 - echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
8281 - echo '</label>';
8282 -
8283 - echo '</div>';
8284 -
8285 - // Post type checkboxes (only visible when mode is include or exclude)
8286 - $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
8287 - echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
8288 -
8289 - // Get all public post types
8290 - $post_types = get_post_types(array('public' => true), 'objects');
8291 -
8292 - foreach ($post_types as $post_type) {
8293 - // Skip attachments
8294 - if ($post_type->name === 'attachment') {
8295 - continue;
1388 + if (!$this->is_activated) {
1389 + echo '<div class="pro-feature-overlay">';
1390 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1391 + echo '</div>';
8296 1392 }
8297 1393
8298 - $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
8299 -
8300 - echo '<label class="mxchat-checkbox-label">';
8301 - echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
8302 - echo '<span>' . esc_html($post_type->label) . '</span>';
8303 - echo '</label>';
1394 + echo '</div>';
8304 1395 }
8305 1396
8306 - echo '</div>'; // End post-type-list
8307 - echo '</div>'; // End post-type-visibility-options
8308 - echo '</div>'; // End mxchat-autosave-section
8309 -}
8310 1397
8311 -public function mxchat_contextual_awareness_callback() {
8312 - // Get value from options array, default to 'off'
8313 - $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
8314 - $checked = ($contextual_awareness === 'on') ? 'checked' : '';
1398 +public function mxchat_append_to_body_callback() {
1399 + $append_to_body_checked = isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on' ? 'checked' : '';
8315 1400 echo '<label class="toggle-switch">';
8316 - echo sprintf(
8317 - '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
8318 - esc_attr($checked)
1401 + printf(
1402 + '<input type="checkbox" id="append_to_body" name="mxchat_options[append_to_body]" %s />',
1403 + esc_attr($append_to_body_checked)
8319 1404 );
8320 1405 echo '<span class="slider"></span>';
8321 1406 echo '</label>';
1407 + echo '<p class="description">Enable to append the chat widget directly to the body element or use shortcode: [mxchat_chatbot floating="yes"]</p>';
8322 1408 }
8323 1409
8324 -public function mxchat_citation_links_toggle_callback() {
8325 - // Get value from options array, default to 'on' (enabled by default)
8326 - $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
8327 - $checked = ($citation_links === 'on') ? 'checked' : '';
8328 - echo '<label class="toggle-switch">';
8329 - echo sprintf(
8330 - '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
8331 - esc_attr($checked)
8332 - );
8333 - echo '<span class="slider"></span>';
8334 - echo '</label>';
8335 -}
8336 1410
8337 -/**
8338 - * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
8339 - * Default ON. The widget reads this through the localized object; the
8340 - * mxchat_satisfaction_rating_enabled filter still lets developers force
8341 - * the value site-wide.
8342 - *
8343 - * The 5 customization fields (idle/question/thanks/placeholder/saved) are
8344 - * rendered inline here inside a single wrapper div whose initial display
8345 - * is set server-side from the toggle value (plan-29caac). Mirrors the
8346 - * auto-display chatbot pattern at mxchat_append_to_body_callback — no
8347 - * DOMContentLoaded race because rows exist as direct children of this
8348 - * callback's output, and the wrapper's display: none is inline at render
8349 - * time so refresh shows the correct state with no flash.
8350 - */
8351 -public function mxchat_satisfaction_rating_toggle_callback() {
8352 - $options = $this->options;
8353 - $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
8354 - $checked = ($value === 'on') ? 'checked' : '';
8355 -
8356 - $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
8357 - $idle = max(5, min(600, $idle));
8358 - $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
8359 - $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
8360 - $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
8361 - $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
8362 -
8363 - echo '<div class="mxchat-autosave-section">';
8364 -
8365 - echo '<label class="toggle-switch">';
8366 - echo sprintf(
8367 - '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
8368 - esc_attr($checked)
8369 - );
8370 - echo '<span class="slider"></span>';
8371 - echo '</label>';
8372 -
8373 - ?>
8374 - <style>
8375 - .mxchat-sub-options-field { margin: 12px 0; }
8376 - .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
8377 - #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
8378 - </style>
8379 - <?php
8380 -
8381 - $display_style = ($value === 'on') ? '' : 'display: none;';
8382 - echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8383 -
8384 - echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
8385 -
8386 - echo '<div class="mxchat-sub-options-field">';
8387 - echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
8388 - printf(
8389 - '<input type="number" id="satisfaction_rating_idle_seconds" name="satisfaction_rating_idle_seconds" value="%d" min="5" max="600" step="1" class="small-text" /> <span class="description">%s</span>',
8390 - (int) $idle,
8391 - esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
8392 - );
8393 - echo '</div>';
8394 -
8395 - echo '<div class="mxchat-sub-options-field">';
8396 - echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
8397 - printf(
8398 - '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8399 - esc_attr($question),
8400 - esc_attr__('Was this helpful?', 'mxchat')
8401 - );
8402 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
8403 - echo '</div>';
8404 -
8405 - echo '<div class="mxchat-sub-options-field">';
8406 - echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
8407 - printf(
8408 - '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
8409 - esc_attr($thanks),
8410 - esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
8411 - );
8412 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
8413 - echo '</div>';
8414 -
8415 - echo '<div class="mxchat-sub-options-field">';
8416 - echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
8417 - printf(
8418 - '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8419 - esc_attr($placeholder),
8420 - esc_attr__('Tell us what could be better…', 'mxchat')
8421 - );
8422 - echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
8423 - echo '</div>';
8424 -
8425 - echo '<div class="mxchat-sub-options-field">';
8426 - echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
8427 - printf(
8428 - '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8429 - esc_attr($saved),
8430 - esc_attr__('Thanks for the feedback.', 'mxchat')
8431 - );
8432 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
8433 - echo '</div>';
8434 -
8435 - echo '</div>'; // #satisfaction-rating-sub-options
8436 - echo '</div>'; // .mxchat-autosave-section
8437 -
8438 - ?>
8439 - <script>
8440 - (function() {
8441 - document.addEventListener('DOMContentLoaded', function() {
8442 - var toggle = document.getElementById('satisfaction_rating_enabled');
8443 - var subOptions = document.getElementById('satisfaction-rating-sub-options');
8444 - if (!toggle || !subOptions) return;
8445 - toggle.addEventListener('change', function() {
8446 - subOptions.style.display = toggle.checked ? '' : 'none';
8447 - });
8448 - });
8449 - })();
8450 - </script>
8451 - <?php
8452 -}
8453 -
8454 1411 public function mxchat_privacy_toggle_callback() {
8455 - // Load from mxchat_options array
8456 - $options = get_option('mxchat_options', []);
1412 + // Check if the privacy toggle is enabled
1413 + $privacy_toggle_checked = isset($this->options['privacy_toggle']) && $this->options['privacy_toggle'] === 'on' ? 'checked' : '';
8457 1414
8458 - // Get privacy toggle value with fallback
8459 - $privacy_toggle = isset($options['privacy_toggle']) ? $options['privacy_toggle'] : 'off';
8460 - $checked = ($privacy_toggle === 'on') ? 'checked' : '';
1415 + // Retrieve the stored privacy text if it exists
1416 + $privacy_text = isset($this->options['privacy_text']) ? wp_kses_post($this->options['privacy_text']) : 'By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.';
8461 1417
8462 - // Get privacy text with fallback
8463 - $privacy_text = isset($options['privacy_text'])
8464 - ? $options['privacy_text']
8465 - : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
8466 -
8467 1418 // Output the toggle switch
8468 1419 echo '<label class="toggle-switch">';
8469 - echo sprintf(
8470 - '<input type="checkbox" id="privacy_toggle" name="privacy_toggle" value="on" %s />',
8471 - esc_attr($checked)
1420 + printf(
1421 + '<input type="checkbox" id="privacy_toggle" name="mxchat_options[privacy_toggle]" %s />',
1422 + esc_attr($privacy_toggle_checked)
8472 1423 );
8473 1424 echo '<span class="slider"></span>';
8474 1425 echo '</label>';
1426 + echo '<p class="description">Enable this option to display a privacy notice below the chat widget.</p>';
8475 1427
8476 1428 // Output the custom text input field
8477 - echo sprintf(
8478 - '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
1429 + printf(
1430 + '<textarea id="privacy_text" name="mxchat_options[privacy_text]" rows="5" cols="50" class="regular-text">%s</textarea>',
8479 1431 esc_textarea($privacy_text)
8480 1432 );
1433 + echo '<p class="description">Enter the privacy policy text. You can include HTML links.</p>';
8481 1434 }
8482 1435
8483 1436
8484 -public function mxchat_complianz_toggle_callback() {
8485 - // Load from mxchat_options array
8486 - $options = get_option('mxchat_options', []);
8487 1437
8488 - // Get complianz toggle value with fallback
8489 - $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
8490 - $checked = ($complianz_toggle === 'on') ? 'checked' : '';
8491 -
8492 - // Output the toggle switch
8493 - echo '<label class="toggle-switch">';
8494 - echo sprintf(
8495 - '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
8496 - esc_attr($checked)
8497 - );
8498 - echo '<span class="slider"></span>';
8499 - echo '</label>';
8500 -}
8501 -
8502 1438 public function mxchat_link_target_toggle_callback() {
8503 - // Load from mxchat_options array
8504 - $options = get_option('mxchat_options', []);
1439 + // Check if the toggle is enabled in the options
1440 + $link_target_toggle = isset($this->options['link_target_toggle']) && $this->options['link_target_toggle'] === 'on' ? 'checked' : '';
8505 1441
8506 - // Get link target toggle value with fallback
8507 - $link_target_toggle = isset($options['link_target_toggle']) ? $options['link_target_toggle'] : 'off';
8508 - $checked = ($link_target_toggle === 'on') ? 'checked' : '';
8509 -
8510 1442 // Output the toggle switch
8511 1443 echo '<label class="toggle-switch">';
8512 - echo sprintf(
8513 - '<input type="checkbox" id="link_target_toggle" name="link_target_toggle" value="on" %s />',
8514 - esc_attr($checked)
1444 + printf(
1445 + '<input type="checkbox" id="link_target_toggle" name="mxchat_options[link_target_toggle]" %s />',
1446 + esc_attr($link_target_toggle)
8515 1447 );
8516 1448 echo '<span class="slider"></span>';
8517 1449 echo '</label>';
1450 + echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
8518 1451 }
8519 1452
8520 -public function mxchat_chat_persistence_toggle_callback() {
8521 - // Load from mxchat_options array
8522 - $options = get_option('mxchat_options', []);
8523 1453
8524 - // Get chat persistence toggle value with fallback
8525 - $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
8526 - $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
8527 1454
8528 - // Output the toggle switch
8529 - echo '<label class="toggle-switch">';
8530 - echo sprintf(
8531 - '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
8532 - esc_attr($checked)
8533 - );
8534 - echo '<span class="slider"></span>';
8535 - echo '</label>';
8536 -}
8537 1455
8538 -public function mxchat_print_button_toggle_callback() {
8539 - // Load from mxchat_options array
8540 - $options = get_option('mxchat_options', []);
1456 + public function mxchat_enqueue_admin_assets() {
1457 + wp_enqueue_style('wp-color-picker');
8541 1458
8542 - // Default ON — the option was previously unexposed and the button always showed.
8543 - $print_button_enabled = isset($options['print_button_enabled']) ? $options['print_button_enabled'] : 'on';
8544 - $checked = ($print_button_enabled === 'on') ? 'checked' : '';
1459 + // Get the plugin version or file modification time for cache busting
1460 + $plugin_version = '1.0.11'; // Replace this with your plugin's version
8545 1461
8546 - // Output the toggle switch
8547 - echo '<label class="toggle-switch">';
8548 - echo sprintf(
8549 - '<input type="checkbox" id="print_button_enabled" name="print_button_enabled" value="on" %s />',
8550 - esc_attr($checked)
8551 - );
8552 - echo '<span class="slider"></span>';
8553 - echo '</label>';
8554 -}
1462 + // File paths
1463 + $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
1464 + $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
1465 + $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
1466 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
8555 1467
8556 -/**
8557 - * Editor Assistant toggle (plan-8cb0cb). Standalone option, NOT in mxchat_options
8558 - * (bypasses the mxchat_sanitize strip-trap + autosave normalization). Default OFF.
8559 - * Saved by the mxchat_editor_assistant_enabled case in class-ajax-handler.php.
8560 - * Renders on Content → Settings (moved there from Settings → Behavior, plan-f7df40).
8561 - */
8562 -public function mxchat_editor_assistant_toggle_callback() {
8563 - $enabled = get_option('mxchat_editor_assistant_enabled', 'off');
8564 - $checked = ($enabled === 'on') ? 'checked' : '';
1468 + // Check if files exist and get modification times
1469 + $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
1470 + $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
1471 + $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
1472 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
1473 +
1474 + // Enqueue scripts and styles with corrected paths
1475 + wp_enqueue_script(
1476 + 'mxchat-color-picker',
1477 + plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
1478 + array('wp-color-picker'),
1479 + $color_picker_version,
1480 + true
1481 + );
8565 1482
8566 - echo '<label class="toggle-switch">';
8567 - echo sprintf(
8568 - '<input type="checkbox" id="mxchat_editor_assistant_enabled" name="mxchat_editor_assistant_enabled" value="on" %s />',
8569 - esc_attr($checked)
8570 - );
8571 - echo '<span class="slider"></span>';
8572 - echo '</label>';
8573 -}
1483 + wp_enqueue_script(
1484 + 'mxchat-embedding-check',
1485 + plugin_dir_url(__FILE__) . '../js/embedding-check.js',
1486 + array(),
1487 + $embedding_check_version,
1488 + true
1489 + );
8574 1490
8575 -/**
8576 - * Hybrid keyword boost toggle (plan-38ffa1; rebuilt on the house toggle pattern
8577 - * in plan-64d34f — the hand-rolled .mxch-toggle markup matched neither selector
8578 - * the autosave JS uses to place its save confirmation, so the control looked
8579 - * dead). Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8580 - * mxchat_hybrid_keyword_toggle case in class-ajax-handler.php, which also runs
8581 - * capability detection on enable.
8582 - */
8583 -public function mxchat_hybrid_keyword_toggle_callback() {
8584 - $enabled = get_option('mxchat_hybrid_keyword_toggle', 'off');
8585 - $checked = ($enabled === 'on') ? 'checked' : '';
1491 + wp_enqueue_script(
1492 + 'mxchat-transcripts-js',
1493 + plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
1494 + array('jquery'),
1495 + $transcripts_js_version,
1496 + true
1497 + );
8586 1498
8587 - echo '<label class="toggle-switch">';
8588 - echo sprintf(
8589 - '<input type="checkbox" id="mxchat_hybrid_keyword_toggle" name="mxchat_hybrid_keyword_toggle" value="on" %s />',
8590 - esc_attr($checked)
8591 - );
8592 - echo '<span class="slider"></span>';
8593 - echo '</label>';
8594 -}
1499 + wp_enqueue_script(
1500 + 'mxchat-admin-js',
1501 + plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
1502 + array('jquery'),
1503 + $plugin_version,
1504 + true
1505 + );
8595 1506
8596 -/**
8597 - * Smart asset loading toggle (plan-915355; rebuilt on the house toggle pattern
8598 - * in plan-64d34f, same dead-save-feedback defect as the hybrid keyword toggle).
8599 - * Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8600 - * mxchat_smart_asset_loading case in class-ajax-handler.php.
8601 - */
8602 -public function mxchat_smart_asset_loading_toggle_callback() {
8603 - $enabled = get_option('mxchat_smart_asset_loading', 'off');
8604 - $checked = ($enabled === 'on') ? 'checked' : '';
1507 + wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
1508 + 'ajax_url' => admin_url('admin-ajax.php'),
1509 + 'nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
1510 + ));
8605 1511
8606 - echo '<label class="toggle-switch">';
8607 - echo sprintf(
8608 - '<input type="checkbox" id="mxchat_smart_asset_loading" name="mxchat_smart_asset_loading" value="on" %s />',
8609 - esc_attr($checked)
8610 - );
8611 - echo '<span class="slider"></span>';
8612 - echo '</label>';
8613 -}
8614 -
8615 -public function mxchat_reset_chat_toggle_callback() {
8616 - // Load from mxchat_options array. plan ac2e81 — default OFF (new, opt-in).
8617 - $options = get_option('mxchat_options', []);
8618 - $reset_chat_enabled = isset($options['reset_chat_enabled']) ? $options['reset_chat_enabled'] : 'off';
8619 - $checked = ($reset_chat_enabled === 'on') ? 'checked' : '';
8620 -
8621 - echo '<label class="toggle-switch">';
8622 - echo sprintf(
8623 - '<input type="checkbox" id="reset_chat_enabled" name="reset_chat_enabled" value="on" %s />',
8624 - esc_attr($checked)
8625 - );
8626 - echo '<span class="slider"></span>';
8627 - echo '</label>';
8628 -}
8629 -
8630 -public function mxchat_reset_chat_label_callback() {
8631 - // Editable label for the "Start new chat" menu item. plan ac2e81.
8632 - $options = get_option('mxchat_options', []);
8633 - $reset_chat_label = isset($options['reset_chat_label']) ? $options['reset_chat_label'] : '';
8634 -
8635 - printf(
8636 - '<input type="text" id="reset_chat_label" name="reset_chat_label" value="%s" placeholder="%s" class="regular-text" />',
8637 - esc_attr($reset_chat_label),
8638 - esc_attr__('Start new chat', 'mxchat')
8639 - );
8640 -}
8641 -
8642 -public function mxchat_popular_question_1_callback() {
8643 - // Load the full plugin options array
8644 - $all_options = get_option('mxchat_options', []);
8645 -
8646 - // Retrieve the specific option for popular_question_1
8647 - $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
8648 -
8649 - // Render the input field
8650 - printf(
8651 - '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
8652 - esc_attr($popular_question_1),
8653 - esc_attr__('Enter Quick Question 1', 'mxchat')
8654 - );
8655 -}
8656 -
8657 -
8658 -public function mxchat_popular_question_2_callback() {
8659 - // Load the full plugin options array
8660 - $all_options = get_option('mxchat_options', []);
8661 -
8662 - // Retrieve the specific option for popular_question_2
8663 - $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
8664 -
8665 - // Render the input field
8666 - printf(
8667 - '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
8668 - esc_attr($popular_question_2),
8669 - esc_attr__('Enter Quick Question 2', 'mxchat')
8670 - );
8671 -}
8672 -
8673 -
8674 -public function mxchat_popular_question_3_callback() {
8675 - // Load the full plugin options array
8676 - $all_options = get_option('mxchat_options', []);
8677 -
8678 - // Retrieve the specific option for popular_question_3
8679 - $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
8680 -
8681 - // Render the input field
8682 - printf(
8683 - '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
8684 - esc_attr($popular_question_3),
8685 - esc_attr(__('Enter Quick Question 3', 'mxchat'))
8686 - );
8687 -}
8688 -
8689 -public function mxchat_additional_popular_questions_callback() {
8690 - $options = get_option('mxchat_options', []);
8691 - $additional_questions = isset($options['additional_popular_questions'])
8692 - ? $options['additional_popular_questions']
8693 - : get_option('additional_popular_questions', array());
8694 -
8695 - echo '<div id="mxchat-additional-questions-container">';
8696 - if (!empty($additional_questions)) {
8697 - foreach ($additional_questions as $index => $question) {
8698 - printf(
8699 - '<div class="mxchat-question-row">
8700 - <input type="text" name="additional_popular_questions[]"
8701 - value="%s"
8702 - placeholder="%s"
8703 - class="regular-text mxchat-question-input"
8704 - data-question-index="%d" />
8705 - <button type="button" class="button mxchat-remove-question"
8706 - aria-label="%s">%s</button>
8707 - </div>',
8708 - esc_attr($question),
8709 - esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
8710 - $index,
8711 - esc_attr(__('Remove question', 'mxchat')),
8712 - esc_html__('Remove', 'mxchat')
8713 - );
8714 - }
8715 - } else {
8716 - printf(
8717 - '<div class="mxchat-question-row">
8718 - <input type="text" name="additional_popular_questions[]"
8719 - value=""
8720 - placeholder="%s"
8721 - class="regular-text mxchat-question-input"
8722 - data-question-index="0" />
8723 - <button type="button" class="button mxchat-remove-question"
8724 - aria-label="%s">%s</button>
8725 - </div>',
8726 - esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
8727 - esc_attr(__('Remove question', 'mxchat')),
8728 - esc_html__('Remove', 'mxchat')
1512 + wp_enqueue_style(
1513 + 'mxchat-admin-css',
1514 + plugin_dir_url(__FILE__) . '../css/admin-style.css',
1515 + array(),
1516 + $admin_css_version
8729 1517 );
8730 - }
8731 - echo '</div>';
8732 - printf(
8733 - '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
8734 - esc_attr(__('Add question', 'mxchat')),
8735 - esc_html__('Add Question', 'mxchat')
8736 - );
8737 -}
8738 1518
8739 -public function mxchat_brave_api_key_callback() {
8740 - $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
8741 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8742 -
8743 - echo '<div class="api-key-wrapper">';
8744 - echo sprintf(
8745 - '<input type="text" id="brave_api_key" name="brave_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
8746 - $brave_api_key,
8747 - $nonce
8748 - );
8749 - echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8750 - echo '</div>';
8751 - echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
8752 -}
8753 -
8754 -public function mxchat_brave_image_count_callback() {
8755 - $brave_image_count = isset($this->options['brave_image_count'])
8756 - ? intval($this->options['brave_image_count'])
8757 - : 4;
8758 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8759 -
8760 - echo '<div class="mxchat-field-wrapper">';
8761 - echo sprintf(
8762 - '<input type="number" id="brave_image_count" name="brave_image_count"
8763 - value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8764 - $brave_image_count,
8765 - $nonce
8766 - );
8767 - echo '</div>';
8768 - echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
8769 -}
8770 -
8771 -public function mxchat_brave_safe_search_callback() {
8772 - $brave_safe_search = isset($this->options['brave_safe_search'])
8773 - ? esc_attr($this->options['brave_safe_search'])
8774 - : 'strict';
8775 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8776 -
8777 - echo '<div class="mxchat-field-wrapper">';
8778 - echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
8779 - echo sprintf(
8780 - '<option value="strict" %s>%s</option>',
8781 - selected($brave_safe_search, 'strict', false),
8782 - __('Strict', 'mxchat')
8783 - );
8784 - echo sprintf(
8785 - '<option value="off" %s>%s</option>',
8786 - selected($brave_safe_search, 'off', false),
8787 - __('Off', 'mxchat')
8788 - );
8789 - echo '</select>';
8790 - echo '</div>';
8791 - echo '<p class="description">' .
8792 - esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
8793 - '</p>';
8794 -}
8795 -
8796 -public function mxchat_brave_news_count_callback() {
8797 - $brave_news_count = isset($this->options['brave_news_count'])
8798 - ? intval($this->options['brave_news_count'])
8799 - : 3;
8800 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8801 -
8802 - echo '<div class="mxchat-field-wrapper">';
8803 - echo sprintf(
8804 - '<input type="number" id="brave_news_count" name="brave_news_count"
8805 - value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8806 - $brave_news_count,
8807 - $nonce
8808 - );
8809 - echo '</div>';
8810 - echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
8811 -}
8812 -
8813 -public function mxchat_brave_country_callback() {
8814 - $brave_country = isset($this->options['brave_country'])
8815 - ? esc_attr($this->options['brave_country'])
8816 - : 'us';
8817 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8818 -
8819 - echo '<div class="mxchat-field-wrapper">';
8820 - echo sprintf(
8821 - '<input type="text" id="brave_country" name="brave_country"
8822 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8823 - $brave_country,
8824 - $nonce
8825 - );
8826 - echo '</div>';
8827 - echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
8828 -}
8829 -
8830 -public function mxchat_brave_language_callback() {
8831 - $brave_language = isset($this->options['brave_language'])
8832 - ? esc_attr($this->options['brave_language'])
8833 - : 'en';
8834 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8835 -
8836 - echo '<div class="mxchat-field-wrapper">';
8837 - echo sprintf(
8838 - '<input type="text" id="brave_language" name="brave_language"
8839 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8840 - $brave_language,
8841 - $nonce
8842 - );
8843 - echo '</div>';
8844 - echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
8845 -}
8846 -
8847 -
8848 -
8849 -
8850 -
8851 -// Section Callback
8852 -public function mxchat_pdf_intent_section_callback() {
8853 - echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
8854 -}
8855 -
8856 -public function mxchat_chat_toolbar_toggle_callback() {
8857 - // Get chat toolbar toggle value with fallback
8858 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
8859 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
8860 -
8861 - // Output the toggle switch
8862 - echo '<label class="toggle-switch">';
8863 - echo sprintf(
8864 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
8865 - esc_attr($checked)
8866 - );
8867 - echo '<span class="slider"></span>';
8868 - echo '</label>';
8869 -
8870 - echo '<p class="description">' . esc_html__('Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).', 'mxchat') . '</p>';
8871 -}
8872 -
8873 -/**
8874 - * Callback for PDF upload button toggle setting
8875 - */
8876 -public function mxchat_show_pdf_upload_button_callback() {
8877 - // Get toggle value with fallback
8878 - $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
8879 - $checked = ($show_pdf_button === 'on') ? 'checked' : '';
8880 -
8881 - // Output the toggle switch
8882 - echo '<label class="toggle-switch">';
8883 - echo sprintf(
8884 - '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
8885 - esc_attr($checked)
8886 - );
8887 - echo '<span class="slider"></span>';
8888 - echo '</label>';
8889 -
8890 - echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
8891 -}
8892 -
8893 -/**
8894 - * Callback for Word upload button toggle setting
8895 - */
8896 -public function mxchat_show_word_upload_button_callback() {
8897 - // Get toggle value with fallback
8898 - $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
8899 - $checked = ($show_word_button === 'on') ? 'checked' : '';
8900 -
8901 - // Output the toggle switch
8902 - echo '<label class="toggle-switch">';
8903 - echo sprintf(
8904 - '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
8905 - esc_attr($checked)
8906 - );
8907 - echo '<span class="slider"></span>';
8908 - echo '</label>';
8909 -
8910 - echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
8911 -}
8912 -
8913 -public function mxchat_pdf_intent_trigger_text_callback() {
8914 - $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
8915 -
8916 - echo sprintf(
8917 - '<textarea id="pdf_intent_trigger_text"
8918 - name="pdf_intent_trigger_text"
8919 - rows="3"
8920 - cols="50"
8921 - placeholder="%s">%s</textarea>',
8922 - esc_attr__('Enter trigger text', 'mxchat'),
8923 - isset($this->options['pdf_intent_trigger_text'])
8924 - ? esc_textarea($this->options['pdf_intent_trigger_text'])
8925 - : esc_textarea($default_text)
8926 - );
8927 - echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
8928 -}
8929 -
8930 -public function mxchat_pdf_intent_success_text_callback() {
8931 - $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
8932 -
8933 - echo sprintf(
8934 - '<textarea id="pdf_intent_success_text"
8935 - name="pdf_intent_success_text"
8936 - rows="3"
8937 - cols="50"
8938 - placeholder="%s">%s</textarea>',
8939 - esc_attr__('Enter success text', 'mxchat'),
8940 - isset($this->options['pdf_intent_success_text'])
8941 - ? esc_textarea($this->options['pdf_intent_success_text'])
8942 - : esc_textarea($default_text)
8943 - );
8944 - echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
8945 -}
8946 -
8947 -public function mxchat_pdf_intent_error_text_callback() {
8948 - $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
8949 -
8950 - echo sprintf(
8951 - '<textarea id="pdf_intent_error_text"
8952 - name="pdf_intent_error_text"
8953 - rows="3"
8954 - cols="50"
8955 - placeholder="%s">%s</textarea>',
8956 - esc_attr__('Enter error text', 'mxchat'),
8957 - isset($this->options['pdf_intent_error_text'])
8958 - ? esc_textarea($this->options['pdf_intent_error_text'])
8959 - : esc_textarea($default_text)
8960 - );
8961 - echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
8962 -}
8963 -
8964 -public function mxchat_pdf_max_pages_callback() {
8965 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
8966 -
8967 - echo sprintf(
8968 - '<input type="range"
8969 - id="pdf_max_pages"
8970 - name="pdf_max_pages"
8971 - min="1"
8972 - max="69"
8973 - value="%d"
8974 - class="range-slider" />',
8975 - esc_attr($max_pages)
8976 - );
8977 - echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
8978 - echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
8979 -}
8980 -
8981 -public function mxchat_live_agent_status_callback() {
8982 - // Always get fresh options instead of using cached $this->options
8983 - $fresh_options = get_option('mxchat_options');
8984 - $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
8985 -
8986 - echo '<label class="toggle-switch">';
8987 - echo sprintf(
8988 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
8989 - checked($status, 'on', false)
8990 - );
8991 - echo '<span class="slider"></span>';
8992 - echo '</label>';
8993 - echo '<label for="live_agent_status" class="mxchat-status-label">';
8994 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
8995 - echo '</label>';
8996 -}
8997 -
8998 -/**
8999 - * Availability-schedule editor (plans 8ccaa2 + 99d7a4).
9000 - *
9001 - * ONE callback, parameterized by channel ('slack' | 'telegram' via the
9002 - * add_settings_field $args) — the markup and CSS are shared, only the bound
9003 - * option and the helper text differ. Each channel's editor renders under its
9004 - * own Integrations tab and governs ONLY that channel's handoff. While the
9005 - * master toggle is off the day grid is inert and handoff availability stays
9006 - * governed solely by that channel's manual status toggle.
9007 - *
9008 - * The day inputs carry NO name attribute and are marked .mxchat-la-field so the
9009 - * generic autosave skips them; the editor JS folds them into the channel's
9010 - * hidden live_agent_schedule_<channel> input and fires one change, reusing the
9011 - * existing autosave transport rather than growing a second one. All hooks the
9012 - * JS needs are CLASSES scoped inside .mxchat-la-schedule, never ids — the
9013 - * markup exists twice on the page.
9014 - */
9015 -public function mxchat_live_agent_schedule_callback($args = array()) {
9016 - if (!class_exists('MxChat_Live_Agent_Schedule')) {
9017 - return;
1519 + // Use wp_json_encode for localizing script
1520 + wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
1521 + 'ajax_url' => admin_url('admin-ajax.php'),
1522 + 'link_target' => $link_target,
1523 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
1524 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
1525 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
1526 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
1527 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
1528 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
1529 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
1530 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
1531 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
1532 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121'
1533 + ));
9018 1534 }
9019 - $channel = (isset($args['channel']) && $args['channel'] === 'telegram') ? 'telegram' : 'slack';
9020 - $field = 'live_agent_schedule_' . $channel;
9021 - $sched = MxChat_Live_Agent_Schedule::get($channel);
9022 - $labels = MxChat_Live_Agent_Schedule::day_labels();
9023 - $tz = MxChat_Live_Agent_Schedule::timezone_label();
9024 - $enabled = !empty($sched['enabled']);
9025 - $channel_label = ($channel === 'telegram') ? __('Telegram', 'mxchat') : __('Slack', 'mxchat');
9026 - ?>
9027 - <div class="mxchat-la-schedule<?php echo $enabled ? ' is-active' : ''; ?>"
9028 - id="mxchat-la-schedule-<?php echo esc_attr($channel); ?>"
9029 - data-channel="<?php echo esc_attr($channel); ?>">
9030 - <label class="toggle-switch">
9031 - <input type="checkbox" id="<?php echo esc_attr($field); ?>_enabled"
9032 - class="mxchat-la-field mxchat-la-enabled" <?php checked($enabled); ?> />
9033 - <span class="slider"></span>
9034 - </label>
9035 - <label for="<?php echo esc_attr($field); ?>_enabled" class="mxchat-status-label">
9036 - <span class="status-text mxchat-la-status-text">
9037 - <?php echo $enabled
9038 - ? esc_html__('Scheduled hours', 'mxchat')
9039 - : esc_html__('Always available', 'mxchat'); ?>
9040 - </span>
9041 - </label>
9042 1535
9043 - <div class="mxchat-la-days" aria-hidden="<?php echo $enabled ? 'false' : 'true'; ?>">
9044 - <?php foreach ($labels as $n => $label) :
9045 - $day = $sched['days'][$n];
9046 - $on = !empty($day['enabled']);
9047 - ?>
9048 - <div class="mxchat-la-day<?php echo $on ? ' is-on' : ''; ?>" data-day="<?php echo esc_attr($n); ?>">
9049 - <label class="mxchat-la-day-label">
9050 - <input type="checkbox" class="mxchat-la-field mxchat-la-day-enabled"
9051 - data-day="<?php echo esc_attr($n); ?>" <?php checked($on); ?> />
9052 - <span class="mxchat-la-day-name"><?php echo esc_html($label); ?></span>
9053 - </label>
9054 - <div class="mxchat-la-times">
9055 - <input type="time" class="mxchat-la-field mxchat-la-start"
9056 - data-day="<?php echo esc_attr($n); ?>"
9057 - value="<?php echo esc_attr($day['start']); ?>"
9058 - aria-label="<?php echo esc_attr(sprintf(__('%s start time', 'mxchat'), $label)); ?>" />
9059 - <span class="mxchat-la-dash">&ndash;</span>
9060 - <input type="time" class="mxchat-la-field mxchat-la-end"
9061 - data-day="<?php echo esc_attr($n); ?>"
9062 - value="<?php echo esc_attr($day['end']); ?>"
9063 - aria-label="<?php echo esc_attr(sprintf(__('%s end time', 'mxchat'), $label)); ?>" />
9064 - </div>
9065 - </div>
9066 - <?php endforeach; ?>
9067 - </div>
1536 + public function mxchat_sanitize($input) {
1537 + $new_input = array();
9068 1538
9069 - <input type="hidden" name="<?php echo esc_attr($field); ?>" id="<?php echo esc_attr($field); ?>"
9070 - class="mxchat-la-hidden" value="<?php echo esc_attr(wp_json_encode($sched)); ?>" />
9071 - </div>
9072 - <p class="description">
9073 - <?php printf(
9074 - /* translators: 1: the handoff channel, e.g. Slack or Telegram; 2: the site's timezone, e.g. America/New_York */
9075 - esc_html__('When on, visitors are only offered a %1$s human handoff during these hours — outside them the chatbot keeps answering and never offers to fetch an agent. Applies to %1$s only. Times use the site timezone (%2$s). Set a day\'s end time earlier than its start for an overnight shift; identical start and end means all day.', 'mxchat'),
9076 - '<strong>' . esc_html($channel_label) . '</strong>',
9077 - '<strong>' . esc_html($tz) . '</strong>'
9078 - ); ?>
9079 - </p>
9080 - <?php
9081 -}
1539 + if (isset($input['api_key'])) {
1540 + $new_input['api_key'] = sanitize_text_field($input['api_key']);
1541 + }
9082 1542
9083 -public function mxchat_live_agent_away_message_callback() {
9084 - $message = isset($this->options['live_agent_away_message'])
9085 - ? $this->options['live_agent_away_message']
9086 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
1543 + if (isset($input['enable_woocommerce_integration'])) {
1544 + $new_input['enable_woocommerce_integration'] = isset($input['enable_woocommerce_integration']) && $input['enable_woocommerce_integration'] === '1' ? '1' : '0';
9087 1545
9088 - printf(
9089 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
9090 - esc_textarea($message)
9091 - );
9092 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9093 -}
1546 + }
1547 +
1548 + if (isset($input['privacy_toggle'])) {
1549 + $new_input['privacy_toggle'] = $input['privacy_toggle'];
1550 + }
1551 +
1552 + // Handle custom privacy text input
1553 + if (isset($input['privacy_text'])) {
1554 + // Allow basic HTML for links
1555 + $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
1556 + }
9094 1557
9095 -public function mxchat_live_agent_notification_message_callback() {
9096 - $message = isset($this->options['live_agent_notification_message'])
9097 - ? $this->options['live_agent_notification_message']
9098 - : __('Live agent has been notified.', 'mxchat');
1558 +
1559 + if (isset($input['enable_woocommerce_order_access'])) {
1560 + $new_input['enable_woocommerce_order_access'] = isset($input['enable_woocommerce_order_access']) && $input['enable_woocommerce_order_access'] === '1' ? '1' : '0';
9099 1561
9100 - printf(
9101 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
9102 - esc_textarea($message)
9103 - );
9104 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9105 -}
1562 + }
9106 1563
9107 -public function mxchat_live_agent_webhook_url_callback() {
9108 - $webhook_url = isset($this->options['live_agent_webhook_url'])
9109 - ? esc_url($this->options['live_agent_webhook_url'])
9110 - : esc_url(get_option('live_agent_webhook_url', ''));
1564 + if (isset($input['system_prompt_instructions'])) {
1565 + $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
1566 + }
9111 1567
9112 - printf(
9113 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
9114 - $webhook_url
9115 - );
9116 - echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9117 - echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
9118 -}
1568 + if (isset($input['mxchat_pro_email'])) {
1569 + $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
1570 + }
9119 1571
9120 -public function mxchat_live_agent_secret_key_callback() {
9121 - printf(
9122 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
9123 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
9124 - );
9125 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9126 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
9127 -}
1572 + if (isset($input['mxchat_activation_key'])) {
1573 + $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
1574 + }
9128 1575
9129 -public function mxchat_live_agent_bot_token_callback() {
9130 - printf(
9131 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
9132 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
9133 - );
9134 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9135 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
9136 -}
1576 + if (isset($input['append_to_body'])) {
1577 + $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
1578 + }
9137 1579
9138 -public function mxchat_live_agent_user_ids_callback() {
9139 - $user_ids = isset($this->options['live_agent_user_ids'])
9140 - ? esc_textarea($this->options['live_agent_user_ids'])
9141 - : '';
1580 + if (isset($input['top_bar_title'])) {
1581 + $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
1582 + }
9142 1583
9143 - printf(
9144 - '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
9145 - $user_ids
9146 - );
9147 - echo '<p class="description">' . esc_html__('Enter Slack User IDs of agents who should be automatically invited to chat channels (one per line). Find user IDs in Slack profiles under "More" → "Copy member ID". Example: U1234567890', 'mxchat') . '</p>';
9148 -}
1584 + if (isset($input['intro_message'])) {
1585 + $new_input['intro_message'] = sanitize_text_field($input['intro_message']);
1586 + }
1587 +
1588 + if (isset($input['input_copy'])) {
1589 + $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
1590 + }
9149 1591
9150 -public function mxchat_live_agent_shared_channel_callback() {
9151 - $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : '';
9152 - printf(
9153 - '<input type="text" id="live_agent_shared_channel" name="live_agent_shared_channel" value="%s" class="regular-text" placeholder="#support or C0123456789" />',
9154 - esc_attr($value)
9155 - );
9156 - echo '<p class="description">' . esc_html__('Optional. Route ALL live agent handoffs into this one existing Slack channel — each conversation becomes its own thread there. Enter a channel ID (starts with C) or a #channel-name, and invite your bot to the channel first (/invite @YourBot). Agents reply inside a conversation\'s thread; !endchat inside the thread ends that chat. Leave blank to keep creating a separate chat- channel per conversation.', 'mxchat') . '</p>';
9157 1592
9158 - // Surface the last failed handoff so a wrong name / missing invite is
9159 - // visible right where it gets fixed. A successful handoff clears this.
9160 - $shared_error = get_option('mxchat_slack_shared_channel_error');
9161 - if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) {
9162 - echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . '</strong> — '
9163 - . esc_html(sprintf(
9164 - /* translators: %s: Slack API error code */
9165 - __('Slack said "%s". Handoffs are falling back to per-conversation channels until this is fixed. Check the channel name or ID and make sure the bot has been invited to it.', 'mxchat'),
9166 - $shared_error['error']
9167 - )) . '</p>';
9168 - }
9169 -}
1593 + if (isset($input['rate_limit_message'])) {
1594 + $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
1595 + }
9170 1596
9171 -public function mxchat_live_agent_archive_on_end_callback() {
9172 - $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off';
9173 - printf(
9174 - '<input type="checkbox" id="live_agent_archive_on_end_toggle" name="live_agent_archive_on_end_toggle" value="on" %s />',
9175 - checked('on', $value, false)
9176 - );
9177 - echo '<label for="live_agent_archive_on_end_toggle" class="mxchat-status-label">' . esc_html__('Archive the conversation\'s chat- channel when an agent ends the chat with !endchat', 'mxchat') . '</label>';
9178 - echo '<p class="description">' . esc_html__('Keeps your Slack sidebar tidy on busy sites — each ended conversation\'s channel is archived instead of living forever. Archived channels stay searchable in Slack, so the record is never lost. Only applies to per-conversation chat- channels; a Shared Handoff Channel is never archived. If a returning visitor requests an agent again, a fresh channel is created automatically.', 'mxchat') . '</p>';
9179 -}
9180 1597
9181 -/**
9182 - * Telegram Integration Callbacks
9183 - */
9184 -public function mxchat_telegram_section_callback() {
9185 - echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
9186 -}
9187 -
9188 -public function mxchat_telegram_status_callback() {
9189 - $fresh_options = get_option('mxchat_options');
9190 - $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
9191 -
9192 - echo '<label class="toggle-switch">';
9193 - echo sprintf(
9194 - '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
9195 - checked($status, 'on', false)
9196 - );
9197 - echo '<span class="slider"></span>';
9198 - echo '</label>';
9199 - echo '<label for="telegram_status" class="mxchat-status-label">';
9200 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9201 - echo '</label>';
9202 -}
9203 -
9204 -public function mxchat_telegram_notification_message_callback() {
9205 - $message = isset($this->options['telegram_notification_message'])
9206 - ? $this->options['telegram_notification_message']
9207 - : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
9208 -
9209 - printf(
9210 - '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
9211 - esc_textarea($message)
9212 - );
9213 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9214 -}
9215 -
9216 -public function mxchat_telegram_away_message_callback() {
9217 - $message = isset($this->options['telegram_away_message'])
9218 - ? $this->options['telegram_away_message']
9219 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9220 -
9221 - printf(
9222 - '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
9223 - esc_textarea($message)
9224 - );
9225 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9226 -}
9227 -
9228 -public function mxchat_telegram_bot_token_callback() {
9229 - printf(
9230 - '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
9231 - isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
9232 - );
9233 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_bot_token\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9234 - echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
9235 -}
9236 -
9237 -public function mxchat_telegram_group_id_callback() {
9238 - printf(
9239 - '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
9240 - isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
9241 - );
9242 - echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
9243 -}
9244 -
9245 -public function mxchat_telegram_webhook_secret_callback() {
9246 - $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
9247 -
9248 - // Auto-generate secret if empty
9249 - if (empty($secret)) {
9250 - $secret = wp_generate_password(64, false, false);
9251 - $options = get_option('mxchat_options', []);
9252 - $options['telegram_webhook_secret'] = $secret;
9253 - update_option('mxchat_options', $options);
9254 - $this->options['telegram_webhook_secret'] = $secret;
9255 - }
9256 -
9257 - printf(
9258 - '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
9259 - esc_attr($secret)
9260 - );
9261 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_webhook_secret\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9262 - echo '<p class="description">' . esc_html__('Secret token for webhook verification. Use this when setting up your Telegram webhook with the secret_token parameter.', 'mxchat') . '</p>';
9263 -}
9264 -
9265 -public function mxchat_similarity_threshold_callback() {
9266 - // Load from mxchat_options array
9267 - $options = get_option('mxchat_options', []);
9268 -
9269 - // Get value from options array with default of 35
9270 - $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
9271 -
9272 - echo '<div class="slider-container">';
9273 - echo sprintf(
9274 - '<input type="range"
9275 - id="similarity_threshold"
9276 - name="similarity_threshold"
9277 - min="20"
9278 - max="85"
9279 - step="1"
9280 - value="%s"
9281 - class="range-slider" />',
9282 - esc_attr($threshold)
9283 - );
9284 - echo sprintf(
9285 - '<span id="threshold_value" class="range-value">%s</span>',
9286 - esc_html($threshold)
9287 - );
9288 - echo '</div>';
9289 -}
9290 -
9291 -public function mxchat_max_input_length_callback() {
9292 - // Load from mxchat_options array (plan a3fae2 part C).
9293 - $options = get_option('mxchat_options', []);
9294 -
9295 - // 0 = unlimited (default — preserves current behavior, no cap).
9296 - $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0;
9297 -
9298 - echo sprintf(
9299 - '<input type="number"
9300 - id="max_input_length"
9301 - name="max_input_length"
9302 - min="0"
9303 - max="100000"
9304 - step="1"
9305 - value="%s"
9306 - placeholder="0"
9307 - class="mxch-input mxch-input-sm" />',
9308 - esc_attr($max_input_length)
9309 - );
9310 -}
9311 -
9312 -public function mxchat_rag_sources_limit_callback() {
9313 - // Load from mxchat_options array
9314 - $options = get_option('mxchat_options', []);
9315 -
9316 - // Get value from options array with default of 3
9317 - $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
9318 -
9319 - echo '<div class="slider-container">';
9320 - echo sprintf(
9321 - '<input type="range"
9322 - id="rag_sources_limit"
9323 - name="rag_sources_limit"
9324 - min="3"
9325 - max="10"
9326 - step="1"
9327 - value="%s"
9328 - class="range-slider" />',
9329 - esc_attr($rag_sources_limit)
9330 - );
9331 - echo sprintf(
9332 - '<span id="rag_sources_limit_value" class="range-value">%s</span>',
9333 - esc_html($rag_sources_limit)
9334 - );
9335 - echo '</div>';
9336 -}
9337 -
9338 -public function mxchat_rag_chunks_limit_callback() {
9339 - // Load from mxchat_options array
9340 - $options = get_option('mxchat_options', []);
9341 -
9342 - // Get value from options array with default of 15
9343 - $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
9344 -
9345 - echo '<div class="slider-container">';
9346 - echo sprintf(
9347 - '<input type="range"
9348 - id="rag_chunks_limit"
9349 - name="rag_chunks_limit"
9350 - min="8"
9351 - max="20"
9352 - step="1"
9353 - value="%s"
9354 - class="range-slider" />',
9355 - esc_attr($rag_chunks_limit)
9356 - );
9357 - echo sprintf(
9358 - '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
9359 - esc_html($rag_chunks_limit)
9360 - );
9361 - echo '</div>';
9362 -}
9363 -
9364 -/**
9365 - * Add body class on the Onboarding wizard page so CSS-only chrome surgery
9366 - * (collapsing the WP admin sidebar) only applies on this page.
9367 - * Plan: plan-mxchat-20260527-905439.
9368 - */
9369 -public function mxchat_add_onboarding_body_class($classes) {
9370 - if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') {
9371 - $classes .= ' mxchat-onboarding-focused';
9372 - }
9373 - return $classes;
9374 -}
9375 -
9376 -public function mxchat_enqueue_admin_assets($hook_suffix = '') {
9377 - // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY
9378 - // guard here was the strpos() on $_GET['page'] below — which is
9379 - // attacker-controlled — so ANY logged-in user (Subscriber included) could
9380 - // load a page they are legitimately allowed to see, e.g.
9381 - // /wp-admin/profile.php?page=mxchat, and receive every nonce this method
9382 - // localizes. Three of the handlers behind those nonces verified the nonce
9383 - // but checked no capability. Every MxChat menu page is registered
9384 - // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for
9385 - // legitimate users.
9386 - if (!current_user_can('manage_options')) {
9387 - return;
9388 - }
9389 -
9390 - // Get plugin version
9391 - $version = MXCHAT_VERSION;
9392 -
9393 - // Use file modification time for development (remove in production)
9394 - if (defined('WP_DEBUG') && WP_DEBUG) {
9395 - $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
9396 - }
9397 -
9398 - $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
9399 - $plugin_url = plugin_dir_url(__FILE__) . '../';
9400 -
9401 - // Only load on MxChat pages. Prefer the server-derived $hook_suffix that
9402 - // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be
9403 - // forged onto a screen MxChat does not own. Falls back to the legacy
9404 - // $_GET check only when the hook is unavailable (direct/legacy callers).
9405 - if ($hook_suffix !== '') {
9406 - if (strpos($hook_suffix, 'mxchat') === false) {
9407 - return;
1598 + if (isset($input['pre_chat_message'])) {
1599 + $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
9408 1600 }
9409 - } elseif (strpos($current_page, 'mxchat') === false) {
9410 - return;
9411 - }
9412 1601
9413 - // Always load these on all MxChat pages
9414 - $this->enqueue_core_admin_assets($plugin_url, $version);
9415 - $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
9416 - $this->localize_admin_scripts($current_page);
9417 -}
9418 -private function enqueue_core_admin_assets($plugin_url, $version) {
9419 - // Core admin styles
9420 - wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
9421 - wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
9422 -
9423 - // New sidebar navigation styles (for main settings page)
9424 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9425 -
9426 - // Core admin scripts
9427 - wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
9428 -}
9429 -private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
9430 - switch ($current_page) {
9431 - case 'mxchat-prompts':
9432 - // Shared shell JS: tab switching, deep-linking and the mobile menu
9433 - // for this page's flat nav (inline copies removed by plan c192a4).
9434 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9435 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9436 - 'copied' => __('Copied', 'mxchat'),
9437 - ));
9438 - // Knowledge processing page assets
9439 - wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
9440 - wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
9441 - // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
9442 - wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
9443 - // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the
9444 - // Testing tab's match-card / chunk-detail components, which are scoped
9445 - // under .mxch-testing-results. Load that stylesheet here so the inspector
9446 - // modal renders identically to the Testing tab.
9447 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version);
9448 - break;
9449 -
9450 - case 'mxchat-transcripts':
9451 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9452 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9453 - // Load transcripts-specific styles
9454 - wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
9455 - wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
9456 - break;
9457 -
9458 - case 'mxchat-actions':
9459 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9460 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9461 - // Load actions-specific styles
9462 - wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
9463 - wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
9464 -
9465 - // Localize script data for actions page
9466 - $is_activated = get_option('mxchat_pro_license_status') === 'active';
9467 - wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
9468 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9469 - 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
9470 - 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9471 - 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
9472 - 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
9473 - 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
9474 - 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9475 - 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9476 - 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9477 - 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9478 - 'isActivated' => $is_activated,
9479 - 'i18n' => array(
9480 - 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'),
9481 - 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'),
9482 - 'saving' => __('Saving...', 'mxchat'),
9483 - 'saved' => __('Saved successfully!', 'mxchat'),
9484 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9485 - 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
9486 - 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
9487 - )
9488 - ));
9489 - break;
9490 -
9491 - case 'mxchat-activation':
9492 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9493 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9494 - // Load pro page-specific styles
9495 - wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
9496 - // Load pro page JavaScript
9497 - wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
9498 - // Load activation script for license activation/deactivation
9499 - wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
9500 - break;
9501 -
9502 - case 'mxchat-content':
9503 - // Load admin sidebar CSS (shared styles for sidebar navigation)
9504 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9505 - // Load content page-specific styles
9506 - wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
9507 - // Load content page JavaScript
9508 - wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
9509 - break;
9510 -
9511 - case 'mxchat-api-access':
9512 - // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
9513 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9514 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9515 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9516 - 'copied' => __('Copied', 'mxchat'),
9517 - ));
9518 - break;
9519 -
9520 - case 'mxchat-max':
9521 - case 'mxchat-onboarding':
9522 - // Onboarding page — uses the shared admin shell PLUS the wizard
9523 - // overlay (plan-905439). admin-onboarding-wizard.css scopes the
9524 - // WP-chrome surgery to body.mxchat-onboarding-focused so it only
9525 - // applies on THIS page. The body class is added below via the
9526 - // admin_body_class filter.
9527 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9528 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9529 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9530 - 'copied' => __('Copied', 'mxchat'),
9531 - ));
9532 - // admin-style.css provides the .mxchat-instructions-modal-* classes
9533 - // the new Behavior step's "View Sample Instructions" modal needs.
9534 - // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay
9535 - // so the wizard's own rules win where they collide. plan-a2e4d6.
9536 - wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version);
9537 - wp_enqueue_style('mxchat-admin-onboarding-wizard-css', $plugin_url . 'css/admin-onboarding-wizard.css', array('mxchat-admin-sidebar-css', 'mxchat-admin-style-css'), $version);
9538 - wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true);
9539 - break;
9540 - default:
9541 - // Settings page: load the shared shell JS for #hash deep-linking
9542 - // to tabs (plan 4ede16). The page's own inline nav script owns
9543 - // clicks/accordion behaviour; the shell script adds load +
9544 - // hashchange activation and replaceState so plain href="#tab"
9545 - // anchors and shared URLs land on the right tab. Kept inside the
9546 - // default case because the settings page also needs everything
9547 - // below (Testing tab chatbot + streaming assets).
9548 - if ($current_page === 'mxchat-settings') {
9549 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9550 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9551 - 'copied' => __('Copied', 'mxchat'),
9552 - ));
1602 + if (isset($input['model'])) {
1603 + $allowed_models = array(
1604 + 'gpt-4o',
1605 + 'gpt-4o-mini',
1606 + 'gpt-4-turbo',
1607 + 'gpt-4',
1608 + 'gpt-3.5-turbo',
1609 + );
1610 + if (in_array($input['model'], $allowed_models)) {
1611 + $new_input['model'] = sanitize_text_field($input['model']);
9553 1612 }
1613 + }
9554 1614
9555 - wp_enqueue_script(
9556 - 'mxchat-test-streaming-js',
9557 - $plugin_url . 'js/mxchat-test-streaming.js',
9558 - ['jquery'],
9559 - $version,
9560 - true
9561 - );
9562 -
9563 - wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
9564 - 'ajax_url' => admin_url('admin-ajax.php'),
9565 - 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
9566 - 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
9567 - ]);
9568 -
9569 - // Testing Tab: Load chatbot assets for the embedded testing chatbot
9570 - wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
9571 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
9572 -
9573 - wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
9574 - wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
9575 -
9576 - // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
9577 - do_action('mxchat_enqueue_testing_tab_assets');
9578 -
9579 - // Localize mxchatChat for the chatbot JS (same settings as frontend)
9580 - $options = get_option('mxchat_options', array());
9581 - $prompts_options = get_option('mxchat_prompts_options', array());
9582 - $theme_options = get_option('mxchat_theme_options', array());
9583 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
9584 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
9585 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
9586 -
9587 - wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
9588 - 'ajax_url' => admin_url('admin-ajax.php'),
9589 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
9590 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
9591 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
9592 - 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
9593 - 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
9594 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9595 - 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
9596 - 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
9597 - 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
9598 - 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
9599 - 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
9600 - 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
9601 - 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
9602 - 'close_button_color' => $options['close_button_color'] ?? '#fff',
9603 - 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
9604 - 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
9605 - 'icon_color' => $options['icon_color'] ?? '#fff',
9606 - 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
9607 - 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
9608 - 'appendWidgetToBody' => 'off',
9609 - 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
9610 - 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
9611 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
9612 - 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
9613 - 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
9614 - 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
9615 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
9616 - 'email_collection_enabled' => 'off', // No email collection in testing
9617 - 'initial_email_state' => null,
9618 - 'skip_email_check' => true,
9619 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
9620 - 'skip_inline_colors' => $skip_inline_colors,
9621 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
9622 - ));
9623 -
9624 - // Localize testing tab script data
9625 - wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
9626 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9627 - 'nonce' => wp_create_nonce('mxchat_test_nonce'),
9628 - 'isAdmin' => true,
9629 - 'testingEnabled' => true
9630 - ));
9631 -
9632 - // Add testing enabled flag for the chatbot to return debug data
9633 - add_action('admin_footer', function() {
9634 - echo '<script>window.mxchatTestingEnabled = true;</script>';
9635 - });
9636 -
9637 - break;
9638 - }
9639 -}
9640 -/**
9641 - * The base mxchatAdmin payload shared by every MxChat admin page.
9642 - *
9643 - * Extracted (plan c192a4) so page-specific re-localizations of the SAME
9644 - * global — the knowledge page prints a second `var mxchatAdmin` via the
9645 - * mxchat-knowledge-processing handle, and last-printed wins — can merge
9646 - * their extra keys on top of this instead of silently narrowing the object
9647 - * that mxchat-admin.js also reads on that page.
9648 - */
9649 -private function mxchat_get_admin_base_localization() {
9650 - return array(
9651 - 'ajax_url' => admin_url('admin-ajax.php'),
9652 - 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
9653 - 'admin_url' => admin_url(),
9654 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
9655 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
9656 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9657 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9658 - 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9659 - 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9660 - 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
9661 - 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9662 - 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9663 - 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9664 - 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9665 - 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9666 - 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
9667 - 'is_activated' => $this->is_activated ? '1' : '0',
9668 - 'status_refresh_interval' => 5000,
9669 - 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'),
9670 - 'unsaved_label' => __('Unsaved', 'mxchat'),
9671 - // Live-agent schedule status text (plan 8ccaa2).
9672 - 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'),
9673 - 'i18n_always_available' => __('Always available', 'mxchat'),
9674 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9675 - 'ajaxurl' => admin_url('admin-ajax.php')
9676 - );
9677 -}
9678 -private function localize_admin_scripts($current_page) {
9679 - // Base localization data for main admin script
9680 - $base_data = $this->mxchat_get_admin_base_localization();
9681 -
9682 - // Localize main admin script with base data
9683 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
9684 -
9685 - // Canonical chat-model catalog for the modal picker grid
9686 - // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php
9687 - // automatically appears here.
9688 - if (!class_exists('MxChat_Model_Catalog')) {
9689 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
9690 - }
9691 - wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape());
9692 -
9693 - // Page-specific localizations
9694 - $this->localize_page_specific_scripts($current_page);
9695 -}
9696 -private function localize_page_specific_scripts($current_page) {
9697 - switch ($current_page) {
9698 - case 'mxchat-prompts':
9699 - // Status updater localization
9700 - wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
9701 - 'ajax_url' => admin_url('admin-ajax.php'),
9702 - 'nonce' => wp_create_nonce('mxchat_status_nonce')
9703 - ));
9704 -
9705 - // Content selector localization
9706 - wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
9707 - 'ajaxurl' => admin_url('admin-ajax.php'),
9708 - 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
9709 - 'i18n' => array(
9710 - 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
9711 - 'selectAll' => __('Select All', 'mxchat'),
9712 - 'process' => __('Process Selected', 'mxchat'),
9713 - 'cancel' => __('Cancel', 'mxchat'),
9714 - 'noResults' => __('No content found.', 'mxchat'),
9715 - 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
9716 - 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
9717 - )
9718 - ));
9719 -
9720 - // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's
9721 - // base one) and last-printed wins — so it must carry the FULL base
9722 - // payload plus the knowledge-page extras, or every mxchatAdmin.*
9723 - // key mxchat-admin.js reads on this page comes up undefined
9724 - // (plan c192a4). Extras merge last: status_refresh_interval stays
9725 - // at this page's faster 2000ms cadence.
9726 - wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge(
9727 - $this->mxchat_get_admin_base_localization(),
9728 - array(
9729 - 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
9730 - 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
9731 - 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
9732 - 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9733 - 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
9734 - 'status_refresh_interval' => 2000,
9735 - 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
9736 - )
9737 - ));
9738 - break;
9739 -
9740 - case 'mxchat-activation':
9741 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9742 - // fixed here by a5b297): this second `var mxchatAdmin` must carry
9743 - // the full base payload plus the page extras.
9744 - wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge(
9745 - $this->mxchat_get_admin_base_localization(),
9746 - array(
9747 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
9748 - )
9749 - ));
9750 - break;
9751 -
9752 - case 'mxchat-content':
9753 - wp_localize_script('mxchat-content-js', 'mxchatContent', array(
9754 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9755 - 'nonce' => wp_create_nonce('mxchat_content_nonce'),
9756 - 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9757 - 'previewUrl' => home_url('/?p='),
9758 - 'isActivated' => $this->is_activated(),
9759 - 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
9760 - 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
9761 - // Whether Search Console is actually LINKED — distinct from hasGSC
9762 - // (add-on active). Reads the same option the add-on's settings
9763 - // card keys off; harmless false when the add-on is absent.
9764 - 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false),
9765 - 'seoOptimize' => array(
9766 - 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
9767 - 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
9768 - 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
9769 - 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
9770 - 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
9771 - 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
9772 - 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
9773 - ),
9774 - 'i18n' => array(
9775 - 'generating' => __('Generating...', 'mxchat'),
9776 - 'planning' => __('Planning content structure...', 'mxchat'),
9777 - 'images' => __('Generating images...', 'mxchat'),
9778 - 'writing' => __('Writing full content...', 'mxchat'),
9779 - 'creating' => __('Creating WordPress post...', 'mxchat'),
9780 - 'done' => __('Content generated successfully!', 'mxchat'),
9781 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9782 - 'editSuccess' => __('Content updated successfully.', 'mxchat'),
9783 - 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
9784 - )
9785 - ));
9786 - break;
9787 -
9788 - case 'mxchat-transcripts':
9789 - // Get chart data for localization
9790 - $chart_data = $this->get_transcripts_chart_data();
9791 -
9792 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9793 - // fixed here by a5b297): merge the base payload under the page keys.
9794 - // export_nonce/setting_nonce/ajax_url duplicate base values identically;
9795 - // delete_nonce and translate_nonce are the page-specific adds.
9796 - wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge(
9797 - $this->mxchat_get_admin_base_localization(),
9798 - array(
9799 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9800 - 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
9801 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9802 - 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
9803 - )
9804 - ));
9805 -
9806 - // Localize chart data separately - use array_values to ensure proper JSON array encoding
9807 - wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
9808 - 'labels' => array_values($chart_data['labels']),
9809 - 'chats' => array_values($chart_data['chats']),
9810 - 'messages' => array_values($chart_data['messages'])
9811 - ));
9812 - break;
9813 -
9814 - case 'mxchat-settings':
9815 - default:
9816 - // The 'mxchatStyleSettings' localize that used to live here was
9817 - // REMOVED by plan-mxchat-20260731-c63fb6.
9818 - //
9819 - // It targeted the script handle 'mxchat-color-picker', which is
9820 - // registered/enqueued NOWHERE in the plugin — so wp_localize_script()
9821 - // returned false and printed nothing. That accident was the only
9822 - // thing keeping it from being a live secret disclosure: the payload
9823 - // carried loops_api_key, live_agent_secret_key and
9824 - // live_agent_bot_token in full, and this whole method ran for any
9825 - // logged-in user (see the capability gate added to
9826 - // mxchat_enqueue_admin_assets). One future
9827 - // wp_enqueue_script('mxchat-color-picker', ...) would have printed
9828 - // three secrets into page HTML for Subscribers.
9829 - //
9830 - // Nothing consumed the object: a tree-wide grep for
9831 - // 'mxchatStyleSettings' returns only this call site, and js/ names
9832 - // loops_api_key only at mxchat-admin.js:572, as a field-NAME string
9833 - // in an autosave allowlist — not a value read. Removed entirely
9834 - // rather than deleting just the three secret keys, so there is no
9835 - // dead payload left for someone to re-arm.
9836 - break;
9837 - }
9838 -
9839 - // Additional localization that was in the original code
9840 - wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
9841 - 'ajax_url' => admin_url('admin-ajax.php'),
9842 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9843 - ));
9844 -}
9845 -
9846 -public function mxchat_sanitize($input) {
9847 - $new_input = array();
9848 -
9849 - if (isset($input['api_key'])) {
9850 - $new_input['api_key'] = sanitize_text_field($input['api_key']);
9851 - }
9852 -
9853 - if (isset($input['similarity_threshold'])) {
9854 - $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
9855 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
9856 - }
9857 -
9858 - if (isset($input['rag_sources_limit'])) {
9859 - $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
9860 - $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
9861 - }
9862 -
9863 - if (isset($input['rag_chunks_limit'])) {
9864 - $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
9865 - $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
9866 - }
9867 -
9868 - if (isset($input['xai_api_key'])) {
9869 - $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
9870 - }
9871 -
9872 - if (isset($input['claude_api_key'])) {
9873 - $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
9874 - }
9875 -
9876 - if (isset($input['enable_streaming_toggle'])) {
9877 - $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
9878 - } else {
9879 - // If checkbox not checked, it won't be in $input, so set to 'off'
9880 - $new_input['enable_streaming_toggle'] = 'off';
9881 - }
9882 -
9883 - if (isset($input['enable_web_search'])) {
9884 - $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
9885 - } else {
9886 - // If checkbox not checked, it won't be in $input, so set to 'off'
9887 - $new_input['enable_web_search'] = 'off';
9888 - }
9889 -
9890 - if (isset($input['deepseek_api_key'])) {
9891 - $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
9892 - }
9893 -
9894 - if (isset($input['gemini_api_key'])) {
9895 - $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
9896 - }
9897 -
9898 - if (isset($input['enable_woocommerce_integration'])) {
9899 - $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
9900 - }
9901 -
9902 - if (isset($input['privacy_toggle'])) {
9903 - $new_input['privacy_toggle'] = $input['privacy_toggle'];
9904 - }
9905 -
9906 - if (isset($input['complianz_toggle'])) {
9907 - $new_input['complianz_toggle'] = $input['complianz_toggle'];
9908 - }
9909 -
9910 - // Handle custom privacy text input
9911 - if (isset($input['privacy_text'])) {
9912 - // Allow basic HTML for links
9913 - $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
9914 - }
9915 -
9916 - if (isset($input['system_prompt_instructions'])) {
9917 - $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
9918 - }
9919 -
9920 - if (isset($input['mxchat_pro_email'])) {
9921 - $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
9922 - }
9923 -
9924 - if (isset($input['mxchat_activation_key'])) {
9925 - $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
9926 - }
9927 -
9928 - if (isset($input['append_to_body'])) {
9929 - $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
9930 - }
9931 -
9932 - // Post type visibility settings
9933 - if (isset($input['post_type_visibility_mode'])) {
9934 - $allowed_modes = array('all', 'include', 'exclude');
9935 - $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
9936 - ? $input['post_type_visibility_mode']
9937 - : 'all';
9938 - }
9939 -
9940 - if (isset($input['post_type_visibility_list'])) {
9941 - if (is_array($input['post_type_visibility_list'])) {
9942 - $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
9943 - } else {
9944 - $new_input['post_type_visibility_list'] = array();
1615 + // Sanitize new pro features
1616 + if (isset($input['close_button_color'])) {
1617 + $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
9945 1618 }
9946 - }
9947 1619
9948 - if (isset($input['contextual_awareness_toggle'])) {
9949 - $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
9950 -}
9951 -
9952 - if (isset($input['citation_links_toggle'])) {
9953 - $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
9954 -}
9955 -
9956 - // Satisfaction rating prompt — defaults ON when unchecked (so first save
9957 - // doesn't accidentally disable it). The form posts 'on' when checked;
9958 - // unchecked checkboxes don't post a value at all, so we infer 'off' only
9959 - // when the autosave/PHP request explicitly clears it via empty string.
9960 - if (array_key_exists('satisfaction_rating_enabled', $input)) {
9961 - $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
9962 - }
9963 -
9964 - // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
9965 - // the 4 text strings are sanitized + capped server-side. Blank values are
9966 - // preserved so the integrator falls back to translated defaults.
9967 - if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
9968 - $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
9969 - }
9970 -
9971 - // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default,
9972 - // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out
9973 - // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist,
9974 - // so without this isset-handler the key is stripped on the next save of ANY field
9975 - // (the 2c02ea global-rate-limit footgun).
9976 - if (array_key_exists('max_input_length', $input)) {
9977 - $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length'])));
9978 - }
9979 - if (array_key_exists('satisfaction_rating_question', $input)) {
9980 - $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
9981 - }
9982 - if (array_key_exists('satisfaction_rating_thanks', $input)) {
9983 - $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
9984 - }
9985 - if (array_key_exists('satisfaction_rating_placeholder', $input)) {
9986 - $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
9987 - }
9988 - if (array_key_exists('satisfaction_rating_saved', $input)) {
9989 - $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
9990 - }
9991 -
9992 - if (isset($input['top_bar_title'])) {
9993 - $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
9994 - }
9995 -
9996 - if (isset($input['ai_agent_text'])) {
9997 - $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
1620 + if (isset($input['chatbot_bg_color'])) {
1621 + $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
9998 1622 }
9999 1623
10000 - if (isset($input['enable_email_block'])) {
10001 - $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
10002 - }
10003 -
10004 - if (isset($input['email_blocker_header_content'])) {
10005 - // wp_kses_post() allows standard HTML tags permitted by WordPress
10006 - $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
10007 - }
10008 - if (isset($input['email_blocker_button_text'])) {
10009 - $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
10010 - }
10011 - // Sanitize name field toggle
10012 - if (isset($input['enable_name_field'])) {
10013 - $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
10014 - } else {
10015 - $new_input['enable_name_field'] = 'off';
10016 - }
10017 - // Sanitize name field placeholder
10018 - if (isset($input['name_field_placeholder'])) {
10019 - $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
10020 - }
10021 - if (isset($input['intro_message'])) {
10022 - $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
10023 - }
10024 -
10025 - if (isset($input['input_copy'])) {
10026 - $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10027 - }
10028 -
10029 - if (isset($input['rate_limit_message'])) {
10030 - $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10031 - }
10032 -
10033 -// Handle the new rate limits format
10034 -if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
10035 - $new_input['rate_limits'] = array();
10036 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10037 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10038 -
10039 - foreach ($input['rate_limits'] as $role_id => $settings) {
10040 - $new_input['rate_limits'][$role_id] = array();
10041 -
10042 - // Sanitize limit
10043 - if (isset($settings['limit'])) {
10044 - $limit = sanitize_text_field($settings['limit']);
10045 - // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive
10046 - // integer (custom value) — mirrors the global branch (plan-2c02ea). Without
10047 - // the custom path the per-role custom input was dropped and reset to the role
10048 - // default on every save (plan-7e23e7).
10049 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10050 - $new_input['rate_limits'][$role_id]['limit'] = $limit;
10051 - } else {
10052 - $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
10053 - }
1624 + if (isset($input['woocommerce_consumer_key'])) {
1625 + $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10054 1626 }
10055 1627
10056 - // Preserve the per-role custom value (mirrors the global branch's limit_custom).
10057 - if (isset($settings['limit_custom'])) {
10058 - $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']);
1628 + if (isset($input['woocommerce_consumer_secret'])) {
1629 + $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
10059 1630 }
10060 1631
10061 - // Sanitize timeframe
10062 - if (isset($settings['timeframe'])) {
10063 - $timeframe = sanitize_text_field($settings['timeframe']);
10064 - if (in_array($timeframe, $allowed_timeframes, true)) {
10065 - $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
10066 - } else {
10067 - $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
10068 - }
1632 + if (isset($input['user_message_bg_color'])) {
1633 + $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
10069 1634 }
10070 1635
10071 - // Sanitize message
10072 - if (isset($settings['message'])) {
10073 - $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
1636 + if (isset($input['user_message_font_color'])) {
1637 + $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
10074 1638 }
10075 - }
10076 -}
10077 1639
10078 -// Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea).
10079 -// Mirrors the per-role block above, adapted to the single global shape. Without
10080 -// this branch the whitelist-rebuild dropped rate_limits_global entirely on every
10081 -// save, so the global cap silently fell back to its 'unlimited' default.
10082 -// MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed.
10083 -if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) {
10084 - $g = $input['rate_limits_global'];
10085 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10086 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10087 - $global_out = array();
10088 -
10089 - if (isset($g['limit'])) {
10090 - $limit = sanitize_text_field($g['limit']);
10091 - // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the
10092 - // autosave handler / renderer), OR any positive integer (custom value).
10093 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10094 - $global_out['limit'] = $limit;
10095 - } else {
10096 - $global_out['limit'] = 'unlimited';
1640 + if (isset($input['bot_message_bg_color'])) {
1641 + $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
10097 1642 }
10098 - }
10099 1643
10100 - if (isset($g['limit_custom'])) {
10101 - $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']);
10102 - }
10103 -
10104 - if (isset($g['timeframe'])) {
10105 - $timeframe = sanitize_text_field($g['timeframe']);
10106 - $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily';
10107 - }
10108 -
10109 - if (isset($g['message'])) {
10110 - $global_out['message'] = sanitize_textarea_field($g['message']);
10111 - }
10112 -
10113 - $new_input['rate_limits_global'] = $global_out;
10114 -}
10115 -
10116 - if (isset($input['pre_chat_message'])) {
10117 - $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10118 - }
10119 -
10120 - if (isset($input['voyage_api_key'])) {
10121 - $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
10122 - }
10123 -
10124 - // Add to your sanitize function
10125 - if (isset($input['embedding_model'])) {
10126 - // Catalog refactor (plan-d14e89): allowlist derived from the canonical
10127 - // catalog in includes/class-mxchat-model-catalog.php.
10128 - if (!class_exists('MxChat_Model_Catalog')) {
10129 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1644 + if (isset($input['bot_message_font_color'])) {
1645 + $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
10130 1646 }
10131 - $allowed_models = MxChat_Model_Catalog::embedding_model_ids();
10132 - if (in_array($input['embedding_model'], $allowed_models)) {
10133 - $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
10134 - }
10135 - }
10136 1647
10137 -if (isset($input['model'])) {
10138 - if ($input['model'] === 'openrouter') {
10139 - $new_input['model'] = 'openrouter';
10140 - } else {
10141 - if (!class_exists('MxChat_Model_Catalog')) {
10142 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1648 + if (isset($input['top_bar_bg_color'])) {
1649 + $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
10143 1650 }
10144 - $allowed_models = MxChat_Model_Catalog::chat_model_ids();
10145 1651
10146 - if (in_array($input['model'], $allowed_models)) {
10147 - $new_input['model'] = sanitize_text_field($input['model']);
10148 - } else {
10149 - // Fallback for any deprecated model
10150 - $new_input['model'] = 'gpt-5.6-sol';
1652 + if (isset($input['send_button_font_color'])) {
1653 + $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
10151 1654 }
10152 - }
10153 -}
10154 -
10155 -if (isset($input['openrouter_selected_model'])) {
10156 - // Just sanitize it, don't validate against a whitelist
10157 - $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
10158 -}
10159 1655
10160 -// ADD THIS:
10161 -if (isset($input['openrouter_selected_model_name'])) {
10162 - $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
10163 -}
10164 -
10165 - if (isset($input['openrouter_api_key'])) {
10166 - $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
10167 - }
10168 -
10169 - // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
10170 - if (isset($input['custom_provider_base_url'])) {
10171 - $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
10172 - }
10173 - if (isset($input['custom_provider_api_key'])) {
10174 - $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
10175 - }
10176 - if (isset($input['custom_provider_model'])) {
10177 - $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
10178 - }
10179 - if (isset($input['custom_provider_auth_scheme'])) {
10180 - $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
10181 - $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
10182 - }
10183 - if (isset($input['custom_provider_for_embeddings'])) {
10184 - $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
10185 - }
10186 - if (isset($input['custom_provider_for_images'])) {
10187 - $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
10188 - }
10189 - if (isset($input['custom_provider_embedding_model'])) {
10190 - $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
10191 - }
10192 - if (isset($input['custom_provider_api_version'])) {
10193 - $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
10194 - }
10195 -
10196 -
10197 -
10198 - if (isset($input['woocommerce_consumer_key'])) {
10199 - $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10200 - }
10201 -
10202 - if (isset($input['woocommerce_consumer_secret'])) {
10203 - $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
10204 - }
10205 -
10206 -
10207 - // Sanitize link_target_toggle
10208 - if (isset($input['link_target_toggle'])) {
10209 - $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
10210 - }
10211 -
10212 - // Sanitize Loops API Key
10213 - if (isset($input['loops_api_key'])) {
10214 - $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
10215 - }
10216 -
10217 - if (isset($input['chat_persistence_toggle'])) {
10218 - $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
10219 - }
10220 -
10221 - // No else clause: an absent key stays absent, so the front-end default ('on') applies
10222 - // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here).
10223 - if (isset($input['print_button_enabled'])) {
10224 - $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off';
10225 - }
10226 -
10227 - // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label.
10228 - // No else on the toggle: an absent key stays absent so the front-end '?? off'
10229 - // default applies, and the full-array autosave rebuild preserves a saved value.
10230 - if (isset($input['reset_chat_enabled'])) {
10231 - $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off';
10232 - }
10233 -
10234 - if (isset($input['reset_chat_label'])) {
10235 - $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']);
10236 - }
10237 -
10238 - if (isset($input['popular_question_1'])) {
10239 - $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
10240 - }
10241 -
10242 - if (isset($input['popular_question_2'])) {
10243 - $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']);
10244 - }
10245 -
10246 - if (isset($input['popular_question_3'])) {
10247 - $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']);
10248 - }
10249 -
10250 - if (isset($input['additional_popular_questions']) && is_array($input['additional_popular_questions'])) {
10251 - $new_input['additional_popular_questions'] = array_map('sanitize_text_field', $input['additional_popular_questions']);
10252 - }
10253 -
10254 - // Sanitize Loops Mailing List
10255 - if (isset($input['loops_mailing_list'])) {
10256 - $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
10257 - }
10258 -
10259 -// Sanitize Triggered Phrase Response
10260 - if (isset($input['triggered_phrase_response'])) {
10261 - $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
10262 - }
10263 - if (isset($input['email_capture_response'])) {
10264 - $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
10265 - }
10266 -
10267 - // Sanitize Brave Search Settings
10268 - if (isset($input['brave_api_key'])) {
10269 - $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
10270 - }
10271 -
10272 - if (isset($input['brave_image_count'])) {
10273 - $image_count = intval($input['brave_image_count']);
10274 - $new_input['brave_image_count'] = ($image_count >=1 && $image_count <=6) ? $image_count : 4;
10275 - }
10276 -
10277 - if (isset($input['brave_safe_search'])) {
10278 - $allowed = array('strict', 'off');
10279 - $new_input['brave_safe_search'] = in_array($input['brave_safe_search'], $allowed, true) ? $input['brave_safe_search'] : 'strict';
10280 - }
10281 -
10282 - if (isset($input['brave_news_count'])) {
10283 - $news_count = intval($input['brave_news_count']);
10284 - $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
10285 - }
10286 -
10287 - if (isset($input['brave_country'])) {
10288 - $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
10289 - }
10290 -
10291 - if (isset($input['brave_language'])) {
10292 - $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
10293 - }
10294 -
10295 - if (isset($input['chat_toolbar_toggle'])) {
10296 - $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
10297 - }
10298 -
10299 - // Sanitize PDF upload button toggle
10300 - if (isset($input['show_pdf_upload_button'])) {
10301 - $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
10302 - } else {
10303 - $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
10304 - }
10305 -
10306 - // Sanitize Word upload button toggle
10307 - if (isset($input['show_word_upload_button'])) {
10308 - $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
10309 - } else {
10310 - $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
10311 - }
10312 -
10313 - if (isset($input['pdf_intent_trigger_text'])) {
10314 - $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
10315 - }
10316 -
10317 - if (isset($input['pdf_intent_success_text'])) {
10318 - $new_input['pdf_intent_success_text'] = sanitize_text_field($input['pdf_intent_success_text']);
10319 - }
10320 -
10321 - if (isset($input['pdf_intent_error_text'])) {
10322 - $new_input['pdf_intent_error_text'] = sanitize_text_field($input['pdf_intent_error_text']);
10323 - }
10324 -
10325 - if (isset($input['pdf_max_pages'])) {
10326 - $new_input['pdf_max_pages'] = intval($input['pdf_max_pages']);
10327 - if ($new_input['pdf_max_pages'] < 1 || $new_input['pdf_max_pages'] > 69) {
10328 - $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
1656 + if (isset($input['chatbot_background_color'])) {
1657 + $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
10329 1658 }
10330 - }
10331 1659
10332 - if (isset($input['live_agent_webhook_url'])) {
10333 - $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
10334 - }
10335 - if (isset($input['live_agent_secret_key'])) {
10336 - $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
10337 - }
10338 -
10339 - // Live Agent Integration
10340 - if (isset($input['live_agent_bot_token'])) {
10341 - $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
10342 - }
10343 -
10344 - if (isset($input['live_agent_shared_channel'])) {
10345 - $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']);
10346 - }
10347 -
10348 - // Default-OFF toggle: absent key stays absent (unchecked box = off).
10349 - if (isset($input['live_agent_archive_on_end_toggle'])) {
10350 - $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off';
10351 - }
10352 -
10353 - if (isset($input['live_agent_user_ids'])) {
10354 - $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
10355 - }
10356 -
10357 - if (isset($input['live_agent_status'])) {
10358 - $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
10359 - }
10360 - if (isset($input['live_agent_away_message'])) {
10361 - $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
10362 - }
10363 - if (isset($input['live_agent_notification_message'])) {
10364 - $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
10365 - }
10366 -
10367 - // Telegram Integration
10368 - if (isset($input['telegram_status'])) {
10369 - $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
10370 - }
10371 - if (isset($input['telegram_bot_token'])) {
10372 - $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
10373 - }
10374 - if (isset($input['telegram_group_id'])) {
10375 - $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
10376 - }
10377 - if (isset($input['telegram_webhook_secret'])) {
10378 - $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
10379 - }
10380 - if (isset($input['telegram_notification_message'])) {
10381 - $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
10382 - }
10383 - if (isset($input['telegram_away_message'])) {
10384 - $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
10385 - }
10386 -
10387 - // Sanitize script loading strategy
10388 - if (isset($input['script_loading_strategy'])) {
10389 - $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
10390 - $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
10391 - ? $input['script_loading_strategy']
10392 - : 'default';
10393 - }
10394 -
10395 - // Sanitize debug mode
10396 - if (isset($input['debug_mode'])) {
10397 - $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
10398 - }
10399 -
10400 - // Content Generator Settings
10401 - if (isset($input['content_model'])) {
10402 - $new_input['content_model'] = sanitize_text_field($input['content_model']);
10403 - }
10404 - if (isset($input['content_image_model'])) {
10405 - $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
10406 - }
10407 - if (isset($input['content_image_quality'])) {
10408 - $q = sanitize_text_field($input['content_image_quality']);
10409 - $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
10410 - }
10411 - if (isset($input['content_enable_images'])) {
10412 - $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
10413 - }
10414 - if (isset($input['content_use_placeholders'])) {
10415 - $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
10416 - }
10417 - if (isset($input['content_internal_linking'])) {
10418 - $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
10419 - }
10420 - if (isset($input['content_tool_use'])) {
10421 - $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
10422 - }
10423 - if (isset($input['content_image_count'])) {
10424 - $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count']));
10425 - }
10426 -
10427 - // SEO Optimize toggle fields
10428 - foreach (array('seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $seo_key) {
10429 - if (isset($input[$seo_key])) {
10430 - $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
1660 + if (isset($input['icon_color'])) {
1661 + $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
10431 1662 }
10432 - }
10433 1663
10434 - // Preserve content generator settings when saving from main settings page
10435 - // (where content fields are not in the form submission)
10436 - $existing = get_option('mxchat_options', array());
10437 - foreach (array('content_model', 'content_image_model', 'content_image_quality', 'content_image_count', 'content_enable_images', 'content_use_placeholders', 'content_internal_linking', 'content_tool_use', 'seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $key) {
10438 - if (!isset($new_input[$key]) && isset($existing[$key])) {
10439 - $new_input[$key] = $existing[$key];
1664 + if (isset($input['chat_input_font_color'])) {
1665 + $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
10440 1666 }
10441 - }
10442 1667
10443 - return $new_input;
10444 -}
10445 -
10446 -/**
10447 - * Log a debug message if debug mode is enabled
10448 - *
10449 - * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
10450 - * @param string $message The log message
10451 - * @param array $data Optional additional data to log
10452 - * @return bool Whether the message was logged
10453 - */
10454 -public static function mxchat_log_debug( $type, $message, $data = array() ) {
10455 - $options = get_option( 'mxchat_options', array() );
10456 -
10457 - // Check if debug mode is enabled
10458 - if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
10459 - return false;
1668 + return $new_input;
10460 1669 }
10461 1670
10462 - // Get current log
10463 - $log = get_option( 'mxchat_debug_log', array() );
10464 - if ( ! is_array( $log ) ) {
10465 - $log = array();
10466 - }
10467 1671
10468 - // Add new entry
10469 - $entry = array(
10470 - 'time' => current_time( 'Y-m-d H:i:s' ),
10471 - 'type' => sanitize_key( $type ),
10472 - 'message' => sanitize_text_field( $message ),
10473 - );
10474 -
10475 - if ( ! empty( $data ) ) {
10476 - $entry['data'] = $data;
10477 - }
10478 -
10479 - // Add to beginning of array (newest first)
10480 - array_unshift( $log, $entry );
10481 -
10482 - // Keep only last 100 entries
10483 - if ( count( $log ) > 100 ) {
10484 - $log = array_slice( $log, 0, 100 );
10485 - }
10486 -
10487 - // Save log
10488 - update_option( 'mxchat_debug_log', $log, false );
10489 -
10490 - return true;
10491 -}
10492 -
10493 -/**
10494 - * Get the debug log entries
10495 - *
10496 - * @return array The debug log entries
10497 - */
10498 -public static function mxchat_get_debug_log() {
10499 - $log = get_option( 'mxchat_debug_log', array() );
10500 - return is_array( $log ) ? $log : array();
10501 -}
10502 -
10503 -/**
10504 - * Clear the debug log
10505 - *
10506 - * @return bool Whether the log was cleared
10507 - */
10508 -public static function mxchat_clear_debug_log() {
10509 - return delete_option( 'mxchat_debug_log' );
10510 -}
10511 -
10512 -/**
10513 - * Export settings as JSON with masked API keys
10514 - *
10515 - * @return array The sanitized settings array
10516 - */
10517 -public static function mxchat_export_settings() {
10518 - $options = get_option( 'mxchat_options', array() );
10519 -
10520 - if ( ! is_array( $options ) ) {
10521 - return array();
10522 - }
10523 -
10524 - // List of API key fields to mask
10525 - $api_key_fields = array(
10526 - 'api_key',
10527 - 'xai_api_key',
10528 - 'claude_api_key',
10529 - 'deepseek_api_key',
10530 - 'voyage_api_key',
10531 - 'gemini_api_key',
10532 - 'openrouter_api_key',
10533 - 'loops_api_key',
10534 - 'brave_api_key',
10535 - 'live_agent_secret_key',
10536 - 'live_agent_bot_token',
10537 - 'telegram_bot_token',
10538 - 'telegram_webhook_secret',
10539 - 'woocommerce_consumer_key',
10540 - 'woocommerce_consumer_secret',
10541 - );
10542 -
10543 - // Mask API keys (show only last 4 characters)
10544 - foreach ( $api_key_fields as $field ) {
10545 - if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
10546 - $value = $options[ $field ];
10547 - if ( strlen( $value ) > 4 ) {
10548 - $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
10549 - } else {
10550 - $options[ $field ] = '****';
10551 - }
10552 - }
10553 - }
10554 -
10555 - // Add metadata
10556 - $export = array(
10557 - 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
10558 - 'export_date' => current_time( 'Y-m-d H:i:s' ),
10559 - 'wordpress_version' => get_bloginfo( 'version' ),
10560 - 'php_version' => phpversion(),
10561 - 'settings' => $options,
10562 - );
10563 -
10564 - return $export;
10565 -}
10566 -
10567 -/**
10568 - * Reset all settings to defaults
10569 - *
10570 - * @return bool Whether the reset was successful
10571 - */
10572 -public static function mxchat_reset_all_settings() {
10573 - // Delete main options
10574 - $deleted = delete_option( 'mxchat_options' );
10575 -
10576 - // Also clear the debug log
10577 - delete_option( 'mxchat_debug_log' );
10578 -
10579 - // Log the reset (will create new log since we just cleared it)
10580 - // We need to temporarily enable debug mode to log this
10581 - $temp_options = array( 'debug_mode' => 'on' );
10582 - update_option( 'mxchat_options', $temp_options );
10583 -
10584 - self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
10585 -
10586 - // Now delete again to trigger re-initialization
10587 - delete_option( 'mxchat_options' );
10588 -
10589 - return $deleted;
10590 -}
10591 -
10592 1672 // Method to append the chatbot to the body
10593 1673 public function mxchat_append_chatbot_to_body() {
10594 1674 $options = get_option('mxchat_options');
10595 1675 if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
@@ -10598,482 +1678,116 @@
10598 1678 }
10599 1679
10600 1680
10601 1681
1682 +private function mxchat_extract_main_content($html) {
1683 + $dom = new DOMDocument;
1684 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
1685 + @$dom->loadHTML($html);
1686 + libxml_clear_errors();
10602 1687
1688 + $xpath = new DOMXPath($dom);
10603 1689
10604 -private function mxchat_fetch_loops_mailing_lists($api_key) {
10605 - $url = 'https://app.loops.so/api/v1/lists';
10606 - $response = wp_remote_get($url, array(
10607 - 'headers' => array(
10608 - 'Authorization' => 'Bearer ' . $api_key,
10609 - 'Content-Type' => 'application/json'
10610 - )
10611 - ));
1690 + // Simplified selectors focusing on common content areas
1691 + $selectors = [
1692 + '//article',
1693 + '//*[@id="content"]',
1694 + '//*[@class="entry-content"]',
1695 + '//main',
1696 + ];
10612 1697
10613 - if (is_wp_error($response)) {
10614 - return array();
1698 + foreach ($selectors as $selector) {
1699 + $nodes = $xpath->query($selector);
1700 + if ($nodes->length > 0) {
1701 + $content = '';
1702 + foreach ($nodes as $node) {
1703 + $content .= $dom->saveHTML($node);
1704 + }
1705 + return $content;
1706 + }
10615 1707 }
10616 1708
10617 - $body = wp_remote_retrieve_body($response);
10618 - $lists = json_decode($body, true);
10619 -
10620 - return isset($lists) && is_array($lists) ? $lists : array();
1709 + // Fallback: Return the entire body content if no specific selector matches
1710 + $body = $dom->getElementsByTagName('body');
1711 + return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
10621 1712 }
10622 1713
10623 -function mxchat_calculate_cosine_similarity($vec1, $vec2) {
10624 - if (empty($vec1) || empty($vec2)) {
10625 - return 0.0;
1714 +public function mxchat_handle_sitemap_submission() {
1715 + if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
1716 + return;
10626 1717 }
10627 1718
10628 - $dot_product = 0.0;
10629 - $norm_a = 0.0;
10630 - $norm_b = 0.0;
1719 + check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
10631 1720
10632 - for ($i = 0; $i < count($vec1); $i++) {
10633 - $dot_product += $vec1[$i] * $vec2[$i];
10634 - $norm_a += pow($vec1[$i], 2);
10635 - $norm_b += pow($vec2[$i], 2);
1721 + $sitemap_url = esc_url_raw($_POST['sitemap_url']);
1722 +
1723 + $response = wp_remote_get($sitemap_url);
1724 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1725 + set_transient('mxchat_admin_notice', 'Failed to fetch the sitemap. Please check the URL and try again.', 30);
1726 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1727 + exit;
10636 1728 }
10637 1729
10638 - if ($norm_a == 0.0 || $norm_b == 0.0) {
10639 - return 0.0;
10640 - } else {
10641 - return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
10642 - }
10643 -}
1730 + $sitemap_content = wp_remote_retrieve_body($response);
10644 1731
10645 -/**
10646 - * Validates nonce and deletes all chat prompts
10647 - */
10648 -public function mxchat_handle_delete_all_prompts() {
10649 - //error_log('=== DELETE ALL DEBUG START ===');
10650 -
10651 - // Verify nonce
10652 - if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
10653 - //error_log('DEBUG: Nonce verification failed');
10654 - wp_die(__('Nonce verification failed.', 'mxchat'));
1732 + $xml = simplexml_load_string($sitemap_content);
1733 + if ($xml === false) {
1734 + set_transient('mxchat_admin_notice', 'Invalid sitemap XML. Please provide a valid sitemap.', 30);
1735 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1736 + exit;
10655 1737 }
10656 -
10657 - // Check permissions
10658 - if (!current_user_can('manage_options')) {
10659 - //error_log('DEBUG: Permission check failed');
10660 - wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
10661 - }
10662 -
10663 - // Get bot_id and content type filter from POST data
10664 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
10665 - $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
10666 1738
10667 - $success = true;
10668 - $error_messages = array();
1739 + $embedding_success = true; // Flag to track if all embeddings are successful
10669 1740
10670 - // Get bot-specific Pinecone configuration
10671 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10672 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
1741 + foreach ($xml->url as $url_element) {
1742 + $page_url = (string)$url_element->loc;
10673 1743
10674 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
1744 + $page_response = wp_remote_get($page_url);
1745 + if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
1746 + continue;
1747 + }
10675 1748
10676 - if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
10677 - // Delete from Pinecone (with optional content type filter)
10678 - $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
1749 + $page_html = wp_remote_retrieve_body($page_response);
1750 + $page_content = $this->mxchat_extract_main_content($page_html);
1751 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10679 1752
10680 - if (!$result['success']) {
10681 - $success = false;
10682 - $error_messages[] = $result['message'];
1753 + if (!empty($sanitized_content)) {
1754 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
1755 + if (is_array($embedding_vector)) {
1756 + MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $this->options['api_key']);
1757 + } else {
1758 + $embedding_success = false; // Set flag to false if any embedding fails
1759 + }
10683 1760 }
1761 + }
10684 1762
1763 + if ($embedding_success) {
1764 + set_transient('mxchat_admin_notice', 'Sitemap content successfully submitted!', 30);
10685 1765 } else {
10686 - // Delete from WordPress database
10687 - global $wpdb;
10688 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
10689 -
10690 - // Build WHERE conditions
10691 - $where_clauses = array();
10692 - $where_values = array();
10693 -
10694 - // Bot filter
10695 - if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
10696 - $where_clauses[] = 'bot_id = %s';
10697 - $where_values[] = $bot_id;
10698 - }
10699 -
10700 - // Content type filter
10701 - if (!empty($content_type_filter)) {
10702 - $where_clauses[] = 'content_type = %s';
10703 - $where_values[] = $content_type_filter;
10704 - }
10705 -
10706 - if (!empty($where_clauses)) {
10707 - $where_sql = implode(' AND ', $where_clauses);
10708 - $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
10709 - } else {
10710 - // No filters — delete all
10711 - $result = $wpdb->query("DELETE FROM {$table_name}");
10712 - }
10713 -
10714 - if ($result === false) {
10715 - $success = false;
10716 - $error_messages[] = 'Failed to delete from WordPress database';
10717 - }
1766 + set_transient('mxchat_admin_notice', 'Some content failed to embed. Please check your API key and try again.', 30);
10718 1767 }
10719 1768
10720 - // Redirect back with a success message and bot_id
10721 - $redirect_url = add_query_arg(array(
10722 - 'page' => 'mxchat-prompts',
10723 - 'bot_id' => $bot_id,
10724 - 'all_deleted' => $success ? 'true' : 'false'
10725 - ), admin_url('admin.php'));
10726 -
10727 - wp_safe_redirect($redirect_url);
1769 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
10728 1770 exit;
10729 1771 }
10730 1772
10731 1773
10732 1774
10733 - /**
10734 - * Handles deletion prompt with nonce validation
10735 - */
10736 - public function mxchat_handle_delete_prompt() {
10737 - // Sanitize and validate nonce
10738 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
10739 - if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
10740 - wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
10741 - }
1775 +private function mxchat_sanitize_content_for_api($content) {
1776 + // Remove script, style tags, and HTML comments
1777 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
1778 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
1779 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
10742 1780
10743 - // Check permissions
10744 - if (!current_user_can('manage_options')) {
10745 - wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
10746 - }
1781 + // Remove all HTML tags and decode HTML entities
1782 + $content = wp_strip_all_tags($content);
1783 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
10747 1784
10748 - // Get ID and source parameters
10749 - $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
10750 - $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
1785 + // Trim and normalize whitespace
1786 + $content = trim(preg_replace('/\s+/', ' ', $content));
10751 1787
10752 - if (empty($id)) {
10753 - wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
10754 - }
10755 -
10756 - $success = false;
10757 - $error_message = '';
10758 -
10759 - // Resolve per-bot Pinecone settings — the global option is the wrong
10760 - // index entirely when the row belongs to a bot with its own host
10761 - $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default';
10762 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10763 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
10764 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
10765 -
10766 - // If source is not specified, determine based on Pinecone configuration
10767 - if (empty($source)) {
10768 - $source = $use_pinecone ? 'pinecone' : 'wordpress';
10769 - }
10770 -
10771 - if ($source === 'pinecone' || $use_pinecone) {
10772 - //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
10773 -
10774 - // Handle Pinecone deletion
10775 - if (empty($pinecone_options['mxchat_pinecone_host']) ||
10776 - empty($pinecone_options['mxchat_pinecone_api_key'])) {
10777 - wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
10778 - }
10779 -
10780 - // Delete from Pinecone using the vector ID directly
10781 - $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
10782 - $id,
10783 - $pinecone_options['mxchat_pinecone_api_key'],
10784 - $pinecone_options['mxchat_pinecone_host'],
10785 - $pinecone_options['mxchat_pinecone_namespace'] ?? ''
10786 - );
10787 - if ($result['success']) {
10788 - $success = true;
10789 -
10790 - // Remove from vector cache
10791 - $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
10792 - $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
10793 -
10794 - set_transient('mxchat_admin_notice_success',
10795 - esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
10796 - } else {
10797 - $error_message = $result['message'];
10798 - set_transient('mxchat_admin_notice_error',
10799 - esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
10800 - }
10801 - } else {
10802 - //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
10803 -
10804 - // Handle WordPress database deletion
10805 - global $wpdb;
10806 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
10807 -
10808 - // Clear cache and delete prompt
10809 - wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
10810 -
10811 - $result = $wpdb->delete(
10812 - $table_name,
10813 - array('id' => intval($id)),
10814 - array('%d')
10815 - );
10816 -
10817 - if ($result !== false) {
10818 - $success = true;
10819 - set_transient('mxchat_admin_notice_success',
10820 - esc_html__('Entry deleted successfully.', 'mxchat'), 30);
10821 - } else {
10822 - set_transient('mxchat_admin_notice_error',
10823 - esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
10824 - }
10825 - }
10826 -
10827 - // Redirect back to the prompts page
10828 - wp_safe_redirect(add_query_arg(
10829 - array(
10830 - 'page' => 'mxchat-prompts',
10831 - 'deleted' => $success ? 'true' : 'false'
10832 - ),
10833 - admin_url('admin.php')
10834 - ));
10835 - exit;
10836 - }
10837 -
10838 -
10839 -
10840 -
10841 - /**
10842 - * Averages multiple vectors into a single vector
10843 - */
10844 - private function mxchat_average_vectors($vectors) {
10845 - $vector_length = count($vectors[0]);
10846 - $sum_vector = array_fill(0, $vector_length, 0);
10847 -
10848 - foreach ($vectors as $vector) {
10849 - for ($i = 0; $i < $vector_length; $i++) {
10850 - $sum_vector[$i] += $vector[$i];
10851 - }
10852 - }
10853 -
10854 - // Divide each component by the number of vectors to get the average
10855 - $num_vectors = count($vectors);
10856 - for ($i = 0; $i < $vector_length; $i++) {
10857 - $sum_vector[$i] /= $num_vectors;
10858 - }
10859 -
10860 - return $sum_vector;
10861 - }
10862 -
10863 -
10864 -
10865 -
10866 - /**
10867 - * Generates embeddings from input text for MXChat
10868 - */
10869 - public function mxchat_generate_embedding($text) {
10870 - // Enable detailed logging for debugging
10871 - //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
10872 - //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
10873 -
10874 - $options = get_option('mxchat_options');
10875 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
10876 - //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
10877 -
10878 - // Determine provider and endpoint
10879 - if (strpos($selected_model, 'voyage') === 0) {
10880 - $api_key = $options['voyage_api_key'] ?? '';
10881 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
10882 - $provider_name = 'Voyage AI';
10883 - //error_log('[MXCHAT-EMBED] Using Voyage AI API');
10884 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
10885 - $api_key = $options['gemini_api_key'] ?? '';
10886 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
10887 - $provider_name = 'Google Gemini';
10888 - //error_log('[MXCHAT-EMBED] Using Google Gemini API');
10889 - } else {
10890 - $api_key = $options['api_key'] ?? '';
10891 - $endpoint = 'https://api.openai.com/v1/embeddings';
10892 - $provider_name = 'OpenAI';
10893 - //error_log('[MXCHAT-EMBED] Using OpenAI API');
10894 - }
10895 -
10896 - //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
10897 -
10898 - if (empty($api_key)) {
10899 - $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
10900 - //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
10901 - return $error_message;
10902 - }
10903 -
10904 - // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
10905 - $estimated_tokens = ceil(str_word_count($text) / 0.75);
10906 - //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
10907 -
10908 - if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
10909 - //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
10910 - // Consider truncating text here
10911 - }
10912 -
10913 - // Prepare request body based on provider
10914 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10915 - // Gemini API format
10916 - $request_body = array(
10917 - 'model' => 'models/' . $selected_model,
10918 - 'content' => array(
10919 - 'parts' => array(
10920 - array('text' => $text)
10921 - )
10922 - )
10923 - );
10924 -
10925 - // Set output dimensionality to 1536 for consistency with other models
10926 - $request_body['outputDimensionality'] = 1536;
10927 - } else {
10928 - // OpenAI/Voyage API format
10929 - $request_body = array(
10930 - 'model' => $selected_model,
10931 - 'input' => $text
10932 - );
10933 -
10934 - // Add output_dimension for voyage-3-large model
10935 - if ($selected_model === 'voyage-3-large') {
10936 - $request_body['output_dimension'] = 2048;
10937 - }
10938 - }
10939 -
10940 - //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
10941 -
10942 - // Prepare headers based on provider
10943 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10944 - // Gemini uses API key as query parameter
10945 - $endpoint .= '?key=' . $api_key;
10946 - $headers = array(
10947 - 'Content-Type' => 'application/json'
10948 - );
10949 - } else {
10950 - // OpenAI/Voyage use Bearer token
10951 - $headers = array(
10952 - 'Authorization' => 'Bearer ' . $api_key,
10953 - 'Content-Type' => 'application/json'
10954 - );
10955 - }
10956 -
10957 - // Make API request
10958 - //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
10959 - $response = wp_remote_post($endpoint, array(
10960 - 'body' => wp_json_encode($request_body),
10961 - 'headers' => $headers,
10962 - 'timeout' => 60 // Increased timeout for large inputs
10963 - ));
10964 -
10965 - // Handle wp_remote_post errors
10966 - if (is_wp_error($response)) {
10967 - $error_message = $response->get_error_message();
10968 - //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
10969 - return 'Connection error: ' . $error_message;
10970 - }
10971 -
10972 - // Get and check HTTP response code
10973 - $http_code = wp_remote_retrieve_response_code($response);
10974 - //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
10975 -
10976 - if ($http_code !== 200) {
10977 - $error_body = wp_remote_retrieve_body($response);
10978 - //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
10979 -
10980 - // Try to parse error for more details
10981 - $error_json = json_decode($error_body, true);
10982 - if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
10983 - $error_type = $error_json['error']['type'] ?? 'unknown';
10984 - $error_message = $error_json['error']['message'] ?? 'No message';
10985 - //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
10986 - //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
10987 -
10988 - // Customize error message for common API errors
10989 - if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
10990 - $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
10991 - } elseif ($error_type === 'authentication_error') {
10992 - $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
10993 - }
10994 -
10995 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
10996 - return $error_message;
10997 - }
10998 -
10999 - $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
11000 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11001 - return $error_message;
11002 - }
11003 -
11004 - // Parse response body
11005 - $response_body = wp_remote_retrieve_body($response);
11006 - //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
11007 -
11008 - $response_data = json_decode($response_body, true);
11009 -
11010 - if (json_last_error() !== JSON_ERROR_NONE) {
11011 - $error = json_last_error_msg();
11012 - //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
11013 - //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
11014 - return "Failed to parse API response: $error";
11015 - }
11016 -
11017 - // Handle different response formats based on provider
11018 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11019 - // Gemini API response format
11020 - if (isset($response_data['embedding']['values'])) {
11021 - $embedding_dimensions = count($response_data['embedding']['values']);
11022 - //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
11023 -
11024 - // Check if embedding dimensions are as expected (should be 1536)
11025 - if ($embedding_dimensions !== 1536) {
11026 - //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
11027 - }
11028 -
11029 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11030 - return $response_data['embedding']['values'];
11031 - } else {
11032 - //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
11033 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11034 -
11035 - if (isset($response_data['error'])) {
11036 - $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
11037 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11038 - return $error_message;
11039 - }
11040 -
11041 - $error_message = "Invalid Gemini API response format: No embedding found";
11042 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11043 - return $error_message;
11044 - }
11045 - } else {
11046 - // OpenAI/Voyage API response format
11047 - if (isset($response_data['data'][0]['embedding'])) {
11048 - $embedding_dimensions = count($response_data['data'][0]['embedding']);
11049 - //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
11050 -
11051 - // Check if embedding dimensions are as expected
11052 - if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
11053 - ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
11054 - //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
11055 - }
11056 -
11057 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11058 - return $response_data['data'][0]['embedding'];
11059 - } else {
11060 - //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
11061 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11062 -
11063 - if (isset($response_data['error'])) {
11064 - $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
11065 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11066 - return $error_message;
11067 - }
11068 -
11069 - $error_message = "Invalid API response format: No embedding found";
11070 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11071 - return $error_message;
11072 - }
11073 - }
11074 - }
11075 -
1788 + return $content;
1789 +}
11076 1790
11077 1791
11078 1792 }
11079 1793 ?>