PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.1.7
MxChat – AI Chatbot & Content Generation for WordPress v1.1.7
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 +1383 -10665 3.2.201.1.7 View file →
@@ -6,395 +6,64 @@
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 - // Seed defaults on init, not here — the constructor runs on
35 - // plugins_loaded, before the mxchat textdomain loads (init, priority 10),
36 - // so translating the default strings here both triggers WP 6.7's
37 - // _load_textdomain_just_in_time notice and stores the untranslated
38 - // English fallbacks. Priority 20 lands after mxchat_load_textdomain().
16 + // Initialize default options if they are not set
39 17 if (!$this->options) {
40 - add_action('init', array($this, 'initialize_default_options'), 20);
18 + $this->initialize_default_options();
41 19 }
42 20
43 21 // Add admin menu and initialize settings
44 22 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
45 - // Pro & Extensions registers at priority 30 so it always lands last in
46 - // the sidebar — below API Access (priority 20) and below any other
47 - // submenu that hooks at default priority 10.
48 - add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
49 - // Onboarding visibility — runs LAST so it can remove the submenu after every
50 - // other add_submenu_page() call. The page stays reachable by direct URL.
51 - add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999);
52 23 add_action('admin_init', array($this, 'mxchat_page_init'));
53 - add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
54 24 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
55 - // Add body class for the Onboarding wizard (plan-905439) so the
56 - // chrome-surgery CSS in admin-onboarding-wizard.css can scope its
57 - // WP-sidebar collapse to this page only.
58 - add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class'));
59 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'));
60 27 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
61 28 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
62 29 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
63 - add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
30 + add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
64 31 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
65 32 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
66 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'));
67 35 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
68 - add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
69 - add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
70 - add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
71 - add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
72 - add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
73 36
74 - // Leads tab (inside Transcripts)
75 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
76 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
77 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
78 37
79 - add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
80 - add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
81 - add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
82 - add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
83 - // Self-heal: the cleanup event is otherwise only scheduled at activation or
84 - // when the retention setting CHANGES — if it is ever lost (deactivate cycle,
85 - // cron-option wipe, DB restore) nothing re-registers it and retention goes
86 - // silently inert while the UI still says it is on (plan-bc08a6).
87 - add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled'));
88 38
89 - add_action('admin_init', array($this, 'register_pinecone_settings'));
90 - add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
91 -
92 - add_action('admin_notices', array($this, 'display_admin_notices'));
93 -
94 - add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
95 - add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
96 - add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
97 -
98 - // wp_ajax_mxchat_save_selected_bot is registered (and handled) in
99 - // admin/class-ajax-handler.php — a duplicate registration here pointed
100 - // at a method this class never defined, a load-order-dependent fatal
101 - // waiting to fire (plan 52bcad).
102 - add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
103 - add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
104 -
105 - // Actions page AJAX handlers
106 - add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
107 - add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
108 - add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
109 - add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
110 - add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
111 - add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
112 - add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
113 - add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
114 - add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
115 - add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
116 -
117 - // Slack test connection
118 - add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
119 -
120 - // Translation handlers
121 - add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
122 - add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
123 -
124 - // 3.2.3: Embedding model switch protection
125 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
126 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
127 - add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax'));
128 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
129 - add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice'));
130 39 }
131 40
132 - /**
133 - * Nudge admins to configure a Telegram webhook secret (plan-0c17b5).
134 - *
135 - * Shown only when a Telegram bot token is configured (integration active)
136 - * AND no webhook secret is set. Without a secret the webhook falls back to a
137 - * Telegram source-IP check — safer than the old fail-open, but a real secret
138 - * is the recommended protection. Dismissible; does not block anything.
139 - */
140 - public function mxchat_telegram_secret_notice() {
141 - if (!current_user_can('manage_options')) {
142 - return;
143 - }
144 - $options = get_option('mxchat_options', array());
145 - $has_token = !empty($options['telegram_bot_token']);
146 - $has_secret = !empty($options['telegram_webhook_secret']);
147 - if (!$has_token || $has_secret) {
148 - return;
149 - }
150 - if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') {
151 - return;
152 - }
153 - $settings_url = admin_url('admin.php?page=mxchat-max');
154 - ?>
155 - <div class="notice notice-warning is-dismissible mxchat-telegram-secret-notice">
156 - <p><strong><?php esc_html_e('MxChat: Telegram webhook is running without a secret token', 'mxchat'); ?></strong></p>
157 - <p>
158 - <?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'); ?>
159 - </p>
160 - <p>
161 - <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
162 - </p>
163 - </div>
164 - <script>
165 - (function(){
166 - var n = document.querySelector('.mxchat-telegram-secret-notice');
167 - if (!n) return;
168 - n.addEventListener('click', function(e){
169 - if (e.target && e.target.classList.contains('notice-dismiss')) {
170 - var d = new FormData();
171 - d.append('action', 'mxchat_dismiss_telegram_secret_notice');
172 - d.append('nonce', '<?php echo esc_js(wp_create_nonce('mxchat_dismiss_telegram_secret')); ?>');
173 - fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', { method: 'POST', body: d, credentials: 'same-origin' });
174 - }
175 - });
176 - })();
177 - </script>
178 - <?php
41 + // Method to check if the license is active
42 + private function is_license_active() {
43 + $license_status = get_option('mxchat_license_status', 'inactive');
44 + return $license_status === 'active';
179 45 }
180 46
181 - /**
182 - * AJAX: persist dismissal of the Telegram-secret admin notice (plan-0c17b5).
183 - */
184 - public function mxchat_dismiss_telegram_secret_notice_ajax() {
185 - if (!current_user_can('manage_options')
186 - || !check_ajax_referer('mxchat_dismiss_telegram_secret', 'nonce', false)) {
187 - wp_send_json_error();
188 - }
189 - update_option('mxchat_dismissed_telegram_secret_notice', '1', 'no');
190 - wp_send_json_success();
191 - }
192 -
193 - /**
194 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
195 - * switch. Pure option comparison — no counts, no DB queries beyond the
196 - * cached options. The dialog is shown whenever the user has previously
197 - * embedded with a different model than the one they're switching to.
198 - */
199 - public function mxchat_check_embedding_switch_ajax() {
200 - check_ajax_referer('mxchat_admin_nonce', 'security');
201 - if (!current_user_can('manage_options')) {
202 - wp_send_json_error(__('Unauthorized', 'mxchat'));
203 - }
204 -
205 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
206 - $options = get_option('mxchat_options', array());
207 - if (isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
208 - // The standard dropdown is inert while custom embeddings are on —
209 - // whatever value it posts, the next embed uses the custom identity.
210 - $new_model = MxChat_Utils::get_selected_embedding_model($options);
211 - }
212 - $active_model = MxChat_Utils::get_active_embedding_model();
213 -
214 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
215 -
216 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
217 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
218 -
219 - wp_send_json_success(array(
220 - 'is_mismatch' => $is_mismatch,
221 - 'active_model' => $active_model,
222 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
223 - 'new_model' => $new_model,
224 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
225 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
226 - 'active_dims' => $active_dims,
227 - 'new_dims' => $new_dims,
228 - ));
229 - }
230 -
231 - /**
232 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
233 - * pair so the banner reappears on the next switch event.
234 - */
235 - public function mxchat_dismiss_embedding_mismatch_ajax() {
236 - check_ajax_referer('mxchat_admin_nonce', 'security');
237 - if (!current_user_can('manage_options')) {
238 - wp_send_json_error(__('Unauthorized', 'mxchat'));
239 - }
240 -
241 - $options = get_option('mxchat_options', array());
242 - $selected = MxChat_Utils::get_selected_embedding_model($options);
243 - $active = MxChat_Utils::get_active_embedding_model();
244 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
245 - wp_send_json_success();
246 - }
247 -
248 - /**
249 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
250 - * (last used to actually embed something) differs from the currently
251 - * selected model. Pure option comparison — no DB queries on every page
252 - * load. The banner auto-clears once both match again, i.e. after a delete
253 - * + re-embed cycle.
254 - */
255 - public function mxchat_embedding_mismatch_notice() {
256 - if (!current_user_can('manage_options')) {
257 - return;
258 - }
259 -
260 - $options = get_option('mxchat_options', array());
261 - $selected = MxChat_Utils::get_selected_embedding_model($options);
262 - $active = MxChat_Utils::get_active_embedding_model();
263 -
264 - if (empty($active) || empty($selected) || $active === $selected) {
265 - return;
266 - }
267 -
268 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
269 - if ($dismissed === $active . '|' . $selected) {
270 - return;
271 - }
272 -
273 - $active_label = MxChat_Utils::embedding_model_label($active);
274 - $selected_label = MxChat_Utils::embedding_model_label($selected);
275 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
276 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
277 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
278 -
279 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
280 - $actions_url = admin_url('admin.php?page=mxchat-actions');
281 -
282 - ?>
283 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
284 - data-active="<?php echo esc_attr($active); ?>"
285 - data-selected="<?php echo esc_attr($selected); ?>">
286 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
287 - <p>
288 - <?php
289 - printf(
290 - /* translators: 1: previously-used model name, 2: currently-selected model name */
291 - 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'),
292 - '<code>' . esc_html($active_label) . '</code>',
293 - '<code>' . esc_html($selected_label) . '</code>'
294 - );
295 - ?>
296 - </p>
297 - <?php if ($dims_differ) : ?>
298 - <p>
299 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
300 - <?php
301 - printf(
302 - /* translators: 1: old dim count, 2: new dim count */
303 - 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'),
304 - (int) $active_dims,
305 - (int) $selected_dims
306 - );
307 - ?>
308 - </p>
309 - <?php endif; ?>
310 - <p>
311 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
312 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
313 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
314 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
315 - </p>
316 - </div>
317 - <script>
318 - (function($){
319 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
320 - $.post(ajaxurl, {
321 - action: 'mxchat_dismiss_embedding_mismatch',
322 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
323 - });
324 - });
325 - })(jQuery);
326 - </script>
327 - <?php
328 - }
329 -
330 -private function is_license_active() {
331 - $license_status = get_option('mxchat_license_status', 'inactive');
332 - return ($license_status === 'active');
333 -}
334 -
335 -public function initialize_default_options() {
336 - // Re-check under the hook: another request may have seeded the option
337 - // between the constructor's check on plugins_loaded and init firing.
338 - if (get_option('mxchat_options')) {
339 - return;
340 - }
47 + // Initialize default options
48 +private function initialize_default_options() {
341 49 $default_options = array(
342 50 'api_key' => '',
343 - 'xai_api_key' => '',
344 - 'claude_api_key' => '',
345 - 'deepseek_api_key' => '',
346 - 'voyage_api_key' => '',
347 - 'gemini_api_key' => '',
348 - 'enable_streaming_toggle' => 'off',
349 - 'enable_web_search' => 'off',
350 - 'embedding_model' => 'text-embedding-ada-002',
351 - '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:
352 -
353 - # Response Style - CRITICALLY IMPORTANT
354 - - MAXIMUM LENGTH: 1-3 short sentences per response
355 - - Ultra-concise: Get straight to the answer with no filler
356 - - No introductions like "Sure!" or "I\'d be happy to help"
357 - - No phrases like "based on my knowledge" or "according to information"
358 - - No explanatory text before giving the answer
359 - - No summaries or repetition
360 - - Hyperlink all URLs
361 - - Respond in user\'s language
362 - - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
363 -
364 - # Knowledge Base Requirements - PREVENT HALLUCINATIONS
365 - - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
366 - - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
367 - - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
368 - - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
369 - - Better to admit insufficient information than provide inaccurate answers',
370 - 'model' => 'gpt-5.6-sol',
371 - 'rate_limit_logged_out' => '100',
372 - 'role_rate_limits' => array(),
373 - 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
374 - 'enable_email_block' => '',
375 - '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'),
376 - 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
377 - 'enable_name_field' => 'off', // NEW
378 - 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
379 - 'enable_consent_checkbox' => 'off', // b062c4 — default OFF: changes an existing form on every install
380 - 'consent_checkbox_label' => __('I agree to the Privacy Policy.', 'mxchat'),
381 - 'consent_checkbox_required' => 'off',
382 - 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
383 - 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
384 - 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
385 - 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
51 + '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:
52 + - Your name is [Chatbot Name]. Always introduce yourself as this name when appropriate.
53 + - 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.
54 + - When appropriate, highlight the benefits of [insert proper subject here]. Offer to guide visitors to relevant pages or provide them with more information.
55 + - 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.
56 + - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
57 + - 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.
58 + - 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.',
59 + 'model' => 'gpt-3.5-turbo',
60 + 'rate_limit' => '100',
61 + 'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
62 + 'top_bar_title' => 'MxChat',
63 + 'intro_message' => 'Hello! How can I assist you today?',
64 + 'input_copy' => 'How can I assist?',
386 65 'append_to_body' => 'off',
387 - 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
388 - 'post_type_visibility_list' => array(), // Array of post type slugs
389 - 'contextual_awareness_toggle' => 'off',
390 - 'citation_links_toggle' => 'on',
391 - 'satisfaction_rating_enabled' => 'off',
392 - 'satisfaction_rating_idle_seconds' => 60,
393 - 'satisfaction_rating_question' => '',
394 - 'satisfaction_rating_thanks' => '',
395 - 'satisfaction_rating_placeholder' => '',
396 - 'satisfaction_rating_saved' => '',
397 66 'close_button_color' => '#fff',
398 67 'chatbot_bg_color' => '#fff',
399 68 'user_message_bg_color' => '#fff',
400 69 'user_message_font_color' => '#212121',
@@ -405,58 +74,18 @@
405 74 'chat_input_font_color' => '#212121',
406 75 'chatbot_background_color' => '#212121',
407 76 'icon_color' => '#fff',
408 77 'enable_woocommerce_integration' => '0',
78 + 'enable_woocommerce_order_access' => '0',
409 79 'link_target_toggle' => 'off',
410 - 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
80 + 'pre_chat_message' => 'Hey there! Ask me anything!',
411 81
412 82 // New fields for Loops Integration
413 83 'loops_api_key' => '',
414 84 'loops_mailing_list' => '',
415 - 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
416 - 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
417 - 'popular_question_1' => '',
418 - 'popular_question_2' => '',
419 - 'popular_question_3' => '',
420 - 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
421 - 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
422 - 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
423 - 'pdf_max_pages' => 69,
424 - 'show_pdf_upload_button' => 'on',
425 - 'show_word_upload_button' => 'on',
426 -
427 - // Live Agent Integration (Slack)
428 - 'live_agent_webhook_url' => '',
429 - 'live_agent_secret_key' => '',
430 - 'live_agent_bot_token' => '',
431 - 'live_agent_message_bg_color' => '#ffffff',
432 - 'live_agent_message_font_color' => '#333333',
433 -
434 - // Telegram Integration
435 - 'telegram_status' => 'off',
436 - 'telegram_bot_token' => '',
437 - 'telegram_group_id' => '',
438 - 'telegram_webhook_secret' => '',
439 - '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'),
440 - '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'),
441 -
442 - // Webhook handoff destination (plan d88e22, outbound-only)
443 - 'webhook_handoff_status' => 'off',
444 - 'webhook_handoff_url' => '',
445 - 'webhook_handoff_secret' => '',
446 - 'webhook_handoff_notification_message' => __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat'),
447 - 'webhook_handoff_away_message' => __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'),
448 -
449 - 'chat_toolbar_toggle' => 'off',
450 - 'mode_indicator_bg_color' => '#767676',
451 - 'mode_indicator_font_color' => '#ffffff',
452 - 'toolbar_icon_color' => '#212121',
453 -
454 - // Optimization settings
455 - 'script_loading_strategy' => 'default',
456 -
457 - // Debug settings
458 - 'debug_mode' => 'off',
85 + 'trigger_keywords' => '',
86 + 'triggered_phrase_response' => 'Would you like to join our mailing list? Please provide your email below.',
87 + 'email_capture_response' => 'Thank you for providing your email! You\'ve been added to our list.',
459 88 );
460 89
461 90
462 91 // Merge existing options with defaults
@@ -467,700 +96,122 @@
467 96 if ($existing_options !== $merged_options) {
468 97 update_option('mxchat_options', $merged_options);
469 98 }
470 99
471 - // Add default limits for each role
472 - $roles = wp_roles()->get_names();
473 - foreach ($roles as $role_id => $role_name) {
474 - $default_options['role_rate_limits'][$role_id] = '100';
475 - }
476 -
477 - return $default_options;
478 -
479 100 // Update the $this->options property
480 101 $this->options = $merged_options;
481 102 }
482 103
483 -public function mxchat_add_plugin_page() {
484 - // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file).
485 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
486 104
487 - // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu
488 - // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now
489 - // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding).
490 - add_menu_page(
491 - esc_html__('MxChat', 'mxchat'),
492 - esc_html__('MxChat', 'mxchat'),
493 - 'manage_options',
494 - 'mxchat-max',
495 - array($this, 'mxchat_create_dashboard_page'),
496 - 'dashicons-testimonial',
497 - 6
498 - );
499 105
500 - // Onboarding submenu — first child under MxChat (plan-d14e89).
501 - // First registration uses menu_slug === parent slug 'mxchat-max' →
502 - // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the
503 - // first child shows as "Onboarding" instead of a redundant pair.
504 - add_submenu_page(
505 - 'mxchat-max',
506 - esc_html__('MxChat Onboarding', 'mxchat'),
507 - esc_html__('Onboarding', 'mxchat'),
508 - 'manage_options',
509 - 'mxchat-max',
510 - array($this, 'mxchat_create_dashboard_page')
511 - );
512 - // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link
513 - // + legacy redirects still target this slug). Parent === null keeps it
514 - // out of the menu while remaining accessible by URL.
515 - add_submenu_page(
516 - null,
517 - esc_html__('MxChat Onboarding', 'mxchat'),
518 - esc_html__('Onboarding', 'mxchat'),
519 - 'manage_options',
520 - 'mxchat-onboarding',
521 - array($this, 'mxchat_create_dashboard_page')
522 - );
106 + public function mxchat_add_plugin_page() {
107 + // Main menu page
108 + add_menu_page(
109 + 'MxChat Settings',
110 + 'MxChat',
111 + 'manage_options',
112 + 'mxchat-max',
113 + array($this, 'mxchat_create_admin_page'),
114 + 'dashicons-testimonial',
115 + 6
116 + );
523 117
524 - // Settings submenu — same callback as before, just at a new slug.
525 - add_submenu_page(
526 - 'mxchat-max',
527 - esc_html__('MxChat Settings', 'mxchat'),
528 - esc_html__('Settings', 'mxchat'),
529 - 'manage_options',
530 - 'mxchat-settings',
531 - array($this, 'mxchat_create_admin_page')
532 - );
118 + // Submenu page for Knowledge
119 + add_submenu_page(
120 + 'mxchat-max',
121 + 'Prompts',
122 + 'Knowledge',
123 + 'manage_options',
124 + 'mxchat-prompts',
125 + array($this, 'mxchat_create_prompts_page')
126 + );
533 127
534 - // Submenu page for Knowledge
535 - add_submenu_page(
536 - 'mxchat-max',
537 - esc_html__('Prompts', 'mxchat'),
538 - esc_html__('Knowledge', 'mxchat'),
539 - 'manage_options',
540 - 'mxchat-prompts',
541 - array($this, 'mxchat_create_prompts_page')
542 - );
128 + // Submenu page for Chat Transcripts
129 + add_submenu_page(
130 + 'mxchat-max', // Corrected parent slug to match the main menu
131 + 'Chat Transcripts',
132 + 'Transcripts',
133 + 'manage_options',
134 + 'mxchat-transcripts',
135 + array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
136 + );
543 137
544 - add_submenu_page(
545 - 'mxchat-max',
546 - esc_html__('Chat Transcripts', 'mxchat'),
547 - esc_html__('Transcripts', 'mxchat'),
548 - 'manage_options',
549 - 'mxchat-transcripts',
550 - array($this, 'mxchat_create_transcripts_page')
551 - );
552 -
553 - add_submenu_page(
554 - 'mxchat-max',
555 - esc_html__('MxChat Actions', 'mxchat'),
556 - esc_html__('Actions', 'mxchat'),
557 - 'manage_options',
558 - 'mxchat-actions',
559 - array($this, 'mxchat_actions_page_html')
560 - );
561 -
562 - // Content Generator page
563 - add_submenu_page(
564 - 'mxchat-max',
565 - esc_html__('Content', 'mxchat'),
566 - esc_html__('Content', 'mxchat'),
567 - 'manage_options',
568 - 'mxchat-content',
569 - array($this, 'mxchat_create_content_page')
570 - );
571 -
572 -}
573 -
574 -/**
575 - * Register the Pro & Extensions submenu on a later admin_menu priority so it
576 - * always renders as the bottom-most item in the MxChat sidebar — below
577 - * configuration pages like API Access (priority 20).
578 - */
579 -public function mxchat_add_pro_extensions_page() {
580 - add_submenu_page(
581 - 'mxchat-max',
582 - esc_html__('Pro & Extensions', 'mxchat'),
583 - esc_html__('Pro & Extensions', 'mxchat'),
584 - 'manage_options',
585 - 'mxchat-activation',
586 - array($this, 'mxchat_create_activation_page')
587 - );
588 -}
589 -
590 -public function mxchat_create_addons_page() {
591 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
592 - $addons_page = new MxChat_Addons();
593 - $addons_page->render_page();
594 -}
595 -
596 -/**
597 - * Render the Content Generator admin page
598 - */
599 -public function mxchat_create_content_page() {
600 - require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
601 - // The Editor Assistant toggle on the Settings tab renders through
602 - // mxchat_render_field_wrapper(), which lives in admin-settings-page.php
603 - // (plan-f7df40 relocation) — load it the same way the settings page does.
604 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
605 - mxchat_render_content_page($this);
606 -}
607 -
608 -/**
609 - * Test actual streaming functionality in the WordPress environment
610 - */
611 -public function mxchat_handle_test_streaming_actual() {
612 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
613 -
614 - // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler
615 - // reads the site's provider keys and spends them on an outbound call, so it
616 - // is billable abuse for any logged-in user who obtained the nonce.
617 - if (!current_user_can('manage_options')) {
618 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
138 + // Submenu page for Activation Key
139 + add_submenu_page(
140 + 'mxchat-max',
141 + 'Pro Upgrade',
142 + 'Pro Upgrade',
143 + 'manage_options',
144 + 'mxchat-activation',
145 + array($this, 'mxchat_create_activation_page')
146 + );
619 147 }
620 148
621 - // Check if headers have already been sent
622 - if (headers_sent()) {
623 - wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
624 - return;
625 - }
626 149
627 - // Check for required functions
628 - if (!function_exists('curl_init')) {
629 - wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
150 +public function mxchat_handle_content_submission() {
151 + // Check if the form was submitted and the user has sufficient permissions
152 + if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
630 153 return;
631 154 }
632 155
633 - // Get user's selected model and API key
634 - $options = get_option('mxchat_options', []);
635 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
636 -
637 - // Get the provider from the model
638 - $model_parts = explode('-', $selected_model);
639 - $provider = strtolower($model_parts[0]);
640 -
641 - // Get the appropriate API key
642 - $api_key = '';
643 - switch ($provider) {
644 - case 'gpt':
645 - case 'o1':
646 - $api_key = $options['api_key'] ?? '';
647 - break;
648 - case 'claude':
649 - $api_key = $options['claude_api_key'] ?? '';
650 - break;
651 - case 'grok':
652 - $api_key = $options['xai_api_key'] ?? '';
653 - break;
654 - case 'deepseek':
655 - $api_key = $options['deepseek_api_key'] ?? '';
656 - break;
657 - case 'gemini':
658 - $api_key = $options['gemini_api_key'] ?? '';
659 - break;
660 - default:
661 - // Default to OpenAI for unknown models
662 - $api_key = $options['api_key'] ?? '';
663 - $provider = 'gpt';
664 - break;
156 + // Verify the nonce field for security
157 + $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
158 + if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
159 + wp_die('Nonce verification failed.');
665 160 }
666 161
667 - if (empty($api_key)) {
668 - wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
669 - return;
670 - }
162 + // Sanitize the content input
163 + $article_content = sanitize_textarea_field($_POST['article_content']);
671 164
672 - // Test streaming with the selected model and provider
673 - try {
674 - $this->perform_streaming_test($provider, $selected_model, $api_key);
675 - } catch (Exception $e) {
676 - wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
677 - }
678 -}
165 + // Sanitize the URL input (optional URL)
166 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : ''; // Default to empty if not provided
679 167
680 -/**
681 - * Perform the actual streaming test
682 - */
683 -private function perform_streaming_test($provider, $model, $api_key) {
684 - // Set streaming headers
685 - header('Content-Type: text/event-stream');
686 - header('Cache-Control: no-cache');
687 - header('X-Accel-Buffering: no'); // Disable nginx buffering
168 + // Generate the embedding vector for the content
169 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
688 170
689 - // Prepare test message
690 - $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
171 + global $wpdb;
172 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
691 173
692 - // Configure API request based on provider
693 - $url = '';
694 - $headers = [];
695 - $body = [];
696 -
697 - switch ($provider) {
698 - case 'gpt':
699 - case 'o1':
700 - $url = 'https://api.openai.com/v1/chat/completions';
701 - $headers = [
702 - 'Content-Type: application/json',
703 - 'Authorization: Bearer ' . $api_key
704 - ];
705 - $body = [
706 - 'model' => $model,
707 - 'messages' => [['role' => 'user', 'content' => $test_message]],
708 - 'max_tokens' => 50,
709 - 'temperature' => 0.3,
710 - 'stream' => true
711 - ];
712 - break;
713 -
714 - case 'claude':
715 - $url = 'https://api.anthropic.com/v1/messages';
716 - $headers = [
717 - 'Content-Type: application/json',
718 - 'x-api-key: ' . $api_key,
719 - 'anthropic-version: 2023-06-01'
720 - ];
721 - $body = [
722 - 'model' => $model,
723 - 'messages' => [['role' => 'user', 'content' => $test_message]],
724 - 'max_tokens' => 50,
725 - 'temperature' => 0.3,
726 - 'stream' => true
727 - ];
728 - // Claude flagships from Opus 4.7 onward reject the temperature
729 - // param outright (400). Reuse the catalog's decision — this path
730 - // previously sent temperature unconditionally, so the streaming
731 - // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5.
732 - if (class_exists('MxChat_Model_Catalog')
733 - && method_exists('MxChat_Model_Catalog', 'supports_temperature')
734 - && !MxChat_Model_Catalog::supports_temperature($model)) {
735 - unset($body['temperature']);
736 - }
737 - break;
738 -
739 - case 'grok':
740 - $url = 'https://api.x.ai/v1/chat/completions';
741 - $headers = [
742 - 'Content-Type: application/json',
743 - 'Authorization: Bearer ' . $api_key
744 - ];
745 - $body = [
746 - 'model' => $model,
747 - 'messages' => [['role' => 'user', 'content' => $test_message]],
748 - 'max_tokens' => 50,
749 - 'temperature' => 0.3,
750 - 'stream' => true
751 - ];
752 - break;
753 -
754 - case 'deepseek':
755 - $url = 'https://api.deepseek.com/v1/chat/completions';
756 - $headers = [
757 - 'Content-Type: application/json',
758 - 'Authorization: Bearer ' . $api_key
759 - ];
760 - $body = [
761 - 'model' => $model,
762 - 'messages' => [['role' => 'user', 'content' => $test_message]],
763 - 'max_tokens' => 50,
764 - 'temperature' => 0.3,
765 - 'stream' => true,
766 - // DeepSeek V4 defaults to thinking mode ON — reasoning would
767 - // consume the 50-token test budget and return no visible text.
768 - 'thinking' => ['type' => 'disabled']
769 - ];
770 - break;
771 -
772 - default:
773 - echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
774 - flush();
775 - return;
174 + // Check if the 'source_url' column exists in the table and add it if it doesn't
175 + if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
176 + // Use wpdb::query and a prepared statement to avoid SQL injection
177 + $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
776 178 }
777 179
778 - // Initialize cURL
779 - $ch = curl_init();
780 - curl_setopt($ch, CURLOPT_URL, $url);
781 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
782 - curl_setopt($ch, CURLOPT_POST, true);
783 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
784 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
785 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
786 - curl_setopt($ch, CURLOPT_TIMEOUT, 30);
787 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
788 - return $this->process_streaming_test_data($data, $provider);
789 - });
180 + if (is_array($embedding_vector)) {
181 + // Serialize the embedding vector before storing it
182 + $embedding_vector_serialized = serialize($embedding_vector);
790 183
791 - // Send initial test message
792 - echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
793 - flush();
794 -
795 - $result = curl_exec($ch);
796 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
797 - $curl_error = curl_error($ch);
798 - curl_close($ch);
799 -
800 - if ($curl_error) {
801 - echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
802 - flush();
803 - return;
804 - }
805 -
806 - if ($http_code !== 200) {
807 - echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
808 - flush();
809 - return;
810 - }
811 -
812 - // Send completion signal
813 - echo "data: [DONE]\n\n";
814 - flush();
815 -}
816 -
817 -/**
818 - * Process streaming data for the test
819 - */
820 -private function process_streaming_test_data($data, $provider) {
821 - static $chunk_count = 0;
822 -
823 - $lines = explode("\n", $data);
824 -
825 - foreach ($lines as $line) {
826 - if (trim($line) === '') {
827 - continue;
828 - }
829 -
830 - // Handle different provider formats
831 - if ($provider === 'claude') {
832 - // Claude uses event: and data: format
833 - if (strpos($line, 'data: ') === 0) {
834 - $json_str = substr($line, 6);
835 - $json = json_decode($json_str, true);
836 -
837 - if (isset($json['type']) && $json['type'] === 'content_block_delta') {
838 - if (isset($json['delta']['text'])) {
839 - $chunk_count++;
840 - echo "data: " . json_encode([
841 - 'content' => $json['delta']['text'],
842 - 'test_chunk' => $chunk_count
843 - ]) . "\n\n";
844 - flush();
845 - }
846 - }
847 - }
848 - } else {
849 - // OpenAI, X.AI, DeepSeek format
850 - if (strpos($line, 'data: ') === 0) {
851 - $json_str = substr($line, 6);
852 -
853 - if ($json_str === '[DONE]') {
854 - // Don't echo [DONE] here, let the main function handle it
855 - continue;
856 - }
857 -
858 - $json = json_decode($json_str, true);
859 - if (isset($json['choices'][0]['delta']['content'])) {
860 - $chunk_count++;
861 - echo "data: " . json_encode([
862 - 'content' => $json['choices'][0]['delta']['content'],
863 - 'test_chunk' => $chunk_count
864 - ]) . "\n\n";
865 - flush();
866 - }
867 - }
868 - }
869 - }
870 -
871 - return strlen($data);
872 -}
873 -
874 -/**
875 - * Updated version of your existing test method (keep this as a fallback)
876 - */
877 -public function mxchat_handle_test_streaming() {
878 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
879 -
880 - // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but
881 - // fail here so the alias never becomes a bypass if that call is refactored.
882 - if (!current_user_can('manage_options')) {
883 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
884 - }
885 -
886 - // Use the actual streaming test instead
887 - $this->mxchat_handle_test_streaming_actual();
888 -}
889 -
890 -
891 -public function register_pinecone_settings() {
892 - register_setting(
893 - 'mxchat_pinecone_addon_options',
894 - 'mxchat_pinecone_addon_options',
895 - array(
896 - 'type' => 'array',
897 - 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
898 - 'default' => array(
899 - 'mxchat_use_pinecone' => '0',
900 - 'mxchat_pinecone_api_key' => '',
901 - 'mxchat_pinecone_host' => '',
902 - 'mxchat_pinecone_index' => '',
903 - 'mxchat_pinecone_environment' => '',
904 - 'mxchat_pinecone_top_k' => '50'
905 - )
906 - )
907 - );
908 -}
909 -
910 -public function sanitize_pinecone_settings($input) {
911 - $sanitized = array();
912 -
913 - $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
914 - $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
915 - $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
916 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
917 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
918 -
919 - // d0cae1: this function REBUILDS the array, so the topK key must be
920 - // carried here or any form save strips it. Clamp mirrors the read site.
921 - $top_k = absint($input['mxchat_pinecone_top_k'] ?? 50);
922 - $sanitized['mxchat_pinecone_top_k'] = (string) (($top_k >= 1 && $top_k <= 1000) ? $top_k : 50);
923 -
924 - // Remove https:// from host if present
925 - $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
926 -
927 - return $sanitized;
928 -}
929 -
930 -public function register_openai_vectorstore_settings() {
931 - register_setting(
932 - 'mxchat_openai_vectorstore_options',
933 - 'mxchat_openai_vectorstore_options',
934 - array(
935 - 'type' => 'array',
936 - 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
937 - 'default' => array(
938 - 'mxchat_use_openai_vectorstore' => '0',
939 - 'mxchat_vectorstore_ids' => '',
940 - 'mxchat_vectorstore_max_results' => 5,
941 - 'mxchat_vectorstore_sync_enabled' => '0',
942 - 'mxchat_vectorstore_sync_store_id' => ''
943 - )
944 - )
945 - );
946 -}
947 -
948 -public function sanitize_openai_vectorstore_settings($input) {
949 - $sanitized = array();
950 -
951 - $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
952 - $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
953 - $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
954 -
955 - // Knowledge-base sync (write path, plan 15b5c6). Store ID may be blank —
956 - // the sync falls back to the first retrieval ID above.
957 - $sanitized['mxchat_vectorstore_sync_enabled'] = isset($input['mxchat_vectorstore_sync_enabled']) ? '1' : '0';
958 - $sanitized['mxchat_vectorstore_sync_store_id'] = sanitize_text_field($input['mxchat_vectorstore_sync_store_id'] ?? '');
959 -
960 - // Ensure max results is within reasonable range
961 - if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
962 - $sanitized['mxchat_vectorstore_max_results'] = 1;
963 - }
964 - if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
965 - $sanitized['mxchat_vectorstore_max_results'] = 20;
966 - }
967 -
968 - return $sanitized;
969 -}
970 -
971 -/**
972 - * AJAX handler to test OpenAI Vector Store connection
973 - */
974 -public function mxchat_test_vectorstore_connection() {
975 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
976 -
977 - if (!current_user_can('manage_options')) {
978 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
979 - return;
980 - }
981 -
982 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
983 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
984 - $mxchat_options = get_option('mxchat_options', array());
985 - $api_key = $mxchat_options['api_key'] ?? '';
986 -
987 - if (empty($api_key)) {
988 - wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
989 - return;
990 - }
991 -
992 - if (empty($vectorstore_ids)) {
993 - wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
994 - return;
995 - }
996 -
997 - // Get the first Vector Store ID for testing
998 - $ids_array = array_map('trim', explode(',', $vectorstore_ids));
999 - $test_id = $ids_array[0];
1000 -
1001 - // Test by retrieving the Vector Store info
1002 - $response = wp_remote_get(
1003 - 'https://api.openai.com/v1/vector_stores/' . $test_id,
1004 - array(
1005 - 'headers' => array(
1006 - 'Authorization' => 'Bearer ' . $api_key,
1007 - 'Content-Type' => 'application/json',
1008 - 'OpenAI-Beta' => 'assistants=v2'
184 + // Insert the content, embedding vector, and source URL into the database, using a prepared statement
185 + $inserted = $wpdb->insert(
186 + $table_name,
187 + array(
188 + 'article_content' => $article_content,
189 + 'embedding_vector' => $embedding_vector_serialized,
190 + 'source_url' => $article_url, // Insert the URL, empty string if not provided
1009 191 ),
1010 - 'timeout' => 30
1011 - )
1012 - );
1013 -
1014 - if (is_wp_error($response)) {
1015 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
1016 - return;
1017 - }
1018 -
1019 - $status_code = wp_remote_retrieve_response_code($response);
1020 - $body = json_decode(wp_remote_retrieve_body($response), true);
1021 -
1022 - if ($status_code === 200 && isset($body['id'])) {
1023 - $file_count = $body['file_counts']['completed'] ?? 0;
1024 - $name = $body['name'] ?? $test_id;
1025 - wp_send_json_success(array(
1026 - 'message' => sprintf(
1027 - __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
1028 - esc_html($name),
1029 - $file_count
192 + array(
193 + '%s', // Format for article_content (string)
194 + '%s', // Format for embedding_vector (serialized string)
195 + '%s', // Format for source_url (string)
1030 196 )
1031 - ));
1032 - } elseif ($status_code === 404) {
1033 - wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
1034 - } elseif ($status_code === 401) {
1035 - wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
1036 - } else {
1037 - $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
1038 - wp_send_json_error(array('message' => $error_message));
1039 - }
1040 -}
1041 -
1042 -/**
1043 - * AJAX handler to test Slack connection and validate scopes
1044 - */
1045 -public function mxchat_test_slack_connection() {
1046 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
1047 -
1048 - if (!current_user_can('manage_options')) {
1049 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1050 - return;
1051 - }
1052 -
1053 - $bot_token = $this->options['live_agent_bot_token'] ?? '';
1054 -
1055 - if (empty($bot_token)) {
1056 - wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
1057 - return;
1058 - }
1059 -
1060 - // Test 1: Validate bot token with auth.test
1061 - $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
1062 - 'headers' => array(
1063 - 'Authorization' => 'Bearer ' . $bot_token,
1064 - 'Content-Type' => 'application/json'
1065 - ),
1066 - 'timeout' => 15
1067 - ));
1068 -
1069 - if (is_wp_error($auth_response)) {
1070 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
1071 - return;
1072 - }
1073 -
1074 - $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
1075 -
1076 - if (!isset($auth_body['ok']) || !$auth_body['ok']) {
1077 - $error = $auth_body['error'] ?? 'unknown_error';
1078 - $error_messages = array(
1079 - 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
1080 - 'not_authed' => __('No authentication token provided.', 'mxchat'),
1081 - 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
1082 - 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
1083 197 );
1084 - $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
1085 - wp_send_json_error(array('message' => $message));
1086 - return;
1087 - }
1088 198
1089 - $team_name = $auth_body['team'] ?? 'Unknown Workspace';
1090 - $bot_name = $auth_body['user'] ?? 'Unknown Bot';
199 + if ($inserted === false) {
200 + //error_log('Error inserting content: ' . $wpdb->last_error);
201 + set_transient('mxchat_admin_notice_error', 'Error inserting content into the database. Please try again.', 30);
202 + } else {
203 + set_transient('mxchat_admin_notice_success', 'Content successfully submitted!', 30);
204 + }
1091 205
1092 - // Test 2: Check if we can list channels (tests channels:read scope)
1093 - $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
1094 - 'headers' => array(
1095 - 'Authorization' => 'Bearer ' . $bot_token,
1096 - 'Content-Type' => 'application/json'
1097 - ),
1098 - 'body' => json_encode(array('limit' => 1)),
1099 - 'timeout' => 15
1100 - ));
1101 -
1102 - $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
1103 - $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
1104 -
1105 - // Test 3: Check if we can create channels (tests channels:manage scope)
1106 - // We'll just check the error message without actually creating
1107 - $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
1108 - 'headers' => array(
1109 - 'Authorization' => 'Bearer ' . $bot_token,
1110 - 'Content-Type' => 'application/json'
1111 - ),
1112 - 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
1113 - 'timeout' => 15
1114 - ));
1115 -
1116 - $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
1117 -
1118 - // If channel was created, delete it immediately
1119 - if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
1120 - wp_remote_post('https://slack.com/api/conversations.archive', array(
1121 - 'headers' => array(
1122 - 'Authorization' => 'Bearer ' . $bot_token,
1123 - 'Content-Type' => 'application/json'
1124 - ),
1125 - 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
1126 - 'timeout' => 15
1127 - ));
1128 - $can_create_channels = true;
1129 206 } else {
1130 - $create_error = $create_body['error'] ?? '';
1131 - // name_taken means we have permission but channel exists
1132 - $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
1133 -
1134 - // Check for missing scope errors
1135 - if ($create_error === 'missing_scope') {
1136 - $can_create_channels = false;
1137 - }
207 + //error_log('Embedding generation failed for article content: ' . $article_content);
208 + set_transient('mxchat_admin_notice_error', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
1138 209 }
1139 210
1140 - // Build result message
1141 - $results = array();
1142 - $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
1143 - $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
1144 - $results[] = '';
1145 - $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
1146 - $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
1147 -
1148 - $missing_scopes = array();
1149 - if (!$can_read_channels) $missing_scopes[] = 'channels:read';
1150 - if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
1151 -
1152 - if (!empty($missing_scopes)) {
1153 - wp_send_json_error(array(
1154 - 'message' => implode("\n", $results),
1155 - 'missing_scopes' => $missing_scopes,
1156 - 'partial' => true
1157 - ));
1158 - } else {
1159 - wp_send_json_success(array(
1160 - 'message' => implode("\n", $results)
1161 - ));
1162 - }
211 + // Redirect after setting the transient
212 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
213 + exit;
1163 214 }
1164 215
1165 216 public function mxchat_display_admin_notice() {
1166 217 // Success notice
@@ -1167,9 +218,9 @@
1167 218 if ($message = get_transient('mxchat_admin_notice_success')) {
1168 219 ?>
1169 220 <div class="notice notice-success is-dismissible">
1170 221 <p><?php echo esc_html($message); ?></p>
1171 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
222 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1172 223 </div>
1173 224 <?php
1174 225 delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1175 226 }
@@ -1178,9 +229,9 @@
1178 229 if ($message = get_transient('mxchat_admin_notice_error')) {
1179 230 ?>
1180 231 <div class="notice notice-error is-dismissible">
1181 232 <p><?php echo esc_html($message); ?></p>
1182 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
233 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1183 234 </div>
1184 235 <?php
1185 236 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1186 237 }
@@ -1185,5165 +236,558 @@
1185 236 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1186 237 }
1187 238 }
1188 239
1189 -public function show_live_agent_disabled_banner() {
1190 - $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1191 240
1192 - if ($show_disabled_notice) {
1193 - ?>
1194 - <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1195 - <div class="mxchat-pro-notification">
1196 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1197 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1198 - <line x1="18" y1="6" x2="6" y2="18"></line>
1199 - <line x1="6" y1="6" x2="18" y2="18"></line>
1200 - </svg>
1201 - </button>
1202 - <div class="mxchat-live-agent-content">
1203 - <h3>🔧 Live Agent Integration Updated!</h3>
1204 - <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>
1205 - </div>
1206 - </div>
1207 - </div>
1208 - <?php
1209 - }
1210 -}
1211 -/**
1212 - * Render the Onboarding page. Delegates to the procedural renderer in
1213 - * includes/admin-onboarding-page.php. Wired to both `?page=mxchat-max`
1214 - * (legacy top-level URL) and `?page=mxchat-onboarding` (the canonical
1215 - * Onboarding submenu).
1216 - *
1217 - * When the user has dismissed onboarding and lands on `mxchat-max` (the
1218 - * legacy URL, since the Onboarding submenu has been removed), redirect to
1219 - * Settings instead — the page is "graduated" and we shouldn't dump them
1220 - * back onto it. They can still navigate here directly via the unhide link.
1221 - */
1222 -public function mxchat_create_dashboard_page() {
1223 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
1224 -
1225 - $current = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1226 - if ($current === 'mxchat-max' && function_exists('mxchat_onboarding_is_dismissed') && mxchat_onboarding_is_dismissed()) {
1227 - wp_safe_redirect(admin_url('admin.php?page=mxchat-settings'));
1228 - exit;
1229 - }
1230 -
1231 - if (function_exists('mxchat_render_onboarding_page')) {
1232 - mxchat_render_onboarding_page();
1233 - return;
1234 - }
1235 - // Defensive: if the include failed to load, fall back to the old Settings page
1236 - // so the top-level menu never lands on an empty screen.
1237 - $this->mxchat_create_admin_page();
1238 -}
1239 -
1240 -/**
1241 - * Hide the Onboarding submenu when the user has dismissed it (either
1242 - * manually or via auto-graduation). The page itself remains routable so
1243 - * the Settings "Show MxChat Onboarding again" link can navigate back to it.
1244 - */
1245 -public function mxchat_apply_onboarding_visibility() {
1246 - if (!function_exists('mxchat_onboarding_is_dismissed')) {
1247 - return;
1248 - }
1249 - if (mxchat_onboarding_is_dismissed()) {
1250 - // The first MxChat child is the same-slug-as-parent registration
1251 - // (slug 'mxchat-max', labelled "Onboarding") added in plan-d14e89.
1252 - // Remove it so the menu opens straight to Settings after dismiss.
1253 - remove_submenu_page('mxchat-max', 'mxchat-max');
1254 - }
1255 -}
1256 -
1257 -public function mxchat_create_admin_page() {
1258 - $this->add_live_agent_nonce();
1259 - $this->add_theme_migration_nonce();
1260 -
1261 - // Include and render the new sidebar-based settings page
1262 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1263 - mxchat_render_settings_page($this);
1264 -}
1265 -
1266 -public function dismiss_live_agent_notice() {
1267 - // Add debugging
1268 - //error_log('dismiss_live_agent_notice called');
1269 - //error_log('POST data: ' . print_r($_POST, true));
1270 -
1271 - // Verify nonce
1272 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1273 - //error_log('Nonce verification failed');
1274 - wp_die('Security check failed');
1275 - }
1276 -
1277 - // Remove the notice flag
1278 - $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1279 - //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
1280 -
1281 - wp_send_json_success();
1282 -}
1283 -public function add_live_agent_nonce() {
1284 - if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1285 - // Make sure your admin script is enqueued and localize the data
1286 - wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1287 - 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1288 - 'ajaxurl' => admin_url('admin-ajax.php')
1289 - ));
1290 - }
1291 -}
1292 -
1293 -/**
1294 - * Show theme migration notice for Pro users with AI-generated themes
1295 - * Only shown once - dismissible and stored in options
1296 - */
1297 -public function show_theme_migration_banner() {
1298 - // Only show if Pro is activated
1299 - if (!$this->is_activated) {
1300 - return;
1301 - }
1302 -
1303 - // Check if notice should be shown
1304 - $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1305 -
1306 - if ($show_notice) {
1307 - ?>
1308 - <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1309 - <div class="mxchat-pro-notification">
1310 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1311 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1312 - <line x1="18" y1="6" x2="6" y2="18"></line>
1313 - <line x1="6" y1="6" x2="18" y2="18"></line>
1314 - </svg>
1315 - </button>
1316 - <div class="mxchat-theme-migration-content">
1317 - <h3>🎨 AI Theme Migration Required</h3>
1318 - <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>
1319 - </div>
1320 - </div>
1321 - </div>
1322 - <?php
1323 - }
1324 -}
1325 -
1326 -/**
1327 - * Dismiss theme migration notice via AJAX
1328 - */
1329 -public function dismiss_theme_migration_notice() {
1330 - // Verify nonce
1331 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1332 - wp_die('Security check failed');
1333 - }
1334 -
1335 - // Remove the notice flag
1336 - delete_option('mxchat_show_theme_migration_notice');
1337 -
1338 - wp_send_json_success();
1339 -}
1340 -
1341 -/**
1342 - * Add nonce for theme migration notice dismiss
1343 - */
1344 -public function add_theme_migration_nonce() {
1345 - if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1346 - wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1347 - 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1348 - 'ajaxurl' => admin_url('admin-ajax.php')
1349 - ));
1350 - }
1351 -}
1352 -
1353 -public function mxchat_create_transcripts_page() {
1354 - global $wpdb;
1355 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1356 -
1357 - // Get basic stats
1358 - $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1359 - $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
1360 -
1361 - // Count unique users with detailed breakdown
1362 - $total_users = $wpdb->get_var("
1363 - SELECT COUNT(DISTINCT
1364 - CASE
1365 - WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1366 - WHEN user_id != 0 THEN CONCAT('user_', user_id)
1367 - WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1368 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1369 - AND user_identifier NOT LIKE 'Language Learner'
1370 - AND user_identifier NOT LIKE 'Casual Browser'
1371 - AND user_identifier NOT LIKE 'Policy Enforcer'
1372 - AND user_identifier NOT LIKE 'Researcher'
1373 - AND user_identifier NOT LIKE 'Loyalty Member'
1374 - AND user_identifier NOT LIKE 'Gift Buyer'
1375 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1376 - THEN user_identifier
1377 - ELSE session_id
1378 - END
1379 - )
1380 - FROM $table_name
1381 - WHERE role != 'assistant'
1382 - ");
1383 -
1384 - // Get user type breakdown
1385 - $registered_users = $wpdb->get_var("
1386 - SELECT COUNT(DISTINCT user_email)
1387 - FROM $table_name
1388 - WHERE user_email != '' AND user_email IS NOT NULL
1389 - ");
1390 -
1391 - $guest_users = $wpdb->get_var("
1392 - SELECT COUNT(DISTINCT user_identifier)
1393 - FROM $table_name
1394 - WHERE (user_email = '' OR user_email IS NULL)
1395 - AND role != 'assistant'
1396 - AND user_identifier NOT LIKE 'Tech-Savvy User'
1397 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1398 - AND user_identifier NOT LIKE 'Language Learner'
1399 - AND user_identifier NOT LIKE 'Casual Browser'
1400 - AND user_identifier NOT LIKE 'Policy Enforcer'
1401 - AND user_identifier NOT LIKE 'Researcher'
1402 - AND user_identifier NOT LIKE 'Loyalty Member'
1403 - AND user_identifier NOT LIKE 'Gift Buyer'
1404 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1405 - ");
1406 -
1407 - // Get agent test messages count
1408 - $agent_tests = $wpdb->get_var("
1409 - SELECT COUNT(DISTINCT session_id)
1410 - FROM $table_name
1411 - WHERE user_identifier IN (
1412 - 'Tech-Savvy User',
1413 - 'Detail-Oriented User',
1414 - 'Language Learner',
1415 - 'Casual Browser',
1416 - 'Policy Enforcer',
1417 - 'Researcher',
1418 - 'Loyalty Member',
1419 - 'Gift Buyer',
1420 - 'Parent or Caregiver'
1421 - )
1422 - ");
1423 - // Get activity metrics
1424 - $today_chats = $wpdb->get_var("
1425 - SELECT COUNT(DISTINCT session_id)
1426 - FROM $table_name
1427 - WHERE DATE(timestamp) = CURDATE()
1428 - ");
1429 -
1430 - $week_chats = $wpdb->get_var("
1431 - SELECT COUNT(DISTINCT session_id)
1432 - FROM $table_name
1433 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1434 - ");
1435 -
1436 - $month_chats = $wpdb->get_var("
1437 - SELECT COUNT(DISTINCT session_id)
1438 - FROM $table_name
1439 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1440 - ");
1441 -
1442 - // Get daily chat data for last 7 days
1443 - $daily_stats = $wpdb->get_results("
1444 - SELECT
1445 - DATE(timestamp) as date,
1446 - COUNT(DISTINCT session_id) as chats,
1447 - COUNT(*) as messages
1448 - FROM $table_name
1449 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1450 - GROUP BY DATE(timestamp)
1451 - ORDER BY date ASC
1452 - ");
1453 -
1454 - // Get average messages per chat
1455 - $avg_messages = $wpdb->get_var("
1456 - SELECT AVG(message_count)
1457 - FROM (
1458 - SELECT session_id, COUNT(*) as message_count
1459 - FROM $table_name
1460 - GROUP BY session_id
1461 - ) as chat_counts
1462 - ");
1463 - $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1464 -
1465 - // Get busiest hour
1466 - $busiest_hour = $wpdb->get_row("
1467 - SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1468 - FROM $table_name
1469 - GROUP BY HOUR(timestamp)
1470 - ORDER BY chat_count DESC
1471 - LIMIT 1
1472 - ");
1473 -
1474 - // Prepare chart data
1475 - $chart_labels = array();
1476 - $chart_chats = array();
1477 - $chart_messages = array();
1478 -
1479 - // Fill last 7 days with data
1480 - for ($i = 6; $i >= 0; $i--) {
1481 - $date = date('Y-m-d', strtotime("-$i days"));
1482 - $day_name = date('D', strtotime("-$i days"));
1483 - $chart_labels[] = $day_name;
1484 -
1485 - $found = false;
1486 - foreach ($daily_stats as $stat) {
1487 - if ($stat->date === $date) {
1488 - $chart_chats[] = (int)$stat->chats;
1489 - $chart_messages[] = (int)$stat->messages;
1490 - $found = true;
1491 - break;
1492 - }
241 + public function mxchat_handle_delete_prompt() {
242 + // Sanitize and validate nonce using wp_unslash and sanitize_text_field
243 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
244 + if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
245 + wp_die('Nonce verification failed.');
1493 246 }
1494 - if (!$found) {
1495 - $chart_chats[] = 0;
1496 - $chart_messages[] = 0;
1497 - }
1498 - }
1499 247
1500 - // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1501 - $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
1502 -
1503 - // Prepare page data for the template
1504 - $page_data = array(
1505 - 'total_chats' => $total_chats,
1506 - 'total_messages' => $total_messages,
1507 - 'total_users' => $total_users,
1508 - 'registered_users' => $registered_users,
1509 - 'guest_users' => $guest_users,
1510 - 'agent_tests' => $agent_tests,
1511 - 'today_chats' => $today_chats,
1512 - 'week_chats' => $week_chats,
1513 - 'month_chats' => $month_chats,
1514 - 'avg_messages' => $avg_messages,
1515 - 'busiest_hour' => $busiest_hour,
1516 - 'chart_labels' => $chart_labels,
1517 - 'chart_chats' => $chart_chats,
1518 - 'chart_messages' => $chart_messages,
1519 - 'satisfaction_stats' => $satisfaction_stats,
1520 - );
1521 -
1522 - // Include and render the new template
1523 - require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1524 - mxchat_render_transcripts_page($this, $page_data);
1525 -}
1526 -
1527 -/**
1528 - * Per-bot satisfaction rating rollup over the last $days days. Used by the
1529 - * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1530 - *
1531 - * @param int $days Window in days.
1532 - * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1533 - */
1534 -public function get_satisfaction_rating_stats($days = 30) {
1535 - global $wpdb;
1536 - $table = $wpdb->prefix . 'mxchat_session_ratings';
1537 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1538 - return array();
1539 - }
1540 - $days = max(1, (int) $days);
1541 - $rows = $wpdb->get_results($wpdb->prepare(
1542 - "SELECT bot_id,
1543 - COUNT(*) AS total,
1544 - SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1545 - SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1546 - FROM {$table}
1547 - WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1548 - GROUP BY bot_id
1549 - ORDER BY total DESC",
1550 - $days
1551 - ));
1552 - $out = array();
1553 - foreach ((array) $rows as $row) {
1554 - $total = (int) $row->total;
1555 - $positive = (int) $row->positive;
1556 - $negative = (int) $row->negative;
1557 - $out[] = array(
1558 - 'bot_id' => $row->bot_id ?: 'default',
1559 - 'total' => $total,
1560 - 'positive' => $positive,
1561 - 'negative' => $negative,
1562 - 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1563 - 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1564 - );
1565 - }
1566 - return $out;
1567 -}
1568 -
1569 -/**
1570 - * Get chart data for transcripts page
1571 - * Used by both page render and script localization
1572 - *
1573 - * @return array Chart data with labels, chats, and messages arrays
1574 - */
1575 -private function get_transcripts_chart_data() {
1576 - global $wpdb;
1577 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1578 -
1579 - // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1580 - $daily_stats = $wpdb->get_results("
1581 - SELECT
1582 - DATE(timestamp) as date,
1583 - COUNT(DISTINCT session_id) as chats,
1584 - COUNT(*) as messages
1585 - FROM $table_name
1586 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1587 - GROUP BY DATE(timestamp)
1588 - ORDER BY date ASC
1589 - ");
1590 -
1591 - // Prepare chart data
1592 - $chart_labels = array();
1593 - $chart_chats = array();
1594 - $chart_messages = array();
1595 -
1596 - // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1597 - for ($i = 6; $i >= 0; $i--) {
1598 - $date = date('Y-m-d', strtotime("-$i days"));
1599 - $day_name = date('D', strtotime("-$i days"));
1600 - $chart_labels[] = $day_name;
1601 -
1602 - $found = false;
1603 - if ($daily_stats) {
1604 - foreach ($daily_stats as $stat) {
1605 - if ($stat->date === $date) {
1606 - $chart_chats[] = (int)$stat->chats;
1607 - $chart_messages[] = (int)$stat->messages;
1608 - $found = true;
1609 - break;
1610 - }
1611 - }
248 + // Check user permissions
249 + if (!current_user_can('manage_options')) {
250 + wp_die('You do not have sufficient permissions to delete prompts.');
1612 251 }
1613 - if (!$found) {
1614 - $chart_chats[] = 0;
1615 - $chart_messages[] = 0;
1616 - }
1617 - }
1618 252
1619 - return array(
1620 - 'labels' => $chart_labels,
1621 - 'chats' => $chart_chats,
1622 - 'messages' => $chart_messages
1623 - );
1624 -}
1625 -
1626 -public function mxchat_transcripts_notification_section_callback() {
1627 - 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>';
1628 -}
1629 -public function mxchat_enable_notifications_callback() {
1630 - $options = get_option('mxchat_transcripts_options', array());
1631 - $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1632 - ?>
1633 - <label for="mxchat_enable_notifications">
1634 - <input type="checkbox" id="mxchat_enable_notifications"
1635 - name="mxchat_transcripts_options[mxchat_enable_notifications]"
1636 - value="1" <?php checked(1, $enabled); ?>>
1637 - <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1638 - </label>
1639 - <p class="description">
1640 - <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
1641 - </p>
1642 - <?php
1643 -}
1644 -public function mxchat_notification_email_callback() {
1645 - $options = get_option('mxchat_transcripts_options', array());
1646 - $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1647 - ?>
1648 - <?php /* type="text", not "email": the browser rejects a comma-separated list outright (plan 2f131a). Validation is server-side in MxChat_Utils. */ ?>
1649 - <input type="text" id="mxchat_notification_email"
1650 - name="mxchat_transcripts_options[mxchat_notification_email]"
1651 - value="<?php echo esc_attr($email); ?>"
1652 - class="regular-text">
1653 - <p class="description">
1654 - <?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); ?>
1655 - </p>
1656 - <?php
1657 -}
1658 -
1659 -public function mxchat_auto_delete_transcripts_callback() {
1660 - $options = get_option('mxchat_transcripts_options', array());
1661 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1662 - ?>
1663 - <select id="mxchat_auto_delete_transcripts"
1664 - name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1665 - <option value="never" <?php selected($interval, 'never'); ?>>
1666 - <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1667 - </option>
1668 - <option value="1week" <?php selected($interval, '1week'); ?>>
1669 - <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1670 - </option>
1671 - <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1672 - <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1673 - </option>
1674 - <option value="1month" <?php selected($interval, '1month'); ?>>
1675 - <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1676 - </option>
1677 - </select>
1678 - <p class="description">
1679 - <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
1680 - </p>
1681 - <?php
1682 -}
1683 -
1684 -/**
1685 - * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1686 - * and deletes transcripts older than the given number of days. Set to 0 to fall
1687 - * back to the dropdown (or "Never" if the dropdown is also Never).
1688 - *
1689 - * Devs can override the final day count via the `mxchat_transcript_retention_days`
1690 - * filter — runs in `cleanup_old_transcripts()` after this option is read.
1691 - *
1692 - * (plan-mxchat-20260509-9b80b1)
1693 - */
1694 -public function mxchat_retention_days_callback() {
1695 - $options = get_option('mxchat_transcripts_options', array());
1696 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1697 - ?>
1698 - <input type="number"
1699 - id="mxchat_retention_days"
1700 - name="mxchat_transcripts_options[mxchat_retention_days]"
1701 - value="<?php echo esc_attr($days); ?>"
1702 - min="0"
1703 - max="3650"
1704 - step="1"
1705 - style="width: 90px;" />
1706 - <p class="description">
1707 - <?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'); ?>
1708 - <br>
1709 - <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1710 - <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
1711 - </p>
1712 - <?php
1713 -}
1714 -
1715 -public function mxchat_auto_email_transcript_callback() {
1716 - $options = get_option('mxchat_transcripts_options', array());
1717 - $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1718 - $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1719 - $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1720 - ?>
1721 - <label>
1722 - <input type="checkbox"
1723 - id="mxchat_auto_email_transcript_enabled"
1724 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1725 - value="1"
1726 - <?php checked($enabled, 1); ?>>
1727 - <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1728 - </label>
1729 - <br><br>
1730 - <label for="mxchat_auto_email_transcript_delay">
1731 - <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1732 - </label>
1733 - <select id="mxchat_auto_email_transcript_delay"
1734 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1735 - <option value="15" <?php selected($delay, '15'); ?>>
1736 - <?php esc_html_e('15 minutes', 'mxchat'); ?>
1737 - </option>
1738 - <option value="30" <?php selected($delay, '30'); ?>>
1739 - <?php esc_html_e('30 minutes', 'mxchat'); ?>
1740 - </option>
1741 - <option value="60" <?php selected($delay, '60'); ?>>
1742 - <?php esc_html_e('1 hour', 'mxchat'); ?>
1743 - </option>
1744 - </select>
1745 - <br><br>
1746 - <label>
1747 - <input type="checkbox"
1748 - id="mxchat_auto_email_transcript_require_contact"
1749 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1750 - value="1"
1751 - <?php checked($require_contact, 1); ?>>
1752 - <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1753 - </label>
1754 - <p class="description">
1755 - <?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'); ?>
1756 - <br>
1757 - <?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'); ?>
1758 - </p>
1759 - <?php
1760 -}
1761 -
1762 -
1763 -
1764 -public function sanitize_transcripts_options($input) {
1765 - $sanitized = array();
1766 -
1767 - $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
1768 -
1769 - if (isset($input['mxchat_notification_email'])) {
1770 - // Same list rule as the Transcripts autosave path (plan 2f131a). These two
1771 - // paths disagreeing is how the original bug survived: this one DID call
1772 - // is_email(), but on sanitize_email()'s output — which is valid even when
1773 - // the input was two addresses mashed into one. See MxChat_Utils.
1774 - $parsed = MxChat_Utils::parse_notification_emails($input['mxchat_notification_email']);
1775 - if ($parsed['error'] !== '') {
1776 - add_settings_error(
1777 - 'mxchat_transcripts_options',
1778 - 'invalid_email',
1779 - $parsed['error'],
1780 - 'error'
1781 - );
1782 - // Keep whatever was already stored. Do NOT fall back to admin_email:
1783 - // that fallback belongs to a genuinely EMPTY field, and using it here
1784 - // would quietly redirect notifications away from the address on screen.
1785 - $existing = get_option('mxchat_transcripts_options', array());
1786 - if (is_array($existing) && isset($existing['mxchat_notification_email'])) {
1787 - $sanitized['mxchat_notification_email'] = $existing['mxchat_notification_email'];
1788 - }
1789 - } else {
1790 - $sanitized['mxchat_notification_email'] = implode(', ', $parsed['emails']);
253 + // Sanitize and validate the 'id' parameter
254 + $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
255 + if ($id <= 0) {
256 + wp_die('Invalid prompt ID.');
1791 257 }
1792 - }
1793 258
1794 - // Sanitize auto-delete setting
1795 - $valid_intervals = array('never', '1week', '2weeks', '1month');
1796 - if (isset($input['mxchat_auto_delete_transcripts'])) {
1797 - $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1798 - ? $input['mxchat_auto_delete_transcripts']
1799 - : 'never';
1800 - } else {
1801 - $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1802 - }
259 + global $wpdb;
260 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1803 261
1804 - // Sanitize custom retention-days override (plan-9b80b1).
1805 - if (isset($input['mxchat_retention_days'])) {
1806 - $days = (int) $input['mxchat_retention_days'];
1807 - $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1808 - } else {
1809 - // Absent key = a partial save (WP-CLI patch, a snippet, any
1810 - // update_option with a subset — this filter runs on ALL of them).
1811 - // Preserve the stored value instead of zeroing it: resetting here
1812 - // silently discarded a hand-set retention on the next unrelated
1813 - // save of this option (plan-3c3338). The page's own autosave path
1814 - // bypasses this filter entirely (direct $wpdb write), so this
1815 - // branch only ever sees programmatic saves.
1816 - $mxch_prev = get_option('mxchat_transcripts_options', array());
1817 - $sanitized['mxchat_retention_days'] = (is_array($mxch_prev) && isset($mxch_prev['mxchat_retention_days']))
1818 - ? max(0, min(3650, (int) $mxch_prev['mxchat_retention_days']))
1819 - : 0;
1820 - }
262 + // Clear relevant cache before deletion
263 + $cache_key = 'prompt_' . $id;
264 + wp_cache_delete($cache_key, 'mxchat_prompts');
1821 265
1822 - // Get old values to check if auto-delete or retention-days changed.
1823 - $old_options = get_option('mxchat_transcripts_options');
1824 - $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1825 - $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
266 + // Delete the record using a prepared statement
267 + $deleted = $wpdb->delete($table_name, array('id' => $id), array('%d'));
1826 268
1827 - // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1828 - // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1829 - // reason to keep the daily cron registered.
1830 - $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1831 - $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1832 - if ($interval_changed || $retention_changed) {
1833 - $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1834 - $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1835 - }
1836 -
1837 - // Sanitize auto-email transcript settings
1838 - $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
1839 -
1840 - $valid_delays = array('15', '30', '60');
1841 - if (isset($input['mxchat_auto_email_transcript_delay'])) {
1842 - $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1843 - ? $input['mxchat_auto_email_transcript_delay']
1844 - : '30';
1845 - } else {
1846 - $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1847 - }
1848 -
1849 - // Sanitize require contact info setting
1850 - $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1851 -
1852 - return $sanitized;
1853 -}
1854 -
1855 -/**
1856 - * Schedule or unschedule the transcript cleanup cron job
1857 - */
1858 -public function schedule_transcript_cleanup($interval) {
1859 - // Clear any existing scheduled event
1860 - $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1861 - if ($timestamp) {
1862 - wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1863 - }
1864 -
1865 - // Schedule new event whenever retention is active. "active" is the canonical
1866 - // value passed by sanitize_transcripts_options when either the dropdown != never
1867 - // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1868 - // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1869 - if ($interval !== 'never') {
1870 - // Schedule to run daily at 3 AM
1871 - $next_run = strtotime('tomorrow 3:00 AM');
1872 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1873 - }
1874 -}
1875 -
1876 -/**
1877 - * Self-heal guard: keep the cleanup cron in sync with the retention setting.
1878 - *
1879 - * Runs on admin_init. Cost when nothing is wrong: one get_option() (cached) and
1880 - * one wp_next_scheduled() (reads the cached cron option) — no writes. It only
1881 - * schedules when retention is active but the event is missing, and only
1882 - * unschedules when retention is off but the event survived. Both directions
1883 - * reuse schedule_transcript_cleanup() so there is exactly one scheduling path.
1884 - * Legacy dropdown values (1week/2weeks/1month) count as active, matching the
1885 - * helper's own semantics. Deliberately not gated on DISABLE_WP_CRON: scheduling
1886 - * writes the cron option regardless of how cron is executed, so a server-side
1887 - * cron runner still picks the event up.
1888 - */
1889 -public function ensure_transcript_cleanup_scheduled() {
1890 - $options = get_option('mxchat_transcripts_options', array());
1891 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1892 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1893 - $active = ($interval !== 'never') || ($days > 0);
1894 - $scheduled = (bool) wp_next_scheduled('mxchat_cleanup_old_transcripts');
1895 -
1896 - if ($active && !$scheduled) {
1897 - $this->schedule_transcript_cleanup('active');
1898 - } elseif (!$active && $scheduled) {
1899 - $this->schedule_transcript_cleanup('never');
1900 - }
1901 -}
1902 -
1903 -/**
1904 - * Delete old transcripts based on the configured interval
1905 - */
1906 -public function cleanup_old_transcripts() {
1907 - $options = get_option('mxchat_transcripts_options', array());
1908 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1909 - $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1910 -
1911 - // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
1912 - $days = 0;
1913 - if ($custom_days > 0) {
1914 - $days = $custom_days;
1915 - } else {
1916 - switch ($interval) {
1917 - case '1week': $days = 7; break;
1918 - case '2weeks': $days = 14; break;
1919 - case '1month': $days = 30; break;
1920 - case 'never':
1921 - default:
1922 - $days = 0;
269 + if ($deleted !== false) {
270 + // Optionally, clear a general cache if you have one
271 + wp_cache_delete('all_prompts', 'mxchat_prompts');
1923 272 }
1924 - }
1925 273
1926 - // Devs can override the final day count programmatically.
1927 - $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
274 + // Redirect to the prompts page with a success message
275 + $redirect_url = add_query_arg(array(
276 + 'page' => 'mxchat-prompts',
277 + 'deleted' => 'true'
278 + ), admin_url('admin.php'));
1928 279
1929 - if ($days <= 0) {
1930 - return; // Retention disabled — bail.
280 + wp_safe_redirect($redirect_url);
281 + exit;
1931 282 }
1932 283
1933 - global $wpdb;
1934 - $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1935 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1936 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
1937 284
1938 - // Defensive: if the main table doesn't exist (fresh-ish install), bail.
1939 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
1940 - return;
1941 - }
285 +public function mxchat_create_admin_page() {
286 + ?>
287 + <div class="wrap mxchat-admin">
288 + <?php if (!$this->is_activated): ?>
289 + <div class="mxchat-pro-banner">
290 + <p>
291 + Want even more features such as a fully customizable theme, WooCommerce integration, dedicated support, and much more?
292 + <a href="https://mxchat.ai/" target="_blank">Upgrade to MxChat Pro today and get a special launch lifetime license for only $49.97!</a>
293 + </p>
294 + </div>
295 + <?php endif; ?>
296 + <h2 class="admin-title">Mx<span class="admin-emphasis">Chat</span></h2>
297 + <h2 class="mxchat-nav-tab-wrapper">
298 + <a href="#chatbot" class="mxchat-nav-tab mxchat-nav-tab-active" data-tab="chatbot">Chatbot</a>
299 + <a href="#embed" class="mxchat-nav-tab" data-tab="embed">Integrations</a>
300 + <a href="#theme" class="mxchat-nav-tab" data-tab="theme">Theme</a>
301 + <a href="#general" class="mxchat-nav-tab" data-tab="general">FAQ</a>
302 + </h2>
303 + <form method="post" action="options.php">
304 + <?php settings_fields('mxchat_option_group'); ?>
305 + <div id="chatbot" class="mxchat-tab-content active">
306 + <?php do_settings_sections('mxchat-chatbot'); ?>
307 + </div>
1942 308
1943 - $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
1944 309
1945 - // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
1946 - // the cron will pick up where it left off on the next tick (within hours).
1947 - $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
1948 310
1949 - $sessions_to_delete = $wpdb->get_col(
1950 - $wpdb->prepare(
1951 - "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
1952 - $cutoff_date,
1953 - $batch_cap
1954 - )
1955 - );
311 +<div id="embed" class="mxchat-tab-content">
312 + <div class="mxchat-settings-section">
313 + <h2>WooCommerce Settings</h2>
314 + <table class="form-table">
315 + <?php do_settings_fields('mxchat-embed', 'mxchat_woocommerce_section'); ?>
316 + </table>
317 + </div>
1956 318
1957 - if (empty($sessions_to_delete)) {
1958 - return;
1959 - }
319 + <div class="section-divider"></div> <!-- Divider -->
1960 320
1961 - $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
321 + <div class="mxchat-settings-section">
322 + <h2>Loops Settings</h2>
323 + <table class="form-table">
324 + <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
325 + </table>
326 + </div>
327 +</div>
1962 328
1963 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1964 - // $placeholders is a server-built list of literal "%s" tokens.
1965 - $deleted_transcripts = (int) $wpdb->query(
1966 - $wpdb->prepare(
1967 - "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
1968 - $sessions_to_delete
1969 - )
1970 - );
1971 329
1972 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
1973 - $wpdb->query(
1974 - $wpdb->prepare(
1975 - "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
1976 - $sessions_to_delete
1977 - )
1978 - );
1979 - }
1980 330
1981 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
1982 - $wpdb->query(
1983 - $wpdb->prepare(
1984 - "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
1985 - $sessions_to_delete
1986 - )
1987 - );
1988 - }
1989 - // phpcs:enable
1990 331
1991 - update_option('mxchat_retention_last_swept_at', time(), false);
1992 - update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
1993 -}
1994 332
1995 -public function export_chat_transcripts() {
1996 - if (!current_user_can('manage_options')) {
1997 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1998 - }
333 + <div id="theme" class="mxchat-tab-content">
334 + <?php do_settings_sections('mxchat-theme'); ?>
335 + </div>
336 + <div id="general" class="mxchat-tab-content">
337 + <?php do_settings_sections('mxchat-general'); ?>
338 +<p>If you're having trouble setting up or getting the responses you need, please don’t hesitate to <a href="https://mxchat.ai/contact/">contact our team</a>.<p> <div class="faq-item">
339 + <h3>How do I add the chatbot to my site?</h3>
340 + <p>
341 + You can add the chatbot using the shortcode <code>[mxchat_chatbot floating="yes"]</code> or <code>[mxchat_chatbot floating="no"]</code>. For initial testing and styling, it's best to use the shortcode on a draft or non-public page. Once you’re ready to go live, enable the “Append Chat Widget to Body” option in the settings for site-wide integration (recommended) or add shortcode to the footer.
342 + </p>
343 + </div>
1999 344
2000 - check_ajax_referer('mxchat_export_transcripts', 'security');
2001 345
2002 - global $wpdb;
2003 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
346 + <div class="faq-item">
347 + <h3>Do I need an API key to use the chatbot?</h3>
348 + <p>
349 + Yes, you need an OpenAI API key to use this chatbot. You can obtain an API key from the <a href="https://platform.openai.com/signup" target="_blank" rel="noopener noreferrer">OpenAI website</a>. After signing up, you will need to add credits to your account, and generally, $5 in credits is enough to start using the chatbot.
350 + </p>
351 + </div>
2004 352
2005 - // Get all transcripts ordered by session and timestamp
2006 - $results = $wpdb->get_results(
2007 - "SELECT session_id, user_email, user_identifier, role, message, timestamp
2008 - FROM {$table_name}
2009 - ORDER BY session_id, timestamp ASC"
2010 - );
353 + <div class="faq-item">
354 + <h3>How does the chatbot use my content to generate responses?</h3>
355 + <p>
356 + The chatbot uses AI and vector embeddings to connect users with relevant information. When you submit content, it converts it into a mathematical format. When a user asks a question, the bot matches it to your stored content and generates a response based on relevance. For example, submitting "Our phone number is 910-123-4567" allows the bot to retrieve this information when asked about contact details. To ensure related information is provided together, submit it in one entry.
357 + </p>
358 + </div>
2011 359
2012 - if (empty($results)) {
2013 - wp_send_json_error(array('message' => 'No transcripts found.'));
2014 - wp_die();
2015 - }
360 + <div class="faq-item">
361 + <h3>Why does the chatbot sometimes make up links or information?</h3>
362 + <p>
363 + Occasionally, the chatbot may generate inaccurate links or information, known as "hallucinations." To minimize this, you can add system instructions to guide its behavior. For example, include an instruction like: "Only provide links you directly have access to or retrieve from the knowledge base. Do not make up links or information that you do not have direct access to." This helps the bot stay aligned with your content.
364 + </p>
365 + </div>
2016 366
2017 - // Set headers for CSV download
2018 - header('Content-Type: text/csv');
2019 - header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
2020 - header('Pragma: no-cache');
2021 - header('Expires: 0');
367 + <div class="faq-item">
368 + <h3>How does the Complianz integration work?</h3>
369 + <p>
370 + The Pro version offers direct integration with the Complianz GDPR plugin, making it easy to stay compliant with GDPR. If Complianz is enabled on your website, users must accept consent before the chatbot widget appears. The chatbot will only display once the user has accepted, ensuring compliance with data privacy regulations.
371 + </p>
372 + </div>
2022 373
2023 - // Create output stream
2024 - $output = fopen('php://output', 'w');
374 + <div class="faq-item">
375 + <h3>How does the WooCommerce integration work?</h3>
376 + <p>
377 + With WooCommerce integration, the chatbot automatically embeds new products and updates existing ones. For already-published products, you can click update or submit the product sitemap. The “Order History Access” setting allows the bot to access users' order history (requires login) and assist with order inquiries. To enable the “Add to Cart” feature, add this system instruction: “After discussing a product, ask if the user wants to add it to their cart. The user must say 'Add to cart' exactly.” Currently, this feature supports English only, with more languages coming soon.
378 + </p>
379 + </div>
2025 380
2026 - // Add UTF-8 BOM for proper Excel encoding
2027 - fputs($output, "\xEF\xBB\xBF");
381 + <div class="faq-item">
382 + <h3>Why isn't my chatbot responding as expected?</h3>
383 + <p>
384 + AI chatbots can sometimes behave in unexpected ways, especially if you're new to configuring AI for specific tasks. We're committed to helping you get the most out of your chatbot experience. While we’re working on comprehensive guides and video tutorials, our team is here to assist you directly. If your chatbot isn't delivering the responses you need, please don’t hesitate to <a href="https://mxchat.ai/contact/" target="_blank" rel="noopener noreferrer">contact us</a> for personalized support.
385 + </p>
386 + <p>
387 + We’re dedicated to your success and ready to guide you in aligning the AI's behavior to meet your goals.
388 + </p>
389 + </div>
2028 390
2029 - // Add CSV headers
2030 - fputcsv($output, array(
2031 - 'Session ID',
2032 - 'Email',
2033 - 'User Identifier',
2034 - 'Role',
2035 - 'Message',
2036 - 'Timestamp'
2037 - ));
391 + <div class="faq-item">
392 + <h3>What is Loops, and how do I get an API key?</h3>
393 + <p>
394 + Loops is a powerful SaaS email service that helps you automate and enhance your email marketing campaigns, making it easy to reach and engage with your audience. To integrate Loops with MxChat, you’ll need an API key from Loops. You can obtain this key by logging into your Loops account and navigating to the API settings. Visit the <a href="https://loops.so" target="_blank" rel="noopener noreferrer">Loops website</a> to get started or to sign up for an account.
395 + </p>
396 + </div>
2038 397
2039 - // Add data rows
2040 - foreach ($results as $row) {
2041 - fputcsv($output, array(
2042 - $row->session_id,
2043 - $row->user_email,
2044 - $row->user_identifier,
2045 - $row->role,
2046 - $row->message,
2047 - $row->timestamp
2048 - ));
2049 - }
2050 398
2051 - fclose($output);
2052 - wp_die();
399 + </div>
400 + <?php submit_button(); ?>
401 + </form>
402 + </div>
403 + <?php
2053 404 }
2054 405
2055 -// ============================================================================
2056 -// Leads tab (inside Transcripts)
2057 -//
2058 -// Leads are derived from existing data — no dedicated table. Primary source:
2059 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
2060 -// source: the mxchat_sessions table's visitor_email/visitor_name columns
2061 -// (plus any unmigrated legacy `mxchat_email_{sid}` wp_options rows) for
2062 -// "orphan" leads who submitted the pre-chat form but never chatted.
2063 -// ============================================================================
2064 406
2065 -/**
2066 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
2067 - */
2068 -public function mxchat_fetch_leads() {
2069 - if (!current_user_can('manage_options')) {
2070 - wp_send_json_error(['message' => 'Insufficient permissions']);
2071 - wp_die();
2072 - }
2073 -
2074 - global $wpdb;
2075 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2076 -
2077 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
2078 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
2079 - $offset = ($page - 1) * $per_page;
2080 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
2081 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
2082 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
2083 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
2084 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
2085 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
2086 -
2087 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
2088 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
2089 -
2090 - // Base WHERE for transcripts leads.
2091 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
2092 - $where_params = [];
2093 -
2094 - if ($date_cutoff) {
2095 - $where_clauses[] = 'timestamp >= %s';
2096 - $where_params[] = $date_cutoff;
2097 - }
2098 - if ($page_filter && $has_page_url_column) {
2099 - $where_clauses[] = 'originating_page_url = %s';
2100 - $where_params[] = $page_filter;
2101 - }
2102 - if ($search !== '') {
2103 - $like = '%' . $wpdb->esc_like($search) . '%';
2104 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
2105 - $where_params[] = $like;
2106 - $where_params[] = $like;
2107 - }
2108 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
2109 -
2110 - // Aggregate query grouped by email.
2111 - $select_sql = $has_page_url_column
2112 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2113 - COUNT(DISTINCT session_id) AS conversation_count"
2114 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2115 - COUNT(DISTINCT session_id) AS conversation_count";
2116 -
2117 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
2118 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
2119 -
2120 - $transcripts_sql = $wpdb->prepare(
2121 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
2122 - array_merge($where_params, [$per_page, $offset])
2123 - );
2124 - $transcript_rows = $wpdb->get_results($transcripts_sql);
2125 -
2126 - // Count of unique transcript-based leads under the same filters.
2127 - $count_sql = $wpdb->prepare(
2128 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
2129 - $where_params
2130 - );
2131 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
2132 -
2133 - // Hydrate each row: name, latest_session_id, top page.
2134 - $leads = [];
2135 - foreach ($transcript_rows as $row) {
2136 - $detail = $has_page_url_column
2137 - ? $wpdb->get_row($wpdb->prepare(
2138 - "SELECT session_id, user_name, originating_page_url, originating_page_title
2139 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2140 - $row->user_email
2141 - ))
2142 - : $wpdb->get_row($wpdb->prepare(
2143 - "SELECT session_id, user_name FROM {$table}
2144 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2145 - $row->user_email
2146 - ));
2147 -
2148 - $leads[] = [
2149 - 'email' => $row->user_email,
2150 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2151 - 'conversation_count' => (int) $row->conversation_count,
2152 - 'last_seen' => $row->last_seen,
2153 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
2154 - 'first_seen' => $row->first_seen,
2155 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
2156 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2157 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
2158 - 'is_orphan' => false,
2159 - 'status' => 'active',
2160 - ];
2161 - }
2162 -
2163 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
2164 - // status filter below. Deduplication priority when the same email appears in multiple
2165 - // sources: transcripts > chat_deleted > orphan.
2166 - $transcripts_emails_seen = array_flip(array_map(
2167 - function ($r) { return strtolower($r['email']); },
2168 - $leads
2169 - ));
2170 -
2171 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
2172 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
2173 - $chat_deleted_leads_all = [];
2174 - if ($status === 'all' || $status === 'chat_deleted') {
2175 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
2176 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
2177 - $chat_deleted_leads_all = array_values(array_filter(
2178 - $chat_deleted_leads_all,
2179 - function ($row) use ($transcripts_emails_seen) {
2180 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2181 - }
2182 - ));
2183 - foreach ($chat_deleted_leads_all as $row) {
2184 - $transcripts_emails_seen[strtolower($row['email'])] = true;
407 + public function mxchat_create_transcripts_page() {
408 + ?>
409 + <div class="wrap mxchat-admin">
410 + <h2><?php esc_html_e('Chat Transcripts', 'mxchat'); ?></h2>
411 + <form id="mxchat-delete-form" method="post">
412 + <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
413 + <div class="mxchat-controls">
414 + <label for="mxchat-select-all-transcripts" class="mxchat-select-all-label">
415 + <input type="checkbox" id="mxchat-select-all-transcripts" /> <?php esc_html_e('Select All', 'mxchat'); ?>
416 + </label>
417 + <input type="submit" value="<?php esc_attr_e('Delete Selected', 'mxchat'); ?>" class="button button-primary delete-chats-button" />
418 + </div>
419 + <div id="mxchat-transcripts">
420 + <!-- Transcripts will be loaded here -->
421 + </div>
422 + </form>
423 + </div>
424 + <?php
2185 425 }
2186 - }
2187 426
2188 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
2189 - // when a date filter is active.
2190 - $orphan_leads_all = [];
2191 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
2192 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
2193 - $orphan_leads_all = array_values(array_filter(
2194 - $orphan_leads_all,
2195 - function ($row) use ($transcripts_emails_seen) {
2196 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2197 - }
2198 - ));
2199 - }
2200 427
2201 - // Apply status filter to the transcripts-derived list.
2202 - if ($status === 'orphan' || $status === 'chat_deleted') {
2203 - $leads = [];
2204 - $transcripts_lead_count = 0;
2205 - }
2206 428
2207 - // Stitch the current page from the three buckets in priority order.
2208 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
2209 - $remaining_slots = $per_page - count($leads);
2210 429
2211 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
2212 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
2213 - if ($start < count($chat_deleted_leads_all)) {
2214 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
2215 - $remaining_slots = $per_page - count($leads);
2216 - }
2217 - }
430 + public function mxchat_create_prompts_page() {
431 + global $wpdb;
432 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2218 433
2219 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
2220 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
2221 - $start = max(0, ($page - 1) * $per_page - $before);
2222 - if ($start < count($orphan_leads_all)) {
2223 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
2224 - }
2225 - }
434 + // Verify the nonce before processing the request
435 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
2226 436
2227 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
2228 -
2229 - // Stats strip: always computed over full dataset, unaffected by filters.
2230 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
2231 -
2232 - // Top pages: top 5 by distinct emails captured.
2233 - $top_pages = [];
2234 - if ($has_page_url_column) {
2235 - $top_pages_rows = $wpdb->get_results(
2236 - "SELECT originating_page_url AS url,
2237 - MAX(originating_page_title) AS title,
2238 - COUNT(DISTINCT user_email) AS lead_count
2239 - FROM {$table}
2240 - WHERE user_email IS NOT NULL AND user_email != ''
2241 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
2242 - GROUP BY originating_page_url
2243 - ORDER BY lead_count DESC, url ASC
2244 - LIMIT 5"
2245 - );
2246 - foreach ($top_pages_rows as $p) {
2247 - $top_pages[] = [
2248 - 'url' => $p->url,
2249 - 'title' => $p->title ?: $p->url,
2250 - 'lead_count' => (int) $p->lead_count,
2251 - ];
437 + if (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce')) {
438 + // Sanitize input data
439 + $search_query = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';
440 + $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
441 + } else {
442 + $search_query = '';
443 + $current_page = 1;
2252 444 }
2253 - }
2254 445
2255 - // Consent state per lead (b062c4). Chat-deleted rows already carry it from
2256 - // their preserved options; the rest read the newest session-store record
2257 - // for that email. Empty string = NOT RECORDED (pre-feature capture or the
2258 - // checkbox was off) — distinct from 'no', which is a recorded decline.
2259 - $can_read_consent = class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'latest_consent');
2260 - foreach ($leads as &$lead_consent_ref) {
2261 - if (array_key_exists('consent', $lead_consent_ref)) {
2262 - continue;
2263 - }
2264 - $consent = $can_read_consent ? MxChat_Session_Store::latest_consent($lead_consent_ref['email']) : null;
2265 - $lead_consent_ref['consent'] = $consent ? $consent['given'] : '';
2266 - $lead_consent_ref['consent_at'] = $consent ? $consent['recorded_at'] : '';
2267 - $lead_consent_ref['consent_label'] = $consent ? wp_strip_all_tags($consent['label']) : '';
2268 - }
2269 - unset($lead_consent_ref);
446 + $per_page = 10;
2270 447
2271 - wp_send_json([
2272 - 'success' => true,
2273 - 'leads' => $leads,
2274 - 'page' => $page,
2275 - 'per_page' => $per_page,
2276 - 'total_count' => $total_count,
2277 - 'total_pages' => $total_pages,
2278 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
2279 - 'showing_end' => min($offset + $per_page, $total_count),
2280 - 'stats' => $stats,
2281 - 'top_pages' => $top_pages,
2282 - ]);
2283 - wp_die();
2284 -}
448 + // Create cache keys
449 + $cache_key_total = 'total_prompts_' . md5($search_query);
450 + $cache_key_prompts = 'prompts_' . md5($search_query . '_' . $current_page);
2285 451
2286 -/**
2287 - * Delete one or more leads by email. Removes every transcripts row for that
2288 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2289 - * mxchat_history_{sid}) and any orphan option entries matching the email.
2290 - */
2291 -public function mxchat_delete_leads() {
2292 - if (!current_user_can('manage_options')) {
2293 - wp_send_json_error(['message' => 'Insufficient permissions']);
2294 - wp_die();
2295 - }
2296 - check_ajax_referer('mxchat_delete_leads', 'security');
2297 -
2298 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2299 - $emails = [];
2300 - foreach ($emails_raw as $e) {
2301 - $clean = sanitize_email((string) $e);
2302 - if ($clean) {
2303 - $emails[] = $clean;
452 + // Retrieve total number of prompts from cache or database
453 + $total_prompts = wp_cache_get($cache_key_total, 'mxchat_prompts');
454 + if ($total_prompts === false) {
455 + if (!empty($search_query)) {
456 + $total_prompts = $wpdb->get_var(
457 + $wpdb->prepare(
458 + "SELECT COUNT(*) FROM {$table_name} WHERE article_content LIKE %s",
459 + '%' . $wpdb->esc_like($search_query) . '%'
460 + )
461 + );
462 + } else {
463 + $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
464 + }
465 + wp_cache_set($cache_key_total, $total_prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
2304 466 }
2305 - }
2306 - if (empty($emails)) {
2307 - wp_send_json_error(['message' => 'No emails provided']);
2308 - wp_die();
2309 - }
2310 467
2311 - $summary = self::mxchat_wipe_leads_by_email($emails);
468 + $total_pages = ceil($total_prompts / $per_page);
469 + $offset = ($current_page - 1) * $per_page;
2312 470
2313 - wp_send_json([
2314 - 'success' => true,
2315 - 'deleted_leads' => count($emails),
2316 - 'deleted_sessions' => $summary['deleted_sessions'],
2317 - 'deleted_rows' => $summary['deleted_rows'],
2318 - ]);
2319 - wp_die();
2320 -}
2321 -
2322 -/**
2323 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2324 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2325 - *
2326 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2327 - * Input emails must already be sanitized with sanitize_email().
2328 - */
2329 -private static function mxchat_wipe_leads_by_email(array $emails) {
2330 - global $wpdb;
2331 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2332 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2333 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
2334 -
2335 - $deleted_sessions = 0;
2336 - $deleted_rows = 0;
2337 - $emails_lc = array_map('strtolower', $emails);
2338 -
2339 - foreach ($emails as $email) {
2340 - $session_ids = $wpdb->get_col($wpdb->prepare(
2341 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2342 - $email
2343 - ));
2344 -
2345 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2346 - if ($rows_removed !== false) {
2347 - $deleted_rows += (int) $rows_removed;
2348 - }
2349 -
2350 - foreach ($session_ids as $sid) {
2351 - $deleted_sessions++;
2352 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2353 - delete_option('mxchat_history_' . $sid);
2354 - delete_option('mxchat_email_' . $sid);
2355 - delete_option('mxchat_name_' . $sid);
2356 - delete_option('mxchat_agent_name_' . $sid);
2357 - delete_option('mxchat_lead_del_email_' . $sid);
2358 - delete_option('mxchat_lead_del_name_' . $sid);
2359 - delete_option('mxchat_lead_del_ts_' . $sid);
2360 - delete_option('mxchat_lead_del_consent_' . $sid);
2361 - delete_option('mxchat_lead_del_consent_label_' . $sid);
2362 - delete_option('mxchat_lead_del_consent_at_' . $sid);
2363 - if (class_exists('MxChat_Session_Store')) {
2364 - MxChat_Session_Store::delete_session($sid); // b64b77
471 + // Retrieve prompts from cache or database
472 + $prompts = wp_cache_get($cache_key_prompts, 'mxchat_prompts');
473 + if ($prompts === false) {
474 + if (!empty($search_query)) {
475 + $prompts = $wpdb->get_results(
476 + $wpdb->prepare(
477 + "SELECT * FROM {$table_name} WHERE article_content LIKE %s ORDER BY timestamp DESC LIMIT %d OFFSET %d",
478 + '%' . $wpdb->esc_like($search_query) . '%',
479 + $per_page,
480 + $offset
481 + )
482 + );
483 + } else {
484 + $prompts = $wpdb->get_results(
485 + $wpdb->prepare(
486 + "SELECT * FROM {$table_name} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
487 + $per_page,
488 + $offset
489 + )
490 + );
2365 491 }
2366 - if ($has_translations) {
2367 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2368 - }
492 + wp_cache_set($cache_key_prompts, $prompts, 'mxchat_prompts', 3600); // Cache for 1 hour
2369 493 }
2370 - }
2371 494
2372 - // Table-side twin of the option sweep below (5658f2): orphan pre-chat
2373 - // captures now live in the sessions table's identity columns.
2374 - if (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'find_by_email')) {
2375 - foreach ($emails as $email) {
2376 - foreach (MxChat_Session_Store::find_by_email($email) as $sid) {
2377 - MxChat_Session_Store::delete_session($sid);
2378 - }
2379 - }
2380 - }
495 + ?>
2381 496
2382 - // Clean up any lingering option entries (unmigrated orphan pre-chat captures +
2383 - // chat_deleted preservations) whose stored value matches one of the emails being wiped.
2384 - $lingering = $wpdb->get_results(
2385 - "SELECT option_name, option_value FROM {$wpdb->options}
2386 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2387 - );
2388 - foreach ($lingering as $opt) {
2389 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2390 - continue;
2391 - }
2392 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2393 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2394 - delete_option('mxchat_lead_del_email_' . $sid);
2395 - delete_option('mxchat_lead_del_name_' . $sid);
2396 - delete_option('mxchat_lead_del_ts_' . $sid);
2397 - delete_option('mxchat_lead_del_consent_' . $sid);
2398 - delete_option('mxchat_lead_del_consent_label_' . $sid);
2399 - delete_option('mxchat_lead_del_consent_at_' . $sid);
2400 - } else {
2401 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2402 - delete_option('mxchat_email_' . $sid);
2403 - delete_option('mxchat_name_' . $sid);
2404 - }
2405 - }
497 + <div class="wrap mxchat-admin">
498 + <div class="mxchat-grid-container">
2406 499
2407 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
500 + <!-- Submit Content -->
501 +<div class="mxchat-grid-item full-width">
502 + <h2>Submit Content</h2>
503 + <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
504 + <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
505 + <div class="mxchat-form-group">
506 + <label for="article_content">Article Content:</label>
507 + <textarea name="article_content" id="article_content" required></textarea>
508 + </div>
509 + <div class="mxchat-form-group">
510 + <label for="article_url">Article URL (Optional):</label>
511 + <input type="url" name="article_url" id="article_url" placeholder="Enter related URL for the content">
512 + </div>
513 + <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
514 + </form>
515 +</div>
2408 516
2409 - return [
2410 - 'deleted_sessions' => $deleted_sessions,
2411 - 'deleted_rows' => $deleted_rows,
2412 - ];
2413 -}
2414 517
2415 -/**
2416 - * Stream a leads CSV. scope=all exports every lead under current filters is not
2417 - * supported to keep semantics simple; caller either exports all leads or a
2418 - * specific set of selected emails.
2419 - */
2420 -public function mxchat_export_leads() {
2421 - if (!current_user_can('manage_options')) {
2422 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2423 - }
2424 - check_ajax_referer('mxchat_export_leads', 'security');
518 + <!-- Submit Sitemap -->
519 + <div class="mxchat-grid-item">
520 + <h2>Submit Sitemap or Page URL</h2>
521 + <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')); ?>">
522 + <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
523 + <div class="mxchat-search-group">
524 + <input type="url" name="sitemap_url" id="sitemap_url" placeholder="Sitemap or URL" required />
525 + <input type="submit" name="submit_sitemap" value="Submit" class="button button-primary" />
526 + </div>
527 + </form>
528 + <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"></div>
529 + <div id="mxchat-loading-text" style="display: none; margin-top: 10px; color: #333;">Loading sitemap content into database, please wait...</div>
530 + </div>
2425 531
2426 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2427 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2428 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
532 + <!-- Search Knowledge -->
533 + <div class="mxchat-grid-item">
534 + <h2>Search Knowledge</h2>
535 + <form method="get" id="knowledge-search">
536 + <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
537 + <input type="hidden" name="page" value="mxchat-prompts" />
538 + <div class="mxchat-search-group">
539 + <input type="text" name="search" placeholder="Search Knowledge" value="<?php echo esc_attr($search_query); ?>" />
540 + <input type="submit" value="Search" class="button button-primary" />
541 + </div>
542 + </form>
543 + </div>
544 + </div>
2429 545
2430 - $emails_in_clean = [];
2431 - foreach ($emails_in as $e) {
2432 - $clean = sanitize_email((string) $e);
2433 - if ($clean) {
2434 - $emails_in_clean[] = $clean;
2435 - }
2436 - }
546 + <!-- Table below the forms -->
547 + <div class="tablenav">
548 + <div class="tablenav-pages">
549 + <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
550 + <?php
551 + $page_links = paginate_links(array(
552 + 'base' => add_query_arg('paged', '%#%', admin_url('admin.php?page=mxchat-prompts')),
553 + 'format' => '',
554 + 'prev_text' => __('&laquo; Previous'),
555 + 'next_text' => __('Next &raquo;'),
556 + 'total' => $total_pages,
557 + 'current' => $current_page,
558 + 'add_args' => array(
559 + 'search' => $search_query,
560 + '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')
561 + ),
562 + ));
2437 563
2438 - global $wpdb;
2439 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2440 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
564 + if ($page_links) {
565 + echo '<div class="tablenav-pages">' . wp_kses_post($page_links) . '</div>';
566 + }
567 + ?>
568 + </div>
569 + </div>
570 + <table class="wp-list-table widefat fixed striped">
571 + <thead>
572 + <tr>
573 + <th>ID</th>
574 + <th>Article Content</th>
575 + <th>URL</th>
576 + <th>Actions</th>
577 + </tr>
578 + </thead>
579 + <tbody>
580 + <?php
581 + if ($prompts) {
582 + foreach ($prompts as $prompt) {
583 + ?>
584 + <tr>
585 + <td><?php echo esc_html($prompt->id); ?></td>
586 + <td class="mxchat_article_content_dashboard"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></td>
587 + <td class="mxchat_article_url_dashboard">
588 + <?php if (!empty($prompt->source_url)): ?>
589 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
590 + <?php else: ?>
591 + N/A
592 + <?php endif; ?>
593 + </td>
594 + <td>
595 + <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>
596 + </td>
597 + </tr>
598 + <?php
599 + }
600 + } else {
601 + ?>
602 + <tr>
603 + <td colspan="4">No prompts found.</td>
604 + </tr>
605 + <?php
606 + }
607 + ?>
608 + </tbody>
609 + </table>
610 + </div>
2441 611
2442 - // Collect leads from transcripts.
2443 - $transcripts_sql = "SELECT user_email AS email,
2444 - MAX(timestamp) AS last_seen,
2445 - COUNT(DISTINCT session_id) AS conversation_count
2446 - FROM {$table}
2447 - WHERE user_email IS NOT NULL AND user_email != ''";
2448 - $params = [];
2449 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2450 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2451 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2452 - $params = $emails_in_clean;
612 + <?php
2453 613 }
2454 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
2455 614
2456 - $rows = !empty($params)
2457 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2458 - : $wpdb->get_results($transcripts_sql);
615 + public function mxchat_generate_embedding($text) {
616 + $options = get_option('mxchat_options');
617 + $api_key = $options['api_key'] ?? 'default_api_key';
2459 618
2460 - // Hydrate each row with name + top page.
2461 - $export_rows = [];
2462 - foreach ($rows as $row) {
2463 - $detail = $has_page_url_column
2464 - ? $wpdb->get_row($wpdb->prepare(
2465 - "SELECT user_name, originating_page_url FROM {$table}
2466 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2467 - $row->email
2468 - ))
2469 - : $wpdb->get_row($wpdb->prepare(
2470 - "SELECT user_name FROM {$table}
2471 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2472 - $row->email
2473 - ));
2474 - $export_rows[] = [
2475 - 'email' => $row->email,
2476 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2477 - 'conversation_count' => (int) $row->conversation_count,
2478 - 'last_seen' => $row->last_seen,
2479 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2480 - ];
2481 - }
2482 -
2483 - // Include orphan + chat_deleted leads when exporting all.
2484 - if ($scope === 'all') {
2485 - $transcripts_emails_lc = array_flip(array_map(
2486 - function ($r) { return strtolower($r['email']); },
2487 - $export_rows
619 + $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
620 + 'body' => wp_json_encode(array(
621 + 'model' => 'text-embedding-ada-002',
622 + 'input' => $text
623 + )),
624 + 'headers' => array(
625 + 'Authorization' => 'Bearer ' . $api_key,
626 + 'Content-Type' => 'application/json'
627 + ),
2488 628 ));
2489 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2490 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2491 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2492 - $export_rows[] = [
2493 - 'email' => $cd['email'],
2494 - 'name' => $cd['name'],
2495 - 'conversation_count' => 0,
2496 - 'last_seen' => $cd['last_seen'],
2497 - 'top_page_url' => '',
2498 - 'consent' => isset($cd['consent']) ? $cd['consent'] : '',
2499 - 'consent_at' => isset($cd['consent_at']) ? $cd['consent_at'] : '',
2500 - 'consent_label' => isset($cd['consent_label']) ? $cd['consent_label'] : '',
2501 - ];
2502 - }
2503 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2504 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2505 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2506 - $export_rows[] = [
2507 - 'email' => $orphan['email'],
2508 - 'name' => $orphan['name'],
2509 - 'conversation_count' => 0,
2510 - 'last_seen' => '',
2511 - 'top_page_url' => '',
2512 - ];
2513 - }
2514 - }
2515 629
2516 - if (empty($export_rows)) {
2517 - wp_send_json_error(['message' => 'No leads to export.']);
2518 - wp_die();
2519 - }
2520 -
2521 - // Consent columns (b062c4). Chat-deleted rows already carry the preserved
2522 - // values; the rest read the newest session-store record for that email.
2523 - // Empty consent = "not recorded" — a pre-feature capture, NOT a decline.
2524 - $can_read_consent = class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'latest_consent');
2525 - foreach ($export_rows as &$export_consent_ref) {
2526 - if (array_key_exists('consent', $export_consent_ref)) {
2527 - continue;
630 + if (is_wp_error($response)) {
631 + return null;
2528 632 }
2529 - $consent = $can_read_consent ? MxChat_Session_Store::latest_consent($export_consent_ref['email']) : null;
2530 - $export_consent_ref['consent'] = $consent ? $consent['given'] : '';
2531 - $export_consent_ref['consent_at'] = $consent ? $consent['recorded_at'] : '';
2532 - $export_consent_ref['consent_label'] = $consent ? wp_strip_all_tags($consent['label']) : '';
2533 - }
2534 - unset($export_consent_ref);
2535 633
2536 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2537 - header('Content-Type: text/csv');
2538 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2539 - header('Pragma: no-cache');
2540 - header('Expires: 0');
2541 -
2542 - $output = fopen('php://output', 'w');
2543 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2544 -
2545 - if ($fields_mode === 'email_only') {
2546 - fputcsv($output, ['Email']);
2547 - foreach ($export_rows as $r) {
2548 - fputcsv($output, [$r['email']]);
2549 - }
2550 - } else {
2551 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page', 'Consent', 'Consent recorded', 'Consent text shown']);
2552 - foreach ($export_rows as $r) {
2553 - fputcsv($output, [
2554 - $r['email'],
2555 - $r['name'],
2556 - $r['conversation_count'],
2557 - $r['last_seen'],
2558 - $r['top_page_url'],
2559 - $r['consent'] !== '' ? $r['consent'] : 'not recorded',
2560 - $r['consent_at'],
2561 - $r['consent_label'],
2562 - ]);
2563 - }
634 + $response_data = json_decode(wp_remote_retrieve_body($response), true);
635 + return $response_data['data'][0]['embedding'] ?? null;
2564 636 }
2565 637
2566 - fclose($output);
2567 - wp_die();
2568 -}
2569 -
2570 -/**
2571 - * Stats strip payload (independent of filters).
2572 - */
2573 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2574 - global $wpdb;
2575 -
2576 - $total_transcripts_emails = (int) $wpdb->get_var(
2577 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2578 - WHERE user_email IS NOT NULL AND user_email != ''"
2579 - );
2580 -
2581 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2582 - "SELECT COUNT(*) FROM (
2583 - SELECT user_email FROM {$table}
2584 - WHERE user_email IS NOT NULL AND user_email != ''
2585 - GROUP BY user_email
2586 - HAVING MIN(timestamp) >= %s
2587 - ) AS new_leads",
2588 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2589 - ));
2590 -
2591 - $total_convos = (int) $wpdb->get_var(
2592 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2593 - WHERE user_email IS NOT NULL AND user_email != ''"
2594 - );
2595 -
2596 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2597 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
2598 -
2599 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2600 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2601 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2602 -
2603 - $avg = $total_transcripts_emails > 0
2604 - ? round($total_convos / $total_transcripts_emails, 1)
2605 - : 0;
2606 -
2607 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2608 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2609 - // inflate this number.
2610 - $orphan_pct = $total_leads > 0
2611 - ? (int) round(($orphan_count / $total_leads) * 100)
2612 - : 0;
2613 -
2614 - return [
2615 - 'total_leads' => $total_leads,
2616 - 'new_this_week' => $new_this_week,
2617 - 'avg_convos' => $avg,
2618 - 'orphan_pct' => $orphan_pct,
2619 - 'orphan_count' => $orphan_count,
2620 - 'chat_deleted_count' => $chat_deleted_count,
2621 - ];
2622 -}
2623 -
2624 -/**
2625 - * Collect leads who had a conversation that an admin later deleted (preserved via
2626 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2627 - * original last-seen timestamp so they still sort and filter sensibly.
2628 - *
2629 - * @param string $search Optional email/name substring filter.
2630 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2631 - * @return array
2632 - */
2633 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2634 - global $wpdb;
2635 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2636 -
2637 - $rows = $wpdb->get_results(
2638 - "SELECT option_name, option_value FROM {$wpdb->options}
2639 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2640 - );
2641 - if (empty($rows)) {
2642 - return [];
2643 - }
2644 -
2645 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2646 - // they've come back and chatted, so they're active leads again.
2647 - $emails_in_transcripts = array_map(
2648 - 'strtolower',
2649 - (array) $wpdb->get_col(
2650 - "SELECT DISTINCT user_email FROM {$table}
2651 - WHERE user_email IS NOT NULL AND user_email != ''"
2652 - )
2653 - );
2654 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2655 -
2656 - $needle = strtolower(trim((string) $search));
2657 - $by_email = [];
2658 -
2659 - foreach ($rows as $opt) {
2660 - $email = sanitize_email(trim((string) $opt->option_value));
2661 - if (!$email) {
2662 - continue;
638 + public function mxchat_delete_chat_history() {
639 + if (!current_user_can('manage_options')) {
640 + echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
641 + wp_die();
2663 642 }
2664 - if (isset($emails_in_transcripts[strtolower($email)])) {
2665 - continue;
2666 - }
2667 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2668 - if (!$sid) {
2669 - continue;
2670 - }
2671 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2672 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2673 643
2674 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2675 - continue;
2676 - }
2677 - if ($needle !== '') {
2678 - $hay = strtolower($email . ' ' . $name);
2679 - if (strpos($hay, $needle) === false) {
2680 - continue;
2681 - }
2682 - }
644 + check_ajax_referer('mxchat_delete_chat_history', 'security');
2683 645
2684 - $key = strtolower($email);
2685 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2686 - // Consent proof preserved at chat-delete time (b062c4) — the
2687 - // session row is gone, so these options are the only copy.
2688 - $consent_state = (string) get_option('mxchat_lead_del_consent_' . $sid, '');
646 + global $wpdb;
647 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2689 648
2690 - $by_email[$key] = [
2691 - 'email' => $email,
2692 - 'name' => $name,
2693 - 'conversation_count' => 0,
2694 - 'last_seen' => $ts,
2695 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2696 - 'first_seen' => $ts,
2697 - 'latest_session_id' => '',
2698 - 'top_page_url' => '',
2699 - 'top_page_title' => '',
2700 - 'is_orphan' => false,
2701 - 'status' => 'chat_deleted',
2702 - 'consent' => $consent_state,
2703 - 'consent_at' => $consent_state !== '' ? (string) get_option('mxchat_lead_del_consent_at_' . $sid, '') : '',
2704 - 'consent_label' => $consent_state !== '' ? wp_strip_all_tags((string) get_option('mxchat_lead_del_consent_label_' . $sid, '')) : '',
2705 - ];
2706 - }
2707 - }
649 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
650 + foreach ($_POST['delete_session_ids'] as $session_id) {
651 + $session_id_sanitized = sanitize_text_field($session_id);
2708 652
2709 - // Newest chat_deleted first.
2710 - usort($by_email, function ($a, $b) {
2711 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2712 - });
2713 - return array_values($by_email);
2714 -}
653 + // Clear relevant cache before deletion
654 + $cache_key = 'chat_session_' . $session_id_sanitized;
655 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
2715 656
2716 -/**
2717 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2718 - */
2719 -private static function mxchat_count_chat_deleted_leads() {
2720 - global $wpdb;
2721 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2722 -
2723 - $emails = $wpdb->get_col(
2724 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2725 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2726 - );
2727 - if (empty($emails)) {
2728 - return 0;
2729 - }
2730 -
2731 - $transcripts_emails = array_map(
2732 - 'strtolower',
2733 - (array) $wpdb->get_col(
2734 - "SELECT DISTINCT user_email FROM {$table}
2735 - WHERE user_email IS NOT NULL AND user_email != ''"
2736 - )
2737 - );
2738 - $transcripts_emails = array_flip($transcripts_emails);
2739 -
2740 - $count = 0;
2741 - $seen = [];
2742 - foreach ($emails as $raw) {
2743 - $email = strtolower(trim((string) $raw));
2744 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2745 - continue;
2746 - }
2747 - $seen[$email] = true;
2748 - $count++;
2749 - }
2750 - return $count;
2751 -}
2752 -
2753 -/**
2754 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2755 - * Returned rows have no conversation_count, no timestamp.
2756 - *
2757 - * @param string $search Optional email/name substring filter.
2758 - * @return array
2759 - */
2760 -private static function mxchat_collect_orphan_leads($search = '') {
2761 - global $wpdb;
2762 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2763 -
2764 - // Primary source since 5658f2: the sessions table's identity columns.
2765 - // The legacy option scan stays for installs still mid-migration.
2766 - $store_rows = (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'identity_rows'))
2767 - ? MxChat_Session_Store::identity_rows()
2768 - : [];
2769 -
2770 - $option_rows = $wpdb->get_results(
2771 - "SELECT option_name, option_value FROM {$wpdb->options}
2772 - WHERE option_name LIKE 'mxchat_email_%'"
2773 - );
2774 - if (empty($option_rows) && empty($store_rows)) {
2775 - return [];
2776 - }
2777 -
2778 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2779 - $session_ids_with_rows = $wpdb->get_col(
2780 - "SELECT DISTINCT session_id FROM {$table}
2781 - WHERE user_email IS NOT NULL AND user_email != ''"
2782 - );
2783 - $session_ids_with_rows = array_flip($session_ids_with_rows);
2784 -
2785 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2786 - $emails_in_transcripts = array_map(
2787 - 'strtolower',
2788 - (array) $wpdb->get_col(
2789 - "SELECT DISTINCT user_email FROM {$table}
2790 - WHERE user_email IS NOT NULL AND user_email != ''"
2791 - )
2792 - );
2793 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2794 -
2795 - $orphans_by_email = [];
2796 - $needle = strtolower(trim((string) $search));
2797 -
2798 - // Normalize both sources into [sid, email, name] candidates. Table rows
2799 - // first — a session can only live in one home, and dedup-by-email below
2800 - // handles any overlap either way.
2801 - $candidates = [];
2802 - foreach ($store_rows as $row) {
2803 - $candidates[] = [
2804 - 'sid' => (string) $row['session_id'],
2805 - 'email' => (string) $row['visitor_email'],
2806 - 'name' => is_string($row['visitor_name'] ?? null) ? $row['visitor_name'] : '',
2807 - ];
2808 - }
2809 - foreach ($option_rows as $opt) {
2810 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2811 - $name_option = $sid ? get_option('mxchat_name_' . $sid, '') : '';
2812 - $candidates[] = [
2813 - 'sid' => (string) $sid,
2814 - 'email' => (string) $opt->option_value,
2815 - 'name' => is_string($name_option) ? $name_option : '',
2816 - ];
2817 - }
2818 -
2819 - foreach ($candidates as $cand) {
2820 - $email = sanitize_email(trim($cand['email']));
2821 - if (!$email) {
2822 - continue;
2823 - }
2824 - $sid = $cand['sid'];
2825 - if (!$sid) {
2826 - continue;
2827 - }
2828 - // Exclude leads who have any transcripts rows (they appear in the main list).
2829 - if (isset($emails_in_transcripts[strtolower($email)])) {
2830 - continue;
2831 - }
2832 - if (isset($session_ids_with_rows[$sid])) {
2833 - continue;
2834 - }
2835 -
2836 - $name = trim($cand['name']);
2837 -
2838 - if ($needle !== '') {
2839 - $hay = strtolower($email . ' ' . $name);
2840 - if (strpos($hay, $needle) === false) {
2841 - continue;
657 + // Perform the deletion
658 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
2842 659 }
2843 - }
2844 660
2845 - $key = strtolower($email);
2846 - if (!isset($orphans_by_email[$key])) {
2847 - $orphans_by_email[$key] = [
2848 - 'email' => $email,
2849 - 'name' => $name,
2850 - 'conversation_count' => 0,
2851 - 'last_seen' => '',
2852 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2853 - 'first_seen' => '',
2854 - 'latest_session_id' => '',
2855 - 'top_page_url' => '',
2856 - 'top_page_title' => '',
2857 - 'is_orphan' => true,
2858 - 'status' => 'orphan',
2859 - ];
2860 - }
2861 - }
661 + // Optionally, clear a general cache if you have one
662 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2862 663
2863 - return array_values($orphans_by_email);
2864 -}
2865 -
2866 -/**
2867 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2868 - */
2869 -private static function mxchat_leads_date_cutoff($date_range) {
2870 - switch ($date_range) {
2871 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2872 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2873 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2874 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2875 - case 'all':
2876 - default: return '';
2877 - }
2878 -}
2879 -
2880 -/**
2881 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2882 - */
2883 -private static function mxchat_leads_format_relative($timestamp) {
2884 - if (!$timestamp) {
2885 - return '';
2886 - }
2887 - $ts = strtotime($timestamp . ' UTC');
2888 - if (!$ts) {
2889 - return '';
2890 - }
2891 - $diff = time() - $ts;
2892 - if ($diff < 60) return __('just now', 'mxchat');
2893 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2894 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2895 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2896 - return wp_date('M j', $ts);
2897 -}
2898 -
2899 -/**
2900 - * Handle translation of chat messages via AJAX
2901 - */
2902 -public function mxchat_translate_messages() {
2903 - if (!current_user_can('manage_options')) {
2904 - wp_send_json_error(['error' => 'Insufficient permissions']);
2905 - wp_die();
2906 - }
2907 -
2908 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2909 - $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
2910 - $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
2911 - $messages = json_decode($messages_json, true);
2912 -
2913 - if (empty($session_id)) {
2914 - wp_send_json_error(['error' => 'No session ID provided']);
2915 - wp_die();
2916 - }
2917 -
2918 - if (empty($messages) || !is_array($messages)) {
2919 - wp_send_json_error(['error' => 'No messages to translate']);
2920 - wp_die();
2921 - }
2922 -
2923 - // Language names for prompting
2924 - $languages = [
2925 - 'en' => 'English',
2926 - 'es' => 'Spanish',
2927 - 'fr' => 'French',
2928 - 'de' => 'German',
2929 - 'it' => 'Italian',
2930 - 'pt' => 'Portuguese',
2931 - 'nl' => 'Dutch',
2932 - 'ru' => 'Russian',
2933 - 'zh' => 'Chinese',
2934 - 'ja' => 'Japanese',
2935 - 'ko' => 'Korean',
2936 - 'ar' => 'Arabic',
2937 - 'hi' => 'Hindi',
2938 - 'tr' => 'Turkish',
2939 - 'pl' => 'Polish',
2940 - 'vi' => 'Vietnamese',
2941 - 'th' => 'Thai',
2942 - 'id' => 'Indonesian',
2943 - 'sv' => 'Swedish',
2944 - 'da' => 'Danish'
2945 - ];
2946 -
2947 - $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
2948 -
2949 - // Build combined text for translation (numbered for parsing)
2950 - $numbered_messages = [];
2951 - foreach ($messages as $i => $msg) {
2952 - $content = isset($msg['content']) ? trim($msg['content']) : '';
2953 - if (!empty($content)) {
2954 - $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
664 + echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
665 + } else {
666 + echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
2955 667 }
2956 - }
2957 668
2958 - if (empty($numbered_messages)) {
2959 - wp_send_json_error(['error' => 'No valid messages to translate']);
2960 669 wp_die();
2961 670 }
2962 671
2963 - $combined_text = implode("\n\n", $numbered_messages);
2964 672
2965 - // Prepare the translation prompt
2966 - $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.";
2967 673
2968 - // Get user's selected model and determine provider
2969 - $options = get_option('mxchat_options', []);
2970 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
2971 -
2972 - // Check if using OpenRouter
2973 - if ($selected_model === 'openrouter') {
2974 - $provider = 'openrouter';
2975 - $selected_model = $options['openrouter_selected_model'] ?? '';
2976 - $api_key = $options['openrouter_api_key'] ?? '';
2977 -
2978 - if (empty($selected_model)) {
2979 - wp_send_json_error(['error' => 'No OpenRouter model selected']);
2980 - wp_die();
2981 - }
2982 - } else {
2983 - // Determine provider from model name
2984 - $model_parts = explode('-', $selected_model);
2985 - $provider = strtolower($model_parts[0]);
2986 -
2987 - // Get the appropriate API key based on provider
2988 - $api_key = '';
2989 - switch ($provider) {
2990 - case 'gpt':
2991 - case 'o1':
2992 - $api_key = $options['api_key'] ?? '';
2993 - break;
2994 - case 'claude':
2995 - $api_key = $options['claude_api_key'] ?? '';
2996 - break;
2997 - case 'grok':
2998 - $api_key = $options['xai_api_key'] ?? '';
2999 - break;
3000 - case 'deepseek':
3001 - $api_key = $options['deepseek_api_key'] ?? '';
3002 - break;
3003 - case 'gemini':
3004 - $api_key = $options['gemini_api_key'] ?? '';
3005 - break;
3006 - default:
3007 - // Default to OpenAI
3008 - $api_key = $options['api_key'] ?? '';
3009 - $provider = 'gpt';
3010 - break;
3011 - }
3012 - }
3013 -
3014 - if (empty($api_key)) {
3015 - wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
3016 - wp_die();
3017 - }
3018 -
3019 - // Make API request based on provider
3020 - $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
3021 -
3022 - if (is_wp_error($response)) {
3023 - wp_send_json_error(['error' => $response->get_error_message()]);
3024 - wp_die();
3025 - }
3026 -
3027 - // Parse the response to extract translated messages
3028 - $translations = [];
3029 - foreach ($messages as $msg) {
3030 - $index = $msg['index'];
3031 - $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
3032 - if (preg_match($pattern, $response, $matches)) {
3033 - $translations[] = [
3034 - 'index' => $index,
3035 - 'translated' => trim($matches[1])
3036 - ];
3037 - }
3038 - }
3039 -
3040 - // Save translations to database
3041 - if (!empty($translations)) {
3042 - $this->save_transcript_translation($session_id, $target_lang, $translations);
3043 - }
3044 -
3045 - wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
3046 - wp_die();
3047 -}
3048 -
3049 -/**
3050 - * Save transcript translation to database
3051 - */
3052 -private function save_transcript_translation($session_id, $language_code, $translations) {
3053 - global $wpdb;
3054 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
3055 -
3056 - // Check if table exists, create if not
3057 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3058 - mxchat_create_translations_table();
3059 - }
3060 -
3061 - $now = current_time('mysql');
3062 - $translations_json = wp_json_encode($translations);
3063 -
3064 - // Use REPLACE to insert or update
3065 - $wpdb->query($wpdb->prepare(
3066 - "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
3067 - VALUES (%s, %s, %s, %s, %s)",
3068 - $session_id,
3069 - $language_code,
3070 - $translations_json,
3071 - $now,
3072 - $now
3073 - ));
3074 -}
3075 -
3076 -/**
3077 - * Get saved translation for a session
3078 - */
3079 -public function mxchat_get_transcript_translation() {
3080 - if (!current_user_can('manage_options')) {
3081 - wp_send_json_error(['error' => 'Insufficient permissions']);
3082 - wp_die();
3083 - }
3084 -
3085 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3086 -
3087 - if (empty($session_id)) {
3088 - wp_send_json_error(['error' => 'No session ID provided']);
3089 - wp_die();
3090 - }
3091 -
3092 - global $wpdb;
3093 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
3094 -
3095 - // Check if table exists
3096 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3097 - wp_send_json(['success' => true, 'has_translation' => false]);
3098 - wp_die();
3099 - }
3100 -
3101 - // Get the most recent translation for this session
3102 - $result = $wpdb->get_row($wpdb->prepare(
3103 - "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
3104 - $session_id
3105 - ));
3106 -
3107 - if ($result) {
3108 - $translations = json_decode($result->translations, true);
3109 - wp_send_json([
3110 - 'success' => true,
3111 - 'has_translation' => true,
3112 - 'language' => $result->language_code,
3113 - 'translations' => $translations
3114 - ]);
3115 - } else {
3116 - wp_send_json(['success' => true, 'has_translation' => false]);
3117 - }
3118 - wp_die();
3119 -}
3120 -
3121 -/**
3122 - * Translate text using the user's selected provider and model
3123 - */
3124 -private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
3125 - switch ($provider) {
3126 - case 'claude':
3127 - return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
3128 - case 'grok':
3129 - return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
3130 - case 'deepseek':
3131 - return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
3132 - case 'gemini':
3133 - return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
3134 - case 'openrouter':
3135 - return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
3136 - case 'gpt':
3137 - case 'o1':
3138 - default:
3139 - return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
3140 - }
3141 -}
3142 -
3143 -/**
3144 - * Translate text using OpenAI API
3145 - */
3146 -private function translate_with_openai($api_key, $model, $system_prompt, $text) {
3147 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
3148 - 'timeout' => 60,
3149 - 'headers' => [
3150 - 'Authorization' => 'Bearer ' . $api_key,
3151 - 'Content-Type' => 'application/json'
3152 - ],
3153 - 'body' => wp_json_encode([
3154 - 'model' => $model,
3155 - 'messages' => [
3156 - ['role' => 'system', 'content' => $system_prompt],
3157 - ['role' => 'user', 'content' => $text]
3158 - ],
3159 - 'temperature' => 0.3
3160 - ])
3161 - ]);
3162 -
3163 - if (is_wp_error($response)) {
3164 - return $response;
3165 - }
3166 -
3167 - $body = json_decode(wp_remote_retrieve_body($response), true);
3168 -
3169 - if (isset($body['error'])) {
3170 - return new WP_Error('api_error', $body['error']['message']);
3171 - }
3172 -
3173 - if (isset($body['choices'][0]['message']['content'])) {
3174 - return $body['choices'][0]['message']['content'];
3175 - }
3176 -
3177 - return new WP_Error('api_error', 'Invalid API response');
3178 -}
3179 -
3180 -/**
3181 - * Translate text using Claude API
3182 - */
3183 -private function translate_with_claude($api_key, $model, $system_prompt, $text) {
3184 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3185 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3186 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3187 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3188 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
3189 - 'timeout' => 60,
3190 - 'headers' => [
3191 - 'x-api-key' => $api_key,
3192 - 'anthropic-version' => '2023-06-01',
3193 - 'Content-Type' => 'application/json'
3194 - ],
3195 - 'body' => wp_json_encode([
3196 - 'model' => $model,
3197 - 'max_tokens' => 4096,
3198 - // Prompt-cache breakpoint (plan 1ff43b): the translate instruction
3199 - // repeats across every message in a batch, so cache reads bill at
3200 - // 0.1x. Below the model's minimum prefix it silently no-ops.
3201 - 'system' => trim((string) $system_prompt) === '' ? $system_prompt : [
3202 - ['type' => 'text', 'text' => $system_prompt, 'cache_control' => ['type' => 'ephemeral']]
3203 - ],
3204 - 'messages' => [
3205 - ['role' => 'user', 'content' => $text]
3206 - ]
3207 - ])
3208 - ]);
3209 -
3210 - if (is_wp_error($response)) {
3211 - return $response;
3212 - }
3213 -
3214 - $body = json_decode(wp_remote_retrieve_body($response), true);
3215 -
3216 - if (isset($body['error'])) {
3217 - return new WP_Error('api_error', $body['error']['message']);
3218 - }
3219 -
3220 - if (isset($body['content'][0]['text'])) {
3221 - return $body['content'][0]['text'];
3222 - }
3223 -
3224 - return new WP_Error('api_error', 'Invalid API response');
3225 -}
3226 -
3227 -/**
3228 - * Translate text using xAI (Grok) API
3229 - */
3230 -private function translate_with_xai($api_key, $model, $system_prompt, $text) {
3231 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
3232 - 'timeout' => 60,
3233 - 'headers' => [
3234 - 'Authorization' => 'Bearer ' . $api_key,
3235 - 'Content-Type' => 'application/json'
3236 - ],
3237 - 'body' => wp_json_encode([
3238 - 'model' => $model,
3239 - 'messages' => [
3240 - ['role' => 'system', 'content' => $system_prompt],
3241 - ['role' => 'user', 'content' => $text]
3242 - ],
3243 - 'temperature' => 0.3
3244 - ])
3245 - ]);
3246 -
3247 - if (is_wp_error($response)) {
3248 - return $response;
3249 - }
3250 -
3251 - $body = json_decode(wp_remote_retrieve_body($response), true);
3252 -
3253 - if (isset($body['error'])) {
3254 - return new WP_Error('api_error', $body['error']['message']);
3255 - }
3256 -
3257 - if (isset($body['choices'][0]['message']['content'])) {
3258 - return $body['choices'][0]['message']['content'];
3259 - }
3260 -
3261 - return new WP_Error('api_error', 'Invalid API response');
3262 -}
3263 -
3264 -/**
3265 - * Translate text using DeepSeek API
3266 - */
3267 -private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
3268 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
3269 - 'timeout' => 60,
3270 - 'headers' => [
3271 - 'Authorization' => 'Bearer ' . $api_key,
3272 - 'Content-Type' => 'application/json'
3273 - ],
3274 - 'body' => wp_json_encode([
3275 - 'model' => $model,
3276 - 'messages' => [
3277 - ['role' => 'system', 'content' => $system_prompt],
3278 - ['role' => 'user', 'content' => $text]
3279 - ],
3280 - 'temperature' => 0.3,
3281 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
3282 - // slow responses); translation wants non-thinking.
3283 - 'thinking' => ['type' => 'disabled']
3284 - ])
3285 - ]);
3286 -
3287 - if (is_wp_error($response)) {
3288 - return $response;
3289 - }
3290 -
3291 - $body = json_decode(wp_remote_retrieve_body($response), true);
3292 -
3293 - if (isset($body['error'])) {
3294 - return new WP_Error('api_error', $body['error']['message']);
3295 - }
3296 -
3297 - if (isset($body['choices'][0]['message']['content'])) {
3298 - return $body['choices'][0]['message']['content'];
3299 - }
3300 -
3301 - return new WP_Error('api_error', 'Invalid API response');
3302 -}
3303 -
3304 -/**
3305 - * Translate text using Google Gemini API
3306 - */
3307 -private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
3308 - if ($model === 'gemini-3-pro-preview') {
3309 - $model = 'gemini-3.1-pro-preview';
3310 - }
3311 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
3312 -
3313 - $response = wp_remote_post($url, [
3314 - 'timeout' => 60,
3315 - 'headers' => [
3316 - 'Content-Type' => 'application/json'
3317 - ],
3318 - 'body' => wp_json_encode([
3319 - 'contents' => [
3320 - [
3321 - 'parts' => [
3322 - ['text' => $system_prompt . "\n\n" . $text]
3323 - ]
3324 - ]
3325 - ],
3326 - 'generationConfig' => [
3327 - 'temperature' => 0.3
3328 - ]
3329 - ])
3330 - ]);
3331 -
3332 - if (is_wp_error($response)) {
3333 - return $response;
3334 - }
3335 -
3336 - $body = json_decode(wp_remote_retrieve_body($response), true);
3337 -
3338 - if (isset($body['error'])) {
3339 - return new WP_Error('api_error', $body['error']['message']);
3340 - }
3341 -
3342 - if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
3343 - return $body['candidates'][0]['content']['parts'][0]['text'];
3344 - }
3345 -
3346 - return new WP_Error('api_error', 'Invalid API response');
3347 -}
3348 -
3349 -/**
3350 - * Translate text using OpenRouter API
3351 - */
3352 -private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
3353 - $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
3354 - 'timeout' => 60,
3355 - 'headers' => [
3356 - 'Authorization' => 'Bearer ' . $api_key,
3357 - 'Content-Type' => 'application/json',
3358 - 'HTTP-Referer' => home_url(),
3359 - 'X-Title' => 'MxChat Translation'
3360 - ],
3361 - 'body' => wp_json_encode([
3362 - 'model' => $model,
3363 - 'messages' => [
3364 - ['role' => 'system', 'content' => $system_prompt],
3365 - ['role' => 'user', 'content' => $text]
3366 - ],
3367 - 'temperature' => 0.3
3368 - ])
3369 - ]);
3370 -
3371 - if (is_wp_error($response)) {
3372 - return $response;
3373 - }
3374 -
3375 - $body = json_decode(wp_remote_retrieve_body($response), true);
3376 -
3377 - if (isset($body['error'])) {
3378 - return new WP_Error('api_error', $body['error']['message']);
3379 - }
3380 -
3381 - if (isset($body['choices'][0]['message']['content'])) {
3382 - return $body['choices'][0]['message']['content'];
3383 - }
3384 -
3385 - return new WP_Error('api_error', 'Invalid API response');
3386 -}
3387 -
3388 674 public function mxchat_fetch_chat_history() {
3389 675 global $wpdb;
3390 676 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3391 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3392 677
678 + // Check if the current user has sufficient permissions
3393 679 if (!current_user_can('manage_options')) {
3394 - wp_send_json_error(['message' => 'Insufficient permissions']);
680 + echo esc_html__('You do not have sufficient permissions to view this page.', 'mxchat');
3395 681 wp_die();
3396 682 }
3397 683
3398 - $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3399 - $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3400 - $offset = ($page - 1) * $per_page;
3401 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3402 - $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3403 - $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3404 - if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3405 - $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3406 - $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3407 - $ratings_join = '';
3408 - $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3409 - if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3410 - // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3411 - $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3412 - $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3413 - }
684 + // Fetch chat transcripts from the database, ordered by timestamp
685 + $chat_transcripts = $wpdb->get_results(
686 + $wpdb->prepare("SELECT * FROM {$table_name} ORDER BY timestamp ASC")
687 + );
3414 688
3415 - // Build search condition
3416 - $search_condition = '';
3417 - $search_params = [];
3418 - if (!empty($search)) {
3419 - $search_condition = "WHERE (
3420 - session_id LIKE %s
3421 - OR user_email LIKE %s
3422 - OR user_name LIKE %s
3423 - OR user_identifier LIKE %s
3424 - OR message LIKE %s
3425 - )";
3426 - $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3427 - }
3428 -
3429 - // Get total count
3430 - $count_query = !empty($search)
3431 - ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3432 - : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3433 - $total_sessions = (int) $wpdb->get_var($count_query);
3434 -
3435 - // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3436 - // and order by rating value (NULLs last) with recency as tiebreaker.
3437 - if ($ratings_join) {
3438 - $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3439 - } else {
3440 - $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3441 - }
3442 - $session_query = !empty($search)
3443 - ? $wpdb->prepare(
3444 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3445 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3446 - array_merge($search_params, [$per_page, $offset])
3447 - )
3448 - : $wpdb->prepare(
3449 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3450 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3451 - $per_page, $offset
3452 - );
3453 - $session_ids = $wpdb->get_col($session_query);
3454 -
3455 - $total_pages = ceil($total_sessions / $per_page);
3456 -
3457 - if (empty($session_ids)) {
3458 - wp_send_json([
3459 - 'success' => true,
3460 - 'sessions' => [],
3461 - 'page' => $page,
3462 - 'total_pages' => 0,
3463 - 'total_sessions' => 0,
3464 - 'showing_start' => 0,
3465 - 'showing_end' => 0
3466 - ]);
689 + // If no transcripts are available, display a message
690 + if (empty($chat_transcripts)) {
691 + echo esc_html__('No chat history available.', 'mxchat');
3467 692 wp_die();
3468 693 }
3469 694
3470 - // Check for optional columns/tables
3471 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3472 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
695 + ob_start();
696 + $current_session_id = '';
3473 697
3474 - // Batch-fetch session ratings for this page (plan-a5b006).
3475 - $ratings_map = array();
3476 - if ($rating_table_exists && !empty($session_ids)) {
3477 - $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3478 - $rating_rows = $wpdb->get_results($wpdb->prepare(
3479 - "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3480 - $session_ids
3481 - ));
3482 - foreach ($rating_rows as $row) {
3483 - $ratings_map[$row->session_id] = array(
3484 - 'value' => (int) $row->rating_value,
3485 - 'feedback' => (string) $row->rating_feedback,
3486 - );
3487 - }
3488 - }
3489 -
3490 - // Build session list data
3491 - $sessions = [];
3492 - foreach ($session_ids as $session_id) {
3493 - // Get session metadata
3494 - $session_data = $originating_columns_exist
3495 - ? $wpdb->get_row($wpdb->prepare(
3496 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3497 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3498 - $session_id
3499 - ))
3500 - : $wpdb->get_row($wpdb->prepare(
3501 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3502 - WHERE session_id = %s LIMIT 1",
3503 - $session_id
3504 - ));
3505 -
3506 - // Get message count and latest timestamp
3507 - $message_stats = $wpdb->get_row($wpdb->prepare(
3508 - "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3509 - $session_id
3510 - ));
3511 -
3512 - // Get first user message as preview
3513 - $first_user_msg = $wpdb->get_var($wpdb->prepare(
3514 - "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3515 - $session_id
3516 - ));
3517 - $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3518 -
3519 - // Build display name
3520 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3521 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3522 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3523 -
3524 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3525 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3526 -
3527 - // Format time - show relative for recent, date for older
3528 - $timestamp = strtotime($message_stats->latest . ' UTC');
3529 - $now = time();
3530 - $diff = $now - $timestamp;
3531 - if ($diff < 3600) {
3532 - $time_display = floor($diff / 60) . 'm ago';
3533 - } elseif ($diff < 86400) {
3534 - $time_display = floor($diff / 3600) . 'h ago';
3535 - } elseif ($diff < 604800) {
3536 - $time_display = floor($diff / 86400) . 'd ago';
3537 - } else {
3538 - $time_display = wp_date('M j', $timestamp);
3539 - }
3540 -
3541 - // Get initials for avatar
3542 - $initials = strtoupper(substr($display_name, 0, 2));
3543 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3544 - $parts = explode(' ', $display_name);
3545 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3546 - }
3547 -
3548 - $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3549 - $rating_value = $rating_entry ? $rating_entry['value'] : null;
3550 - $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3551 -
3552 - $sessions[] = [
3553 - 'session_id' => $session_id,
3554 - 'display_name' => $display_name,
3555 - 'display_sub' => $display_sub,
3556 - 'initials' => $initials,
3557 - 'preview' => $preview,
3558 - 'message_count' => (int) $message_stats->count,
3559 - 'time_display' => $time_display,
3560 - 'timestamp' => $message_stats->latest,
3561 - 'rating_value' => $rating_value,
3562 - 'rating_feedback' => $rating_feedback,
3563 - ];
3564 - }
3565 -
3566 - wp_send_json([
3567 - 'success' => true,
3568 - 'sessions' => $sessions,
3569 - 'page' => $page,
3570 - 'total_pages' => $total_pages,
3571 - 'total_sessions' => $total_sessions,
3572 - 'showing_start' => $offset + 1,
3573 - 'showing_end' => min($offset + $per_page, $total_sessions)
3574 - ]);
3575 - wp_die();
3576 -}
3577 -
3578 -/**
3579 - * Fetch single conversation details for split-panel view
3580 - */
3581 -public function mxchat_fetch_conversation() {
3582 - global $wpdb;
3583 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3584 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3585 -
3586 - if (!current_user_can('manage_options')) {
3587 - wp_send_json_error(['message' => 'Insufficient permissions']);
3588 - wp_die();
3589 - }
3590 -
3591 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3592 - if (empty($session_id)) {
3593 - wp_send_json_error(['message' => 'No session ID provided']);
3594 - wp_die();
3595 - }
3596 -
3597 - // Check for optional columns/tables
3598 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3599 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3600 -
3601 - // Get session metadata
3602 - $session_data = $originating_columns_exist
3603 - ? $wpdb->get_row($wpdb->prepare(
3604 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3605 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3606 - $session_id
3607 - ))
3608 - : $wpdb->get_row($wpdb->prepare(
3609 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3610 - WHERE session_id = %s LIMIT 1",
3611 - $session_id
3612 - ));
3613 -
3614 - if (!$session_data) {
3615 - wp_send_json_error(['message' => 'Session not found']);
3616 - wp_die();
3617 - }
3618 -
3619 - // Get clicked URLs
3620 - $clicked_urls = [];
3621 - if ($url_table_exists) {
3622 - $url_clicks = $wpdb->get_results($wpdb->prepare(
3623 - "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3624 - WHERE session_id = %s ORDER BY click_timestamp ASC",
3625 - $session_id
3626 - ));
3627 - foreach ($url_clicks as $click) {
3628 - $clicked_urls[] = $click->clicked_url;
3629 - }
3630 - }
3631 -
3632 - // Get all messages
3633 - $messages = $wpdb->get_results($wpdb->prepare(
3634 - "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3635 - $session_id
3636 - ));
3637 -
3638 - // Build user info
3639 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3640 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3641 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3642 -
3643 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3644 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3645 -
3646 - // Get initials
3647 - $initials = strtoupper(substr($display_name, 0, 2));
3648 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3649 - $parts = explode(' ', $display_name);
3650 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3651 - }
3652 -
3653 - // Page info
3654 - $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3655 - $page_title = '';
3656 - if ($page_url) {
3657 - $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3658 - }
3659 -
3660 - // Format messages for output
3661 - $formatted_messages = [];
3662 - foreach ($messages as $msg) {
3663 - $is_user = ($msg->role === 'user');
3664 - // Live-agent replies (Slack/Telegram handoff) persist with role 'agent'.
3665 - // Kept OUT of $is_bot so the RAG Sources link below stays bot-only.
3666 - $is_agent = ($msg->role === 'agent');
3667 - $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3668 -
3669 - $content = wp_kses(
3670 - stripslashes($msg->message),
3671 - [
3672 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3673 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3674 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3675 - 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3676 - 'img' => ['src' => [], 'alt' => [], 'class' => []],
3677 - 'h3' => ['class' => []],
3678 - 'h4' => ['class' => []],
3679 - 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
3680 - 'select' => ['class' => [], 'data-attribute' => []],
3681 - 'option' => ['value' => []],
3682 - 'span' => ['class' => []],
3683 - 'del' => [], 'ins' => [],
3684 - ]
3685 - );
3686 - $formatted_content = $this->format_transcript_message($content);
3687 -
3688 - $has_rag = $is_bot && !empty($msg->rag_context);
3689 -
3690 - $formatted_messages[] = [
3691 - 'id' => $msg->id,
3692 - 'role' => $msg->role,
3693 - 'is_user' => $is_user,
3694 - 'is_agent' => $is_agent,
3695 - 'is_bot' => $is_bot,
3696 - 'content' => $formatted_content,
3697 - 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
3698 - 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
3699 - 'has_rag' => $has_rag
3700 - ];
3701 - }
3702 -
3703 - // First message timestamp for "started" display
3704 - $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
3705 -
3706 - // Pull rating_feedback for this session (if any) so the details drawer can show it.
3707 - $rating_feedback = '';
3708 - $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
3709 - if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
3710 - $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
3711 - "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
3712 - $session_id
3713 - ));
3714 - }
3715 -
3716 - wp_send_json([
3717 - 'success' => true,
3718 - 'session_id' => $session_id,
3719 - 'user' => [
3720 - 'name' => $display_name,
3721 - 'sub' => $display_sub,
3722 - 'initials' => $initials,
3723 - 'email' => $user_email,
3724 - 'identifier' => $user_identifier
3725 - ],
3726 - 'page' => [
3727 - 'url' => $page_url,
3728 - 'title' => $page_title
3729 - ],
3730 - 'clicked_urls' => $clicked_urls,
3731 - 'messages' => $formatted_messages,
3732 - 'message_count' => count($messages),
3733 - 'started' => $started,
3734 - 'rating_feedback' => $rating_feedback
3735 - ]);
3736 - wp_die();
3737 -}
3738 -
3739 -
3740 -/**
3741 - * ALTERNATIVE: Simpler helper method using string replacement
3742 - */
3743 -private function highlight_clicked_links($message_content, $clicked_urls) {
3744 - if (empty($clicked_urls)) {
3745 - return wp_kses(
3746 - $message_content,
3747 - [
3748 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3749 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3750 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3751 - ]
3752 - );
3753 - }
3754 -
3755 - // First apply standard sanitization
3756 - $message_content = wp_kses(
3757 - $message_content,
3758 - [
3759 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3760 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3761 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3762 - ]
3763 - );
3764 -
3765 - // Process each clicked URL
3766 - foreach ($clicked_urls as $clicked_url) {
3767 - // Try multiple patterns to catch different link formats
3768 - $patterns = [
3769 - // Standard link format
3770 - '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
3771 - // Link with trailing slash
3772 - '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
3773 - // Encoded entities version
3774 - '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
3775 - ];
3776 -
3777 - foreach ($patterns as $pattern) {
3778 - if (preg_match($pattern, $message_content)) {
3779 - $message_content = preg_replace_callback(
3780 - $pattern,
3781 - function($matches) {
3782 - $full_match = $matches[0];
3783 - $attributes = $matches[1];
3784 -
3785 - // Check if it already has the class
3786 - if (strpos($full_match, 'mxchat-clicked-link') !== false) {
3787 - return $full_match;
3788 - }
3789 -
3790 - // Check if class attribute exists
3791 - if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
3792 - // Add to existing class
3793 - $new_attributes = preg_replace(
3794 - '/class=["\']([^"\']*)["\']/',
3795 - 'class="$1 mxchat-clicked-link"',
3796 - $attributes
3797 - );
3798 - } else {
3799 - // Add new class attribute
3800 - $new_attributes = $attributes . ' class="mxchat-clicked-link"';
3801 - }
3802 -
3803 - // Add title if not present
3804 - if (strpos($new_attributes, 'title=') === false) {
3805 - $new_attributes .= ' title="User clicked this link"';
3806 - }
3807 -
3808 - return '<a' . $new_attributes . '>';
3809 - },
3810 - $message_content
3811 - );
3812 -
3813 - // If we found and replaced, break out of the patterns loop
3814 - break;
698 + foreach ($chat_transcripts as $transcript) {
699 + // Start a new session block if session ID changes
700 + if ($current_session_id !== $transcript->session_id) {
701 + if ($current_session_id !== '') {
702 + echo '</div>'; // Close the previous session block
3815 703 }
704 + $current_session_id = sanitize_text_field($transcript->session_id);
705 + echo '<div class="chat-session">';
706 + 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>';
3816 707 }
3817 - }
3818 708
3819 - return $message_content;
3820 -}
709 + // Format the timestamp for display
710 + $formatted_timestamp = date_i18n('F j, Y g:i a', strtotime($transcript->timestamp));
3821 711
3822 -public function mxchat_create_prompts_page() {
3823 - //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
712 + // Determine the role to display (user identifier or email for users, bot for the AI)
713 + $role = $transcript->role;
714 + if ($role === 'user') {
715 + // Sanitize email if available
716 + if (!empty($transcript->user_email)) {
717 + $role = sanitize_email($transcript->user_email);
718 + } else {
719 + // Sanitize user identifier, anonymize if it's an IP address
720 + $user_identifier = sanitize_text_field($transcript->user_identifier);
3824 721
3825 - global $wpdb;
3826 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3827 -
3828 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3829 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
3830 -
3831 - // Display success message if all prompts were deleted
3832 - if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
3833 - 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>';
3834 - }
3835 -
3836 - // Set up pagination, search query, and content type filter
3837 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
3838 - $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
3839 - $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
3840 - $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
3841 - $per_page = 25;
3842 -
3843 - //error_log('DEBUG: Search query: ' . $search_query);
3844 - //error_log('DEBUG: Content type filter: ' . $content_type_filter);
3845 - //error_log('DEBUG: Current page: ' . $current_page);
3846 - //error_log('DEBUG: Per page: ' . $per_page);
3847 -
3848 - // ================================
3849 - // MULTI-BOT CONFIGURATION
3850 - // ================================
3851 -
3852 - // Check for multi-bot and set up bot selection
3853 - if (class_exists('MxChat_Multi_Bot_Manager')) {
3854 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
3855 - $available_bots = $multi_bot_manager->get_available_bots();
3856 -
3857 - // Get saved bot selection (user-specific first, then site-wide default)
3858 - $user_id = get_current_user_id();
3859 - $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
3860 - if (empty($saved_bot_id)) {
3861 - $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
3862 - }
3863 -
3864 - // Allow URL override but default to saved selection
3865 - $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
3866 - $multibot_active = true;
3867 - } else {
3868 - $current_bot_id = 'default';
3869 - $multibot_active = false;
3870 - }
3871 -
3872 - // ================================
3873 - // DATA SOURCE CONFIGURATION
3874 - // ================================
3875 -
3876 - // Get bot-specific Pinecone settings
3877 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
3878 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3879 - $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
3880 -
3881 - // Get OpenAI Vector Store settings
3882 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
3883 - $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
3884 -
3885 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3886 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
3887 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
3888 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
3889 -
3890 - if ($use_pinecone && !empty($pinecone_api_key)) {
3891 - //error_log('DEBUG: Using PINECONE data source with bot-specific config');
3892 - // PINECONE DATA SOURCE
3893 - $data_source = 'pinecone';
3894 -
3895 - // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
3896 - // UPDATED 2.5.6: Added content_type_filter parameter
3897 - $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
3898 -
3899 - // TEMPORARY DEBUG - Add this right after the fetch call
3900 - //error_log('=== DEBUG: Bot switching issue ===');
3901 - //error_log('Current bot ID: ' . $current_bot_id);
3902 - //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3903 - //error_log('Records returned: ' . count($records['data'] ?? []));
3904 - //error_log('Total records: ' . ($records['total'] ?? 0));
3905 -
3906 - // Check first few records to see their bot_id
3907 - if (!empty($records['data'])) {
3908 - foreach (array_slice($records['data'], 0, 3) as $i => $record) {
3909 - $record_bot_id = $record->bot_id ?? 'NOT_SET';
3910 - //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
3911 - }
3912 - }
3913 - //error_log('=== END DEBUG ===');
3914 -
3915 - $total_records = $records['total'] ?? 0;
3916 - $prompts = $records['data'] ?? array();
3917 - $total_in_database = $records['total_in_database'] ?? 0;
3918 - $showing_recent_only = $records['showing_recent_only'] ?? false;
3919 -
3920 - $total_pages = ceil($total_records / $per_page);
3921 -
3922 - } else {
3923 - //error_log('DEBUG: Using WORDPRESS DB data source');
3924 - // WORDPRESS DB DATA SOURCE (your existing logic)
3925 - $data_source = 'wordpress';
3926 -
3927 - // Initialize these variables for WordPress DB
3928 - $total_in_database = 0;
3929 - $showing_recent_only = false;
3930 -
3931 - $offset = ($current_page - 1) * $per_page;
3932 -
3933 - // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
3934 - $where_clauses = array();
3935 - $where_values = array();
3936 -
3937 - if ($search_query) {
3938 - $where_clauses[] = "article_content LIKE %s";
3939 - $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
3940 - }
3941 -
3942 - if ($content_type_filter) {
3943 - $where_clauses[] = "content_type = %s";
3944 - $where_values[] = $content_type_filter;
3945 - }
3946 -
3947 - $sql_where = "";
3948 - if (!empty($where_clauses)) {
3949 - $sql_where = "WHERE " . implode(" AND ", $where_clauses);
3950 - }
3951 -
3952 - // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
3953 - // This ensures pagination shows X entries per page, not X chunks
3954 - // Entries with empty source_url are counted individually
3955 - if (!empty($where_values)) {
3956 - // Count unique source_urls + count of rows with empty source_url
3957 - $count_query = $wpdb->prepare(
3958 - "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
3959 - (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
3960 - array_merge($where_values, $where_values)
3961 - );
3962 - } else {
3963 - $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
3964 - (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
3965 - }
3966 - $total_records = $wpdb->get_var($count_query);
3967 - $total_pages = ceil($total_records / $per_page);
3968 -
3969 - // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
3970 - // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
3971 - if (!empty($where_values)) {
3972 - $urls_query = $wpdb->prepare(
3973 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
3974 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3975 - array_merge($where_values, array($per_page, $offset))
3976 - );
3977 - } else {
3978 - $urls_query = $wpdb->prepare(
3979 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
3980 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3981 - $per_page, $offset
3982 - );
3983 - }
3984 - $page_urls = $wpdb->get_results($urls_query);
3985 -
3986 - // Step 2: Fetch all rows for these source_urls
3987 - $prompts = array();
3988 - if (!empty($page_urls)) {
3989 - // Build URL order map to preserve newest-first ordering from step 1
3990 - $url_order_map = array();
3991 - $url_list = array();
3992 - $has_empty_url = false;
3993 - $order_index = 0;
3994 - foreach ($page_urls as $url_row) {
3995 - if (empty($url_row->source_url)) {
3996 - $has_empty_url = true;
3997 - $url_order_map['__empty__'] = $order_index++;
722 + // Check if the user identifier is an IP address and anonymize it
723 + if (filter_var($user_identifier, FILTER_VALIDATE_IP)) {
724 + $role = preg_replace('/\.\d+$/', '.xxx', $user_identifier); // Mask the last octet
3998 725 } else {
3999 - $url_list[] = $url_row->source_url;
4000 - $url_order_map[$url_row->source_url] = $order_index++;
726 + $role = $user_identifier; // If it's not an IP, just display the identifier
4001 727 }
4002 728 }
4003 -
4004 - // Build query to fetch all rows for these URLs
4005 - $url_conditions = array();
4006 - $url_values = array();
4007 -
4008 - if (!empty($url_list)) {
4009 - $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
4010 - $url_conditions[] = "source_url IN ($placeholders)";
4011 - $url_values = array_merge($url_values, $url_list);
4012 - }
4013 -
4014 - if ($has_empty_url) {
4015 - $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
4016 - }
4017 -
4018 - if (!empty($url_conditions)) {
4019 - $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
4020 -
4021 - // Add original filters back
4022 - if (!empty($where_clauses)) {
4023 - $url_where .= " AND " . implode(" AND ", $where_clauses);
4024 - $url_values = array_merge($url_values, $where_values);
4025 - }
4026 -
4027 - if (!empty($url_values)) {
4028 - $prompts_query = $wpdb->prepare(
4029 - "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
4030 - $url_values
4031 - );
4032 - } else {
4033 - $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
4034 - }
4035 -
4036 - $prompts = $wpdb->get_results($prompts_query);
4037 -
4038 - // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
4039 - usort($prompts, function($a, $b) use ($url_order_map) {
4040 - $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
4041 - $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
4042 - $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
4043 - $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
4044 -
4045 - // First sort by URL order (newest URLs first)
4046 - if ($order_a !== $order_b) {
4047 - return $order_a - $order_b;
4048 - }
4049 -
4050 - // Within same URL, sort by timestamp DESC (newest chunks first)
4051 - return strtotime($b->timestamp) - strtotime($a->timestamp);
4052 - });
4053 - }
4054 729 }
4055 - }
4056 730
4057 - // ================================
4058 - // PAGINATION GENERATION
4059 - // ================================
4060 -
4061 - // Generate pagination links
4062 - if ($total_pages > 1) {
4063 - // Build a clean base URL with only necessary parameters
4064 - $pagination_args = array('page' => 'mxchat-prompts');
4065 -
4066 - // Preserve bot_id parameter if multi-bot is active
4067 - if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
4068 - $pagination_args['bot_id'] = $current_bot_id;
4069 - }
4070 -
4071 - // Preserve search query and nonce if present
4072 - if ($search_query) {
4073 - $pagination_args['search'] = $search_query;
4074 - if (!empty($nonce)) {
4075 - $pagination_args['_wpnonce'] = $nonce;
4076 - }
4077 - }
4078 -
4079 - // Preserve content type filter if present
4080 - if ($content_type_filter) {
4081 - $pagination_args['content_type'] = $content_type_filter;
4082 - }
4083 -
4084 - // Build clean base URL
4085 - $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
4086 -
4087 - $page_links = paginate_links(array(
4088 - 'base' => $base_url . '%_%',
4089 - 'format' => '&paged=%#%',
4090 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4091 - 'next_text' => __('Next &raquo;', 'mxchat'),
4092 - 'total' => $total_pages,
4093 - 'current' => $current_page,
4094 - 'type' => 'plain',
4095 - ));
4096 - } else {
4097 - $page_links = '';
731 + // Output the chat message
732 + echo '<div class="chat-message">';
733 + echo '<strong>' . esc_html($role) . ' (' . esc_html($formatted_timestamp) . '):</strong> ';
734 + echo wp_kses_post($transcript->message);
735 + echo '</div>';
4098 736 }
4099 737
4100 - // ================================
4101 - // PROCESSING STATUS RETRIEVAL
4102 - // ================================
738 + // Close the final session block
739 + echo '</div>';
4103 740
4104 - // Retrieve processing statuses using queue-based method
4105 - $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
4106 - $pdf_status = $processing_statuses['pdf_status'];
4107 - $sitemap_status = $processing_statuses['sitemap_status'];
4108 - $is_processing = $processing_statuses['is_processing'];
741 + $output = ob_get_clean();
4109 742
4110 - //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
4111 -
4112 - // ================================
4113 - // RENDER PAGE WITH NEW SIDEBAR LAYOUT
4114 - // ================================
4115 -
4116 - // Include the new knowledge page template
4117 - require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
4118 -
4119 - // Package all page data for the render function
4120 - $page_data = array(
4121 - 'prompts' => $prompts,
4122 - 'total_records' => $total_records,
4123 - 'total_pages' => $total_pages,
4124 - 'current_page' => $current_page,
4125 - 'per_page' => $per_page,
4126 - 'page_links' => $page_links,
4127 - 'search_query' => $search_query,
4128 - 'content_type_filter' => $content_type_filter,
4129 - 'data_source' => $data_source,
4130 - 'use_pinecone' => $use_pinecone,
4131 - 'use_vectorstore' => $use_vectorstore,
4132 - 'multibot_active' => $multibot_active,
4133 - 'current_bot_id' => $current_bot_id,
4134 - 'pdf_status' => $pdf_status,
4135 - 'sitemap_status' => $sitemap_status,
4136 - 'is_processing' => $is_processing,
4137 - 'total_in_database' => $total_in_database ?? 0,
4138 - 'showing_recent_only' => $showing_recent_only ?? false,
4139 - );
4140 -
4141 - // Render the new sidebar-based page
4142 - mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
4143 -}
4144 -
4145 -/**
4146 - * Get bot-specific Pinecone configuration
4147 - * Used in the knowledge retrieval functions
4148 - */
4149 -private function get_bot_pinecone_config($bot_id = 'default') {
4150 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
4151 -
4152 - // If default bot or multi-bot add-on not active, use default Pinecone config
4153 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
4154 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
4155 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
4156 - $config = array(
4157 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
4158 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
4159 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
4160 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
4161 - );
4162 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
4163 - return $config;
4164 - }
4165 -
4166 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
4167 -
4168 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
4169 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
4170 -
4171 - if (!empty($bot_pinecone_config)) {
4172 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
4173 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
4174 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
4175 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
4176 - } else {
4177 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
4178 - }
4179 -
4180 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
4181 -}
4182 -
4183 -public function mxchat_delete_chat_history() {
4184 - if (!current_user_can('manage_options')) {
4185 - echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4186 - wp_die();
4187 - }
4188 - check_ajax_referer('mxchat_delete_chat_history', 'security');
4189 -
4190 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
4191 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
4192 - wp_die();
4193 - }
4194 -
4195 - global $wpdb;
4196 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4197 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
4198 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
4199 -
4200 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
4201 - // across the whole table). Default false: the chat rows go away but the lead is
4202 - // preserved as a separate "chat deleted" lead in the Leads tab.
4203 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
4204 -
4205 - $deleted_count = 0;
4206 - $preserved_as_deleted_leads = 0;
4207 - $emails_to_fully_wipe = [];
4208 -
4209 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
4210 - $session_id_sanitized = MxChat_Utils::sanitize_session_id($session_id);
4211 - if ($session_id_sanitized === '') {
4212 - continue;
4213 - }
4214 -
4215 - // Capture the lead info attached to this session *before* we delete the rows.
4216 - $lead_row = $wpdb->get_row($wpdb->prepare(
4217 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
4218 - FROM {$table_name}
4219 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
4220 - GROUP BY user_email, user_name
4221 - ORDER BY last_ts DESC LIMIT 1",
4222 - $session_id_sanitized
4223 - ));
4224 -
4225 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
4226 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
4227 -
4228 - if ($has_translations) {
4229 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
4230 - }
4231 -
4232 - // Read the consent record BEFORE delete_session() destroys the row —
4233 - // a preserved "chat deleted" lead must keep its consent proof (b062c4).
4234 - $consent_to_preserve = null;
4235 - if ($lead_row && !empty($lead_row->user_email) && class_exists('MxChat_Session_Store')) {
4236 - $consent_state = MxChat_Session_Store::get($session_id_sanitized, 'consent', '');
4237 - if ($consent_state !== '' && $consent_state !== false) {
4238 - $consent_to_preserve = [
4239 - 'given' => (string) $consent_state,
4240 - 'label' => (string) MxChat_Session_Store::get($session_id_sanitized, 'consent_label', ''),
4241 - 'at' => (string) MxChat_Session_Store::get($session_id_sanitized, 'consent_at', ''),
4242 - ];
4243 - }
4244 - }
4245 -
4246 - delete_option('mxchat_history_' . $session_id_sanitized);
4247 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
4248 - if (class_exists('MxChat_Session_Store')) {
4249 - MxChat_Session_Store::delete_session($session_id_sanitized); // b64b77
4250 - }
4251 -
4252 - if ($lead_row && !empty($lead_row->user_email)) {
4253 - if ($also_delete_lead) {
4254 - // Full-wipe requested — queue the email so that all their sessions and
4255 - // related options get swept below. Also clear this session's pre-chat
4256 - // capture options (they're no longer meaningful).
4257 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
4258 - delete_option('mxchat_email_' . $session_id_sanitized);
4259 - delete_option('mxchat_name_' . $session_id_sanitized);
4260 - } else {
4261 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
4262 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
4263 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
4264 - if (!empty($lead_row->user_name)) {
4265 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
4266 - }
4267 - if (!empty($lead_row->last_ts)) {
4268 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
4269 - }
4270 - if ($consent_to_preserve !== null) {
4271 - update_option('mxchat_lead_del_consent_' . $session_id_sanitized, $consent_to_preserve['given'], false);
4272 - update_option('mxchat_lead_del_consent_label_' . $session_id_sanitized, $consent_to_preserve['label'], false);
4273 - update_option('mxchat_lead_del_consent_at_' . $session_id_sanitized, $consent_to_preserve['at'], false);
4274 - }
4275 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
4276 - delete_option('mxchat_email_' . $session_id_sanitized);
4277 - delete_option('mxchat_name_' . $session_id_sanitized);
4278 - $preserved_as_deleted_leads++;
4279 - }
4280 - } else {
4281 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
4282 - delete_option('mxchat_email_' . $session_id_sanitized);
4283 - delete_option('mxchat_name_' . $session_id_sanitized);
4284 - }
4285 -
4286 - $deleted_count++;
4287 - }
4288 -
4289 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
4290 - // chat_deleted preservation) for each affected email. Reuses the same internal
4291 - // helper as the Leads-tab Delete button for consistency.
4292 - if (!empty($emails_to_fully_wipe)) {
4293 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
4294 - }
4295 -
4296 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
4297 -
4298 - echo wp_json_encode([
4299 - 'success' => sprintf(
4300 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
4301 - $deleted_count
4302 - ),
4303 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
4304 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
4305 - ]);
743 + echo $output;
4306 744 wp_die();
4307 745 }
4308 746
4309 -/**
4310 - * Format transcript message content with markdown processing
4311 - * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
4312 - */
4313 -private function format_transcript_message($text) {
4314 - if (empty($text)) {
4315 - return '';
4316 - }
4317 747
4318 - // Normalize line endings and clean up excessive whitespace
4319 - $text = str_replace("\r\n", "\n", $text);
4320 - $text = str_replace("\r", "\n", $text);
4321 -
4322 - // Clean up existing <br> tags that may have been saved (legacy data)
4323 - // Convert <br>, <br/>, <br /> back to newlines for consistent processing
4324 - $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
4325 -
4326 - // Collapse 3+ consecutive newlines to just 2 (paragraph break)
4327 - $text = preg_replace('/\n{3,}/', "\n\n", $text);
4328 -
4329 - // Process markdown headers (# Header)
4330 - $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
4331 - $level = strlen($matches[1]);
4332 - $content = esc_html(trim($matches[2]));
4333 - return "<h{$level}>{$content}</h{$level}>";
4334 - }, $text);
4335 -
4336 - // Process code blocks with triple backticks
4337 - $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
4338 - $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
4339 - $code = esc_html($matches[2]);
4340 - return "<pre><code{$language}>{$code}</code></pre>";
4341 - }, $text);
4342 -
4343 - // Process inline code with single backticks
4344 - $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
4345 -
4346 - // Process bold text **text** or __text__
4347 - $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
4348 - $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
4349 -
4350 - // Process italic text *text* or _text_ (but not if part of URL)
4351 - $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
4352 - $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
4353 -
4354 - // Process markdown links [text](url)
4355 - $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
4356 - $link_text = esc_html($matches[1]);
4357 - $url = esc_url($matches[2]);
4358 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
4359 - }, $text);
4360 -
4361 - // Process citation-style brackets [URL]
4362 - $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
4363 - $url = esc_url($matches[1]);
4364 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
4365 - }, $text);
4366 -
4367 - // Process standalone URLs (not already in links or img src)
4368 - $text = preg_replace_callback(
4369 - '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
4370 - function($matches) {
4371 - $url = esc_url($matches[1]);
4372 - // Truncate display URL if too long
4373 - $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
4374 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
4375 - },
4376 - $text
4377 - );
4378 -
4379 - // Process mailto links
4380 - $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
4381 - $link_text = esc_html($matches[1]);
4382 - $mailto = esc_url($matches[2]);
4383 - return "<a href=\"{$mailto}\">{$link_text}</a>";
4384 - }, $text);
4385 -
4386 - // Convert paragraphs: split by double newlines, wrap in <p> tags
4387 - // This creates proper paragraph structure instead of excessive <br> tags
4388 - $paragraphs = preg_split('/\n\n+/', $text);
4389 -
4390 - // Filter out empty paragraphs but preserve content like "0"
4391 - $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
4392 - return $p !== '';
4393 - }));
4394 -
4395 - if (empty($paragraphs)) {
4396 - // No content after filtering
4397 - return '';
4398 - } elseif (count($paragraphs) > 1) {
4399 - // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
4400 - $formatted_paragraphs = array_map(function($p) {
4401 - return nl2br($p);
4402 - }, $paragraphs);
4403 - $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4404 - } else {
4405 - // Single paragraph - just convert newlines to <br>
4406 - $text = nl2br($paragraphs[0]);
4407 - }
4408 -
4409 - return $text;
4410 -}
4411 -
4412 -/**
4413 - * AJAX handler to fetch RAG context for a specific message
4414 - * Used by the transcript viewer to show retrieved documents
4415 - */
4416 -public function mxchat_get_rag_context() {
4417 - // Check permissions
4418 - if (!current_user_can('manage_options')) {
4419 - wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4420 - wp_die();
4421 - }
4422 -
4423 - // Validate message ID
4424 - if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4425 - wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4426 - wp_die();
4427 - }
4428 -
4429 - $message_id = absint($_POST['message_id']);
4430 -
4431 - global $wpdb;
4432 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4433 -
4434 - // Fetch the RAG context for this message
4435 - $result = $wpdb->get_row($wpdb->prepare(
4436 - "SELECT rag_context FROM {$table_name} WHERE id = %d",
4437 - $message_id
4438 - ));
4439 -
4440 - if (!$result || empty($result->rag_context)) {
4441 - wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4442 - wp_die();
4443 - }
4444 -
4445 - // Decode the JSON data
4446 - $rag_context = json_decode($result->rag_context, true);
4447 -
4448 - if (json_last_error() !== JSON_ERROR_NONE) {
4449 - wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4450 - wp_die();
4451 - }
4452 -
4453 - wp_send_json_success($rag_context);
4454 - wp_die();
4455 -}
4456 -
4457 -public function display_admin_notices() {
4458 - // Check if we're on a MXChat admin page
4459 - $screen = get_current_screen();
4460 - if (!$screen || strpos($screen->base, 'mxchat') === false) {
4461 - return;
4462 - }
4463 -
4464 - $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4465 -
4466 - // Check for error notices
4467 - $error_notice = get_transient('mxchat_admin_notice_error');
4468 - if ($error_notice) {
4469 - echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4470 - delete_transient('mxchat_admin_notice_error');
4471 - }
4472 -
4473 - // Check for success notices
4474 - $success_notice = get_transient('mxchat_admin_notice_success');
4475 - if ($success_notice) {
4476 - echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4477 - delete_transient('mxchat_admin_notice_success');
4478 - }
4479 -
4480 - // Check for info notices
4481 - $info_notice = get_transient('mxchat_admin_notice_info');
4482 - if ($info_notice) {
4483 - echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4484 - delete_transient('mxchat_admin_notice_info');
4485 - }
4486 -}
4487 -
4488 -
4489 748 public function mxchat_create_activation_page() {
4490 - // Include the new Pro & Extensions page template
4491 - require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
749 + $license_status = get_option('mxchat_license_status', 'inactive');
750 + $license_error = get_option('mxchat_license_error', '');
4492 751
4493 - // Get addons configuration from the MxChat_Addons class
4494 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4495 - $addons_instance = new MxChat_Addons();
4496 - $addons_config = $addons_instance->get_addons_config();
4497 -
4498 - // Render the consolidated Pro & Extensions page
4499 - mxchat_render_pro_page($this, $addons_config);
4500 -}
4501 -
4502 -/**
4503 - * Check if current activation is linked to a domain
4504 - * This checks YOUR website's database, not the user's local database
4505 - */
4506 -public function is_current_activation_linked($domain) {
4507 - $license_key = get_option('mxchat_activation_key');
4508 - $email = get_option('mxchat_pro_email');
4509 -
4510 - if (empty($license_key) || empty($email)) {
4511 - return false;
4512 - }
4513 -
4514 - // Check with YOUR website's API
4515 - $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4516 - 'body' => array(
4517 - 'license_key' => $license_key,
4518 - 'email' => $email,
4519 - 'domain' => $domain
4520 - ),
4521 - 'timeout' => 10,
4522 - 'sslverify' => false
4523 - ));
4524 -
4525 - if (is_wp_error($response)) {
4526 - return false;
4527 - }
4528 -
4529 - $body = json_decode(wp_remote_retrieve_body($response), true);
4530 - return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
4531 -}
4532 -
4533 -
4534 -public function mxchat_actions_page_html() {
4535 - if (!current_user_can('manage_options')) {
4536 - return;
4537 - }
4538 -
4539 - global $wpdb;
4540 - $table_name = $wpdb->prefix . 'mxchat_intents';
4541 -
4542 - // Get stats for dashboard
4543 - $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4544 - $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4545 - $disabled_actions = $total_actions - $enabled_actions;
4546 -
4547 - // Get unique action types count
4548 - $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
4549 -
4550 - // Get action type distribution
4551 - $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");
4552 - $available_callbacks = $this->mxchat_get_available_callbacks();
4553 - $callback_groups = $this->mxchat_get_available_callbacks(true, true);
4554 -
4555 - $action_type_distribution = array();
4556 - foreach ($type_distribution_raw as $row) {
4557 - $label = isset($available_callbacks[$row->callback_function]['label'])
4558 - ? $available_callbacks[$row->callback_function]['label']
4559 - : $row->callback_function;
4560 - $action_type_distribution[$label] = $row->count;
4561 - }
4562 -
4563 - // Native function-calling (AI Tools) data — plan-mxchat-20260617-a41dee.
4564 - // The AI Tools checklist reads from MxChat_Tool_Registry, the SAME single
4565 - // source the chat-time function-calling loop reads, so the two never drift.
4566 - if (!class_exists('MxChat_Tool_Registry')) {
4567 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-tool-registry.php';
4568 - }
4569 - if (!class_exists('MxChat_Model_Catalog')) {
4570 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
4571 - }
4572 - $fc_options = get_option('mxchat_options', array());
4573 - $fc_current_model = isset($fc_options['model']) ? $fc_options['model'] : 'gpt-5.6-sol';
4574 - $fc_model_capable = class_exists('MxChat_Model_Catalog')
4575 - ? MxChat_Model_Catalog::supports_tools($fc_current_model) : true;
4576 - $active_tab = (isset($_GET['tab']) && $_GET['tab'] === 'ai-tools') ? 'ai-tools' : 'dashboard';
4577 -
4578 - // Enrich each AI Tool with the dashicon its callback already uses on the
4579 - // Trigger Phrases "Choose what it does" grid, so the AI Tools cards/modal
4580 - // share the same iconography (plan 8bbf98 part 4). View-layer only — the
4581 - // registry's model-facing data is untouched. Default admin-generic.
4582 - $fc_tools = MxChat_Tool_Registry::available_tools();
4583 - foreach ($fc_tools as &$fc_tool_ref) {
4584 - $fc_cb_ref = $fc_tool_ref['callback'];
4585 - $fc_tool_ref['icon'] = isset($available_callbacks[$fc_cb_ref]['icon'])
4586 - ? $available_callbacks[$fc_cb_ref]['icon']
4587 - : 'admin-generic';
4588 - }
4589 - unset($fc_tool_ref);
4590 -
4591 - // Count of ACTIVE tools — drives the AI Tools sidebar nav badge, mirroring
4592 - // $total_actions for Trigger Phrases. A tool in the list = active (plan
4593 - // d450a7), so the badge shows the same number the list pane shows (plan 5f7409).
4594 - $total_tools = count(array_filter($fc_tools, function ($t) {
4595 - return !empty($t['enabled']);
4596 - }));
4597 -
4598 - // Brave-key dependency check (plan 183856): Web Search + Image Search run on
4599 - // the Brave Search API. If either is enabled as a tool but no brave_api_key is
4600 - // configured, surface a graceful "key not set" notice so the admin isn't met
4601 - // with a silently no-firing tool.
4602 - $fc_brave_missing = false;
4603 - $brave_key = isset($fc_options['brave_api_key']) ? trim($fc_options['brave_api_key']) : '';
4604 - if ($brave_key === '') {
4605 - foreach ($fc_tools as $fc_t) {
4606 - if (!empty($fc_t['enabled']) && isset($fc_t['requires_key']) && $fc_t['requires_key'] === 'brave_api_key') {
4607 - $fc_brave_missing = true;
4608 - break;
4609 - }
4610 - }
4611 - }
4612 -
4613 - // Prepare page data
4614 - $page_data = array(
4615 - 'total_actions' => $total_actions,
4616 - 'enabled_actions' => $enabled_actions,
4617 - 'disabled_actions' => $disabled_actions,
4618 - 'action_types_count' => $action_types_count,
4619 - 'action_type_distribution' => $action_type_distribution,
4620 - 'available_callbacks' => $available_callbacks,
4621 - 'callback_groups' => $callback_groups,
4622 - // AI Tools section
4623 - 'active_tab' => $active_tab,
4624 - 'fc_enabled' => MxChat_Tool_Registry::is_enabled(),
4625 - 'total_tools' => $total_tools,
4626 - 'fc_tools' => $fc_tools,
4627 - 'fc_current_model' => $fc_current_model,
4628 - 'fc_model_capable' => $fc_model_capable,
4629 - 'fc_brave_missing' => $fc_brave_missing,
4630 - 'fc_saved' => isset($_GET['mxchat_fc_saved']),
4631 - );
4632 -
4633 - // Include and render the new template
4634 - require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4635 - mxchat_render_actions_page($this, $page_data);
4636 -}
4637 -
4638 -/**
4639 - * LEGACY HTML - Preserved below for reference, to be removed in future update
4640 - */
4641 -function mxchat_actions_page_legacy_html() {
4642 - // This function is deprecated and no longer used
4643 - // The new template is in includes/admin-actions-page.php
4644 752 ?>
4645 - <div class="wrap mxchat-wrapper">
4646 - <!-- Hero Section -->
4647 - <div class="mxchat-hero">
4648 - <h1 class="mxchat-main-title">
4649 - <span class="mxchat-gradient-text">Actions</span> Manager
4650 - </h1>
4651 - <p class="mxchat-hero-subtitle">
4652 - <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
4653 - </p>
4654 - </div>
4655 -
4656 - <!-- Actions Header with Search and Filter -->
4657 - <div class="mxchat-actions-header">
4658 - <div class="mxchat-actions-filters">
4659 - <form method="get" class="mxchat-search-form">
4660 - <input type="hidden" name="page" value="mxchat-actions">
4661 - <div class="mxchat-search-group">
4662 - <span class="dashicons dashicons-search"></span>
4663 - <input type="text" name="s" class="mxchat-search-input"
4664 - placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
4665 - value="<?php echo esc_attr($search_term); ?>">
4666 - </div>
4667 - <select name="callback_filter" class="mxchat-action-filter">
4668 - <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
4669 - <?php foreach ($available_callbacks as $function => $callback_data) :
4670 - $label = $callback_data['label']; ?>
4671 - <option value="<?php echo esc_attr($function); ?>"
4672 - <?php selected($callback_filter, $function); ?>>
4673 - <?php echo esc_html($label); ?>
4674 - </option>
4675 - <?php endforeach; ?>
4676 - </select>
4677 - <button type="submit" class="mxchat-button-secondary">
4678 - <?php esc_html_e('Filter', 'mxchat'); ?>
4679 - </button>
4680 - </form>
753 + <div class="wrap mxchat-admin">
754 + <h2>MxChat Pro: Activation</h2>
755 + <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
756 + <div class="error notice">
757 + <p><?php echo esc_html($license_error); ?></p>
4681 758 </div>
4682 - <div class="mxchat-actions-controls">
4683 - <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
4684 - <span class="dashicons dashicons-plus-alt"></span>
4685 - <?php esc_html_e('Add New Action', 'mxchat'); ?>
4686 - </button>
4687 - </div>
4688 - </div>
4689 -
4690 - <!-- Actions Grid Layout - All actions in a single grid -->
4691 - <div class="mxchat-actions-grid">
4692 - <div class="mxchat-cards-container">
4693 - <?php if (!empty($actions)) : ?>
4694 - <?php foreach ($actions as $action) :
4695 - $callback_function = $action->callback_function;
4696 - $callback_label = isset($available_callbacks[$callback_function]['label'])
4697 - ? $available_callbacks[$callback_function]['label']
4698 - : $callback_function;
4699 - $threshold_value = isset($action->similarity_threshold)
4700 - ? round($action->similarity_threshold * 100)
4701 - : 85;
4702 -
4703 - // Check if this is a form action
4704 - $is_form_action = strpos($action->intent_label, 'Form ') === 0;
4705 -
4706 - // Get action status (enabled/disabled) - default to true if column doesn't exist
4707 - $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
4708 -
4709 - // Get enabled bots for display
4710 - $enabled_bots = [];
4711 - if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
4712 - $enabled_bots = json_decode($action->enabled_bots, true);
4713 - if (!is_array($enabled_bots)) {
4714 - $enabled_bots = ['default'];
4715 - }
4716 - } else {
4717 - $enabled_bots = ['default']; // Backward compatibility
4718 - }
4719 - ?>
4720 - <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
4721 - <div class="mxchat-card-header">
4722 - <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
4723 - <div class="mxchat-card-toggle">
4724 - <label class="mxchat-switch">
4725 - <input type="checkbox" class="mxchat-action-toggle"
4726 - data-action-id="<?php echo esc_attr($action->id); ?>"
4727 - <?php checked($is_enabled); ?>>
4728 - <span class="mxchat-slider round"></span>
4729 - </label>
4730 - </div>
4731 - </div>
4732 -
4733 - <div class="mxchat-card-body">
4734 - <div class="mxchat-card-description">
4735 - <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
4736 - <?php echo esc_html($callback_label); ?>
4737 - </div>
4738 -
4739 - <div class="mxchat-card-phrases">
4740 - <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
4741 - <div class="mxchat-phrases-preview">
4742 - <?php
4743 - // Check if the helper function exists, otherwise use a simple substring
4744 - if (method_exists($this, 'get_trimmed_phrases')) {
4745 - echo esc_html($this->get_trimmed_phrases($action->phrases));
4746 - } else {
4747 - echo esc_html(strlen($action->phrases) > 100 ?
4748 - substr($action->phrases, 0, 97) . '...' :
4749 - $action->phrases);
4750 - }
4751 - ?>
4752 - </div>
4753 - </div>
4754 -
4755 - <div class="mxchat-threshold-control">
4756 - <div class="mxchat-threshold-label">
4757 - <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
4758 - <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
4759 - </div>
4760 - </div>
4761 -
4762 - <!-- Bot Availability Display (Read-only) -->
4763 - <div class="mxchat-card-bots">
4764 - <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
4765 - <div class="mxchat-bot-badges">
4766 - <?php
4767 - foreach ($enabled_bots as $bot_id) {
4768 - if ($bot_id === 'default') {
4769 - echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
4770 - } else {
4771 - // Try to get bot name from multi-bot manager
4772 - if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
4773 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4774 - $available_bots = $multi_bot_manager->get_available_bots();
4775 - $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
4776 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
4777 - } else {
4778 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
4779 - }
4780 - }
4781 - }
4782 - ?>
4783 - </div>
4784 - </div>
4785 - </div>
4786 -
4787 - <div class="mxchat-card-footer">
4788 - <?php
4789 - // Check if it's a form action
4790 - $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
4791 -
4792 - // Check if it's a recommendation flow action
4793 - $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
4794 -
4795 - if ($is_form_action) {
4796 - $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
4797 - ?>
4798 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
4799 - class="mxchat-button-primary">
4800 - <span class="dashicons dashicons-feedback"></span>
4801 - <?php esc_html_e('Edit Form', 'mxchat'); ?>
4802 - </a>
4803 - <?php } elseif ($is_flow_action) {
4804 - ?>
4805 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
4806 - class="mxchat-button-primary">
4807 - <span class="dashicons dashicons-list-view"></span>
4808 - <?php esc_html_e('Manage Flows', 'mxchat'); ?>
4809 - </a>
4810 - <?php } else { ?>
4811 - <button type="button"
4812 - class="mxchat-button-secondary mxchat-edit-button"
4813 - data-action-id="<?php echo esc_attr($action->id); ?>"
4814 - data-phrases="<?php echo esc_attr($action->phrases); ?>"
4815 - data-label="<?php echo esc_attr($action->intent_label); ?>"
4816 - data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
4817 - data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
4818 - data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
4819 - <span class="dashicons dashicons-edit"></span>
4820 - <?php esc_html_e('Edit', 'mxchat'); ?>
4821 - </button>
4822 - <form method="post"
4823 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
4824 - class="mxchat-delete-form"
4825 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
4826 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
4827 - <input type="hidden" name="action" value="mxchat_delete_intent">
4828 - <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
4829 - <button type="submit" class="mxchat-button-text mxchat-delete-button">
4830 - <span class="dashicons dashicons-trash"></span>
4831 - <?php esc_html_e('Delete', 'mxchat'); ?>
4832 - </button>
4833 - </form>
4834 - <?php } ?>
4835 - </div>
4836 - </div>
4837 - <?php endforeach; ?>
4838 - <?php else : ?>
4839 - <!-- If no actions found -->
4840 - <div class="mxchat-no-actions">
4841 - <div class="mxchat-empty-state">
4842 - <span class="dashicons dashicons-format-chat"></span>
4843 - <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4844 - <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4845 - <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4846 - <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4847 - </button>
4848 - </div>
4849 - </div>
4850 - <?php endif; ?>
4851 - </div>
4852 - </div>
4853 -
4854 - <?php if ($total_pages > 1) : ?>
4855 - <div class="mxchat-pagination">
4856 - <?php
4857 - echo paginate_links(array(
4858 - 'base' => add_query_arg('paged', '%#%'),
4859 - 'format' => '',
4860 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4861 - 'next_text' => __('Next &raquo;', 'mxchat'),
4862 - 'total' => $total_pages,
4863 - 'current' => $page
4864 - ));
4865 - ?>
4866 - </div>
4867 759 <?php endif; ?>
4868 -
4869 -<!-- Add/Edit Action Modal with Step-Based Approach -->
4870 -<!-- Complete Modal HTML with Defined Groups Variable -->
4871 -<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
4872 - <div class="mxchat-modal-content">
4873 - <span class="mxchat-modal-close">&times;</span>
4874 -
4875 - <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4876 - <!-- Dynamic nonce field -->
4877 - <div id="action-nonce-container">
4878 - <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
4879 - </div>
4880 - <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4881 - <input type="hidden" name="intent_id" id="edit_action_id" value="">
4882 - <input type="hidden" name="callback_function" id="callback_function" value="">
4883 -
4884 - <!-- Step 1: Action Type Selection -->
4885 - <div id="mxchat-action-step-1" class="mxchat-action-step active">
4886 - <div class="mxchat-step-indicator">
4887 - <div class="mxchat-step-number">1</div>
4888 - <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4889 - </div>
4890 -
4891 - <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4892 - <div class="mxchat-action-type-search">
4893 - <span class="dashicons dashicons-search"></span>
4894 - <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4895 - </div>
4896 -
4897 - <?php
4898 - // Get the callbacks - IMPORTANT: Define the $groups variable here
4899 - $groups = $this->mxchat_get_available_callbacks(true, true);
4900 - ?>
4901 -
4902 - <div class="mxchat-action-type-categories">
4903 - <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
4904 - <?php
4905 - // Get unique categories from the defined groups
4906 - foreach ($groups as $group_label => $group_callbacks) :
4907 - $category_slug = sanitize_title($group_label);
4908 - ?>
4909 - <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4910 - <?php endforeach; ?>
4911 - </div>
4912 -
4913 - <div class="mxchat-action-types-grid">
4914 - <?php
4915 - // Generate action cards from available callbacks
4916 - foreach ($groups as $group_label => $group_callbacks) :
4917 - $category_slug = sanitize_title($group_label);
4918 -
4919 - foreach ($group_callbacks as $function => $data) :
4920 - $label = $data['label'];
4921 - $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4922 - $description = isset($data['description']) ? $data['description'] : '';
4923 - $is_addon = isset($data['addon']) && $data['addon'] !== false;
4924 - $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4925 - $is_installed = isset($data['installed']) ? $data['installed'] : true;
4926 - $is_promo = !empty($data['addon_promo']) && !$is_installed;
4927 -
4928 - // Determine card status and styling
4929 - $card_class = 'mxchat-action-type-card';
4930 - $icon_class = 'mxchat-action-type-icon';
4931 - $status_badge = '';
4932 -
4933 - if ($is_promo) {
4934 - // Promotional card — not selectable, just informational
4935 - $card_class .= ' not-installed mxchat-promo-card';
4936 - $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4937 - } elseif ($is_addon && !$is_installed) {
4938 - // Add-on not installed
4939 - $card_class .= ' not-installed';
4940 - $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4941 - }
4942 -
4943 - // Default description if none provided
4944 - if (empty($description)) {
4945 - $description = sprintf(
4946 - esc_html__('Use the %s action in your chatbot', 'mxchat'),
4947 - $label
4948 - );
4949 - }
4950 - ?>
4951 - <div class="<?php echo esc_attr($card_class); ?>"
4952 - data-category="<?php echo esc_attr($category_slug); ?>"
4953 - <?php if (!$is_promo) : ?>
4954 - data-value="<?php echo esc_attr($function); ?>"
4955 - data-label="<?php echo esc_attr($label); ?>"
4956 - <?php endif; ?>
4957 - data-pro="false"
4958 - data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4959 - data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
4960 - <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
4961 - <div class="<?php echo esc_attr($icon_class); ?>">
4962 - <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4963 - </div>
4964 - <div class="mxchat-action-type-info">
4965 - <h4><?php echo esc_html($label); ?></h4>
4966 - <p><?php echo esc_html($description); ?></p>
4967 - <?php if (!empty($status_badge)) : ?>
4968 - <?php echo $status_badge; ?>
4969 - <?php endif; ?>
4970 -
4971 - <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
4972 - <div class="mxchat-addon-info">
4973 - <?php echo esc_html(sprintf(
4974 - __('Requires %s', 'mxchat'),
4975 - $addon_name
4976 - )); ?>
4977 - — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
4978 - </div>
4979 - <?php endif; ?>
4980 - </div>
4981 - </div>
4982 - <?php endforeach;
4983 - endforeach; ?>
4984 - </div>
4985 - </div>
4986 -
4987 - <div class="mxchat-modal-actions">
4988 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4989 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4990 - </button>
4991 - </div>
4992 - </div>
4993 -
4994 - <!-- Step 2: Action Configuration -->
4995 - <div id="mxchat-action-step-2" class="mxchat-action-step">
4996 - <div class="mxchat-step-indicator">
4997 - <div class="mxchat-step-number">2</div>
4998 - <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4999 - </div>
5000 -
5001 - <div class="mxchat-selected-action">
5002 - <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
5003 - <span class="dashicons dashicons-arrow-left-alt"></span>
5004 - <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
5005 - </button>
5006 - <div class="mxchat-selected-action-info">
5007 - <div id="selected-action-icon" class="mxchat-action-type-icon">
5008 - <span class="dashicons dashicons-admin-generic"></span>
5009 - </div>
5010 - <div class="mxchat-selected-action-details">
5011 - <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
5012 - <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
5013 - </div>
5014 - </div>
5015 - </div>
5016 -
5017 - <div class="mxchat-form-group">
5018 - <label for="intent_label">
5019 - <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
5020 - </label>
5021 - <input name="intent_label" type="text" id="intent_label" required
5022 - class="mxchat-intent-input"
5023 - placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
5024 - </div>
5025 -
5026 - <div class="mxchat-form-group">
5027 - <label for="phrases">
5028 - <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
5029 - </label>
5030 - <textarea name="phrases" id="action_phrases" rows="5" required
5031 - class="mxchat-intent-textarea"
5032 - placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
5033 - </div>
5034 -
5035 - <div class="mxchat-form-group">
5036 - <label for="similarity_threshold">
5037 - <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
5038 - <span class="mxchat-threshold-value-display">85%</span>
5039 - </label>
5040 - <div class="mxchat-slider-group modal-slider">
5041 - <input type="range"
5042 - name="similarity_threshold"
5043 - id="similarity_threshold"
5044 - min="10"
5045 - max="95"
5046 - value="85"
5047 - class="mxchat-intent-slider"
5048 - oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
5049 - </div>
5050 - <div class="mxchat-threshold-hint">
5051 - <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
5052 - </div>
5053 - </div>
5054 -
5055 - <!-- Bot Selection Section -->
5056 - <div class="mxchat-form-group">
5057 - <label for="enabled_bots">
5058 - <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
5059 - </label>
5060 - <div class="mxchat-bot-selector">
5061 - <div class="mxchat-bot-option">
5062 - <label class="mxchat-checkbox-label">
5063 - <input type="checkbox"
5064 - name="enabled_bots[]"
5065 - value="default"
5066 - id="bot_default"
5067 - checked="checked">
5068 - <span class="mxchat-checkmark"></span>
5069 - <?php esc_html_e('Default Bot', 'mxchat'); ?>
5070 - </label>
5071 - </div>
5072 -
5073 - <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
5074 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
5075 - $available_bots = $multi_bot_manager->get_available_bots();
5076 -
5077 - foreach ($available_bots as $bot_id => $bot_name) :
5078 - if ($bot_id === 'default') continue; // Skip default, already shown above
5079 - ?>
5080 - <div class="mxchat-bot-option">
5081 - <label class="mxchat-checkbox-label">
5082 - <input type="checkbox"
5083 - name="enabled_bots[]"
5084 - value="<?php echo esc_attr($bot_id); ?>"
5085 - id="bot_<?php echo esc_attr($bot_id); ?>">
5086 - <span class="mxchat-checkmark"></span>
5087 - <?php echo esc_html($bot_name); ?>
5088 - </label>
5089 - </div>
5090 - <?php
5091 - endforeach;
5092 - endif; ?>
5093 - </div>
5094 - </div>
5095 -
5096 - <div class="mxchat-modal-actions">
5097 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
5098 - <?php esc_html_e('Cancel', 'mxchat'); ?>
5099 - </button>
5100 - <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
5101 - <?php esc_html_e('Save Action', 'mxchat'); ?>
5102 - </button>
5103 - </div>
5104 - </div>
760 + <form id="mxchat-activation-form">
761 + <table class="form-table">
762 + <tr valign="top">
763 + <th scope="row">Email Address</th>
764 + <td>
765 + <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" />
766 + </td>
767 + </tr>
768 + <tr valign="top">
769 + <th scope="row">Activation Key</th>
770 + <td>
771 + <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" />
772 + </td>
773 + </tr>
774 + </table>
775 + <?php if ($license_status !== 'active'): ?>
776 + <?php submit_button('Activate License', 'primary', 'activate_license'); ?>
777 + <?php else: ?>
778 + <h3>MxChat Pro</h3>
779 + <?php endif; ?>
5105 780 </form>
781 + <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
5106 782 </div>
5107 -</div>
5108 -
5109 -<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
5110 - <div class="mxchat-action-loading-spinner"></div>
5111 - <div class="mxchat-action-loading-text">
5112 - <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
5113 - </div>
5114 -</div>
5115 - </div><!-- .mxchat-wrapper -->
5116 783 <?php
5117 784 }
5118 -private function get_trimmed_phrases($phrases, $max_length = 100) {
5119 - if (strlen($phrases) <= $max_length) {
5120 - return $phrases;
5121 - }
5122 785
5123 - $trimmed = substr($phrases, 0, $max_length);
5124 - $last_comma = strrpos($trimmed, ',');
5125 786
5126 - if ($last_comma !== false) {
5127 - $trimmed = substr($trimmed, 0, $last_comma);
5128 - }
5129 787
5130 - return $trimmed . '...';
5131 -}
5132 -public function mxchat_add_enabled_column_to_intents() {
5133 - global $wpdb;
5134 - $table_name = $wpdb->prefix . 'mxchat_intents';
5135 -
5136 - // Check if the column already exists
5137 - $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
5138 -
5139 - if (empty($columns)) {
5140 - // Add the column with default value of 1 (enabled)
5141 - $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
5142 - }
5143 -}
5144 -
5145 -public function mxchat_handle_delete_intent() {
5146 - if ( ! current_user_can( 'manage_options' ) ) {
5147 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
5148 - }
5149 -
5150 - check_admin_referer('mxchat_delete_intent_nonce');
5151 -
5152 - if (isset($_POST['intent_id'])) {
5153 - global $wpdb;
5154 - $table_name = $wpdb->prefix . 'mxchat_intents';
5155 - $intent_id = intval($_POST['intent_id']);
5156 -
5157 - $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5158 - }
5159 -
5160 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5161 - exit;
5162 -}
5163 -public function mxchat_handle_edit_intent() {
5164 - // Security checks (nonce and permissions)
5165 - if (!current_user_can('manage_options')) {
5166 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5167 - }
5168 - check_admin_referer('mxchat_edit_intent');
5169 -
5170 - // Get POST data
5171 - $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
5172 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5173 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5174 - $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
5175 - $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
5176 -
5177 - // Handle enabled_bots
5178 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5179 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5180 -
5181 - // Ensure default is always included for backward compatibility
5182 - if (!in_array('default', $enabled_bots)) {
5183 - $enabled_bots[] = 'default';
5184 - }
5185 -
5186 - $enabled_bots_json = json_encode($enabled_bots);
5187 -
5188 - // Validate inputs
5189 - if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
5190 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5191 - return;
5192 - }
5193 -
5194 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5195 - if (empty($phrases_array)) {
5196 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5197 - return;
5198 - }
5199 -
5200 - // Generate embeddings with improved error handling
5201 - $vectors = [];
5202 - $failed_phrases = [];
5203 -
5204 - foreach ($phrases_array as $phrase) {
5205 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5206 - if (is_array($embedding_vector)) {
5207 - $vectors[] = $embedding_vector;
5208 - } else {
5209 - $failed_phrases[] = $phrase;
5210 - }
5211 - }
5212 -
5213 - if (!empty($failed_phrases)) {
5214 - $this->handle_embedding_error(
5215 - sprintf(
5216 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5217 - implode(', ', $failed_phrases)
5218 - )
5219 - );
5220 - return;
5221 - }
5222 -
5223 - if (empty($vectors)) {
5224 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5225 - return;
5226 - }
5227 -
5228 - $combined_vector = $this->mxchat_average_vectors($vectors);
5229 - $serialized_vector = maybe_serialize($combined_vector);
5230 -
5231 - // Update the database
5232 - global $wpdb;
5233 - $table_name = $wpdb->prefix . 'mxchat_intents';
5234 -
5235 - $result = $wpdb->update(
5236 - $table_name,
5237 - array(
5238 - 'intent_label' => $intent_label,
5239 - 'phrases' => implode(', ', $phrases_array),
5240 - 'embedding_vector' => $serialized_vector,
5241 - 'similarity_threshold' => $similarity_threshold,
5242 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
5243 - ),
5244 - array('id' => $intent_id),
5245 - array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
5246 - array('%d') // Where format: integer
5247 - );
5248 -
5249 - if (false === $result) {
5250 - $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
5251 - return;
5252 - }
5253 -
5254 - // Set success message and redirect
5255 - set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
5256 -
5257 - $redirect_url = add_query_arg(
5258 - array(
5259 - 'page' => 'mxchat-actions'
5260 - ),
5261 - admin_url('admin.php')
5262 - );
5263 - wp_safe_redirect($redirect_url);
5264 - exit;
5265 -}
5266 -public function mxchat_handle_add_intent() {
5267 - if (!current_user_can('manage_options')) {
5268 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5269 - }
5270 - check_admin_referer('mxchat_add_intent_nonce');
5271 - global $wpdb;
5272 - $table_name = $wpdb->prefix . 'mxchat_intents';
5273 -
5274 - // Sanitize and get form data
5275 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5276 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5277 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5278 -
5279 - // Get similarity threshold from form (convert percentage to decimal)
5280 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5281 -
5282 - // Handle enabled_bots
5283 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5284 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5285 -
5286 - // Ensure default is always included for backward compatibility with existing actions
5287 - if (!in_array('default', $enabled_bots)) {
5288 - $enabled_bots[] = 'default';
5289 - }
5290 -
5291 - $enabled_bots_json = json_encode($enabled_bots);
5292 -
5293 - // Validate required fields
5294 - if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
5295 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5296 - return;
5297 - }
5298 -
5299 - // Validate callback function
5300 - $available_callbacks = $this->mxchat_get_available_callbacks();
5301 - if (!array_key_exists($callback_function, $available_callbacks)) {
5302 - $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
5303 - return;
5304 - }
5305 -
5306 - // Check if this is an add-on promotional placeholder (not a real action)
5307 - if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
5308 - $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
5309 - $this->handle_embedding_error(sprintf(
5310 - __('This action requires the %s to be installed and activated.', 'mxchat'),
5311 - $addon_name
5312 - ));
5313 - return;
5314 - }
5315 -
5316 - // Process phrases
5317 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5318 - if (empty($phrases_array)) {
5319 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5320 - return;
5321 - }
5322 -
5323 - // Generate embeddings with improved error handling
5324 - $vectors = [];
5325 - $failed_phrases = [];
5326 - foreach ($phrases_array as $phrase) {
5327 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5328 - if (is_array($embedding_vector)) {
5329 - $vectors[] = $embedding_vector;
5330 - } else {
5331 - $failed_phrases[] = $phrase;
5332 - }
5333 - }
5334 -
5335 - // Check for embedding failures
5336 - if (!empty($failed_phrases)) {
5337 - $this->handle_embedding_error(
5338 - sprintf(
5339 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5340 - implode(', ', $failed_phrases)
5341 - )
5342 - );
5343 - return;
5344 - }
5345 -
5346 - if (empty($vectors)) {
5347 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5348 - return;
5349 - }
5350 -
5351 - // Create combined vector and insert into database
5352 - $combined_vector = $this->mxchat_average_vectors($vectors);
5353 - $serialized_vector = maybe_serialize($combined_vector);
5354 -
5355 - $result = $wpdb->insert($table_name, [
5356 - 'intent_label' => $intent_label,
5357 - 'phrases' => implode(', ', $phrases_array),
5358 - 'embedding_vector' => $serialized_vector,
5359 - 'callback_function' => $callback_function,
5360 - 'similarity_threshold' => $similarity_threshold,
5361 - 'enabled_bots' => $enabled_bots_json, // NEW field
5362 - ]);
5363 -
5364 - if ($result === false) {
5365 - $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
5366 - return;
5367 - }
5368 -
5369 - // Set success message and redirect
5370 - set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
5371 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5372 - exit;
5373 -}
5374 -
5375 -
5376 -
5377 -
5378 -private function handle_embedding_error($message, $redirect = true) {
5379 - // Store the error message in the existing transient
5380 - set_transient('mxchat_admin_notice_error', $message, 60);
5381 -
5382 - if ($redirect) {
5383 - // Redirect back to the actions page
5384 - $redirect_url = add_query_arg(
5385 - array(
5386 - 'page' => 'mxchat-actions'
5387 - ),
5388 - admin_url('admin.php')
5389 - );
5390 - wp_safe_redirect($redirect_url);
5391 - exit;
5392 - }
5393 -}
5394 -
5395 -/**
5396 - * AJAX handler to fetch actions list for the new split-panel UI
5397 - */
5398 -public function mxchat_fetch_actions_list() {
5399 - check_ajax_referer('mxchat_actions_nonce', 'security');
5400 -
5401 - if (!current_user_can('manage_options')) {
5402 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5403 - }
5404 -
5405 - global $wpdb;
5406 - $table_name = $wpdb->prefix . 'mxchat_intents';
5407 -
5408 - $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
5409 - $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
5410 - $offset = ($page - 1) * $per_page;
5411 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
5412 - $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
5413 - $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
5414 -
5415 - // Build WHERE clause
5416 - $where = '1=1';
5417 - $params = array();
5418 -
5419 - if ($search) {
5420 - $search_like = '%' . $wpdb->esc_like($search) . '%';
5421 - $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
5422 - $params[] = $search_like;
5423 - $params[] = $search_like;
5424 - }
5425 -
5426 - if ($callback_filter) {
5427 - $where .= ' AND callback_function = %s';
5428 - $params[] = $callback_filter;
5429 - }
5430 -
5431 - // Get total count
5432 - $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
5433 - if (!empty($params)) {
5434 - $count_query = $wpdb->prepare($count_query, $params);
5435 - }
5436 - $total_actions = $wpdb->get_var($count_query);
5437 -
5438 - // Get actions
5439 - $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
5440 - $all_params = array_merge($params, array($per_page, $offset));
5441 - $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
5442 -
5443 - // Get available callbacks for labels/icons
5444 - $available_callbacks = $this->mxchat_get_available_callbacks();
5445 -
5446 - // Prefetch individual phrase counts for all fetched actions
5447 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5448 - $phrase_counts = array();
5449 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5450 - $action_ids = wp_list_pluck($actions, 'id');
5451 - if (!empty($action_ids)) {
5452 - $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5453 - $count_results = $wpdb->get_results($wpdb->prepare(
5454 - "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
5455 - $action_ids
5456 - ));
5457 - foreach ($count_results as $row) {
5458 - $phrase_counts[$row->intent_id] = intval($row->cnt);
5459 - }
5460 - }
5461 - }
5462 -
5463 - // Format actions for response
5464 - $formatted_actions = array();
5465 - foreach ($actions as $action) {
5466 - $callback_data = isset($available_callbacks[$action->callback_function])
5467 - ? $available_callbacks[$action->callback_function]
5468 - : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5469 -
5470 - $enabled_bots = json_decode($action->enabled_bots, true);
5471 - if (!is_array($enabled_bots)) {
5472 - $enabled_bots = array('default');
5473 - }
5474 -
5475 - $formatted_actions[] = array(
5476 - 'id' => intval($action->id),
5477 - 'label' => $action->intent_label,
5478 - 'phrases' => $action->phrases,
5479 - 'callback_function' => $action->callback_function,
5480 - 'callback_label' => $callback_data['label'],
5481 - 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5482 - 'threshold' => round($action->similarity_threshold * 100),
5483 - 'enabled' => (bool) $action->enabled,
5484 - 'enabled_bots' => $enabled_bots,
5485 - 'has_legacy_vector' => !empty($action->embedding_vector),
5486 - 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5487 - );
5488 - }
5489 -
5490 - $total_pages = ceil($total_actions / $per_page);
5491 - $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5492 - $showing_end = min($offset + $per_page, $total_actions);
5493 -
5494 - wp_send_json_success(array(
5495 - 'actions' => $formatted_actions,
5496 - 'page' => $page,
5497 - 'per_page' => $per_page,
5498 - 'total_actions' => intval($total_actions),
5499 - 'total_pages' => $total_pages,
5500 - 'showing_start' => $showing_start,
5501 - 'showing_end' => $showing_end,
5502 - ));
5503 -}
5504 -
5505 -/**
5506 - * AJAX handler to toggle action enabled status
5507 - */
5508 -public function mxchat_toggle_action_status() {
5509 - check_ajax_referer('mxchat_actions_nonce', 'security');
5510 -
5511 - if (!current_user_can('manage_options')) {
5512 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5513 - }
5514 -
5515 - $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5516 - $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
5517 -
5518 - if (!$action_id) {
5519 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5520 - }
5521 -
5522 - global $wpdb;
5523 - $table_name = $wpdb->prefix . 'mxchat_intents';
5524 -
5525 - $result = $wpdb->update(
5526 - $table_name,
5527 - array('enabled' => $enabled ? 1 : 0),
5528 - array('id' => $action_id),
5529 - array('%d'),
5530 - array('%d')
5531 - );
5532 -
5533 - if ($result === false) {
5534 - wp_send_json_error(__('Failed to update action status', 'mxchat'));
5535 - }
5536 -
5537 - wp_send_json_success(array('enabled' => (bool) $enabled));
5538 -}
5539 -
5540 -/**
5541 - * AJAX handler to bulk delete actions
5542 - */
5543 -public function mxchat_bulk_delete_actions() {
5544 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5545 -
5546 - if (!current_user_can('manage_options')) {
5547 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5548 - }
5549 -
5550 - $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5551 -
5552 - if (empty($action_ids)) {
5553 - wp_send_json_error(__('No actions selected', 'mxchat'));
5554 - }
5555 -
5556 - global $wpdb;
5557 - $table_name = $wpdb->prefix . 'mxchat_intents';
5558 -
5559 - $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5560 - $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5561 - $result = $wpdb->query($query);
5562 -
5563 - if ($result === false) {
5564 - wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5565 - }
5566 -
5567 - // Also delete individual phrases for these intents
5568 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5569 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5570 - $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5571 - }
5572 -
5573 - wp_send_json_success(array('deleted' => $result));
5574 -}
5575 -
5576 -/**
5577 - * AJAX handler to add a new intent/action
5578 - */
5579 -public function mxchat_add_intent_ajax() {
5580 - check_ajax_referer('mxchat_add_intent_nonce', 'security');
5581 -
5582 - if (!current_user_can('manage_options')) {
5583 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5584 - }
5585 -
5586 - global $wpdb;
5587 - $table_name = $wpdb->prefix . 'mxchat_intents';
5588 -
5589 - // Sanitize input
5590 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5591 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5592 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5593 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5594 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5595 -
5596 - // Validate
5597 - // Check if using new individual phrases mode or legacy mode
5598 - $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5599 - $use_individual = !empty($individual_phrases);
5600 -
5601 - // Validate required fields (phrases not required when using individual mode)
5602 - if (empty($intent_label) || empty($callback_function)) {
5603 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5604 - }
5605 - if (!$use_individual && empty($phrases_input)) {
5606 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5607 - }
5608 -
5609 - // Ensure default bot is included
5610 - if (!in_array('default', $enabled_bots)) {
5611 - $enabled_bots[] = 'default';
5612 - }
5613 - $enabled_bots_json = json_encode($enabled_bots);
5614 -
5615 - if ($use_individual) {
5616 - // New mode: individual phrases each get their own vector
5617 - // Insert the intent row with empty legacy fields
5618 - $result = $wpdb->insert(
5619 - $table_name,
5620 - array(
5621 - 'intent_label' => $intent_label,
5622 - 'phrases' => '',
5623 - 'embedding_vector' => '',
5624 - 'similarity_threshold' => $similarity_threshold,
5625 - 'callback_function' => $callback_function,
5626 - 'enabled' => 1,
5627 - 'enabled_bots' => $enabled_bots_json,
5628 - )
5629 - );
5630 -
5631 - if ($result === false) {
5632 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5633 - }
5634 -
5635 - $intent_id = $wpdb->insert_id;
5636 -
5637 - // Insert each phrase individually with its own embedding
5638 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5639 - $failed_phrases = array();
5640 - foreach ($individual_phrases as $phrase) {
5641 - $phrase = trim($phrase);
5642 - if (empty($phrase)) continue;
5643 -
5644 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5645 - if (is_wp_error($embedding_vector)) {
5646 - $failed_phrases[] = $phrase;
5647 - continue;
5648 - }
5649 -
5650 - $wpdb->insert(
5651 - $phrases_table,
5652 - array(
5653 - 'intent_id' => $intent_id,
5654 - 'phrase' => $phrase,
5655 - 'embedding_vector' => maybe_serialize($embedding_vector),
5656 - )
5657 - );
5658 - }
5659 -
5660 - $response = array('id' => $intent_id);
5661 - if (!empty($failed_phrases)) {
5662 - $response['failed_phrases'] = $failed_phrases;
5663 - }
5664 - wp_send_json_success($response);
5665 -
5666 - } else {
5667 - // Legacy mode: combine all phrases into one embedding (backwards compatible)
5668 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5669 - if (empty($phrases_array)) {
5670 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5671 - }
5672 -
5673 - // Generate embedding (combine phrases into single string for embedding)
5674 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5675 - if (is_wp_error($embedding_vector)) {
5676 - // Fallback: store without embedding
5677 - $serialized_vector = null;
5678 - } else {
5679 - $serialized_vector = maybe_serialize($embedding_vector);
5680 - }
5681 -
5682 - // Insert
5683 - $result = $wpdb->insert(
5684 - $table_name,
5685 - array(
5686 - 'intent_label' => $intent_label,
5687 - 'phrases' => implode(', ', $phrases_array),
5688 - 'embedding_vector' => $serialized_vector,
5689 - 'similarity_threshold' => $similarity_threshold,
5690 - 'callback_function' => $callback_function,
5691 - 'enabled' => 1,
5692 - 'enabled_bots' => $enabled_bots_json,
5693 - )
5694 - );
5695 -
5696 - if ($result === false) {
5697 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5698 - }
5699 -
5700 - wp_send_json_success(array('id' => $wpdb->insert_id));
5701 - }
5702 -}
5703 -
5704 -/**
5705 - * AJAX handler to edit an existing intent/action
5706 - */
5707 -public function mxchat_edit_intent_ajax() {
5708 - check_ajax_referer('mxchat_edit_intent', 'security');
5709 -
5710 - if (!current_user_can('manage_options')) {
5711 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5712 - }
5713 -
5714 - global $wpdb;
5715 - $table_name = $wpdb->prefix . 'mxchat_intents';
5716 -
5717 - // Sanitize input
5718 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5719 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5720 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5721 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5722 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5723 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5724 -
5725 - // Validate
5726 - if (!$intent_id || empty($intent_label)) {
5727 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5728 - }
5729 -
5730 - // Check if phrases are managed individually (empty phrases_input means individual mode)
5731 - $uses_individual_phrases = empty($phrases_input);
5732 -
5733 - if ($uses_individual_phrases) {
5734 - // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
5735 - $update_data = array(
5736 - 'intent_label' => $intent_label,
5737 - 'similarity_threshold' => $similarity_threshold,
5738 - 'callback_function' => $callback_function,
5739 - 'enabled_bots' => json_encode($enabled_bots),
5740 - );
5741 - } else {
5742 - // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
5743 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5744 - if (empty($phrases_array)) {
5745 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5746 - }
5747 -
5748 - // Generate new embedding (combine phrases into single string for embedding)
5749 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5750 - if (is_wp_error($embedding_vector)) {
5751 - // Keep existing embedding
5752 - $update_data = array(
5753 - 'intent_label' => $intent_label,
5754 - 'phrases' => implode(', ', $phrases_array),
5755 - 'similarity_threshold' => $similarity_threshold,
5756 - 'callback_function' => $callback_function,
5757 - 'enabled_bots' => json_encode($enabled_bots),
5758 - );
5759 - } else {
5760 - $serialized_vector = maybe_serialize($embedding_vector);
5761 - $update_data = array(
5762 - 'intent_label' => $intent_label,
5763 - 'phrases' => implode(', ', $phrases_array),
5764 - 'embedding_vector' => $serialized_vector,
5765 - 'similarity_threshold' => $similarity_threshold,
5766 - 'callback_function' => $callback_function,
5767 - 'enabled_bots' => json_encode($enabled_bots),
5768 - );
5769 - }
5770 - }
5771 -
5772 - // Ensure default bot is included
5773 - if (!in_array('default', $enabled_bots)) {
5774 - $enabled_bots[] = 'default';
5775 - }
5776 - $update_data['enabled_bots'] = json_encode($enabled_bots);
5777 -
5778 - $result = $wpdb->update(
5779 - $table_name,
5780 - $update_data,
5781 - array('id' => $intent_id),
5782 - null,
5783 - array('%d')
5784 - );
5785 -
5786 - if ($result === false) {
5787 - wp_send_json_error(__('Failed to update action.', 'mxchat'));
5788 - }
5789 -
5790 - wp_send_json_success(array('updated' => true));
5791 -}
5792 -
5793 -/**
5794 - * AJAX handler to delete a single intent/action
5795 - */
5796 -public function mxchat_delete_intent_ajax() {
5797 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5798 -
5799 - if (!current_user_can('manage_options')) {
5800 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5801 - }
5802 -
5803 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5804 -
5805 - if (!$intent_id) {
5806 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5807 - }
5808 -
5809 - global $wpdb;
5810 - $table_name = $wpdb->prefix . 'mxchat_intents';
5811 -
5812 - $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
5813 -
5814 - if ($result === false) {
5815 - wp_send_json_error(__('Failed to delete action', 'mxchat'));
5816 - }
5817 -
5818 - // Also delete individual phrases for this intent
5819 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5820 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5821 - $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
5822 - }
5823 -
5824 - wp_send_json_success(array('deleted' => true));
5825 -}
5826 -
5827 -/**
5828 - * AJAX handler to add a single phrase with its own embedding to an intent
5829 - */
5830 -public function mxchat_add_phrase_ajax() {
5831 - check_ajax_referer('mxchat_add_phrase_nonce', 'security');
5832 -
5833 - if (!current_user_can('manage_options')) {
5834 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5835 - }
5836 -
5837 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5838 - $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
5839 -
5840 - if (!$intent_id || empty($phrase)) {
5841 - wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
5842 - }
5843 -
5844 - // Verify the intent exists
5845 - global $wpdb;
5846 - $intents_table = $wpdb->prefix . 'mxchat_intents';
5847 - $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
5848 - if (!$intent) {
5849 - wp_send_json_error(__('Action not found.', 'mxchat'));
5850 - }
5851 -
5852 - // Generate embedding for this single phrase
5853 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5854 - if (is_wp_error($embedding_vector)) {
5855 - wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
5856 - }
5857 -
5858 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5859 - $result = $wpdb->insert(
5860 - $phrases_table,
5861 - array(
5862 - 'intent_id' => $intent_id,
5863 - 'phrase' => $phrase,
5864 - 'embedding_vector' => maybe_serialize($embedding_vector),
5865 - )
5866 - );
5867 -
5868 - if ($result === false) {
5869 - wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
5870 - }
5871 -
5872 - wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
5873 -}
5874 -
5875 -/**
5876 - * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
5877 - */
5878 -public function mxchat_delete_phrase_ajax() {
5879 - check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
5880 -
5881 - if (!current_user_can('manage_options')) {
5882 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5883 - }
5884 -
5885 - $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
5886 - if (!$phrase_id) {
5887 - wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
5888 - }
5889 -
5890 - global $wpdb;
5891 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5892 - $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
5893 -
5894 - if ($result === false) {
5895 - wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
5896 - }
5897 -
5898 - wp_send_json_success(array('deleted' => true));
5899 -}
5900 -
5901 -/**
5902 - * AJAX handler to fetch individual phrases for an intent
5903 - */
5904 -public function mxchat_get_phrases_ajax() {
5905 - check_ajax_referer('mxchat_get_phrases_nonce', 'security');
5906 -
5907 - if (!current_user_can('manage_options')) {
5908 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5909 - }
5910 -
5911 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5912 - if (!$intent_id) {
5913 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5914 - }
5915 -
5916 - global $wpdb;
5917 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5918 -
5919 - $phrases = array();
5920 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5921 - $phrases = $wpdb->get_results($wpdb->prepare(
5922 - "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
5923 - $intent_id
5924 - ));
5925 - }
5926 -
5927 - wp_send_json_success(array('phrases' => $phrases));
5928 -}
5929 -
5930 -/**
5931 - * AJAX handler to clear legacy phrases and embedding from the main intents table
5932 - */
5933 -public function mxchat_delete_legacy_phrases_ajax() {
5934 - check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
5935 -
5936 - if (!current_user_can('manage_options')) {
5937 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5938 - }
5939 -
5940 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5941 - if (!$intent_id) {
5942 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5943 - }
5944 -
5945 - global $wpdb;
5946 - $table_name = $wpdb->prefix . 'mxchat_intents';
5947 -
5948 - $result = $wpdb->update(
5949 - $table_name,
5950 - array('phrases' => '', 'embedding_vector' => ''),
5951 - array('id' => $intent_id),
5952 - array('%s', '%s'),
5953 - array('%d')
5954 - );
5955 -
5956 - if ($result === false) {
5957 - wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
5958 - }
5959 -
5960 - wp_send_json_success(array('cleared' => true));
5961 -}
5962 -
5963 -/**
5964 - * Enhanced get_available_callbacks function with form action exclusion
5965 - *
5966 - * @param bool $grouped Whether to return callbacks grouped by category
5967 - * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
5968 - * @return array Callbacks data with icons, descriptions and availability status
5969 - */
5970 -private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
5971 - // Load WordPress plugin functions if needed
5972 - if (!function_exists('get_plugins')) {
5973 - require_once ABSPATH . 'wp-admin/includes/plugin.php';
5974 - }
5975 -
5976 - // Get active plugins
5977 - $active_plugins = get_option('active_plugins', array());
5978 -
5979 - // Functions to exclude from the action selector only if Pro is activated
5980 - // If user doesn't have Pro, show these so they can see what they're missing
5981 - $excluded_when_pro_active_functions = array(
5982 - 'mxchat_handle_form_collection' // Forms add-on action
5983 - );
5984 -
5985 - // Always excluded functions (regardless of Pro status)
5986 - $always_excluded_functions = array();
5987 -
5988 - // Combine exclusion lists based on Pro activation status
5989 - $excluded_functions = $always_excluded_functions;
5990 - if ($this->is_activated) {
5991 - // Only exclude add-on managed functions if Pro is active
5992 - $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
5993 - }
5994 -
5995 - // Define add-on plugin files and their corresponding action functions
5996 - $addon_plugins = array(
5997 - 'mxchat-woo/mxchat-woo.php' => array(
5998 - 'functions' => array(
5999 - 'mxchat_handle_product_recommendations',
6000 - 'mxchat_handle_order_history',
6001 - 'mxchat_show_product_card',
6002 - 'mxchat_add_to_cart',
6003 - 'mxchat_checkout_redirect',
6004 - 'mxchat_handle_featured_products'
6005 - ),
6006 - 'name' => __('WooCommerce Add-on', 'mxchat'),
6007 - 'pro_required' => true
6008 - ),
6009 - 'mxchat-perplexity/mxchat-perplexity.php' => array(
6010 - 'functions' => array('mxchat_perplexity_research'),
6011 - 'name' => __('Perplexity Add-on', 'mxchat'),
6012 - 'pro_required' => true
6013 - ),
6014 - 'mxchat-forms/mxchat-forms.php' => array(
6015 - 'functions' => array('mxchat_handle_form_collection'),
6016 - 'name' => __('Forms Add-on', 'mxchat'),
6017 - 'pro_required' => true
6018 - ),
6019 - // Add other add-ons and their functions here
6020 - );
6021 -
6022 - // Get the functions that are provided by active add-ons
6023 - $addon_provided_functions = array();
6024 - $addon_function_mapping = array(); // Maps functions to their add-on info
6025 -
6026 - // Check which add-ons are active
6027 - foreach ($addon_plugins as $plugin_file => $addon_info) {
6028 - $is_active = in_array($plugin_file, $active_plugins);
6029 -
6030 - // For each function in this addon
6031 - foreach ($addon_info['functions'] as $function) {
6032 - // Consider a function installed only if:
6033 - // 1. The add-on is active AND
6034 - // 2. Either it doesn't require Pro OR Pro is activated
6035 - $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
6036 -
6037 - // If the add-on is installed, mark this function as provided by an add-on
6038 - if ($is_installed) {
6039 - $addon_provided_functions[] = $function;
6040 - }
6041 -
6042 - // Store addon info for this function regardless of installation status
6043 - $addon_function_mapping[$function] = array(
6044 - 'addon' => basename(dirname($plugin_file)),
6045 - 'addon_name' => $addon_info['name'],
6046 - 'pro_required' => $addon_info['pro_required'],
6047 - 'is_active' => $is_active,
6048 - 'is_installed' => $is_installed
6049 - );
6050 - }
6051 - }
6052 -
6053 - // Core callbacks - always available in the base plugin
6054 - $core_callbacks = array(
6055 - 'mxchat_handle_email_capture' => array(
6056 - 'label' => __('Loops Email Capture', 'mxchat'),
6057 - 'pro_only' => false,
6058 - 'group' => __('Customer Engagement', 'mxchat'),
6059 - 'icon' => 'email-alt',
6060 - 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
6061 - 'addon' => false, // Not from an add-on
6062 - 'installed' => true // Always installed with base plugin
6063 - ),
6064 - 'mxchat_handle_search_request' => array(
6065 - 'label' => __('Brave Web Search', 'mxchat'),
6066 - 'pro_only' => false,
6067 - 'group' => __('Search Features', 'mxchat'),
6068 - 'icon' => 'search',
6069 - 'description' => __('Let users search the web directly from the chat (requires a Brave Search API key)', 'mxchat'),
6070 - 'addon' => false,
6071 - 'installed' => true
6072 - ),
6073 - 'mxchat_handle_image_search_request' => array(
6074 - 'label' => __('Brave Image Search', 'mxchat'),
6075 - 'pro_only' => false,
6076 - 'group' => __('Search Features', 'mxchat'),
6077 - 'icon' => 'format-image',
6078 - 'description' => __('Search and display images in the chat conversation (requires a Brave Search API key)', 'mxchat'),
6079 - 'addon' => false,
6080 - 'installed' => true
6081 - ),
6082 - // Pro core features - check is_activated property
6083 - 'mxchat_generate_image' => array(
6084 - 'label' => __('Generate Image (OpenAI)', 'mxchat'),
6085 - 'pro_only' => false,
6086 - 'group' => __('Other Features', 'mxchat'),
6087 - 'icon' => 'art',
6088 - 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
6089 - 'addon' => false,
6090 - 'installed' => true
6091 - ),
6092 - 'mxchat_generate_gemini_image' => array(
6093 - 'label' => __('Generate Image (Gemini)', 'mxchat'),
6094 - 'pro_only' => false,
6095 - 'group' => __('Other Features', 'mxchat'),
6096 - 'icon' => 'art',
6097 - 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
6098 - 'addon' => false,
6099 - 'installed' => true
6100 - ),
6101 - 'mxchat_handle_pdf_discussion' => array(
6102 - 'label' => __('Chat with PDF', 'mxchat'),
6103 - 'pro_only' => false,
6104 - 'group' => __('Other Features', 'mxchat'),
6105 - 'icon' => 'media-document',
6106 - 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
6107 - 'addon' => false,
6108 - 'installed' => true
6109 - ),
6110 - 'mxchat_live_agent_handover' => array(
6111 - 'label' => __('Slack Live Agent', 'mxchat'),
6112 - 'pro_only' => false,
6113 - 'group' => __('Customer Engagement', 'mxchat'),
6114 - 'icon' => 'admin-users',
6115 - 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
6116 - 'addon' => false,
6117 - 'installed' => true
6118 - ),
6119 - 'mxchat_telegram_live_agent_handover' => array(
6120 - 'label' => __('Telegram Live Agent', 'mxchat'),
6121 - 'pro_only' => false,
6122 - 'group' => __('Customer Engagement', 'mxchat'),
6123 - 'icon' => 'format-chat',
6124 - 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
6125 - 'addon' => false,
6126 - 'installed' => true
6127 - ),
6128 - 'mxchat_webhook_live_agent_handover' => array(
6129 - 'label' => __('Webhook Live Agent', 'mxchat'),
6130 - 'pro_only' => false,
6131 - 'group' => __('Customer Engagement', 'mxchat'),
6132 - 'icon' => 'external',
6133 - 'description' => __('Send the conversation to your own webhook URL so your team can follow up', 'mxchat'),
6134 - 'addon' => false,
6135 - 'installed' => true
6136 - ),
6137 - 'mxchat_handle_switch_to_chatbot_intent' => array(
6138 - 'label' => __('Back to Chatbot', 'mxchat'),
6139 - 'pro_only' => false,
6140 - 'group' => __('Customer Engagement', 'mxchat'),
6141 - 'icon' => 'backup',
6142 - 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
6143 - 'addon' => false,
6144 - 'installed' => true
6145 - ),
6146 - );
6147 -
6148 - // Add-on callbacks with placeholders - only include if the add-on is NOT active
6149 - // These are promotional/informational only — not selectable as real actions
6150 - $addon_callbacks = array(
6151 - // WooCommerce Add-on
6152 - 'mxchat_handle_product_recommendations' => array(
6153 - 'label' => __('Product Recommendations', 'mxchat'),
6154 - 'pro_only' => false,
6155 - 'addon_promo' => true,
6156 - 'group' => __('WooCommerce Features', 'mxchat'),
6157 - 'icon' => 'cart',
6158 - 'description' => __('Suggest products based on customer preferences', 'mxchat'),
6159 - ),
6160 - 'mxchat_handle_order_history' => array(
6161 - 'label' => __('Order History', 'mxchat'),
6162 - 'pro_only' => false,
6163 - 'addon_promo' => true,
6164 - 'group' => __('WooCommerce Features', 'mxchat'),
6165 - 'icon' => 'clipboard',
6166 - 'description' => __('Allow customers to check their order status', 'mxchat'),
6167 - ),
6168 - 'mxchat_show_product_card' => array(
6169 - 'label' => __('Show Product Card', 'mxchat'),
6170 - 'pro_only' => false,
6171 - 'addon_promo' => true,
6172 - 'group' => __('WooCommerce Features', 'mxchat'),
6173 - 'icon' => 'products',
6174 - 'description' => __('Display product information in the chat', 'mxchat'),
6175 - ),
6176 - 'mxchat_add_to_cart' => array(
6177 - 'label' => __('Add to Cart', 'mxchat'),
6178 - 'pro_only' => false,
6179 - 'addon_promo' => true,
6180 - 'group' => __('WooCommerce Features', 'mxchat'),
6181 - 'icon' => 'plus-alt',
6182 - 'description' => __('Add products to cart directly from chat', 'mxchat'),
6183 - ),
6184 - 'mxchat_checkout_redirect' => array(
6185 - 'label' => __('Proceed to Checkout', 'mxchat'),
6186 - 'pro_only' => false,
6187 - 'addon_promo' => true,
6188 - 'group' => __('WooCommerce Features', 'mxchat'),
6189 - 'icon' => 'arrow-right-alt',
6190 - 'description' => __('Redirect customer to checkout page', 'mxchat'),
6191 - ),
6192 - 'mxchat_handle_featured_products' => array(
6193 - 'label' => __('Featured Products Showcase', 'mxchat'),
6194 - 'pro_only' => false,
6195 - 'addon_promo' => true,
6196 - 'group' => __('WooCommerce Features', 'mxchat'),
6197 - 'icon' => 'star-filled',
6198 - 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
6199 - ),
6200 -
6201 - // Perplexity Add-on
6202 - 'mxchat_perplexity_research' => array(
6203 - 'label' => __('Perplexity Research', 'mxchat'),
6204 - 'pro_only' => false,
6205 - 'addon_promo' => true,
6206 - 'group' => __('Search Features', 'mxchat'),
6207 - 'icon' => 'book-alt',
6208 - 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
6209 - ),
6210 -
6211 - // Forms Add-on
6212 - 'mxchat_handle_form_collection' => array(
6213 - 'label' => __('Form Collection', 'mxchat'),
6214 - 'pro_only' => false,
6215 - 'addon_promo' => true,
6216 - 'group' => __('Form Features', 'mxchat'),
6217 - 'icon' => 'feedback',
6218 - 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
6219 - ),
6220 - );
6221 -
6222 - // Enhance add-on callbacks with installation status and addon info
6223 - foreach ($addon_callbacks as $function => $data) {
6224 - if (isset($addon_function_mapping[$function])) {
6225 - $addon_info = $addon_function_mapping[$function];
6226 -
6227 - $addon_callbacks[$function]['addon'] = $addon_info['addon'];
6228 - $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6229 - $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
6230 -
6231 - // Set pro_only based on add-on configuration
6232 - $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6233 - } else {
6234 - $addon_callbacks[$function]['addon'] = 'unknown';
6235 - $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
6236 - $addon_callbacks[$function]['installed'] = false;
6237 - }
6238 - }
6239 -
6240 - // Initialize callbacks with core features
6241 - $callbacks = $core_callbacks;
6242 -
6243 - // Get callbacks from active add-ons
6244 - $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
6245 -
6246 - // Add placeholder callbacks only for add-ons that aren't active
6247 - if ($include_all) {
6248 - foreach ($addon_callbacks as $function => $data) {
6249 - // Skip placeholders for functions provided by active add-ons
6250 - if (in_array($function, $addon_provided_functions)) {
6251 - continue;
6252 - }
6253 -
6254 - // Skip excluded functions
6255 - if (in_array($function, $excluded_functions)) {
6256 - continue;
6257 - }
6258 -
6259 - // Add the placeholder
6260 - $callbacks[$function] = $data;
6261 - }
6262 - }
6263 -
6264 - // Add callbacks from active add-ons (will override placeholders)
6265 - foreach ($active_addon_callbacks as $function => $data) {
6266 - // Skip excluded functions
6267 - if (in_array($function, $excluded_functions)) {
6268 - continue;
6269 - }
6270 -
6271 - // Always include callbacks from add-ons
6272 - $callbacks[$function] = $data;
6273 -
6274 - // Ensure they have the proper add-on info
6275 - if (isset($addon_function_mapping[$function])) {
6276 - $addon_info = $addon_function_mapping[$function];
6277 - $callbacks[$function]['addon'] = $addon_info['addon'];
6278 - $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6279 - $callbacks[$function]['installed'] = $addon_info['is_installed'];
6280 - $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6281 - }
6282 - }
6283 -
6284 - // Just before returning callbacks, sort them to prioritize free features
6285 - if (!$grouped) {
6286 - // Create temporary arrays for sorting
6287 - $free_callbacks = array();
6288 - $pro_callbacks = array();
6289 -
6290 - // Split callbacks into free and pro
6291 - foreach ($callbacks as $key => $data) {
6292 - if (isset($data['pro_only']) && $data['pro_only']) {
6293 - $pro_callbacks[$key] = $data;
6294 - } else {
6295 - $free_callbacks[$key] = $data;
6296 - }
6297 - }
6298 -
6299 - // Merge with free callbacks first
6300 - $callbacks = array_merge($free_callbacks, $pro_callbacks);
6301 - }
6302 -
6303 - // Return grouped structure if requested
6304 - if ($grouped) {
6305 - $grouped_callbacks = array();
6306 - foreach ($callbacks as $key => $data) {
6307 - $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
6308 -
6309 - // Ensure we carry forward all the new fields in grouped mode
6310 - $callback_data = array(
6311 - 'label' => $data['label'],
6312 - 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
6313 - 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
6314 - 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
6315 - 'addon' => isset($data['addon']) ? $data['addon'] : false,
6316 - 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
6317 - 'installed' => isset($data['installed']) ? $data['installed'] : true
6318 - );
6319 -
6320 - $grouped_callbacks[$group_label][$key] = $callback_data;
6321 - }
6322 -
6323 - // Sort within each group to prioritize free features
6324 - foreach ($grouped_callbacks as $group => $items) {
6325 - $free_items = array();
6326 - $pro_items = array();
6327 -
6328 - foreach ($items as $key => $data) {
6329 - if (isset($data['pro_only']) && $data['pro_only']) {
6330 - $pro_items[$key] = $data;
6331 - } else {
6332 - $free_items[$key] = $data;
6333 - }
6334 - }
6335 -
6336 - $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
6337 - }
6338 -
6339 - return $grouped_callbacks;
6340 - }
6341 -
6342 - return $callbacks;
6343 -}
6344 -
6345 788 public function mxchat_page_init() {
789 + // Register settings
6346 790 register_setting(
6347 791 'mxchat_option_group',
6348 792 'mxchat_options',
6349 793 array($this, 'mxchat_sanitize')
@@ -6348,217 +792,36 @@
6348 792 'mxchat_options',
6349 793 array($this, 'mxchat_sanitize')
6350 794 );
6351 795
6352 - register_setting(
6353 - 'mxchat_option_group',
6354 - 'mxchat_similarity_threshold',
6355 - array(
6356 - 'type' => 'number',
6357 - 'sanitize_callback' => function($value) {
6358 - $value = absint($value);
6359 - return min(max($value, 20), 95);
6360 - },
6361 - 'default' => 80,
6362 - )
6363 - );
6364 -
6365 796 // Chatbot Settings Section
6366 797 add_settings_section(
6367 798 'mxchat_chatbot_section',
6368 - esc_html__('Chatbot Settings', 'mxchat'),
799 + 'Chatbot Settings',
6369 800 null,
6370 801 'mxchat-chatbot'
6371 802 );
6372 803
6373 - // API Keys Settings Section
6374 - add_settings_section(
6375 - 'mxchat_api_keys_section',
6376 - esc_html__('API Keys', 'mxchat'),
6377 - array($this, 'mxchat_api_keys_section_callback'),
6378 - 'mxchat-api-keys'
6379 - );
6380 -
6381 - // OpenAI API Key
804 + // Registering fields for the Chatbot Settings section
6382 805 add_settings_field(
6383 806 'api_key',
6384 - esc_html__('OpenAI API Key', 'mxchat'),
807 + 'API Key',
6385 808 array($this, 'api_key_callback'),
6386 - 'mxchat-api-keys',
6387 - 'mxchat_api_keys_section'
6388 - );
6389 -
6390 - // X.AI API Key
6391 - add_settings_field(
6392 - 'xai_api_key',
6393 - esc_html__('X.AI API Key', 'mxchat'),
6394 - array($this, 'xai_api_key_callback'),
6395 - 'mxchat-api-keys',
6396 - 'mxchat_api_keys_section'
6397 - );
6398 -
6399 - // Claude API Key
6400 - add_settings_field(
6401 - 'claude_api_key',
6402 - esc_html__('Claude API Key', 'mxchat'),
6403 - array($this, 'claude_api_key_callback'),
6404 - 'mxchat-api-keys',
6405 - 'mxchat_api_keys_section'
6406 - );
6407 -
6408 - // DeepSeek API Key
6409 - add_settings_field(
6410 - 'deepseek_api_key',
6411 - esc_html__('DeepSeek API Key', 'mxchat'),
6412 - array($this, 'deepseek_api_key_callback'),
6413 - 'mxchat-api-keys',
6414 - 'mxchat_api_keys_section'
6415 - );
6416 -
6417 - // Google Gemini API Key
6418 - add_settings_field(
6419 - 'gemini_api_key',
6420 - esc_html__('Google Gemini API Key', 'mxchat'),
6421 - array($this, 'gemini_api_key_callback'),
6422 - 'mxchat-api-keys',
6423 - 'mxchat_api_keys_section'
6424 - );
6425 -
6426 - // Voyage AI API Key
6427 - add_settings_field(
6428 - 'voyage_api_key',
6429 - esc_html__('Voyage AI API Key', 'mxchat'),
6430 - array($this, 'voyage_api_key_callback'),
6431 - 'mxchat-api-keys',
6432 - 'mxchat_api_keys_section'
6433 - );
6434 -
6435 - // OpenRouter API Key
6436 - add_settings_field(
6437 - 'openrouter_api_key',
6438 - esc_html__('OpenRouter API Key', 'mxchat'),
6439 - array($this, 'openrouter_api_key_callback'),
6440 - 'mxchat-api-keys',
6441 - 'mxchat_api_keys_section'
6442 - );
6443 -
6444 - // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6445 - add_settings_field(
6446 - 'custom_provider',
6447 - esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
6448 - array($this, 'custom_provider_callback'),
6449 - 'mxchat-api-keys',
6450 - 'mxchat_api_keys_section'
6451 - );
6452 -
6453 - // Loops API Key
6454 - add_settings_field(
6455 - 'loops_api_key',
6456 - esc_html__('Loops API Key', 'mxchat'),
6457 - array($this, 'mxchat_loops_api_key_callback'),
6458 - 'mxchat-api-keys',
6459 - 'mxchat_api_keys_section'
6460 - );
6461 -
6462 - // Brave Search API Key
6463 - add_settings_field(
6464 - 'brave_api_key',
6465 - __('Brave API Key', 'mxchat'),
6466 - array($this, 'mxchat_brave_api_key_callback'),
6467 - 'mxchat-api-keys',
6468 - 'mxchat_api_keys_section'
6469 - );
6470 -
6471 - // Similarity Threshold Slider
6472 - add_settings_field(
6473 - 'similarity_threshold', // Field ID
6474 - esc_html__('Similarity Threshold', 'mxchat'), // Field title
6475 - array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6476 - 'mxchat-chatbot', // Page
6477 - 'mxchat_chatbot_section' // Section
6478 - );
6479 -
6480 - // RAG Sources Limit Slider
6481 - add_settings_field(
6482 - 'rag_sources_limit', // Field ID
6483 - esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6484 - array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6485 - 'mxchat-chatbot', // Page
6486 - 'mxchat_chatbot_section' // Section
6487 - );
6488 -
6489 - // RAG Chunks Limit Slider
6490 - add_settings_field(
6491 - 'rag_chunks_limit', // Field ID
6492 - esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6493 - array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6494 - 'mxchat-chatbot', // Page
6495 - 'mxchat_chatbot_section' // Section
6496 - );
6497 -
6498 - add_settings_field(
6499 - 'append_to_body',
6500 - esc_html__('Auto-Display Chatbot', 'mxchat'),
6501 - array($this, 'mxchat_append_to_body_callback'),
6502 809 'mxchat-chatbot',
6503 810 'mxchat_chatbot_section'
6504 811 );
6505 812
6506 813 add_settings_field(
6507 - 'contextual_awareness_toggle',
6508 - esc_html__('Contextual Awareness', 'mxchat'),
6509 - array($this, 'mxchat_contextual_awareness_callback'),
814 + 'system_prompt_instructions',
815 + 'AI Instructions',
816 + array($this, 'system_prompt_instructions_callback'),
6510 817 'mxchat-chatbot',
6511 818 'mxchat_chatbot_section'
6512 819 );
6513 820
6514 821 add_settings_field(
6515 - 'citation_links_toggle',
6516 - esc_html__('Citation Links', 'mxchat'),
6517 - array($this, 'mxchat_citation_links_toggle_callback'),
6518 - 'mxchat-chatbot',
6519 - 'mxchat_chatbot_section'
6520 - );
6521 -
6522 - // Strip unapproved links (plan 58f8b4) — the enforcement half of the old
6523 - // Citation Links conflation, now its own control.
6524 - add_settings_field(
6525 - 'strip_unapproved_links_toggle',
6526 - esc_html__('Strip Unapproved Links', 'mxchat'),
6527 - array($this, 'mxchat_strip_unapproved_links_toggle_callback'),
6528 - 'mxchat-chatbot',
6529 - 'mxchat_chatbot_section'
6530 - );
6531 -
6532 - // Satisfaction rating toggle (plan-a5b006).
6533 - add_settings_field(
6534 - 'satisfaction_rating_enabled',
6535 - esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6536 - array($this, 'mxchat_satisfaction_rating_toggle_callback'),
6537 - 'mxchat-chatbot',
6538 - 'mxchat_chatbot_section'
6539 - );
6540 -
6541 - // Satisfaction rating customization (plan-141a12, plan-29caac):
6542 - // the 5 customization fields are now inline-rendered inside
6543 - // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6544 -
6545 - add_settings_field(
6546 - 'enable_streaming_toggle',
6547 - esc_html__('Enable Streaming', 'mxchat'),
6548 - array($this, 'enable_streaming_toggle_callback'),
6549 - 'mxchat-chatbot',
6550 - 'mxchat_chatbot_section', // Same section as your working toggle
6551 - array(
6552 - 'class' => 'mxchat-setting-row streaming-setting',
6553 - 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6554 - )
6555 - );
6556 -
6557 -
6558 - add_settings_field(
6559 822 'model',
6560 - esc_html__('Chat Model', 'mxchat'),
823 + 'Model',
6561 824 array($this, 'mxchat_model_callback'),
6562 825 'mxchat-chatbot',
6563 826 'mxchat_chatbot_section'
6564 827 );
@@ -6563,27 +826,10 @@
6563 826 'mxchat_chatbot_section'
6564 827 );
6565 828
6566 829 add_settings_field(
6567 - 'embedding_model',
6568 - esc_html__('Embedding Model', 'mxchat'),
6569 - array($this, 'embedding_model_callback'),
6570 - 'mxchat-chatbot',
6571 - 'mxchat_chatbot_section'
6572 - );
6573 -
6574 - add_settings_field(
6575 - 'system_prompt_instructions',
6576 - esc_html__('AI Instructions (Behavior)', 'mxchat'),
6577 - array($this, 'system_prompt_instructions_callback'),
6578 - 'mxchat-chatbot',
6579 - 'mxchat_chatbot_section'
6580 - );
6581 -
6582 -
6583 - add_settings_field(
6584 830 'top_bar_title',
6585 - esc_html__('Top Bar Title', 'mxchat'),
831 + 'Top Bar Title',
6586 832 array($this, 'mxchat_top_bar_title_callback'),
6587 833 'mxchat-chatbot',
6588 834 'mxchat_chatbot_section'
6589 835 );
@@ -6588,82 +834,58 @@
6588 834 'mxchat_chatbot_section'
6589 835 );
6590 836
6591 837 add_settings_field(
6592 - 'ai_agent_text',
6593 - esc_html__('AI Agent Text', 'mxchat'),
6594 - array($this, 'mxchat_ai_agent_text_callback'),
838 + 'intro_message',
839 + 'Introductory Message',
840 + array($this, 'mxchat_intro_message_callback'),
6595 841 'mxchat-chatbot',
6596 842 'mxchat_chatbot_section'
6597 843 );
6598 844
6599 845 add_settings_field(
6600 - 'enable_email_block',
6601 - esc_html__('Require Email To Chat', 'mxchat'),
6602 - array($this, 'enable_email_block_callback'),
846 + 'input_copy',
847 + 'Input Copy',
848 + array($this, 'mxchat_input_copy_callback'),
6603 849 'mxchat-chatbot',
6604 850 'mxchat_chatbot_section'
6605 851 );
6606 852
6607 853 add_settings_field(
6608 - 'email_blocker_header_content',
6609 - esc_html__('Require Email Chat Content', 'mxchat'),
6610 - array($this, 'email_blocker_header_content_callback'),
854 + 'rate_limit',
855 + 'Rate Limit',
856 + array($this, 'mxchat_rate_limit_callback'),
6611 857 'mxchat-chatbot',
6612 858 'mxchat_chatbot_section'
6613 859 );
6614 860
6615 861 add_settings_field(
6616 - 'email_blocker_button_text',
6617 - esc_html__('Require Email Chat Button Text', 'mxchat'),
6618 - [$this, 'email_blocker_button_text_callback'],
862 + 'rate_limit_message',
863 + 'Rate Limit Message',
864 + array($this, 'mxchat_rate_limit_message_callback'),
6619 865 'mxchat-chatbot',
6620 866 'mxchat_chatbot_section'
6621 867 );
6622 868
6623 869 add_settings_field(
6624 - 'enable_name_field',
6625 - esc_html__('Require Name Field', 'mxchat'),
6626 - array($this, 'enable_name_field_callback'),
870 + 'pre_chat_message',
871 + 'Pre-Chat Message',
872 + array($this, 'mxchat_pre_chat_message_callback'),
6627 873 'mxchat-chatbot',
6628 874 'mxchat_chatbot_section'
6629 875 );
6630 876
6631 - add_settings_field(
6632 - 'name_field_placeholder',
6633 - esc_html__('Name Field Placeholder', 'mxchat'),
6634 - array($this, 'name_field_placeholder_callback'),
877 + add_settings_field(
878 + 'append_to_body',
879 + 'Append Chat Widget to Body',
880 + array($this, 'mxchat_append_to_body_callback'),
6635 881 'mxchat-chatbot',
6636 882 'mxchat_chatbot_section'
6637 883 );
6638 884
6639 - add_settings_field(
6640 - 'intro_message',
6641 - esc_html__('Introductory Message', 'mxchat'),
6642 - array($this, 'mxchat_intro_message_callback'),
6643 - 'mxchat-chatbot',
6644 - 'mxchat_chatbot_section'
6645 - );
6646 -
6647 - add_settings_field(
6648 - 'input_copy',
6649 - esc_html__('Input Copy', 'mxchat'),
6650 - array($this, 'mxchat_input_copy_callback'),
6651 - 'mxchat-chatbot',
6652 - 'mxchat_chatbot_section'
6653 - );
6654 -
6655 - add_settings_field(
6656 - 'pre_chat_message',
6657 - esc_html__('Chat Teaser Pop-up', 'mxchat'),
6658 - array($this, 'mxchat_pre_chat_message_callback'),
6659 - 'mxchat-chatbot',
6660 - 'mxchat_chatbot_section'
6661 - );
6662 -
6663 - add_settings_field(
885 + add_settings_field(
6664 886 'privacy_toggle',
6665 - esc_html__('Toggle Privacy Notice', 'mxchat'),
887 + 'Toggle Privacy Notice',
6666 888 array($this, 'mxchat_privacy_toggle_callback'),
6667 889 'mxchat-chatbot',
6668 890 'mxchat_chatbot_section'
6669 891 );
@@ -6669,9 +891,9 @@
6669 891 );
6670 892
6671 893 add_settings_field(
6672 894 'complianz_toggle',
6673 - esc_html__('Enable Complianz', 'mxchat'),
895 + 'Enable Complianz',
6674 896 array($this, 'mxchat_complianz_toggle_callback'),
6675 897 'mxchat-chatbot',
6676 898 'mxchat_chatbot_section'
6677 899 );
@@ -6677,9 +899,9 @@
6677 899 );
6678 900
6679 901 add_settings_field(
6680 902 'link_target_toggle',
6681 - esc_html__('Open Links in a New Tab', 'mxchat'),
903 + 'Open Links in a New Tab',
6682 904 array($this, 'mxchat_link_target_toggle_callback'),
6683 905 'mxchat-chatbot',
6684 906 'mxchat_chatbot_section'
6685 907 );
@@ -6684,759 +906,321 @@
6684 906 'mxchat_chatbot_section'
6685 907 );
6686 908
6687 909 add_settings_field(
6688 - 'chat_persistence_toggle',
6689 - esc_html__('Enable Chat Persistence', 'mxchat'),
6690 - array($this, 'mxchat_chat_persistence_toggle_callback'),
6691 - 'mxchat-chatbot',
6692 - 'mxchat_chatbot_section'
910 + 'chat_persistence_toggle',
911 + 'Enable Chat Persistence',
912 + array($this, 'mxchat_chat_persistence_toggle_callback'),
913 + 'mxchat-chatbot',
914 + 'mxchat_chatbot_section'
6693 915 );
6694 916
6695 - add_settings_field(
6696 - 'print_button_enabled',
6697 - esc_html__('Show Download Transcript Button', 'mxchat'),
6698 - array($this, 'mxchat_print_button_toggle_callback'),
6699 - 'mxchat-chatbot',
6700 - 'mxchat_chatbot_section'
6701 - );
6702 917
6703 - add_settings_field(
6704 - 'reset_chat_enabled',
6705 - esc_html__('Show Start-New-Chat Button', 'mxchat'),
6706 - array($this, 'mxchat_reset_chat_toggle_callback'),
6707 - 'mxchat-chatbot',
6708 - 'mxchat_chatbot_section'
6709 - );
918 +// WooCommerce Settings Section
919 +add_settings_section(
920 + 'mxchat_woocommerce_section',
921 + 'WooCommerce Settings',
922 + null,
923 + 'mxchat-embed'
924 +);
6710 925
6711 - add_settings_field(
6712 - 'reset_chat_label',
6713 - esc_html__('Start-New-Chat Button Label', 'mxchat'),
6714 - array($this, 'mxchat_reset_chat_label_callback'),
6715 - 'mxchat-chatbot',
6716 - 'mxchat_chatbot_section'
6717 - );
926 +// Loops Settings Section
927 +add_settings_section(
928 + 'mxchat_loops_section',
929 + 'Loops Settings',
930 + null,
931 + 'mxchat-embed'
932 +);
6718 933
6719 - add_settings_field(
6720 - 'popular_question_1',
6721 - esc_html__('Quick Question 1', 'mxchat'),
6722 - array($this, 'mxchat_popular_question_1_callback'),
6723 - 'mxchat-chatbot',
6724 - 'mxchat_chatbot_section'
6725 - );
934 +// WooCommerce Settings Fields
935 +add_settings_field(
936 + 'enable_woocommerce_integration',
937 + 'Automatically Embed Products',
938 + array($this, 'mxchat_enable_woocommerce_integration_callback'),
939 + 'mxchat-embed',
940 + 'mxchat_woocommerce_section'
941 +);
6726 942
6727 - add_settings_field(
6728 - 'popular_question_2',
6729 - esc_html__('Quick Question 2', 'mxchat'),
6730 - array($this, 'mxchat_popular_question_2_callback'),
6731 - 'mxchat-chatbot',
6732 - 'mxchat_chatbot_section'
6733 - );
943 +add_settings_field(
944 + 'enable_woocommerce_order_access',
945 + 'Order History Access',
946 + array($this, 'mxchat_enable_woocommerce_order_access_callback'),
947 + 'mxchat-embed',
948 + 'mxchat_woocommerce_section'
949 +);
6734 950
6735 - add_settings_field(
6736 - 'popular_question_3',
6737 - esc_html__('Quick Question 3', 'mxchat'),
6738 - array($this, 'mxchat_popular_question_3_callback'),
6739 - 'mxchat-chatbot',
6740 - 'mxchat_chatbot_section'
6741 - );
951 +add_settings_field(
952 + 'woocommerce_consumer_key',
953 + 'WooCommerce Consumer Key',
954 + array($this, 'mxchat_woocommerce_consumer_key_callback'),
955 + 'mxchat-embed',
956 + 'mxchat_woocommerce_section'
957 +);
6742 958
6743 - add_settings_field(
6744 - 'additional_popular_questions',
6745 - esc_html__('Additional Quick Questions', 'mxchat'),
6746 - array($this, 'mxchat_additional_popular_questions_callback'),
6747 - 'mxchat-chatbot',
6748 - 'mxchat_chatbot_section'
6749 - );
959 +add_settings_field(
960 + 'woocommerce_consumer_secret',
961 + 'WooCommerce Consumer Secret',
962 + array($this, 'mxchat_woocommerce_consumer_secret_callback'),
963 + 'mxchat-embed',
964 + 'mxchat_woocommerce_section'
965 +);
6750 966
967 +// Loops Settings Fields
968 +add_settings_field(
969 + 'loops_api_key',
970 + 'Loops API Key',
971 + array($this, 'mxchat_loops_api_key_callback'),
972 + 'mxchat-embed',
973 + 'mxchat_loops_section'
974 +);
6751 975
6752 - add_settings_field(
6753 - 'rate_limits',
6754 - __('Rate Limits Settings', 'mxchat'),
6755 - array($this, 'mxchat_rate_limits_callback'),
6756 - 'mxchat-chatbot',
6757 - 'mxchat_chatbot_section'
6758 - );
976 +add_settings_field(
977 + 'loops_mailing_list',
978 + 'Loops Mailing List',
979 + array($this, 'mxchat_loops_mailing_list_callback'),
980 + 'mxchat-embed',
981 + 'mxchat_loops_section'
982 +);
6759 983
6760 - // Loops Settings Section
6761 - add_settings_section(
6762 - 'mxchat_loops_section',
6763 - esc_html__('Loops Settings', 'mxchat'),
6764 - null,
6765 - 'mxchat-embed'
6766 - );
984 +add_settings_field(
985 + 'trigger_keywords',
986 + 'Email Capture Trigger Keywords',
987 + array($this, 'mxchat_trigger_keywords_callback'),
988 + 'mxchat-embed',
989 + 'mxchat_loops_section'
990 +);
6767 991
6768 - // Loops Settings Fields (API Key moved to API Keys tab)
6769 - add_settings_field(
6770 - 'loops_mailing_list',
6771 - esc_html__('Loops Mailing List', 'mxchat'),
6772 - array($this, 'mxchat_loops_mailing_list_callback'),
6773 - 'mxchat-embed',
6774 - 'mxchat_loops_section'
6775 - );
992 +add_settings_field(
993 + 'triggered_phrase_response',
994 + 'Triggered Phrase Response',
995 + array($this, 'mxchat_triggered_phrase_response_callback'),
996 + 'mxchat-embed',
997 + 'mxchat_loops_section'
998 +);
6776 999
6777 - add_settings_field(
6778 - 'triggered_phrase_response',
6779 - esc_html__('Triggered Phrase Response', 'mxchat'),
6780 - array($this, 'mxchat_triggered_phrase_response_callback'),
6781 - 'mxchat-embed',
6782 - 'mxchat_loops_section'
6783 - );
1000 +add_settings_field(
1001 + 'email_capture_response',
1002 + 'Email Capture Response',
1003 + array($this, 'mxchat_email_capture_response_callback'),
1004 + 'mxchat-embed',
1005 + 'mxchat_loops_section'
1006 +);
6784 1007
6785 - add_settings_field(
6786 - 'email_capture_response',
6787 - esc_html__('Email Capture Response', 'mxchat'),
6788 - array($this, 'mxchat_email_capture_response_callback'),
6789 - 'mxchat-embed',
6790 - 'mxchat_loops_section'
6791 - );
6792 -
6793 - // Brave Search Settings Fields
1008 + // Theme Settings Section
6794 1009 add_settings_section(
6795 - 'mxchat_brave_section',
6796 - __('Brave Search Settings', 'mxchat'),
6797 - array($this, 'mxchat_brave_section_callback'),
6798 - 'mxchat-embed'
1010 + 'mxchat_theme_section',
1011 + 'Theme Settings',
1012 + null,
1013 + 'mxchat-theme'
6799 1014 );
6800 1015
6801 - // Brave API Key moved to API Keys tab
6802 1016 add_settings_field(
6803 - 'brave_image_count',
6804 - __('Number of Images to Return', 'mxchat'),
6805 - array($this, 'mxchat_brave_image_count_callback'),
6806 - 'mxchat-embed',
6807 - 'mxchat_brave_section'
1017 + 'close_button_color',
1018 + 'Close Button & Title Color',
1019 + array($this, 'mxchat_close_button_color_callback'),
1020 + 'mxchat-theme',
1021 + 'mxchat_theme_section'
6808 1022 );
6809 1023
6810 1024 add_settings_field(
6811 - 'brave_safe_search',
6812 - __('Safe Search', 'mxchat'),
6813 - array($this, 'mxchat_brave_safe_search_callback'),
6814 - 'mxchat-embed',
6815 - 'mxchat_brave_section'
1025 + 'chatbot_bg_color',
1026 + 'Chatbot Background Color',
1027 + array($this, 'mxchat_chatbot_bg_color_callback'),
1028 + 'mxchat-theme',
1029 + 'mxchat_theme_section'
6816 1030 );
6817 1031
6818 1032 add_settings_field(
6819 - 'brave_news_count',
6820 - __('Number of News Articles', 'mxchat'),
6821 - array($this, 'mxchat_brave_news_count_callback'),
6822 - 'mxchat-embed',
6823 - 'mxchat_brave_section'
1033 + 'user_message_bg_color',
1034 + 'User Message Background Color',
1035 + array($this, 'mxchat_user_message_bg_color_callback'),
1036 + 'mxchat-theme',
1037 + 'mxchat_theme_section'
6824 1038 );
6825 1039
6826 1040 add_settings_field(
6827 - 'brave_country',
6828 - __('Country', 'mxchat'),
6829 - array($this, 'mxchat_brave_country_callback'),
6830 - 'mxchat-embed',
6831 - 'mxchat_brave_section'
1041 + 'user_message_font_color',
1042 + 'User Message Font Color',
1043 + array($this, 'mxchat_user_message_font_color_callback'),
1044 + 'mxchat-theme',
1045 + 'mxchat_theme_section'
6832 1046 );
6833 1047
6834 1048 add_settings_field(
6835 - 'brave_language',
6836 - __('Language', 'mxchat'),
6837 - array($this, 'mxchat_brave_language_callback'),
6838 - 'mxchat-embed',
6839 - 'mxchat_brave_section'
1049 + 'bot_message_bg_color',
1050 + 'Bot Message Background Color',
1051 + array($this, 'mxchat_bot_message_bg_color_callback'),
1052 + 'mxchat-theme',
1053 + 'mxchat_theme_section'
6840 1054 );
6841 1055
6842 - // Chat with PDF Intent Settings Fields
6843 - add_settings_section(
6844 - 'mxchat_pdf_intent_section',
6845 - __('Toolbar Settings & Intents', 'mxchat'),
6846 - array($this, 'mxchat_pdf_intent_section_callback'),
6847 - 'mxchat-embed'
6848 - );
6849 -
6850 1056 add_settings_field(
6851 - 'chat_toolbar_toggle',
6852 - __('Show Chat Toolbar', 'mxchat'),
6853 - array($this, 'mxchat_chat_toolbar_toggle_callback'),
6854 - 'mxchat-embed',
6855 - 'mxchat_pdf_intent_section'
1057 + 'bot_message_font_color',
1058 + 'Bot Message Font Color',
1059 + array($this, 'mxchat_bot_message_font_color_callback'),
1060 + 'mxchat-theme',
1061 + 'mxchat_theme_section'
6856 1062 );
6857 1063
6858 - // PDF Upload Button Toggle
6859 1064 add_settings_field(
6860 - 'show_pdf_upload_button',
6861 - __('Show PDF Upload Button', 'mxchat'),
6862 - array($this, 'mxchat_show_pdf_upload_button_callback'),
6863 - 'mxchat-embed',
6864 - 'mxchat_pdf_intent_section'
1065 + 'top_bar_bg_color',
1066 + 'Top Bar Background Color',
1067 + array($this, 'mxchat_top_bar_bg_color_callback'),
1068 + 'mxchat-theme',
1069 + 'mxchat_theme_section'
6865 1070 );
6866 1071
6867 - // Word Upload Button Toggle
6868 1072 add_settings_field(
6869 - 'show_word_upload_button',
6870 - __('Show Word Upload Button', 'mxchat'),
6871 - array($this, 'mxchat_show_word_upload_button_callback'),
6872 - 'mxchat-embed',
6873 - 'mxchat_pdf_intent_section'
1073 + 'send_button_font_color',
1074 + 'Send Button Color',
1075 + array($this, 'mxchat_send_button_font_color_callback'),
1076 + 'mxchat-theme',
1077 + 'mxchat_theme_section'
6874 1078 );
6875 1079
6876 1080 add_settings_field(
6877 - 'pdf_intent_trigger_text',
6878 - __('Intent Trigger Text', 'mxchat'),
6879 - array($this, 'mxchat_pdf_intent_trigger_text_callback'),
6880 - 'mxchat-embed',
6881 - 'mxchat_pdf_intent_section'
1081 + 'chat_input_font_color',
1082 + 'Chat Input Font Color',
1083 + array($this, 'mxchat_chat_input_font_color_callback'),
1084 + 'mxchat-theme',
1085 + 'mxchat_theme_section'
6882 1086 );
6883 1087
6884 1088 add_settings_field(
6885 - 'pdf_intent_success_text',
6886 - __('Success Text', 'mxchat'),
6887 - array($this, 'mxchat_pdf_intent_success_text_callback'),
6888 - 'mxchat-embed',
6889 - 'mxchat_pdf_intent_section'
1089 + 'chatbot_background_color',
1090 + 'Floating Widget Background Color',
1091 + array($this, 'mxchat_chatbot_background_color_callback'),
1092 + 'mxchat-theme',
1093 + 'mxchat_theme_section'
6890 1094 );
6891 1095
6892 1096 add_settings_field(
6893 - 'pdf_intent_error_text',
6894 - __('Error Text', 'mxchat'),
6895 - array($this, 'mxchat_pdf_intent_error_text_callback'),
6896 - 'mxchat-embed',
6897 - 'mxchat_pdf_intent_section'
1097 + 'icon_color',
1098 + 'Chatbot Icon Color',
1099 + array($this, 'mxchat_icon_color_callback'),
1100 + 'mxchat-theme',
1101 + 'mxchat_theme_section'
6898 1102 );
6899 1103
6900 - // Add PDF Maximum Pages Field
6901 - add_settings_field(
6902 - 'pdf_max_pages',
6903 - __('Maximum Document Pages', 'mxchat'),
6904 - array($this, 'mxchat_pdf_max_pages_callback'),
6905 - 'mxchat-embed',
6906 - 'mxchat_pdf_intent_section'
6907 - );
6908 -
6909 - // Live Agent Settings Fields
6910 - add_settings_section(
6911 - 'mxchat_live_agent_section',
6912 - __('Live Agent Settings', 'mxchat'),
6913 - array($this, 'mxchat_live_agent_section_callback'),
6914 - 'mxchat-embed'
6915 - );
6916 -
6917 - // Live Agent Status Fields (add at top of live agent settings)
6918 - add_settings_field(
6919 - 'live_agent_status',
6920 - __('Live Agent Status', 'mxchat'),
6921 - array($this, 'mxchat_live_agent_status_callback'),
6922 - 'mxchat-embed',
6923 - 'mxchat_live_agent_section'
6924 - );
6925 -
6926 - // Slack availability schedule (plans 8ccaa2 + 99d7a4). Each handoff channel
6927 - // owns an independent schedule rendered under its own Integrations tab; this
6928 - // one governs Slack only. Same callback as Telegram's, parameterized.
6929 - add_settings_field(
6930 - 'live_agent_schedule_slack',
6931 - __('Availability Schedule', 'mxchat'),
6932 - array($this, 'mxchat_live_agent_schedule_callback'),
6933 - 'mxchat-embed',
6934 - 'mxchat_live_agent_section',
6935 - array('channel' => 'slack')
6936 - );
6937 -
6938 - add_settings_field(
6939 - 'live_agent_notification_message',
6940 - __('Notification Message', 'mxchat'),
6941 - array($this, 'mxchat_live_agent_notification_message_callback'),
6942 - 'mxchat-embed',
6943 - 'mxchat_live_agent_section'
6944 - );
6945 -
6946 - add_settings_field(
6947 - 'live_agent_away_message',
6948 - __('Away Message', 'mxchat'),
6949 - array($this, 'mxchat_live_agent_away_message_callback'),
6950 - 'mxchat-embed',
6951 - 'mxchat_live_agent_section'
6952 - );
6953 -
6954 - add_settings_field(
6955 - 'live_agent_user_ids',
6956 - __('Slack Agent User IDs', 'mxchat'),
6957 - array($this, 'mxchat_live_agent_user_ids_callback'),
6958 - 'mxchat-embed',
6959 - 'mxchat_live_agent_section'
6960 - );
6961 -
6962 - // Shared handoff channel (plan 9f7756): route every handoff into one
6963 - // pre-existing channel as threads instead of creating chat-* channels.
6964 - add_settings_field(
6965 - 'live_agent_shared_channel',
6966 - __('Shared Handoff Channel', 'mxchat'),
6967 - array($this, 'mxchat_live_agent_shared_channel_callback'),
6968 - 'mxchat-embed',
6969 - 'mxchat_live_agent_section'
6970 - );
6971 -
6972 - // Auto-archive per-conversation chat- channels on !endchat (plan 7458a7).
6973 - // Default OFF; never touches the shared handoff channel.
6974 - add_settings_field(
6975 - 'live_agent_archive_on_end_toggle',
6976 - __('Archive Channel When Chat Ends', 'mxchat'),
6977 - array($this, 'mxchat_live_agent_archive_on_end_callback'),
6978 - 'mxchat-embed',
6979 - 'mxchat_live_agent_section'
6980 - );
6981 -
6982 - add_settings_field(
6983 - 'live_agent_webhook_url',
6984 - __('Slack Webhook URL', 'mxchat'),
6985 - array($this, 'mxchat_live_agent_webhook_url_callback'),
6986 - 'mxchat-embed',
6987 - 'mxchat_live_agent_section'
6988 - );
6989 -
6990 - add_settings_field(
6991 - 'live_agent_secret_key',
6992 - __('Slack Secret Key', 'mxchat'),
6993 - array($this, 'mxchat_live_agent_secret_key_callback'),
6994 - 'mxchat-embed',
6995 - 'mxchat_live_agent_section'
6996 - );
6997 -
6998 - // Live Agent Integration Fields
6999 - add_settings_field(
7000 - 'live_agent_bot_token',
7001 - __('Slack Bot OAuth Token', 'mxchat'),
7002 - array($this, 'mxchat_live_agent_bot_token_callback'),
7003 - 'mxchat-embed',
7004 - 'mxchat_live_agent_section'
7005 - );
7006 -
7007 - // Telegram Integration Section
7008 - add_settings_section(
7009 - 'mxchat_telegram_section',
7010 - __('Telegram Settings', 'mxchat'),
7011 - array($this, 'mxchat_telegram_section_callback'),
7012 - 'mxchat-embed'
7013 - );
7014 -
7015 - add_settings_field(
7016 - 'telegram_status',
7017 - __('Live Agent Status', 'mxchat'),
7018 - array($this, 'mxchat_telegram_status_callback'),
7019 - 'mxchat-embed',
7020 - 'mxchat_telegram_section'
7021 - );
7022 -
7023 - // Telegram availability schedule (plan 99d7a4) — independent of Slack's,
7024 - // rendered right under the Telegram status toggle it extends.
7025 - add_settings_field(
7026 - 'live_agent_schedule_telegram',
7027 - __('Availability Schedule', 'mxchat'),
7028 - array($this, 'mxchat_live_agent_schedule_callback'),
7029 - 'mxchat-embed',
7030 - 'mxchat_telegram_section',
7031 - array('channel' => 'telegram')
7032 - );
7033 -
7034 - add_settings_field(
7035 - 'telegram_notification_message',
7036 - __('Notification Message', 'mxchat'),
7037 - array($this, 'mxchat_telegram_notification_message_callback'),
7038 - 'mxchat-embed',
7039 - 'mxchat_telegram_section'
7040 - );
7041 -
7042 - add_settings_field(
7043 - 'telegram_away_message',
7044 - __('Away Message', 'mxchat'),
7045 - array($this, 'mxchat_telegram_away_message_callback'),
7046 - 'mxchat-embed',
7047 - 'mxchat_telegram_section'
7048 - );
7049 -
7050 - add_settings_field(
7051 - 'telegram_bot_token',
7052 - __('Telegram Bot Token', 'mxchat'),
7053 - array($this, 'mxchat_telegram_bot_token_callback'),
7054 - 'mxchat-embed',
7055 - 'mxchat_telegram_section'
7056 - );
7057 -
7058 - add_settings_field(
7059 - 'telegram_group_id',
7060 - __('Telegram Group ID', 'mxchat'),
7061 - array($this, 'mxchat_telegram_group_id_callback'),
7062 - 'mxchat-embed',
7063 - 'mxchat_telegram_section'
7064 - );
7065 -
7066 - add_settings_field(
7067 - 'telegram_webhook_secret',
7068 - __('Webhook Secret Token', 'mxchat'),
7069 - array($this, 'mxchat_telegram_webhook_secret_callback'),
7070 - 'mxchat-embed',
7071 - 'mxchat_telegram_section'
7072 - );
7073 -
7074 - // Webhook Handoff Section (plan d88e22) — the third live-agent destination.
7075 - // Outbound-only: handoffs POST to the owner's URL; the chat stays in AI mode.
7076 - add_settings_section(
7077 - 'mxchat_webhook_handoff_section',
7078 - __('Webhook Handoff Settings', 'mxchat'),
7079 - array($this, 'mxchat_webhook_handoff_section_callback'),
7080 - 'mxchat-embed'
7081 - );
7082 -
7083 - add_settings_field(
7084 - 'webhook_handoff_status',
7085 - __('Live Agent Status', 'mxchat'),
7086 - array($this, 'mxchat_webhook_handoff_status_callback'),
7087 - 'mxchat-embed',
7088 - 'mxchat_webhook_handoff_section'
7089 - );
7090 -
7091 - // Webhook availability schedule — independent of Slack's and Telegram's,
7092 - // same parameterized editor (plans 8ccaa2 + 99d7a4 + d88e22).
7093 - add_settings_field(
7094 - 'live_agent_schedule_webhook',
7095 - __('Availability Schedule', 'mxchat'),
7096 - array($this, 'mxchat_live_agent_schedule_callback'),
7097 - 'mxchat-embed',
7098 - 'mxchat_webhook_handoff_section',
7099 - array('channel' => 'webhook')
7100 - );
7101 -
7102 - add_settings_field(
7103 - 'webhook_handoff_notification_message',
7104 - __('Notification Message', 'mxchat'),
7105 - array($this, 'mxchat_webhook_handoff_notification_message_callback'),
7106 - 'mxchat-embed',
7107 - 'mxchat_webhook_handoff_section'
7108 - );
7109 -
7110 - add_settings_field(
7111 - 'webhook_handoff_away_message',
7112 - __('Away Message', 'mxchat'),
7113 - array($this, 'mxchat_webhook_handoff_away_message_callback'),
7114 - 'mxchat-embed',
7115 - 'mxchat_webhook_handoff_section'
7116 - );
7117 -
7118 - add_settings_field(
7119 - 'webhook_handoff_url',
7120 - __('Webhook URL', 'mxchat'),
7121 - array($this, 'mxchat_webhook_handoff_url_callback'),
7122 - 'mxchat-embed',
7123 - 'mxchat_webhook_handoff_section'
7124 - );
7125 -
7126 - add_settings_field(
7127 - 'webhook_handoff_secret',
7128 - __('Signing Secret', 'mxchat'),
7129 - array($this, 'mxchat_webhook_handoff_secret_callback'),
7130 - 'mxchat-embed',
7131 - 'mxchat_webhook_handoff_section'
7132 - );
7133 -
7134 1104 // General Settings Section
7135 1105 add_settings_section(
7136 1106 'mxchat_general_section',
7137 - esc_html__('YouTube Tutorials', 'mxchat'),
1107 + 'Frequently Asked Questions (FAQ)',
7138 1108 null,
7139 1109 'mxchat-general'
7140 1110 );
7141 -}
7142 1111
7143 -public function mxchat_prompts_page_init() {
7144 - register_setting(
7145 - 'mxchat_prompts_options',
7146 - 'mxchat_prompts_options',
7147 - array(
7148 - 'type' => 'array',
7149 - 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
7150 - 'default' => array(
7151 - 'mxchat_auto_sync_posts' => 0,
7152 - 'mxchat_auto_sync_pages' => 0,
7153 - 'mxchat_use_pinecone' => 0,
7154 - 'mxchat_pinecone_api_key' => '',
7155 - 'mxchat_pinecone_environment' => '',
7156 - 'mxchat_pinecone_index' => '',
7157 - 'mxchat_pinecone_host' => '',
7158 - ),
7159 - 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
7160 - )
7161 - );
7162 1112
7163 - add_action('admin_notices', array($this, 'sync_settings_notice'));
7164 1113 }
7165 1114
7166 -public function mxchat_transcripts_page_init() {
7167 - register_setting(
7168 - 'mxchat_transcripts_options',
7169 - 'mxchat_transcripts_options',
7170 - array(
7171 - 'type' => 'array',
7172 - 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
7173 - 'default' => array(
7174 - 'mxchat_enable_notifications' => 0,
7175 - 'mxchat_notification_email' => get_option('admin_email'),
7176 - 'mxchat_auto_delete_transcripts' => 'never',
7177 - ),
7178 - 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
7179 - )
7180 - );
7181 1115
7182 - add_settings_section(
7183 - 'mxchat_transcripts_notification_section',
7184 - esc_html__('Chat Notification Settings', 'mxchat'),
7185 - array($this, 'mxchat_transcripts_notification_section_callback'),
7186 - 'mxchat-transcripts'
7187 - );
7188 1116
7189 - add_settings_field(
7190 - 'mxchat_enable_notifications',
7191 - esc_html__('Enable Chat Notifications', 'mxchat'),
7192 - array($this, 'mxchat_enable_notifications_callback'),
7193 - 'mxchat-transcripts',
7194 - 'mxchat_transcripts_notification_section'
7195 - );
7196 1117
7197 - add_settings_field(
7198 - 'mxchat_notification_email',
7199 - esc_html__('Notification Email Address', 'mxchat'),
7200 - array($this, 'mxchat_notification_email_callback'),
7201 - 'mxchat-transcripts',
7202 - 'mxchat_transcripts_notification_section'
7203 - );
1118 + public function mxchat_handle_activate_license() {
1119 + check_ajax_referer('mxchat_activate_license_nonce', 'security');
7204 1120
7205 - add_settings_field(
7206 - 'mxchat_auto_delete_transcripts',
7207 - esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
7208 - array($this, 'mxchat_auto_delete_transcripts_callback'),
7209 - 'mxchat-transcripts',
7210 - 'mxchat_transcripts_notification_section'
7211 - );
1121 + $license_key = isset($_POST['key']) ? sanitize_text_field($_POST['key']) : '';
1122 + $customer_email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
7212 1123
7213 - add_settings_field(
7214 - 'mxchat_retention_days',
7215 - esc_html__('Custom Retention (Days)', 'mxchat'),
7216 - array($this, 'mxchat_retention_days_callback'),
7217 - 'mxchat-transcripts',
7218 - 'mxchat_transcripts_notification_section'
7219 - );
1124 + if (empty($license_key) || empty($customer_email)) {
1125 + wp_send_json_error('Email or License Key is missing');
1126 + }
7220 1127
7221 - add_settings_field(
7222 - 'mxchat_auto_email_transcript',
7223 - esc_html__('Auto-Email Full Transcript', 'mxchat'),
7224 - array($this, 'mxchat_auto_email_transcript_callback'),
7225 - 'mxchat-transcripts',
7226 - 'mxchat_transcripts_notification_section'
7227 - );
7228 -}
1128 + $product_id = 'MxChatPRO';
7229 1129
1130 + $response = wp_remote_get("http://mxchat.ai/?wc-api=software-api&request=activation&email={$customer_email}&license_key={$license_key}&product_id={$product_id}");
7230 1131
7231 -/**
7232 - * Sanitize all prompts options
7233 - *
7234 - * @param array $input The unsanitized options array
7235 - * @return array The sanitized options array
7236 - */
7237 -public function sanitize_prompts_options($input) {
7238 - // Log the incoming input.
7239 - //error_log('Sanitizing inputs: ' . print_r($input, true));
1132 + if (is_wp_error($response)) {
1133 + wp_send_json_error('Activation failed due to a server error');
1134 + }
7240 1135
7241 - $sanitized = array();
1136 + $body = wp_remote_retrieve_body($response);
1137 + $data = json_decode($body);
7242 1138
7243 - // Boolean options
7244 - $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
7245 - $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
7246 -$sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
7247 -
7248 - // API Key: if less than 32 characters, flag as invalid.
7249 - $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
7250 - if (!empty($api_key) && strlen($api_key) < 32) {
7251 - add_settings_error(
7252 - 'mxchat_prompts_options',
7253 - 'invalid_api_key',
7254 - __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
7255 - );
7256 - $existing_options = get_option('mxchat_prompts_options', array());
7257 - $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
7258 - } else {
7259 - $sanitized['mxchat_pinecone_api_key'] = $api_key;
7260 - }
7261 -
7262 - // Environment and Index Name
7263 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
7264 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
7265 -
7266 - // Host: Remove protocol and validate format.
7267 - $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
7268 - $host = preg_replace('#^https?://#', '', $host);
7269 - //error_log('Host after removing protocol: ' . $host);
7270 - if (!empty($host)) {
7271 - if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
7272 - add_settings_error(
7273 - 'mxchat_prompts_options',
7274 - 'invalid_host',
7275 - __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
7276 - );
7277 - $existing_options = get_option('mxchat_prompts_options', array());
7278 - $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
1139 + if ($data && isset($data->activated) && $data->activated) {
1140 + update_option('mxchat_license_status', 'active');
1141 + wp_send_json_success();
7279 1142 } else {
7280 - $sanitized['mxchat_pinecone_host'] = $host;
1143 + $error_message = isset($data->error) ? $data->error : 'Activation failed';
1144 + update_option('mxchat_license_status', 'inactive');
1145 + update_option('mxchat_license_error', $error_message);
1146 + wp_send_json_error($error_message);
7281 1147 }
7282 - } else {
7283 - $sanitized['mxchat_pinecone_host'] = '';
7284 1148 }
7285 1149
7286 - //error_log('Final sanitized array: ' . print_r($sanitized, true));
7287 1150
7288 - return $sanitized;
7289 -}
1151 +public function mxchat_rate_limit_callback() {
1152 + $rate_limits = array('5', '10', '15', '20', '100');
1153 + $selected_rate_limit = isset($this->options['rate_limit']) ? $this->options['rate_limit'] : '100';
7290 1154
7291 -public function sync_settings_notice() {
7292 - // Only show notice on our plugin page
7293 - if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
7294 - return;
1155 + // Remove the is_activated check and make it always enabled
1156 + echo '<div class="pro-feature-wrapper active">';
1157 + echo '<select id="rate_limit" name="mxchat_options[rate_limit]">';
1158 + foreach ($rate_limits as $limit) {
1159 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7295 1160 }
7296 -
7297 - // Check if settings were updated
7298 - if (isset($_GET['settings-updated'])) {
7299 -
7300 - ?>
7301 - <div class="notice notice-success is-dismissible">
7302 - <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
7303 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
7304 - </div>
7305 - <?php
7306 -
7307 - }
1161 + echo '</select>';
1162 + echo '</div>';
7308 1163 }
7309 -// Add this sanitization function to your class
7310 -public function sanitize_sync_setting($input) {
7311 - return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
7312 -}
7313 1164
7314 -public function mxchat_rate_limits_callback() {
7315 - $all_options = get_option('mxchat_options', []);
7316 1165
7317 - // Define available rate limits
7318 - $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7319 -
7320 - // Define available timeframes
7321 - $timeframes = array(
7322 - 'hourly' => __('Per Hour', 'mxchat'),
7323 - 'daily' => __('Per Day', 'mxchat'),
7324 - 'weekly' => __('Per Week', 'mxchat'),
7325 - 'monthly' => __('Per Month', 'mxchat')
1166 +public function mxchat_rate_limit_message_callback() {
1167 + // Remove the is_activated check and make it always enabled
1168 + echo '<div class="pro-feature-wrapper active">';
1169 + printf(
1170 + '<textarea id="rate_limit_message" name="mxchat_options[rate_limit_message]" rows="3" cols="50">%s</textarea>',
1171 + isset($this->options['rate_limit_message']) ? esc_textarea($this->options['rate_limit_message']) : 'Rate limit exceeded. Please try again later.'
7326 1172 );
7327 -
7328 - // Get all roles plus a "logged_out" pseudo-role
7329 - $roles = wp_roles()->get_names();
7330 - $roles['logged_out'] = __('Logged Out Users', 'mxchat');
7331 -
7332 - // Start the wrapper
7333 - echo '<div class="pro-feature-wrapper active">';
7334 - echo '<div class="mxchat-rate-limits-container">';
7335 -
7336 - echo '<p class="description" style="margin-bottom: 20px;">' .
7337 - 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') .
7338 - '</p>';
7339 -
7340 - // Add markdown link documentation
7341 - echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
7342 - echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
7343 - echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
7344 - echo '<ul style="margin-left: 20px;">';
7345 - echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
7346 - echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
7347 - echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
7348 - echo '</ul>';
7349 1173 echo '</div>';
1174 +}
7350 1175
7351 - // Output the controls for each role
7352 - foreach ($roles as $role_id => $role_name) {
7353 - // Get saved options or defaults
7354 - $default_limit = ($role_id === 'logged_out') ? '10' : '100';
7355 - $default_timeframe = 'daily';
7356 - $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
7357 1176
7358 - $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
7359 - ? $all_options['rate_limits'][$role_id]['limit']
7360 - : $default_limit;
1177 +public function mxchat_enable_woocommerce_integration_callback() {
1178 + $checked = isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1' ? 'checked' : '';
1179 + $disabled = $this->is_activated ? '' : 'disabled';
1180 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7361 1181
7362 - $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
7363 - ? $all_options['rate_limits'][$role_id]['timeframe']
7364 - : $default_timeframe;
1182 + echo '<div class="' . esc_attr($class) . '">';
1183 + echo '<label class="toggle-switch">';
1184 + echo '<input type="checkbox" id="enable_woocommerce_integration" name="mxchat_options[enable_woocommerce_integration]" value="1" ' . $checked . ' ' . $disabled . '>';
1185 + echo '<span class="slider"></span>';
1186 + echo '</label>';
7365 1187
7366 - $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
7367 - ? $all_options['rate_limits'][$role_id]['message']
7368 - : $default_message;
1188 + if (!$this->is_activated) {
1189 + echo '<div class="pro-feature-overlay">';
1190 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1191 + echo '</div>';
1192 + }
7369 1193
7370 - // Output the row
7371 - echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
1194 + echo '</div>';
1195 +}
7372 1196
7373 - // Role label
7374 - echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
7375 1197
7376 - // Controls section
7377 - echo '<div class="mxchat-rate-limit-controls-wrapper">';
1198 +public function mxchat_enable_woocommerce_order_access_callback() {
1199 + $checked = isset($this->options['enable_woocommerce_order_access']) && $this->options['enable_woocommerce_order_access'] === '1' ? 'checked' : '';
1200 + $disabled = $this->is_activated ? '' : 'disabled';
1201 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7378 1202
7379 - // Rate limit and timeframe controls
7380 - echo '<div class="mxchat-rate-limit-controls">';
1203 + echo '<div class="' . esc_attr($class) . '">';
1204 + echo '<label class="toggle-switch">';
1205 + echo '<input type="checkbox" id="enable_woocommerce_order_access" name="mxchat_options[enable_woocommerce_order_access]" value="1" ' . $checked . ' ' . $disabled . '>';
1206 + echo '<span class="slider"></span>';
1207 + echo '</label>';
7381 1208
7382 - // Limit dropdown
7383 - echo '<div>';
7384 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
7385 - echo '<select
7386 - id="rate_limits_' . esc_attr($role_id) . '_limit"
7387 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
7388 - class="mxchat-autosave-field">';
7389 - foreach ($rate_limits as $limit) {
7390 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7391 - }
7392 - echo '</select>';
1209 + if (!$this->is_activated) {
1210 + echo '<div class="pro-feature-overlay">';
1211 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
7393 1212 echo '</div>';
7394 -
7395 - // Timeframe dropdown
7396 - echo '<div>';
7397 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
7398 - echo '<select
7399 - id="rate_limits_' . esc_attr($role_id) . '_timeframe"
7400 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
7401 - class="mxchat-autosave-field">';
7402 - foreach ($timeframes as $value => $label) {
7403 - echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
7404 - }
7405 - echo '</select>';
7406 - echo '</div>';
7407 -
7408 - echo '</div>'; // End controls
7409 -
7410 - // Custom message textarea
7411 - echo '<div class="mxchat-rate-limit-message">';
7412 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
7413 - echo '<textarea
7414 - id="rate_limits_' . esc_attr($role_id) . '_message"
7415 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
7416 - class="mxchat-autosave-field"
7417 - placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
7418 - esc_textarea($custom_message) .
7419 - '</textarea>';
7420 - echo '<p class="description">' .
7421 - esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
7422 - '</p>';
7423 - echo '</div>'; // End message
7424 -
7425 - echo '</div>'; // End controls wrapper
7426 -
7427 - echo '</div>'; // End row
7428 1213 }
7429 1214
7430 - echo '</div>'; // End container
1215 + echo '</div>';
1216 +}
7431 1217
7432 - echo '</div>'; // End pro-feature-wrapper
7433 -}
7434 1218
7435 -private function mxchat_add_option_field($id, $title, $callback = '') {
1219 + private function mxchat_add_option_field($id, $title, $callback = '') {
7436 1220 add_settings_field(
7437 1221 $id,
7438 - __($title, 'mxchat'),
1222 + $title,
7439 1223 $callback ? array($this, $callback) : array($this, $id . '_callback'),
7440 1224 'mxchat-max',
7441 1225 'mxchat_setting_section_id',
7442 1226 $id === 'model' ? ['label_for' => 'model'] : []
@@ -7442,3138 +1226,755 @@
7442 1226 $id === 'model' ? ['label_for' => 'model'] : []
7443 1227 );
7444 1228 }
7445 1229
7446 -// API Keys Section Callback
7447 -public function mxchat_api_keys_section_callback() {
7448 - 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>';
7449 -}
7450 1230
7451 -// OpenAI API Key
7452 -public function api_key_callback() {
7453 - $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
7454 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1231 + public function api_key_callback() {
1232 + $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
1233 + echo '<input type="password" id="api_key" name="mxchat_options[api_key]" value="' . $apiKey . '" class="regular-text" />';
1234 + echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
1235 + }
7455 1236
7456 - echo '<div class="api-key-wrapper">';
7457 - 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 . '" />';
7458 - echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7459 - echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
7460 - echo $this->mxchat_provider_key_test_button('openai', 'api_key');
7461 - echo '</div>';
7462 -}
7463 1237
7464 -// X.AI API Key
7465 -public function xai_api_key_callback() {
7466 - $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
7467 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7468 1238
7469 - echo '<div class="api-key-wrapper">';
7470 - 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 . '" />';
7471 - echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7472 - echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
7473 - echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key');
7474 - echo '</div>';
7475 -}
7476 -// Claude API Key
7477 -public function claude_api_key_callback() {
7478 - $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
7479 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1239 +public function mxchat_woocommerce_consumer_key_callback() {
1240 + $disabled = $this->is_activated ? '' : 'disabled';
1241 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7480 1242
7481 - echo '<div class="api-key-wrapper">';
7482 - 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 . '" />';
7483 - echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7484 - echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
7485 - echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key');
7486 - echo '</div>';
7487 -}
1243 + echo '<div class="' . esc_attr($class) . '">';
1244 + printf(
1245 + '<input type="text" id="woocommerce_consumer_key" name="mxchat_options[woocommerce_consumer_key]" value="%s" class="regular-text" %s />',
1246 + isset($this->options['woocommerce_consumer_key']) ? esc_attr($this->options['woocommerce_consumer_key']) : '',
1247 + $disabled
1248 + );
7488 1249
7489 -// DeepSeek API Key
7490 -public function deepseek_api_key_callback() {
7491 - $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
7492 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1250 + if (!$this->is_activated) {
1251 + echo '<div class="pro-feature-overlay">';
1252 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1253 + echo '</div>';
1254 + }
7493 1255
7494 - echo '<div class="api-key-wrapper">';
7495 - 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 . '" />';
7496 - echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7497 - echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
7498 - echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key');
7499 1256 echo '</div>';
7500 1257 }
7501 1258
7502 -// Gemini API Key
7503 -public function gemini_api_key_callback() {
7504 - $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
7505 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1259 +public function mxchat_woocommerce_consumer_secret_callback() {
1260 + $disabled = $this->is_activated ? '' : 'disabled';
1261 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7506 1262
7507 - echo '<div class="api-key-wrapper">';
7508 - 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 . '" />';
7509 - echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7510 - echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
7511 - echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key');
7512 - echo '</div>';
7513 -}
1263 + echo '<div class="' . esc_attr($class) . '">';
1264 + printf(
1265 + '<input type="password" id="woocommerce_consumer_secret" name="mxchat_options[woocommerce_consumer_secret]" value="%s" class="regular-text" %s />',
1266 + isset($this->options['woocommerce_consumer_secret']) ? esc_attr($this->options['woocommerce_consumer_secret']) : '',
1267 + $disabled
1268 + );
1269 + echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';
7514 1270
7515 -
7516 -// OpenRouter API Key
7517 -public function openrouter_api_key_callback() {
7518 - $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
7519 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7520 -
7521 - echo '<div class="api-key-wrapper">';
7522 - 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 . '" />';
7523 - echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7524 - echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
7525 - echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key');
7526 - echo '</div>';
7527 -}
7528 -
7529 -/**
7530 - * Renders a "Test key" button + result target next to a built-in provider key
7531 - * field, and emits the shared delegated click handler ONCE (static guard). The
7532 - * button carries data-target = the key field id so the owner can test the value
7533 - * they just typed (test-before-save); the AJAX handler falls back to the saved
7534 - * key when the field is empty. Styled with the WP `button` class to match the
7535 - * adjacent Custom-provider "Test Connection" button on this same page.
7536 - * plan-mxchat-20260623-c41f74.
7537 - */
7538 -public function mxchat_provider_key_test_button($provider, $target_id) {
7539 - static $script_emitted = false;
7540 - $nonce = wp_create_nonce('mxchat_test_provider_key');
7541 - $html = '<div class="mxchat-key-test" style="margin-top:8px;">'
7542 - . '<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>'
7543 - . '<span class="mxchat-test-provider-key-result" style="margin-left:10px;font-size:13px;vertical-align:middle;"></span>'
7544 - . '</div>';
7545 - if (!$script_emitted) {
7546 - $script_emitted = true;
7547 - $html .= $this->mxchat_provider_key_test_script();
1271 + if (!$this->is_activated) {
1272 + echo '<div class="pro-feature-overlay">';
1273 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1274 + echo '</div>';
7548 1275 }
7549 - return $html;
7550 -}
7551 1276
7552 -/**
7553 - * One-time delegated click handler shared by every .mxchat-test-provider-key
7554 - * button. Posts the typed key value + provider to mxchat_test_provider_key and
7555 - * renders the success/error message inline. Mirrors the Custom-provider test.
7556 - */
7557 -private function mxchat_provider_key_test_script() {
7558 - $t_testing = esc_js(__('Testing...', 'mxchat'));
7559 - $t_valid = esc_js(__('Key is valid.', 'mxchat'));
7560 - $t_failed = esc_js(__('Failed', 'mxchat'));
7561 - $t_req = esc_js(__('Request failed', 'mxchat'));
7562 - return '<script>(function(){'
7563 - . 'if (window.__mxchatProviderKeyTestWired) { return; }'
7564 - . 'window.__mxchatProviderKeyTestWired = true;'
7565 - . 'document.addEventListener("click", function(e){'
7566 - . 'var btn = e.target && e.target.closest ? e.target.closest(".mxchat-test-provider-key") : null;'
7567 - . 'if (!btn) { return; }'
7568 - . 'e.preventDefault();'
7569 - . 'var field = btn.getAttribute("data-target") ? document.getElementById(btn.getAttribute("data-target")) : null;'
7570 - . 'var out = btn.parentNode ? btn.parentNode.querySelector(".mxchat-test-provider-key-result") : null;'
7571 - . 'if (out) { out.textContent = "' . $t_testing . '"; out.style.color = "#646970"; }'
7572 - . 'btn.disabled = true;'
7573 - . 'var fd = new FormData();'
7574 - . 'fd.append("action", "mxchat_test_provider_key");'
7575 - . 'fd.append("_wpnonce", btn.getAttribute("data-nonce"));'
7576 - . 'fd.append("provider", btn.getAttribute("data-provider") || "");'
7577 - . 'fd.append("key", field ? field.value : "");'
7578 - . 'fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })'
7579 - . '.then(function(r){ return r.json(); })'
7580 - . '.then(function(j){'
7581 - . 'if (out) {'
7582 - . 'if (j && j.success) { out.textContent = "✓ " + ((j.data && j.data.message) ? j.data.message : "' . $t_valid . '"); out.style.color = "#00a32a"; }'
7583 - . 'else { out.textContent = "⚠ " + ((j && j.data && j.data.message) ? j.data.message : "' . $t_failed . '"); out.style.color = "#d63638"; }'
7584 - . '}'
7585 - . 'btn.disabled = false;'
7586 - . '})'
7587 - . '.catch(function(){ if (out) { out.textContent = "⚠ ' . $t_req . '"; out.style.color = "#d63638"; } btn.disabled = false; });'
7588 - . '});'
7589 - . '})();</script>';
7590 -}
7591 -
7592 -// Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
7593 -public function custom_provider_callback() {
7594 - $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
7595 - $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
7596 - $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
7597 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
7598 - $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
7599 - $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
7600 - $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
7601 - $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
7602 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7603 - $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
7604 -
7605 - echo '<style>
7606 - .mxchat-cp { max-width: 680px; }
7607 - .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
7608 - .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
7609 - .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
7610 - .mxchat-cp .mxchat-cp-row > input[type="text"],
7611 - .mxchat-cp .mxchat-cp-row > input[type="password"],
7612 - .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
7613 - .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
7614 - .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
7615 - .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
7616 - .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; }
7617 - .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; }
7618 - .mxchat-cp .mxchat-cp-azure ol { margin: 0; padding: 0 0 0 18px; color: #50575e; font-size: 12px; line-height: 1.7; }
7619 - .mxchat-cp .mxchat-cp-azure code { background: #eceefb; padding: 1px 5px; border-radius: 3px; font-size: 11px; }
7620 - </style>';
7621 -
7622 - echo '<div class="api-key-wrapper mxchat-cp">';
7623 - 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>';
7624 -
7625 - // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout
7626 - // so admins can configure Azure without piecing it together from each field's hint.
7627 - echo '<div class="mxchat-cp-azure">';
7628 - echo '<span class="mxchat-cp-azure-title">' . esc_html__('Azure OpenAI quick start', 'mxchat') . '</span>';
7629 - echo '<ol>';
7630 - 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>';
7631 - echo '<li>' . wp_kses(__('<strong>API Key</strong> → your Azure OpenAI key (required)', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7632 - echo '<li>' . wp_kses(__('<strong>Auth Scheme</strong> → <code>api-key header (Azure OpenAI)</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7633 - 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>';
7634 - echo '</ol>';
7635 1277 echo '</div>';
7636 -
7637 - echo '<div class="mxchat-cp-row">';
7638 - echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
7639 - 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 . '" />';
7640 - 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>';
7641 - echo '</div>';
7642 -
7643 - echo '<div class="mxchat-cp-row">';
7644 - echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
7645 - 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 . '" />';
7646 - echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
7647 - echo '</div>';
7648 -
7649 - echo '<div class="mxchat-cp-row">';
7650 - echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
7651 - 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 . '" />';
7652 - 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>';
7653 - echo '</div>';
7654 -
7655 - echo '<div class="mxchat-cp-row">';
7656 - echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
7657 - echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7658 - echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
7659 - echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
7660 - echo '</select>';
7661 - echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
7662 - echo '</div>';
7663 -
7664 - echo '<div class="mxchat-cp-row">';
7665 - echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
7666 - 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 . '" />';
7667 - 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>';
7668 - echo '</div>';
7669 -
7670 - // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
7671 - echo '<div class="mxchat-cp-row">';
7672 - 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>';
7673 - 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>';
7674 - 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>';
7675 - 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>';
7676 - echo '</div>';
7677 -
7678 - echo '<div class="mxchat-cp-row">';
7679 - echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
7680 - 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 . '" />';
7681 - 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>';
7682 - echo '</div>';
7683 -
7684 - echo '<div class="mxchat-cp-test">';
7685 - echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
7686 - echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
7687 - echo '</div>';
7688 -
7689 - echo '<script>(function(){
7690 - var btn = document.getElementById("mxchat-test-custom-provider");
7691 - if (!btn || btn._wired) { return; } btn._wired = true;
7692 - btn.addEventListener("click", function(){
7693 - var out = document.getElementById("mxchat-test-custom-provider-result");
7694 - out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
7695 - out.style.color = "#646970";
7696 - var fd = new FormData();
7697 - fd.append("action", "mxchat_test_custom_provider");
7698 - fd.append("_wpnonce", btn.getAttribute("data-nonce"));
7699 - fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
7700 - .then(function(r){ return r.json(); })
7701 - .then(function(j){
7702 - if (j && j.success) {
7703 - out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
7704 - out.style.color = "#00a32a";
7705 - } else {
7706 - out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
7707 - out.style.color = "#d63638";
7708 - }
7709 - })
7710 - .catch(function(){
7711 - out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
7712 - out.style.color = "#d63638";
7713 - });
7714 - });
7715 - })();</script>';
7716 -
7717 - echo '</div>';
7718 1278 }
7719 1279
7720 -// Voyage API Key
7721 -public function voyage_api_key_callback() {
7722 - $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
7723 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7724 1280
7725 - echo '<div class="api-key-wrapper">';
7726 - 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 . '" />';
7727 - echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7728 - echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
7729 - echo '</div>';
7730 -}
7731 1281
7732 1282 public function mxchat_loops_api_key_callback() {
7733 1283 $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7734 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7735 1284
7736 1285 echo '<div class="api-key-wrapper">';
7737 - echo sprintf(
7738 - '<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" />',
7739 - $loops_api_key,
7740 - $nonce
1286 + printf(
1287 + '<input type="password" id="loops_api_key" name="mxchat_options[loops_api_key]" value="%s" class="regular-text" />',
1288 + $loops_api_key
7741 1289 );
7742 - echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
1290 + echo '<button type="button" id="toggleLoopsApiKeyVisibility">Show</button>';
7743 1291 echo '</div>';
7744 - // Cross-reference back to where the list is chosen, so the two screens point
7745 - // at each other (plan-mxchat-20260802-907a63).
7746 - echo '<p class="description">' . wp_kses(
7747 - sprintf(
7748 - /* translators: %s: link to the Loops integration tab. */
7749 - __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'),
7750 - '<a href="#integrations-loops">' . esc_html__('Integrations, Loops', 'mxchat') . '</a>'
7751 - ),
7752 - self::mxchat_loops_pointer_allowed_html()
7753 - ) . '</p>';
1292 + echo '<p class="description">Enter your Loops API Key here. (See FAQ for details)</p>';
7754 1293 }
7755 -public function mxchat_loops_mailing_list_callback() {
7756 - // Add error handling and type checking
7757 - $loops_api_key = '';
7758 - $selected_list = '';
7759 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7760 1294
7761 - // Safely get the API key
7762 - if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
7763 - $loops_api_key = $this->options['loops_api_key'];
7764 - }
7765 1295
7766 - // Safely get the selected list
7767 - if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
7768 - $selected_list = $this->options['loops_mailing_list'];
7769 - }
1296 +public function mxchat_loops_mailing_list_callback() {
1297 + // Retrieve Loops API key and lists
1298 + $loops_api_key = isset($this->options['loops_api_key']) ? $this->options['loops_api_key'] : '';
1299 + $selected_list = isset($this->options['loops_mailing_list']) ? $this->options['loops_mailing_list'] : '';
7770 1300
7771 - if (!empty($loops_api_key)) {
1301 + if ($loops_api_key) {
1302 + // Fetch lists from Loops API
7772 1303 $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7773 - if (is_array($lists) && !empty($lists)) {
7774 - echo '<div class="mxchat-field-wrapper">';
7775 - echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7776 1304
7777 - // Add a default "Select a list" option
7778 - echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
7779 -
1305 + if ($lists) {
1306 + echo '<select id="loops_mailing_list" name="mxchat_options[loops_mailing_list]">';
7780 1307 foreach ($lists as $list) {
7781 - if (is_array($list) && isset($list['id']) && isset($list['name'])) {
7782 - echo sprintf(
7783 - '<option value="%s" %s>%s</option>',
7784 - esc_attr($list['id']),
7785 - selected($selected_list, $list['id'], false),
7786 - esc_html($list['name'])
7787 - );
7788 - }
1308 + echo '<option value="' . esc_attr($list['id']) . '" ' . selected($selected_list, $list['id'], false) . '>' . esc_html($list['name']) . '</option>';
7789 1309 }
7790 1310 echo '</select>';
7791 - echo '</div>';
7792 - echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
7793 1311 } else {
7794 - echo '<p class="description">' . wp_kses(
7795 - self::mxchat_loops_api_key_pointer(
7796 - /* translators: %s: link to the API Keys tab. */
7797 - __('No lists found. Please check your Loops API key under %s.', 'mxchat')
7798 - ),
7799 - self::mxchat_loops_pointer_allowed_html()
7800 - ) . '</p>';
1312 + echo '<p class="description">No lists found. Please verify your API Key.</p>';
7801 1313 }
7802 1314 } else {
7803 - echo '<p class="description">' . wp_kses(
7804 - self::mxchat_loops_api_key_pointer(
7805 - /* translators: %s: link to the API Keys tab. */
7806 - __('Enter your Loops API key under %s to load mailing lists.', 'mxchat')
7807 - ),
7808 - self::mxchat_loops_pointer_allowed_html()
7809 - ) . '</p>';
1315 + echo '<p class="description">Enter a valid Loops API Key to load mailing lists.</p>';
7810 1316 }
7811 1317 }
7812 1318
7813 -/**
7814 - * Build the "API Keys" pointer used by the Loops mailing-list field.
7815 - *
7816 - * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API
7817 - * Keys tab, but this field's copy still read as though the input were beside
7818 - * it, so users had nowhere to go. Both live on the SAME screen
7819 - * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this
7820 - * dropdown under Integrations > Loops — so the pointer is an in-page tab
7821 - * switch, not a cross-page link.
7822 - *
7823 - * A plain href="#api-keys" is all it takes: the shared admin shell
7824 - * (js/admin-sidebar.js) honours section-naming hashes on load AND on
7825 - * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old
7826 - * data-target workaround on these pointer anchors is gone.
7827 - *
7828 - * @param string $template Translatable string containing one %s placeholder.
7829 - * @return string
7830 - */
7831 -private static function mxchat_loops_api_key_pointer($template) {
7832 - return sprintf(
7833 - $template,
7834 - '<a href="#api-keys">' . esc_html__('API Keys', 'mxchat') . '</a>'
7835 - );
1319 +public function mxchat_trigger_keywords_callback() {
1320 + $trigger_keywords = isset($this->options['trigger_keywords']) ? $this->options['trigger_keywords'] : '';
1321 + echo '<input type="text" id="trigger_keywords" name="mxchat_options[trigger_keywords]" value="' . esc_attr($trigger_keywords) . '">';
1322 + echo '<p class="description">Enter comma-separated trigger keywords (e.g., subscribe, discount, newsletter).</p>';
7836 1323 }
7837 1324
7838 -/**
7839 - * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook.
7840 - */
7841 -private static function mxchat_loops_pointer_allowed_html() {
7842 - return array(
7843 - 'a' => array(
7844 - 'href' => array(),
7845 - 'data-target' => array(),
7846 - ),
7847 - );
1325 +public function mxchat_triggered_phrase_response_callback() {
1326 + $triggered_response = isset($this->options['triggered_phrase_response']) ? $this->options['triggered_phrase_response'] : '';
1327 + echo '<textarea id="triggered_phrase_response" name="mxchat_options[triggered_phrase_response]" rows="3" cols="50">' . esc_textarea($triggered_response) . '</textarea>';
1328 + echo '<p class="description">Enter the chatbot response when a trigger keyword is detected, prompting the user to share their email.</p>';
7848 1329 }
7849 -public function mxchat_triggered_phrase_response_callback() {
7850 - $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
7851 - $triggered_response = isset($this->options['triggered_phrase_response'])
7852 - ? $this->options['triggered_phrase_response']
7853 - : $default_response;
7854 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7855 1330
7856 - echo '<div class="mxchat-field-wrapper">';
7857 - echo sprintf(
7858 - '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7859 - $nonce,
7860 - esc_textarea($triggered_response)
7861 - );
7862 - echo '</div>';
7863 - 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>';
7864 -}
7865 1331
7866 1332 public function mxchat_email_capture_response_callback() {
7867 - $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
7868 - $email_capture_response = isset($this->options['email_capture_response'])
7869 - ? $this->options['email_capture_response']
7870 - : $default_response;
7871 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7872 -
7873 - echo '<div class="mxchat-field-wrapper">';
7874 - echo sprintf(
7875 - '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7876 - $nonce,
7877 - esc_textarea($email_capture_response)
7878 - );
7879 - echo '</div>';
7880 - 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>';
1333 + $email_capture_response = isset($this->options['email_capture_response']) ? $this->options['email_capture_response'] : 'Thank you for providing your email! You\'ve been added to our list.';
1334 + echo '<textarea id="email_capture_response" name="mxchat_options[email_capture_response]" rows="3" cols="50">' . esc_textarea($email_capture_response) . '</textarea>';
1335 + echo '<p class="description">Enter the message to send when a user provides their email.</p>';
7881 1336 }
7882 -public function mxchat_pre_chat_message_callback() {
7883 - // Load the entire 'mxchat_options' array
7884 - $all_options = get_option('mxchat_options', []);
7885 1337
7886 - // Retrieve the saved message or use the default value
7887 - $default_message = __('Hey there! Ask me anything!', 'mxchat');
7888 - $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
7889 1338
7890 - // Output the textarea
7891 - printf(
7892 - '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
7893 - esc_textarea($pre_chat_message)
7894 - );
7895 -}
1339 + public function mxchat_pre_chat_message_callback() {
1340 + printf(
1341 + '<textarea id="pre_chat_message" name="mxchat_options[pre_chat_message]" rows="5" cols="50">%s</textarea>',
1342 + isset($this->options['pre_chat_message']) ? esc_textarea($this->options['pre_chat_message']) : ''
1343 + );
1344 + }
7896 1345
7897 -// Callback for AI Instructions textarea
7898 -public function system_prompt_instructions_callback() {
7899 - // Retrieve the current value of the system prompt instructions
7900 - $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
7901 - // Render the textarea field
7902 - printf(
7903 - '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
7904 - $instructions
7905 - );
7906 - // Personalization hint
7907 - echo '<p class="description" style="margin-top: 8px;">';
7908 - echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
7909 - echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
7910 - echo '</p>';
7911 - // Sample instructions button
7912 - echo '<div class="mxchat-instructions-container">';
7913 - echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
7914 - 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">';
7915 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7916 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7917 - echo '</svg>';
7918 - echo esc_html__('View Sample Instructions', 'mxchat');
7919 - echo '</button>';
7920 - echo '</div>';
7921 -
7922 - // Add modal to WordPress admin footer instead of inline
7923 - add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
7924 -}
7925 -
7926 -// New method to render modal in admin footer
7927 -public function render_sample_instructions_modal() {
7928 - static $modal_rendered = false;
7929 - if ($modal_rendered) return; // Prevent duplicate modals
7930 - $modal_rendered = true;
7931 -
7932 - echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
7933 - echo '<div class="mxchat-instructions-modal-content">';
7934 - echo '<div class="mxchat-instructions-modal-header">';
7935 - echo '<h3 class="mxchat-instructions-modal-title">';
7936 - 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">';
7937 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7938 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7939 - echo '</svg>';
7940 - echo esc_html__('Sample AI Instructions', 'mxchat');
7941 - echo '</h3>';
7942 - echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
7943 - 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">';
7944 - echo '<line x1="18" y1="6" x2="6" y2="18"/>';
7945 - echo '<line x1="6" y1="6" x2="18" y2="18"/>';
7946 - echo '</svg>';
7947 - echo '</button>';
7948 - echo '</div>';
7949 - echo '<div class="mxchat-instructions-modal-body">';
7950 - echo '<div class="mxchat-instructions-content">';
7951 - 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:
7952 -
7953 -# Response Style - CRITICALLY IMPORTANT
7954 -- MAXIMUM LENGTH: 1-3 short sentences per response
7955 -- Ultra-concise: Get straight to the answer with no filler
7956 -- No introductions like "Sure!" or "I\'d be happy to help"
7957 -- No phrases like "based on my knowledge" or "according to information"
7958 -- No explanatory text before giving the answer
7959 -- No summaries or repetition
7960 -- Hyperlink all URLs
7961 -- Respond in user\'s language
7962 -- Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
7963 -
7964 -# Knowledge Base Requirements - PREVENT HALLUCINATIONS
7965 -- ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
7966 -- If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
7967 -- NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
7968 -- When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
7969 -- Better to admit insufficient information than provide inaccurate answers');
7970 - echo '</div>';
7971 - echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
7972 - 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">';
7973 - echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
7974 - echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
7975 - echo '</svg>';
7976 - echo esc_html__('Copy Instructions', 'mxchat');
7977 - echo '</button>';
7978 - echo '</div>';
7979 - echo '<div class="mxchat-instructions-modal-footer">';
7980 - echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
7981 - echo '</div>';
7982 - echo '</div>';
7983 - echo '</div>';
7984 -}
7985 -
7986 -
7987 -public function mxchat_model_callback() {
7988 - // Catalog refactor (plan-d14e89): single source of truth lives in
7989 - // includes/class-mxchat-model-catalog.php. Dropdown groups are the
7990 - // provider labels; each group maps model_id => "Label" strings.
7991 - if (!class_exists('MxChat_Model_Catalog')) {
7992 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1346 + // Callback for AI Instructions textarea
1347 + public function system_prompt_instructions_callback() {
1348 + printf(
1349 + '<textarea id="system_prompt_instructions" name="mxchat_options[system_prompt_instructions]" rows="5" cols="50">%s</textarea>',
1350 + isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''
1351 + );
7993 1352 }
7994 - // Retrieve the currently selected model from saved options
7995 - $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.6-sol';
7996 1353
7997 - // Pass the saved model so a provider-retired id keeps rendering as the
7998 - // current selection instead of a blank select (plan e46b8f).
7999 - $models = MxChat_Model_Catalog::settings_dropdown_groups($selected_model);
1354 + public function mxchat_model_callback() {
1355 + $models = array(
1356 + 'gpt-4o' => 'gpt-4o',
1357 + 'gpt-4o-mini' => 'gpt-4o-mini',
1358 + 'gpt-4-turbo' => 'gpt-4-turbo',
1359 + 'gpt-4' => 'gpt-4',
1360 + 'gpt-3.5-turbo' => 'gpt-3.5-turbo',
1361 + );
8000 1362
8001 - // Begin the select dropdown
8002 - echo '<select id="model" name="model">';
1363 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';
8003 1364
8004 - // Iterate over groups of models
8005 - foreach ($models as $group_label => $group_models) {
8006 - echo '<optgroup label="' . esc_attr($group_label) . '">';
8007 -
8008 - foreach ($group_models as $model_value => $model_label) {
1365 + echo '<select id="model" name="mxchat_options[model]">';
1366 + foreach ($models as $model_value => $model_label) {
8009 1367 echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
8010 1368 }
8011 -
8012 - echo '</optgroup>';
1369 + echo '</select>';
8013 1370 }
8014 1371
8015 - echo '</select>';
8016 -
8017 - // Add a note for OpenRouter
8018 - echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
8019 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
8020 - echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
8021 - echo '</p>';
8022 -
8023 - // API Key Status Messages (hidden by default, shown by JS based on selected model)
8024 - $has_openai_key = !empty($this->options['api_key']);
8025 - $has_claude_key = !empty($this->options['claude_api_key']);
8026 - $has_xai_key = !empty($this->options['xai_api_key']);
8027 - $has_deepseek_key = !empty($this->options['deepseek_api_key']);
8028 - $has_gemini_key = !empty($this->options['gemini_api_key']);
8029 - $has_openrouter_key = !empty($this->options['openrouter_api_key']);
8030 -
8031 - // OpenAI/GPT models
8032 - echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
8033 - if ($has_openai_key) {
8034 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8035 - } else {
8036 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1372 + public function mxchat_top_bar_title_callback() {
1373 + printf(
1374 + '<input type="text" id="top_bar_title" name="mxchat_options[top_bar_title]" value="%s" />',
1375 + isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : ''
1376 + );
8037 1377 }
8038 - echo '</p>';
8039 1378
8040 - // Claude models
8041 - echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
8042 - if ($has_claude_key) {
8043 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
8044 - } else {
8045 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1379 + public function mxchat_intro_message_callback() {
1380 + printf(
1381 + '<textarea id="intro_message" name="mxchat_options[intro_message]" rows="5" cols="50">%s</textarea>',
1382 + isset($this->options['intro_message']) ? esc_textarea($this->options['intro_message']) : 'Hello! How can I assist you today?'
1383 + );
8046 1384 }
8047 - echo '</p>';
8048 1385
8049 - // X.AI models
8050 - echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
8051 - if ($has_xai_key) {
8052 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
8053 - } else {
8054 - 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>';
1386 + public function mxchat_input_copy_callback() {
1387 + printf(
1388 + '<input type="text" id="input_copy" name="mxchat_options[input_copy]" value="%s" placeholder="How can I assist?" />',
1389 + isset($this->options['input_copy']) ? esc_attr($this->options['input_copy']) : 'How can I assist?'
1390 + );
1391 + echo '<p class="description">This is the placeholder text for the chat input field.</p>';
8055 1392 }
8056 - echo '</p>';
8057 1393
8058 - // DeepSeek models
8059 - echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
8060 - if ($has_deepseek_key) {
8061 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
8062 - } else {
8063 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8064 - }
8065 - echo '</p>';
8066 1394
8067 - // Gemini models
8068 - echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
8069 - if ($has_gemini_key) {
8070 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8071 - } else {
8072 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8073 - }
8074 - echo '</p>';
8075 1395
8076 - // OpenRouter models
8077 - echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
8078 - if ($has_openrouter_key) {
8079 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
8080 - } else {
8081 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8082 - }
8083 - echo '</p>';
8084 1396
8085 - // ADD THESE HIDDEN FIELDS RIGHT HERE:
8086 - $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
8087 - $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
8088 1397
8089 - echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
8090 - echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
8091 -}
8092 1398
8093 -// Update your existing callback method
8094 -public function enable_streaming_toggle_callback() {
8095 - // Get value from options array, default to 'on'
8096 - $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
8097 - $checked = ($enabled === 'on') ? 'checked' : '';
1399 + public function mxchat_close_button_color_callback() {
1400 + $disabled = $this->is_activated ? '' : 'disabled';
8098 1401
8099 - echo '<label class="toggle-switch">';
8100 - echo sprintf(
8101 - '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
8102 - esc_attr($checked)
1402 + echo '<div class="pro-feature-wrapper">';
1403 + printf(
1404 + '<input type="text" id="close_button_color" name="mxchat_options[close_button_color]" value="%s" class="my-color-field" data-default-color="#4a4a4a" %s />',
1405 + isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '',
1406 + esc_attr($disabled)
8103 1407 );
8104 - echo '<span class="slider"></span>';
8105 - echo '</label>';
8106 1408
8107 - // Test button — branded .mxch-btn with inline SVG (IDs preserved for AJAX binding)
8108 - echo '<div class="mxch-streaming-test-row">';
8109 - echo '<button type="button" id="mxchat-test-streaming-btn" class="mxch-btn mxch-btn-secondary">';
8110 - 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>';
8111 - echo esc_html__('Test Streaming Compatibility', 'mxchat');
8112 - echo '</button>';
8113 - echo '<p id="mxchat-test-streaming-result" class="mxch-streaming-test-result"></p>';
8114 - echo '</div>';
8115 -}
8116 -
8117 -// Web Search toggle callback
8118 -public function enable_web_search_toggle_callback() {
8119 - // Get value from options array, default to 'off'
8120 - $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
8121 - $checked = ($enabled === 'on') ? 'checked' : '';
8122 -
8123 - // Get current model to determine if we should show/enable the toggle
8124 - $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
8125 -
8126 - // Models that DON'T support web search — OpenAI-docs-driven exception list.
8127 - // Keep hardcoded; the catalog can't infer "supports web search" per-model, so any
8128 - // future OpenAI model that lacks Responses-API web_search support is added here.
8129 - $unsupported_models = array('gpt-4.1-nano');
8130 -
8131 - // Web-search-capable chat-model allowlists, derived from the central model catalog
8132 - // (class-mxchat-model-catalog.php). When a new OpenAI/Gemini chat model is added there,
8133 - // the Web Search toggle picks it up automatically — no edit here.
8134 - // OpenAI grounds via the Responses-API web_search tool; Gemini grounds natively via the
8135 - // Google Search tool (plan 46b9ea wired the Gemini dispatch — every shipped Gemini chat
8136 - // model is 2.x/3.x and grounds, matching that path's empty opt-out list, so all catalog
8137 - // Gemini models are supported here).
8138 - if (!class_exists('MxChat_Model_Catalog')) {
8139 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1409 + if (!$this->is_activated) {
1410 + echo '<div class="pro-feature-overlay">';
1411 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1412 + echo '</div>';
8140 1413 }
8141 - $chat_catalog = MxChat_Model_Catalog::chat_models();
8142 - $openai_models = (isset($chat_catalog['openai']['models']) && is_array($chat_catalog['openai']['models']))
8143 - ? array_keys($chat_catalog['openai']['models'])
8144 - : array();
8145 - $gemini_models = (isset($chat_catalog['gemini']['models']) && is_array($chat_catalog['gemini']['models']))
8146 - ? array_keys($chat_catalog['gemini']['models'])
8147 - : array();
8148 1414
8149 - $is_capable = in_array($current_model, $openai_models) || in_array($current_model, $gemini_models);
8150 - $is_supported = $is_capable && !in_array($current_model, $unsupported_models);
8151 -
8152 - // Wrapper div with data attributes for JS to show/hide. data-openai-models is kept for
8153 - // back-compat; data-gemini-models is the added second provider the JS now also honors.
8154 - 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;"' : '') . '>';
8155 -
8156 - echo '<label class="toggle-switch">';
8157 - echo sprintf(
8158 - '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
8159 - esc_attr($checked)
8160 - );
8161 - echo '<span class="slider"></span>';
8162 - echo '</label>';
8163 -
8164 1415 echo '</div>';
1416 + }
8165 1417
8166 - // Message shown when a model that can't ground (Claude, Grok, DeepSeek, OpenRouter, etc.) is selected
8167 - echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
8168 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
8169 - echo esc_html__('Web search is only available for OpenAI and Gemini models.', 'mxchat');
8170 - echo '</p>';
8171 -}
1418 + public function mxchat_chatbot_bg_color_callback() {
1419 + $disabled = $this->is_activated ? '' : 'disabled';
8172 1420
8173 -// AJAX handler to fetch OpenRouter models
8174 -public function fetch_openrouter_models() {
8175 - check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
1421 + echo '<div class="pro-feature-wrapper">';
1422 + printf(
1423 + '<input type="text" id="chatbot_bg_color" name="mxchat_options[chatbot_bg_color]" value="%s" class="my-color-field" data-default-color="#f9f9f9" %s />',
1424 + isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '',
1425 + esc_attr($disabled)
1426 + );
8176 1427
8177 - // plan-mxchat-20260731-c63fb6 — nonce is not authorization.
8178 - if (!current_user_can('manage_options')) {
8179 - wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')), 403);
8180 - }
1428 + if (!$this->is_activated) {
1429 + echo '<div class="pro-feature-overlay">';
1430 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1431 + echo '</div>';
1432 + }
8181 1433
8182 - $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
8183 -
8184 - if (empty($api_key)) {
8185 - wp_send_json_error(array('message' => 'API key is required'));
1434 + echo '</div>';
8186 1435 }
8187 -
8188 - $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
8189 - 'headers' => array(
8190 - 'Authorization' => 'Bearer ' . $api_key,
8191 - 'Content-Type' => 'application/json',
8192 - ),
8193 - 'timeout' => 15,
8194 - ));
8195 -
8196 - if (is_wp_error($response)) {
8197 - wp_send_json_error(array('message' => $response->get_error_message()));
8198 - }
8199 -
8200 - $body = wp_remote_retrieve_body($response);
8201 - $data = json_decode($body, true);
8202 -
8203 - if (isset($data['data']) && is_array($data['data'])) {
8204 - // Format the models for the frontend
8205 - $models = array_map(function($model) {
8206 - return array(
8207 - 'id' => $model['id'],
8208 - 'name' => $model['name'] ?? $model['id'],
8209 - 'description' => $model['description'] ?? '',
8210 - 'context_length' => $model['context_length'] ?? 0,
8211 - 'pricing' => array(
8212 - 'prompt' => $model['pricing']['prompt'] ?? 0,
8213 - 'completion' => $model['pricing']['completion'] ?? 0,
8214 - ),
8215 - );
8216 - }, $data['data']);
8217 -
8218 - wp_send_json_success(array('models' => $models));
8219 - } else {
8220 - wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
8221 - }
8222 -}
8223 1436
8224 -// Callback function for embedding model selection
8225 -public function embedding_model_callback() {
8226 - $models = array(
8227 - esc_html__('OpenAI Embeddings', 'mxchat') => array(
8228 - 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
8229 - 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
8230 - 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
8231 - ),
8232 - esc_html__('Voyage AI Embeddings', 'mxchat') => array(
8233 - 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
8234 - ),
8235 - esc_html__('Google Gemini Embeddings', 'mxchat') => array(
8236 - 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
8237 - )
8238 - );
8239 - $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
8240 - // With custom-provider embeddings on, this picker is inert — the effective
8241 - // model comes from the Custom Embedding Model field (plan ae02cb). Autosave
8242 - // fires only on user change events, so the disabled attribute cannot cause
8243 - // a missing-key save; JS keeps the state in sync with the toggle live.
8244 - $custom_embeddings_on = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
8245 - echo '<select id="embedding_model" name="embedding_model"' . ($custom_embeddings_on ? ' disabled' : '') . '>';
8246 - foreach ($models as $group_label => $group_models) {
8247 - echo '<optgroup label="' . esc_attr($group_label) . '">';
8248 - foreach ($group_models as $model_value => $model_label) {
8249 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
8250 - }
8251 - echo '</optgroup>';
8252 - }
8253 - echo '</select>';
8254 - echo '<p class="mxch-field-description mxchat-embedding-custom-note" id="mxchat_embedding_custom_note"' . ($custom_embeddings_on ? '' : ' style="display:none;"') . '>';
8255 - echo esc_html__('Custom provider embeddings are in use — the model is set in the Custom Embedding Model field under Custom Provider.', 'mxchat');
8256 - echo '</p>';
1437 + public function mxchat_user_message_bg_color_callback() {
1438 + $disabled = $this->is_activated ? '' : 'disabled';
8257 1439
8258 - // API Key Status Messages for Embedding Models
8259 - $has_openai_key = !empty($this->options['api_key']);
8260 - $has_voyage_key = !empty($this->options['voyage_api_key']);
8261 - $has_gemini_key = !empty($this->options['gemini_api_key']);
1440 + echo '<div class="pro-feature-wrapper">';
1441 + printf(
1442 + '<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 />',
1443 + isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '',
1444 + esc_attr($disabled)
1445 + );
8262 1446
8263 - // OpenAI Embeddings
8264 - echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
8265 - if ($has_openai_key) {
8266 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8267 - } else {
8268 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8269 - }
8270 - echo '</p>';
1447 + if (!$this->is_activated) {
1448 + echo '<div class="pro-feature-overlay">';
1449 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1450 + echo '</div>';
1451 + }
8271 1452
8272 - // Voyage AI Embeddings
8273 - echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
8274 - if ($has_voyage_key) {
8275 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
8276 - } else {
8277 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
1453 + echo '</div>';
8278 1454 }
8279 - echo '</p>';
8280 1455
8281 - // Gemini Embeddings
8282 - echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
8283 - if ($has_gemini_key) {
8284 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8285 - } else {
8286 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8287 - }
8288 - echo '</p>';
1456 + public function mxchat_user_message_font_color_callback() {
1457 + $disabled = $this->is_activated ? '' : 'disabled';
8289 1458
8290 -}
1459 + echo '<div class="pro-feature-wrapper">';
1460 + printf(
1461 + '<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 />',
1462 + isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '',
1463 + esc_attr($disabled)
1464 + );
8291 1465
1466 + if (!$this->is_activated) {
1467 + echo '<div class="pro-feature-overlay">';
1468 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1469 + echo '</div>';
1470 + }
8292 1471
8293 -public function mxchat_top_bar_title_callback() {
8294 - // Retrieve the current value of the top bar title from saved options
8295 - $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
1472 + echo '</div>';
1473 + }
8296 1474
8297 - // Render the input field
8298 - echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
8299 -}
8300 -public function mxchat_ai_agent_text_callback() {
8301 - // Retrieve the current value of the AI agent text from saved options
8302 - $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
8303 - // Render the input field
8304 - echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
8305 -}
1475 + public function mxchat_bot_message_bg_color_callback() {
1476 + $disabled = $this->is_activated ? '' : 'disabled';
8306 1477
1478 + echo '<div class="pro-feature-wrapper">';
1479 + printf(
1480 + '<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 />',
1481 + isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '',
1482 + esc_attr($disabled)
1483 + );
8307 1484
8308 -public function enable_email_block_callback() {
8309 - // Load full plugin options array
8310 - $all_options = get_option('mxchat_options', []);
1485 + if (!$this->is_activated) {
1486 + echo '<div class="pro-feature-overlay">';
1487 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1488 + echo '</div>';
1489 + }
8311 1490
8312 - // Get the value, default to 'off'
8313 - $enable_email_block = isset($all_options['enable_email_block']) ? $all_options['enable_email_block'] : 'off';
1491 + echo '</div>';
1492 + }
8314 1493
8315 - // Check if it's 'on'
8316 - $checked = ($enable_email_block === 'on') ? 'checked' : '';
1494 + public function mxchat_bot_message_font_color_callback() {
1495 + $disabled = $this->is_activated ? '' : 'disabled';
8317 1496
8318 - echo '<label class="toggle-switch">';
8319 - echo sprintf(
8320 - '<input type="checkbox" id="enable_email_block" name="enable_email_block" value="on" %s />',
8321 - esc_attr($checked)
8322 - );
8323 - echo '<span class="slider"></span>';
8324 - echo '</label>';
8325 -}
1497 + echo '<div class="pro-feature-wrapper">';
1498 + printf(
1499 + '<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 />',
1500 + isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '',
1501 + esc_attr($disabled)
1502 + );
8326 1503
8327 -public function email_blocker_header_content_callback() {
8328 - // Load the entire 'mxchat_options' array
8329 - $all_options = get_option('mxchat_options', []);
1504 + if (!$this->is_activated) {
1505 + echo '<div class="pro-feature-overlay">';
1506 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1507 + echo '</div>';
1508 + }
8330 1509
8331 - // Retrieve the saved content or default to empty
8332 - $content = isset($all_options['email_blocker_header_content'])
8333 - ? $all_options['email_blocker_header_content']
8334 - : '';
1510 + echo '</div>';
1511 + }
8335 1512
8336 - // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
8337 - echo '<textarea
8338 - id="email_blocker_header_content"
8339 - name="email_blocker_header_content"
8340 - rows="5"
8341 - cols="70"
8342 - data-setting="email_blocker_header_content"
8343 - >' . esc_textarea($content) . '</textarea>';
8344 -}
1513 + public function mxchat_top_bar_bg_color_callback() {
1514 + $disabled = $this->is_activated ? '' : 'disabled';
8345 1515
8346 -public function email_blocker_button_text_callback() {
8347 - // Load the entire 'mxchat_options' array
8348 - $all_options = get_option('mxchat_options', []);
1516 + echo '<div class="pro-feature-wrapper">';
1517 + printf(
1518 + '<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 />',
1519 + isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '',
1520 + esc_attr($disabled)
1521 + );
8349 1522
8350 - // Retrieve the saved button text or default to empty
8351 - $button_text = isset($all_options['email_blocker_button_text'])
8352 - ? $all_options['email_blocker_button_text']
8353 - : '';
1523 + if (!$this->is_activated) {
1524 + echo '<div class="pro-feature-overlay">';
1525 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1526 + echo '</div>';
1527 + }
8354 1528
8355 - // Use esc_attr to safely render the existing text
8356 - echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
8357 -}
1529 + echo '</div>';
1530 + }
8358 1531
8359 -//Enable name field callback
8360 -public function enable_name_field_callback() {
8361 - // Load full plugin options array
8362 - $all_options = get_option('mxchat_options', []);
8363 - // Get the value, default to 'off'
8364 - $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
8365 - // Check if it's 'on'
8366 - $checked = ($enable_name_field === 'on') ? 'checked' : '';
8367 - echo '<label class="toggle-switch">';
8368 - echo sprintf(
8369 - '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
8370 - esc_attr($checked)
8371 - );
8372 - echo '<span class="slider"></span>';
8373 - echo '</label>';
8374 -}
8375 -//Name field placeholder callback
8376 -public function name_field_placeholder_callback() {
8377 - $all_options = get_option('mxchat_options', []);
8378 - $placeholder = isset($all_options['name_field_placeholder'])
8379 - ? $all_options['name_field_placeholder']
8380 - : esc_html__('Enter your name', 'mxchat');
1532 + public function mxchat_send_button_font_color_callback() {
1533 + $disabled = $this->is_activated ? '' : 'disabled';
8381 1534
8382 - echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
8383 -}
1535 + echo '<div class="pro-feature-wrapper">';
1536 + printf(
1537 + '<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 />',
1538 + isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '',
1539 + esc_attr($disabled)
1540 + );
8384 1541
8385 -// Consent checkbox toggle (b062c4)
8386 -public function enable_consent_checkbox_callback() {
8387 - $all_options = get_option('mxchat_options', []);
8388 - $enabled = isset($all_options['enable_consent_checkbox']) ? $all_options['enable_consent_checkbox'] : 'off';
8389 - $checked = ($enabled === 'on') ? 'checked' : '';
8390 - echo '<label class="toggle-switch">';
8391 - echo sprintf(
8392 - '<input type="checkbox" id="enable_consent_checkbox" name="enable_consent_checkbox" value="on" %s />',
8393 - esc_attr($checked)
8394 - );
8395 - echo '<span class="slider"></span>';
8396 - echo '</label>';
8397 -}
1542 + if (!$this->is_activated) {
1543 + echo '<div class="pro-feature-overlay">';
1544 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1545 + echo '</div>';
1546 + }
8398 1547
8399 -// Consent checkbox label (b062c4). Owner content; a safe HTML subset is
8400 -// allowed (anchor + inline emphasis) so the Privacy Policy can be linked.
8401 -public function consent_checkbox_label_callback() {
8402 - $all_options = get_option('mxchat_options', []);
8403 - $label = isset($all_options['consent_checkbox_label'])
8404 - ? $all_options['consent_checkbox_label']
8405 - : __('I agree to the Privacy Policy.', 'mxchat');
1548 + echo '</div>';
1549 + }
8406 1550
8407 - echo '<textarea
8408 - id="consent_checkbox_label"
8409 - name="consent_checkbox_label"
8410 - rows="2"
8411 - cols="70"
8412 - data-setting="consent_checkbox_label"
8413 - >' . esc_textarea($label) . '</textarea>';
8414 -}
1551 + public function mxchat_chatbot_background_color_callback() {
1552 + $disabled = $this->is_activated ? '' : 'disabled';
8415 1553
8416 -// Consent required toggle (b062c4)
8417 -public function consent_checkbox_required_callback() {
8418 - $all_options = get_option('mxchat_options', []);
8419 - $required = isset($all_options['consent_checkbox_required']) ? $all_options['consent_checkbox_required'] : 'off';
8420 - $checked = ($required === 'on') ? 'checked' : '';
8421 - echo '<label class="toggle-switch">';
8422 - echo sprintf(
8423 - '<input type="checkbox" id="consent_checkbox_required" name="consent_checkbox_required" value="on" %s />',
8424 - esc_attr($checked)
8425 - );
8426 - echo '<span class="slider"></span>';
8427 - echo '</label>';
8428 -}
1554 + echo '<div class="pro-feature-wrapper">';
1555 + printf(
1556 + '<input type="text" id="chatbot_background_color" name="mxchat_options[chatbot_background_color]" value="%s" class="my-color-field" data-default-color="#000000" %s />',
1557 + isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '',
1558 + esc_attr($disabled)
1559 + );
8429 1560
1561 + if (!$this->is_activated) {
1562 + echo '<div class="pro-feature-overlay">';
1563 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1564 + echo '</div>';
1565 + }
8430 1566
1567 + echo '</div>';
1568 + }
8431 1569
8432 -public function mxchat_intro_message_callback() {
8433 - // Load the entire 'mxchat_options' array
8434 - $all_options = get_option('mxchat_options', []);
8435 - // Retrieve the saved intro message or use the default
8436 - $default_message = __('Hello! How can I assist you today?', 'mxchat');
8437 - $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
8438 - // Escape on output (esc_textarea) — neutralizes any payload already stored before the
8439 - // Wordfence Stored-XSS fix (CWE-79, plan-3f8158) and prevents </textarea> context-breakout.
8440 - ?>
8441 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea( $saved_message ); ?></textarea>
8442 - <p class="description" style="margin-top: 8px;">
8443 - <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
8444 - <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
8445 - </p>
8446 - <?php
8447 -}
1570 + public function mxchat_icon_color_callback() {
1571 + $disabled = $this->is_activated ? '' : 'disabled';
8448 1572
8449 -public function mxchat_input_copy_callback() {
8450 - // Load the entire 'mxchat_options' array
8451 - $all_options = get_option('mxchat_options', []);
1573 + echo '<div class="pro-feature-wrapper">';
1574 + printf(
1575 + '<input type="text" id="icon_color" name="mxchat_options[icon_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
1576 + isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '',
1577 + esc_attr($disabled)
1578 + );
8452 1579
8453 - // Retrieve the saved input copy or use the default value
8454 - $default_copy = __('How can I assist?', 'mxchat');
8455 - $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
1580 + if (!$this->is_activated) {
1581 + echo '<div class="pro-feature-overlay">';
1582 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1583 + echo '</div>';
1584 + }
8456 1585
8457 - // Output the input field with the saved value
8458 - printf(
8459 - '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
8460 - esc_attr($input_copy),
8461 - esc_attr__('How can I assist?', 'mxchat')
8462 - );
8463 -}
8464 -
8465 -
8466 -public function mxchat_append_to_body_callback() {
8467 - // Fetch fresh options to ensure we have the latest saved values
8468 - $options = get_option('mxchat_options', array());
8469 -
8470 - // Get value from options array, default to 'off'
8471 - $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
8472 - $checked = ($append_to_body === 'on') ? 'checked' : '';
8473 -
8474 - // Get post type visibility settings
8475 - $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
8476 - $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
8477 - if (!is_array($visibility_list)) {
8478 - $visibility_list = array();
1586 + echo '</div>';
8479 1587 }
8480 1588
8481 - echo '<div class="mxchat-autosave-section">';
1589 + public function mxchat_chat_input_font_color_callback() {
1590 + $disabled = $this->is_activated ? '' : 'disabled';
8482 1591
8483 - // Main toggle
8484 - echo '<label class="toggle-switch">';
8485 - echo sprintf(
8486 - '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
8487 - esc_attr($checked)
8488 - );
8489 - echo '<span class="slider"></span>';
8490 - echo '</label>';
1592 + echo '<div class="pro-feature-wrapper">';
1593 + printf(
1594 + '<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 />',
1595 + isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '',
1596 + esc_attr($disabled)
1597 + );
8491 1598
8492 - // Post Type Visibility Options (only visible when auto-display is ON)
8493 - $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
8494 - echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8495 -
8496 - echo '<div class="mxchat-post-type-visibility-header">';
8497 - echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
8498 - echo '</div>';
8499 -
8500 - // Mode selector (radio buttons)
8501 - echo '<div class="mxchat-visibility-mode">';
8502 -
8503 - echo '<label class="mxchat-radio-label">';
8504 - echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
8505 - echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
8506 - echo '</label>';
8507 -
8508 - echo '<label class="mxchat-radio-label">';
8509 - echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
8510 - echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
8511 - echo '</label>';
8512 -
8513 - echo '<label class="mxchat-radio-label">';
8514 - echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
8515 - echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
8516 - echo '</label>';
8517 -
8518 - echo '</div>';
8519 -
8520 - // Post type checkboxes (only visible when mode is include or exclude)
8521 - $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
8522 - echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
8523 -
8524 - // Get all public post types
8525 - $post_types = get_post_types(array('public' => true), 'objects');
8526 -
8527 - foreach ($post_types as $post_type) {
8528 - // Skip attachments
8529 - if ($post_type->name === 'attachment') {
8530 - continue;
1599 + if (!$this->is_activated) {
1600 + echo '<div class="pro-feature-overlay">';
1601 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1602 + echo '</div>';
8531 1603 }
8532 1604
8533 - $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
8534 -
8535 - echo '<label class="mxchat-checkbox-label">';
8536 - echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
8537 - echo '<span>' . esc_html($post_type->label) . '</span>';
8538 - echo '</label>';
1605 + echo '</div>';
8539 1606 }
8540 1607
8541 - echo '</div>'; // End post-type-list
8542 - echo '</div>'; // End post-type-visibility-options
8543 - echo '</div>'; // End mxchat-autosave-section
8544 -}
8545 1608
8546 -public function mxchat_contextual_awareness_callback() {
8547 - // Get value from options array, default to 'off'
8548 - $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
8549 - $checked = ($contextual_awareness === 'on') ? 'checked' : '';
1609 +public function mxchat_append_to_body_callback() {
1610 + $append_to_body_checked = isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on' ? 'checked' : '';
8550 1611 echo '<label class="toggle-switch">';
8551 - echo sprintf(
8552 - '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
8553 - esc_attr($checked)
1612 + printf(
1613 + '<input type="checkbox" id="append_to_body" name="mxchat_options[append_to_body]" %s />',
1614 + esc_attr($append_to_body_checked)
8554 1615 );
8555 1616 echo '<span class="slider"></span>';
8556 1617 echo '</label>';
1618 +echo '<p class="description">Enable this option to automatically append the chat widget to the body of every page (recommended). No need to manually use the shortcode [mxchat_chatbot floating="yes"].</p>';
8557 1619 }
8558 1620
8559 -public function mxchat_citation_links_toggle_callback() {
8560 - // Get value from options array, default to 'on' (enabled by default)
8561 - $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
8562 - $checked = ($citation_links === 'on') ? 'checked' : '';
8563 - echo '<label class="toggle-switch">';
8564 - echo sprintf(
8565 - '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
8566 - esc_attr($checked)
8567 - );
8568 - echo '<span class="slider"></span>';
8569 - echo '</label>';
8570 -}
8571 1621
8572 -/**
8573 - * "Strip unapproved links" toggle (plan 58f8b4). Until the site saves an
8574 - * explicit value the rendered state is the install-stamp default — on for
8575 - * installs born at 3.2.20+, off for upgrades — so what the admin sees here
8576 - * always matches what the response URL guard is actually doing.
8577 - */
8578 -public function mxchat_strip_unapproved_links_toggle_callback() {
8579 - if (isset($this->options['strip_unapproved_links_toggle'])) {
8580 - $strip_links = $this->options['strip_unapproved_links_toggle'];
8581 - } else {
8582 - $strip_links = function_exists('mxchat_strip_unapproved_links_default')
8583 - ? mxchat_strip_unapproved_links_default()
8584 - : 'off';
8585 - }
8586 - $checked = ($strip_links === 'on') ? 'checked' : '';
8587 - echo '<label class="toggle-switch">';
8588 - echo sprintf(
8589 - '<input type="checkbox" id="strip_unapproved_links_toggle" name="strip_unapproved_links_toggle" value="on" %s />',
8590 - esc_attr($checked)
8591 - );
8592 - echo '<span class="slider"></span>';
8593 - echo '</label>';
8594 -}
8595 -
8596 -/**
8597 - * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
8598 - * Default ON. The widget reads this through the localized object; the
8599 - * mxchat_satisfaction_rating_enabled filter still lets developers force
8600 - * the value site-wide.
8601 - *
8602 - * The 5 customization fields (idle/question/thanks/placeholder/saved) are
8603 - * rendered inline here inside a single wrapper div whose initial display
8604 - * is set server-side from the toggle value (plan-29caac). Mirrors the
8605 - * auto-display chatbot pattern at mxchat_append_to_body_callback — no
8606 - * DOMContentLoaded race because rows exist as direct children of this
8607 - * callback's output, and the wrapper's display: none is inline at render
8608 - * time so refresh shows the correct state with no flash.
8609 - */
8610 -public function mxchat_satisfaction_rating_toggle_callback() {
8611 - $options = $this->options;
8612 - $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
8613 - $checked = ($value === 'on') ? 'checked' : '';
8614 -
8615 - $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
8616 - $idle = max(5, min(600, $idle));
8617 - $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
8618 - $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
8619 - $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
8620 - $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
8621 -
8622 - echo '<div class="mxchat-autosave-section">';
8623 -
8624 - echo '<label class="toggle-switch">';
8625 - echo sprintf(
8626 - '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
8627 - esc_attr($checked)
8628 - );
8629 - echo '<span class="slider"></span>';
8630 - echo '</label>';
8631 -
8632 - ?>
8633 - <style>
8634 - .mxchat-sub-options-field { margin: 12px 0; }
8635 - .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
8636 - #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
8637 - </style>
8638 - <?php
8639 -
8640 - $display_style = ($value === 'on') ? '' : 'display: none;';
8641 - echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8642 -
8643 - echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
8644 -
8645 - echo '<div class="mxchat-sub-options-field">';
8646 - echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
8647 - printf(
8648 - '<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>',
8649 - (int) $idle,
8650 - esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
8651 - );
8652 - echo '</div>';
8653 -
8654 - echo '<div class="mxchat-sub-options-field">';
8655 - echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
8656 - printf(
8657 - '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8658 - esc_attr($question),
8659 - esc_attr__('Was this helpful?', 'mxchat')
8660 - );
8661 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
8662 - echo '</div>';
8663 -
8664 - echo '<div class="mxchat-sub-options-field">';
8665 - echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
8666 - printf(
8667 - '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
8668 - esc_attr($thanks),
8669 - esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
8670 - );
8671 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
8672 - echo '</div>';
8673 -
8674 - echo '<div class="mxchat-sub-options-field">';
8675 - echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
8676 - printf(
8677 - '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8678 - esc_attr($placeholder),
8679 - esc_attr__('Tell us what could be better…', 'mxchat')
8680 - );
8681 - echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
8682 - echo '</div>';
8683 -
8684 - echo '<div class="mxchat-sub-options-field">';
8685 - echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
8686 - printf(
8687 - '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8688 - esc_attr($saved),
8689 - esc_attr__('Thanks for the feedback.', 'mxchat')
8690 - );
8691 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
8692 - echo '</div>';
8693 -
8694 - echo '</div>'; // #satisfaction-rating-sub-options
8695 - echo '</div>'; // .mxchat-autosave-section
8696 -
8697 - ?>
8698 - <script>
8699 - (function() {
8700 - document.addEventListener('DOMContentLoaded', function() {
8701 - var toggle = document.getElementById('satisfaction_rating_enabled');
8702 - var subOptions = document.getElementById('satisfaction-rating-sub-options');
8703 - if (!toggle || !subOptions) return;
8704 - toggle.addEventListener('change', function() {
8705 - subOptions.style.display = toggle.checked ? '' : 'none';
8706 - });
8707 - });
8708 - })();
8709 - </script>
8710 - <?php
8711 -}
8712 -
8713 1622 public function mxchat_privacy_toggle_callback() {
8714 - // Load from mxchat_options array
8715 - $options = get_option('mxchat_options', []);
1623 + // Check if the privacy toggle is enabled
1624 + $privacy_toggle_checked = isset($this->options['privacy_toggle']) && $this->options['privacy_toggle'] === 'on' ? 'checked' : '';
8716 1625
8717 - // Get privacy toggle value with fallback
8718 - $privacy_toggle = isset($options['privacy_toggle']) ? $options['privacy_toggle'] : 'off';
8719 - $checked = ($privacy_toggle === 'on') ? 'checked' : '';
1626 + // Retrieve the stored privacy text if it exists
1627 + $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>.';
8720 1628
8721 - // Get privacy text with fallback
8722 - $privacy_text = isset($options['privacy_text'])
8723 - ? $options['privacy_text']
8724 - : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
8725 -
8726 1629 // Output the toggle switch
8727 1630 echo '<label class="toggle-switch">';
8728 - echo sprintf(
8729 - '<input type="checkbox" id="privacy_toggle" name="privacy_toggle" value="on" %s />',
8730 - esc_attr($checked)
1631 + printf(
1632 + '<input type="checkbox" id="privacy_toggle" name="mxchat_options[privacy_toggle]" %s />',
1633 + esc_attr($privacy_toggle_checked)
8731 1634 );
8732 1635 echo '<span class="slider"></span>';
8733 1636 echo '</label>';
1637 + echo '<p class="description">Enable this option to display a privacy notice below the chat widget.</p>';
8734 1638
8735 1639 // Output the custom text input field
8736 - echo sprintf(
8737 - '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
1640 + printf(
1641 + '<textarea id="privacy_text" name="mxchat_options[privacy_text]" rows="5" cols="50" class="regular-text">%s</textarea>',
8738 1642 esc_textarea($privacy_text)
8739 1643 );
1644 + echo '<p class="description">Enter the privacy policy text. You can include HTML links.</p>';
8740 1645 }
8741 1646
8742 1647
8743 1648 public function mxchat_complianz_toggle_callback() {
8744 - // Load from mxchat_options array
8745 - $options = get_option('mxchat_options', []);
1649 + // Check if the Complianz toggle is enabled
1650 + $complianz_toggle_checked = isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on' ? 'checked' : '';
8746 1651
8747 - // Get complianz toggle value with fallback
8748 - $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
8749 - $checked = ($complianz_toggle === 'on') ? 'checked' : '';
1652 + // Check if the plugin is activated (paid feature)
1653 + $disabled = $this->is_activated ? '' : 'disabled';
1654 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8750 1655
8751 - // Output the toggle switch
8752 - echo '<label class="toggle-switch">';
8753 - echo sprintf(
8754 - '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
8755 - esc_attr($checked)
8756 - );
8757 - echo '<span class="slider"></span>';
8758 - echo '</label>';
8759 -}
1656 + echo '<div class="' . esc_attr($class) . '">';
8760 1657
8761 -public function mxchat_link_target_toggle_callback() {
8762 - // Load from mxchat_options array
8763 - $options = get_option('mxchat_options', []);
8764 -
8765 - // Get link target toggle value with fallback
8766 - $link_target_toggle = isset($options['link_target_toggle']) ? $options['link_target_toggle'] : 'off';
8767 - $checked = ($link_target_toggle === 'on') ? 'checked' : '';
8768 -
8769 1658 // Output the toggle switch
8770 1659 echo '<label class="toggle-switch">';
8771 - echo sprintf(
8772 - '<input type="checkbox" id="link_target_toggle" name="link_target_toggle" value="on" %s />',
8773 - esc_attr($checked)
1660 + printf(
1661 + '<input type="checkbox" id="complianz_toggle" name="mxchat_options[complianz_toggle]" %s %s />',
1662 + esc_attr($complianz_toggle_checked),
1663 + esc_attr($disabled)
8774 1664 );
8775 1665 echo '<span class="slider"></span>';
8776 1666 echo '</label>';
8777 -}
1667 + echo '<p class="description">Enable this option to apply Complianz consent logic to the chatbot.</p>';
8778 1668
8779 -public function mxchat_chat_persistence_toggle_callback() {
8780 - // Load from mxchat_options array
8781 - $options = get_option('mxchat_options', []);
8782 -
8783 - // Get chat persistence toggle value with fallback
8784 - $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
8785 - $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
8786 -
8787 - // Output the toggle switch
8788 - echo '<label class="toggle-switch">';
8789 - echo sprintf(
8790 - '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
8791 - esc_attr($checked)
8792 - );
8793 - echo '<span class="slider"></span>';
8794 - echo '</label>';
8795 -}
8796 -
8797 -public function mxchat_print_button_toggle_callback() {
8798 - // Load from mxchat_options array
8799 - $options = get_option('mxchat_options', []);
8800 -
8801 - // Default ON — the option was previously unexposed and the button always showed.
8802 - $print_button_enabled = isset($options['print_button_enabled']) ? $options['print_button_enabled'] : 'on';
8803 - $checked = ($print_button_enabled === 'on') ? 'checked' : '';
8804 -
8805 - // Output the toggle switch
8806 - echo '<label class="toggle-switch">';
8807 - echo sprintf(
8808 - '<input type="checkbox" id="print_button_enabled" name="print_button_enabled" value="on" %s />',
8809 - esc_attr($checked)
8810 - );
8811 - echo '<span class="slider"></span>';
8812 - echo '</label>';
8813 -}
8814 -
8815 -/**
8816 - * Editor Assistant toggle (plan-8cb0cb). Standalone option, NOT in mxchat_options
8817 - * (bypasses the mxchat_sanitize strip-trap + autosave normalization). Default OFF.
8818 - * Saved by the mxchat_editor_assistant_enabled case in class-ajax-handler.php.
8819 - * Renders on Content → Settings (moved there from Settings → Behavior, plan-f7df40).
8820 - */
8821 -public function mxchat_editor_assistant_toggle_callback() {
8822 - $enabled = get_option('mxchat_editor_assistant_enabled', 'off');
8823 - $checked = ($enabled === 'on') ? 'checked' : '';
8824 -
8825 - echo '<label class="toggle-switch">';
8826 - echo sprintf(
8827 - '<input type="checkbox" id="mxchat_editor_assistant_enabled" name="mxchat_editor_assistant_enabled" value="on" %s />',
8828 - esc_attr($checked)
8829 - );
8830 - echo '<span class="slider"></span>';
8831 - echo '</label>';
8832 -}
8833 -
8834 -/**
8835 - * Hybrid keyword boost toggle (plan-38ffa1; rebuilt on the house toggle pattern
8836 - * in plan-64d34f — the hand-rolled .mxch-toggle markup matched neither selector
8837 - * the autosave JS uses to place its save confirmation, so the control looked
8838 - * dead). Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8839 - * mxchat_hybrid_keyword_toggle case in class-ajax-handler.php, which also runs
8840 - * capability detection on enable.
8841 - */
8842 -public function mxchat_hybrid_keyword_toggle_callback() {
8843 - $enabled = get_option('mxchat_hybrid_keyword_toggle', 'off');
8844 - $checked = ($enabled === 'on') ? 'checked' : '';
8845 -
8846 - echo '<label class="toggle-switch">';
8847 - echo sprintf(
8848 - '<input type="checkbox" id="mxchat_hybrid_keyword_toggle" name="mxchat_hybrid_keyword_toggle" value="on" %s />',
8849 - esc_attr($checked)
8850 - );
8851 - echo '<span class="slider"></span>';
8852 - echo '</label>';
8853 -}
8854 -
8855 -/**
8856 - * Smart asset loading toggle (plan-915355; rebuilt on the house toggle pattern
8857 - * in plan-64d34f, same dead-save-feedback defect as the hybrid keyword toggle).
8858 - * Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8859 - * mxchat_smart_asset_loading case in class-ajax-handler.php.
8860 - */
8861 -public function mxchat_smart_asset_loading_toggle_callback() {
8862 - $enabled = get_option('mxchat_smart_asset_loading', 'off');
8863 - $checked = ($enabled === 'on') ? 'checked' : '';
8864 -
8865 - echo '<label class="toggle-switch">';
8866 - echo sprintf(
8867 - '<input type="checkbox" id="mxchat_smart_asset_loading" name="mxchat_smart_asset_loading" value="on" %s />',
8868 - esc_attr($checked)
8869 - );
8870 - echo '<span class="slider"></span>';
8871 - echo '</label>';
8872 -}
8873 -
8874 -public function mxchat_reset_chat_toggle_callback() {
8875 - // Load from mxchat_options array. plan ac2e81 — default OFF (new, opt-in).
8876 - $options = get_option('mxchat_options', []);
8877 - $reset_chat_enabled = isset($options['reset_chat_enabled']) ? $options['reset_chat_enabled'] : 'off';
8878 - $checked = ($reset_chat_enabled === 'on') ? 'checked' : '';
8879 -
8880 - echo '<label class="toggle-switch">';
8881 - echo sprintf(
8882 - '<input type="checkbox" id="reset_chat_enabled" name="reset_chat_enabled" value="on" %s />',
8883 - esc_attr($checked)
8884 - );
8885 - echo '<span class="slider"></span>';
8886 - echo '</label>';
8887 -}
8888 -
8889 -public function mxchat_reset_chat_label_callback() {
8890 - // Editable label for the "Start new chat" menu item. plan ac2e81.
8891 - $options = get_option('mxchat_options', []);
8892 - $reset_chat_label = isset($options['reset_chat_label']) ? $options['reset_chat_label'] : '';
8893 -
8894 - printf(
8895 - '<input type="text" id="reset_chat_label" name="reset_chat_label" value="%s" placeholder="%s" class="regular-text" />',
8896 - esc_attr($reset_chat_label),
8897 - esc_attr__('Start new chat', 'mxchat')
8898 - );
8899 -}
8900 -
8901 -public function mxchat_popular_question_1_callback() {
8902 - // Load the full plugin options array
8903 - $all_options = get_option('mxchat_options', []);
8904 -
8905 - // Retrieve the specific option for popular_question_1
8906 - $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
8907 -
8908 - // Render the input field
8909 - printf(
8910 - '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
8911 - esc_attr($popular_question_1),
8912 - esc_attr__('Enter Quick Question 1', 'mxchat')
8913 - );
8914 -}
8915 -
8916 -
8917 -public function mxchat_popular_question_2_callback() {
8918 - // Load the full plugin options array
8919 - $all_options = get_option('mxchat_options', []);
8920 -
8921 - // Retrieve the specific option for popular_question_2
8922 - $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
8923 -
8924 - // Render the input field
8925 - printf(
8926 - '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
8927 - esc_attr($popular_question_2),
8928 - esc_attr__('Enter Quick Question 2', 'mxchat')
8929 - );
8930 -}
8931 -
8932 -
8933 -public function mxchat_popular_question_3_callback() {
8934 - // Load the full plugin options array
8935 - $all_options = get_option('mxchat_options', []);
8936 -
8937 - // Retrieve the specific option for popular_question_3
8938 - $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
8939 -
8940 - // Render the input field
8941 - printf(
8942 - '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
8943 - esc_attr($popular_question_3),
8944 - esc_attr(__('Enter Quick Question 3', 'mxchat'))
8945 - );
8946 -}
8947 -
8948 -public function mxchat_additional_popular_questions_callback() {
8949 - $options = get_option('mxchat_options', []);
8950 - $additional_questions = isset($options['additional_popular_questions'])
8951 - ? $options['additional_popular_questions']
8952 - : get_option('additional_popular_questions', array());
8953 -
8954 - echo '<div id="mxchat-additional-questions-container">';
8955 - if (!empty($additional_questions)) {
8956 - foreach ($additional_questions as $index => $question) {
8957 - printf(
8958 - '<div class="mxchat-question-row">
8959 - <input type="text" name="additional_popular_questions[]"
8960 - value="%s"
8961 - placeholder="%s"
8962 - class="regular-text mxchat-question-input"
8963 - data-question-index="%d" />
8964 - <button type="button" class="button mxchat-remove-question"
8965 - aria-label="%s">%s</button>
8966 - </div>',
8967 - esc_attr($question),
8968 - esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
8969 - $index,
8970 - esc_attr(__('Remove question', 'mxchat')),
8971 - esc_html__('Remove', 'mxchat')
8972 - );
8973 - }
8974 - } else {
8975 - printf(
8976 - '<div class="mxchat-question-row">
8977 - <input type="text" name="additional_popular_questions[]"
8978 - value=""
8979 - placeholder="%s"
8980 - class="regular-text mxchat-question-input"
8981 - data-question-index="0" />
8982 - <button type="button" class="button mxchat-remove-question"
8983 - aria-label="%s">%s</button>
8984 - </div>',
8985 - esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
8986 - esc_attr(__('Remove question', 'mxchat')),
8987 - esc_html__('Remove', 'mxchat')
8988 - );
1669 + // If the feature is not activated, show the Pro feature overlay
1670 + if (!$this->is_activated) {
1671 + echo '<div class="pro-feature-overlay">';
1672 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1673 + echo '</div>';
8989 1674 }
8990 - echo '</div>';
8991 - printf(
8992 - '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
8993 - esc_attr(__('Add question', 'mxchat')),
8994 - esc_html__('Add Question', 'mxchat')
8995 - );
8996 -}
8997 1675
8998 -public function mxchat_brave_api_key_callback() {
8999 - $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
9000 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
9001 -
9002 - echo '<div class="api-key-wrapper">';
9003 - echo sprintf(
9004 - '<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" />',
9005 - $brave_api_key,
9006 - $nonce
9007 - );
9008 - echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9009 1676 echo '</div>';
9010 - echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
9011 1677 }
9012 1678
9013 -public function mxchat_brave_image_count_callback() {
9014 - $brave_image_count = isset($this->options['brave_image_count'])
9015 - ? intval($this->options['brave_image_count'])
9016 - : 4;
9017 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
9018 1679
9019 - echo '<div class="mxchat-field-wrapper">';
9020 - echo sprintf(
9021 - '<input type="number" id="brave_image_count" name="brave_image_count"
9022 - value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9023 - $brave_image_count,
9024 - $nonce
9025 - );
9026 - echo '</div>';
9027 - echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
9028 -}
9029 1680
9030 -public function mxchat_brave_safe_search_callback() {
9031 - $brave_safe_search = isset($this->options['brave_safe_search'])
9032 - ? esc_attr($this->options['brave_safe_search'])
9033 - : 'strict';
9034 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
9035 1681
9036 - echo '<div class="mxchat-field-wrapper">';
9037 - echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
9038 - echo sprintf(
9039 - '<option value="strict" %s>%s</option>',
9040 - selected($brave_safe_search, 'strict', false),
9041 - __('Strict', 'mxchat')
9042 - );
9043 - echo sprintf(
9044 - '<option value="off" %s>%s</option>',
9045 - selected($brave_safe_search, 'off', false),
9046 - __('Off', 'mxchat')
9047 - );
9048 - echo '</select>';
9049 - echo '</div>';
9050 - echo '<p class="description">' .
9051 - esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
9052 - '</p>';
9053 -}
9054 1682
9055 -public function mxchat_brave_news_count_callback() {
9056 - $brave_news_count = isset($this->options['brave_news_count'])
9057 - ? intval($this->options['brave_news_count'])
9058 - : 3;
9059 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
1683 +public function mxchat_link_target_toggle_callback() {
1684 + // Check if the toggle is enabled in the options
1685 + $link_target_toggle = isset($this->options['link_target_toggle']) && $this->options['link_target_toggle'] === 'on' ? 'checked' : '';
9060 1686
9061 - echo '<div class="mxchat-field-wrapper">';
9062 - echo sprintf(
9063 - '<input type="number" id="brave_news_count" name="brave_news_count"
9064 - value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9065 - $brave_news_count,
9066 - $nonce
9067 - );
9068 - echo '</div>';
9069 - echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
9070 -}
9071 -
9072 -public function mxchat_brave_country_callback() {
9073 - $brave_country = isset($this->options['brave_country'])
9074 - ? esc_attr($this->options['brave_country'])
9075 - : 'us';
9076 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
9077 -
9078 - echo '<div class="mxchat-field-wrapper">';
9079 - echo sprintf(
9080 - '<input type="text" id="brave_country" name="brave_country"
9081 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9082 - $brave_country,
9083 - $nonce
9084 - );
9085 - echo '</div>';
9086 - echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
9087 -}
9088 -
9089 -public function mxchat_brave_language_callback() {
9090 - $brave_language = isset($this->options['brave_language'])
9091 - ? esc_attr($this->options['brave_language'])
9092 - : 'en';
9093 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
9094 -
9095 - echo '<div class="mxchat-field-wrapper">';
9096 - echo sprintf(
9097 - '<input type="text" id="brave_language" name="brave_language"
9098 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
9099 - $brave_language,
9100 - $nonce
9101 - );
9102 - echo '</div>';
9103 - echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
9104 -}
9105 -
9106 -
9107 -
9108 -
9109 -
9110 -// Section Callback
9111 -public function mxchat_pdf_intent_section_callback() {
9112 - echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
9113 -}
9114 -
9115 -public function mxchat_chat_toolbar_toggle_callback() {
9116 - // Get chat toolbar toggle value with fallback
9117 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
9118 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
9119 -
9120 1687 // Output the toggle switch
9121 1688 echo '<label class="toggle-switch">';
9122 - echo sprintf(
9123 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
9124 - esc_attr($checked)
1689 + printf(
1690 + '<input type="checkbox" id="link_target_toggle" name="mxchat_options[link_target_toggle]" %s />',
1691 + esc_attr($link_target_toggle)
9125 1692 );
9126 1693 echo '<span class="slider"></span>';
9127 1694 echo '</label>';
9128 -
9129 - 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>';
1695 + echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
9130 1696 }
9131 1697
9132 -/**
9133 - * Callback for PDF upload button toggle setting
9134 - */
9135 -public function mxchat_show_pdf_upload_button_callback() {
9136 - // Get toggle value with fallback
9137 - $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
9138 - $checked = ($show_pdf_button === 'on') ? 'checked' : '';
1698 +public function mxchat_chat_persistence_toggle_callback() {
1699 + // Check if chat persistence toggle is enabled
1700 + $chat_persistence_toggle_checked = isset($this->options['chat_persistence_toggle']) && $this->options['chat_persistence_toggle'] === 'on' ? 'checked' : '';
9139 1701
9140 - // Output the toggle switch
9141 - echo '<label class="toggle-switch">';
9142 - echo sprintf(
9143 - '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
9144 - esc_attr($checked)
9145 - );
9146 - echo '<span class="slider"></span>';
9147 - echo '</label>';
1702 + // Check if the plugin is activated (paid feature)
1703 + $disabled = $this->is_activated ? '' : 'disabled';
1704 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9148 1705
9149 - echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
9150 -}
1706 + echo '<div class="' . esc_attr($class) . '">';
9151 1707
9152 -/**
9153 - * Callback for Word upload button toggle setting
9154 - */
9155 -public function mxchat_show_word_upload_button_callback() {
9156 - // Get toggle value with fallback
9157 - $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
9158 - $checked = ($show_word_button === 'on') ? 'checked' : '';
9159 -
9160 1708 // Output the toggle switch
9161 1709 echo '<label class="toggle-switch">';
9162 - echo sprintf(
9163 - '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
9164 - esc_attr($checked)
9165 - );
9166 - echo '<span class="slider"></span>';
9167 - echo '</label>';
9168 -
9169 - echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
9170 -}
9171 -
9172 -public function mxchat_pdf_intent_trigger_text_callback() {
9173 - $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
9174 -
9175 - echo sprintf(
9176 - '<textarea id="pdf_intent_trigger_text"
9177 - name="pdf_intent_trigger_text"
9178 - rows="3"
9179 - cols="50"
9180 - placeholder="%s">%s</textarea>',
9181 - esc_attr__('Enter trigger text', 'mxchat'),
9182 - isset($this->options['pdf_intent_trigger_text'])
9183 - ? esc_textarea($this->options['pdf_intent_trigger_text'])
9184 - : esc_textarea($default_text)
9185 - );
9186 - echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
9187 -}
9188 -
9189 -public function mxchat_pdf_intent_success_text_callback() {
9190 - $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
9191 -
9192 - echo sprintf(
9193 - '<textarea id="pdf_intent_success_text"
9194 - name="pdf_intent_success_text"
9195 - rows="3"
9196 - cols="50"
9197 - placeholder="%s">%s</textarea>',
9198 - esc_attr__('Enter success text', 'mxchat'),
9199 - isset($this->options['pdf_intent_success_text'])
9200 - ? esc_textarea($this->options['pdf_intent_success_text'])
9201 - : esc_textarea($default_text)
9202 - );
9203 - echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
9204 -}
9205 -
9206 -public function mxchat_pdf_intent_error_text_callback() {
9207 - $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
9208 -
9209 - echo sprintf(
9210 - '<textarea id="pdf_intent_error_text"
9211 - name="pdf_intent_error_text"
9212 - rows="3"
9213 - cols="50"
9214 - placeholder="%s">%s</textarea>',
9215 - esc_attr__('Enter error text', 'mxchat'),
9216 - isset($this->options['pdf_intent_error_text'])
9217 - ? esc_textarea($this->options['pdf_intent_error_text'])
9218 - : esc_textarea($default_text)
9219 - );
9220 - echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
9221 -}
9222 -
9223 -public function mxchat_pdf_max_pages_callback() {
9224 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
9225 -
9226 - echo sprintf(
9227 - '<input type="range"
9228 - id="pdf_max_pages"
9229 - name="pdf_max_pages"
9230 - min="1"
9231 - max="69"
9232 - value="%d"
9233 - class="range-slider" />',
9234 - esc_attr($max_pages)
9235 - );
9236 - echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
9237 - echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
9238 -}
9239 -
9240 -public function mxchat_live_agent_status_callback() {
9241 - // Always get fresh options instead of using cached $this->options
9242 - $fresh_options = get_option('mxchat_options');
9243 - $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
9244 -
9245 - echo '<label class="toggle-switch">';
9246 - echo sprintf(
9247 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
9248 - checked($status, 'on', false)
9249 - );
9250 - echo '<span class="slider"></span>';
9251 - echo '</label>';
9252 - echo '<label for="live_agent_status" class="mxchat-status-label">';
9253 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9254 - echo '</label>';
9255 -}
9256 -
9257 -/**
9258 - * Availability-schedule editor (plans 8ccaa2 + 99d7a4).
9259 - *
9260 - * ONE callback, parameterized by channel ('slack' | 'telegram' via the
9261 - * add_settings_field $args) — the markup and CSS are shared, only the bound
9262 - * option and the helper text differ. Each channel's editor renders under its
9263 - * own Integrations tab and governs ONLY that channel's handoff. While the
9264 - * master toggle is off the day grid is inert and handoff availability stays
9265 - * governed solely by that channel's manual status toggle.
9266 - *
9267 - * The day inputs carry NO name attribute and are marked .mxchat-la-field so the
9268 - * generic autosave skips them; the editor JS folds them into the channel's
9269 - * hidden live_agent_schedule_<channel> input and fires one change, reusing the
9270 - * existing autosave transport rather than growing a second one. All hooks the
9271 - * JS needs are CLASSES scoped inside .mxchat-la-schedule, never ids — the
9272 - * markup exists twice on the page.
9273 - */
9274 -public function mxchat_live_agent_schedule_callback($args = array()) {
9275 - if (!class_exists('MxChat_Live_Agent_Schedule')) {
9276 - return;
9277 - }
9278 - $channel = (isset($args['channel']) && in_array($args['channel'], MxChat_Live_Agent_Schedule::channels(), true))
9279 - ? $args['channel']
9280 - : 'slack';
9281 - $field = 'live_agent_schedule_' . $channel;
9282 - $sched = MxChat_Live_Agent_Schedule::get($channel);
9283 - $labels = MxChat_Live_Agent_Schedule::day_labels();
9284 - $tz = MxChat_Live_Agent_Schedule::timezone_label();
9285 - $enabled = !empty($sched['enabled']);
9286 - $channel_labels = array(
9287 - 'slack' => __('Slack', 'mxchat'),
9288 - 'telegram' => __('Telegram', 'mxchat'),
9289 - 'webhook' => __('Webhook', 'mxchat'),
9290 - );
9291 - $channel_label = $channel_labels[$channel];
9292 - ?>
9293 - <div class="mxchat-la-schedule<?php echo $enabled ? ' is-active' : ''; ?>"
9294 - id="mxchat-la-schedule-<?php echo esc_attr($channel); ?>"
9295 - data-channel="<?php echo esc_attr($channel); ?>">
9296 - <label class="toggle-switch">
9297 - <input type="checkbox" id="<?php echo esc_attr($field); ?>_enabled"
9298 - class="mxchat-la-field mxchat-la-enabled" <?php checked($enabled); ?> />
9299 - <span class="slider"></span>
9300 - </label>
9301 - <label for="<?php echo esc_attr($field); ?>_enabled" class="mxchat-status-label">
9302 - <span class="status-text mxchat-la-status-text">
9303 - <?php echo $enabled
9304 - ? esc_html__('Scheduled hours', 'mxchat')
9305 - : esc_html__('Always available', 'mxchat'); ?>
9306 - </span>
9307 - </label>
9308 -
9309 - <div class="mxchat-la-days" aria-hidden="<?php echo $enabled ? 'false' : 'true'; ?>">
9310 - <?php foreach ($labels as $n => $label) :
9311 - $day = $sched['days'][$n];
9312 - $on = !empty($day['enabled']);
9313 - ?>
9314 - <div class="mxchat-la-day<?php echo $on ? ' is-on' : ''; ?>" data-day="<?php echo esc_attr($n); ?>">
9315 - <label class="mxchat-la-day-label">
9316 - <input type="checkbox" class="mxchat-la-field mxchat-la-day-enabled"
9317 - data-day="<?php echo esc_attr($n); ?>" <?php checked($on); ?> />
9318 - <span class="mxchat-la-day-name"><?php echo esc_html($label); ?></span>
9319 - </label>
9320 - <div class="mxchat-la-times">
9321 - <input type="time" class="mxchat-la-field mxchat-la-start"
9322 - data-day="<?php echo esc_attr($n); ?>"
9323 - value="<?php echo esc_attr($day['start']); ?>"
9324 - aria-label="<?php echo esc_attr(sprintf(__('%s start time', 'mxchat'), $label)); ?>" />
9325 - <span class="mxchat-la-dash">&ndash;</span>
9326 - <input type="time" class="mxchat-la-field mxchat-la-end"
9327 - data-day="<?php echo esc_attr($n); ?>"
9328 - value="<?php echo esc_attr($day['end']); ?>"
9329 - aria-label="<?php echo esc_attr(sprintf(__('%s end time', 'mxchat'), $label)); ?>" />
9330 - </div>
9331 - </div>
9332 - <?php endforeach; ?>
9333 - </div>
9334 -
9335 - <input type="hidden" name="<?php echo esc_attr($field); ?>" id="<?php echo esc_attr($field); ?>"
9336 - class="mxchat-la-hidden" value="<?php echo esc_attr(wp_json_encode($sched)); ?>" />
9337 - </div>
9338 - <p class="description">
9339 - <?php printf(
9340 - /* translators: 1: the handoff channel, e.g. Slack or Telegram; 2: the site's timezone, e.g. America/New_York */
9341 - 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'),
9342 - '<strong>' . esc_html($channel_label) . '</strong>',
9343 - '<strong>' . esc_html($tz) . '</strong>'
9344 - ); ?>
9345 - </p>
9346 - <?php
9347 -}
9348 -
9349 -public function mxchat_live_agent_away_message_callback() {
9350 - $message = isset($this->options['live_agent_away_message'])
9351 - ? $this->options['live_agent_away_message']
9352 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9353 -
9354 1710 printf(
9355 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
9356 - esc_textarea($message)
1711 + '<input type="checkbox" id="chat_persistence_toggle" name="mxchat_options[chat_persistence_toggle]" %s %s />',
1712 + esc_attr($chat_persistence_toggle_checked),
1713 + esc_attr($disabled)
9357 1714 );
9358 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9359 -}
9360 -
9361 -public function mxchat_live_agent_notification_message_callback() {
9362 - $message = isset($this->options['live_agent_notification_message'])
9363 - ? $this->options['live_agent_notification_message']
9364 - : __('Live agent has been notified.', 'mxchat');
9365 -
9366 - printf(
9367 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
9368 - esc_textarea($message)
9369 - );
9370 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9371 -}
9372 -
9373 -public function mxchat_live_agent_webhook_url_callback() {
9374 - $webhook_url = isset($this->options['live_agent_webhook_url'])
9375 - ? esc_url($this->options['live_agent_webhook_url'])
9376 - : esc_url(get_option('live_agent_webhook_url', ''));
9377 -
9378 - printf(
9379 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
9380 - $webhook_url
9381 - );
9382 - echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9383 - echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
9384 -}
9385 -
9386 -public function mxchat_live_agent_secret_key_callback() {
9387 - printf(
9388 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
9389 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
9390 - );
9391 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9392 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
9393 -}
9394 -
9395 -public function mxchat_live_agent_bot_token_callback() {
9396 - printf(
9397 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
9398 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
9399 - );
9400 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9401 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
9402 -}
9403 -
9404 -public function mxchat_live_agent_user_ids_callback() {
9405 - $user_ids = isset($this->options['live_agent_user_ids'])
9406 - ? esc_textarea($this->options['live_agent_user_ids'])
9407 - : '';
9408 -
9409 - printf(
9410 - '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
9411 - $user_ids
9412 - );
9413 - 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>';
9414 -}
9415 -
9416 -public function mxchat_live_agent_shared_channel_callback() {
9417 - $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : '';
9418 - printf(
9419 - '<input type="text" id="live_agent_shared_channel" name="live_agent_shared_channel" value="%s" class="regular-text" placeholder="#support or C0123456789" />',
9420 - esc_attr($value)
9421 - );
9422 - 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>';
9423 -
9424 - // Surface the last failed handoff so a wrong name / missing invite is
9425 - // visible right where it gets fixed. A successful handoff clears this.
9426 - $shared_error = get_option('mxchat_slack_shared_channel_error');
9427 - if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) {
9428 - echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . '</strong> — '
9429 - . esc_html(sprintf(
9430 - /* translators: %s: Slack API error code */
9431 - __('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'),
9432 - $shared_error['error']
9433 - )) . '</p>';
9434 - }
9435 -}
9436 -
9437 -public function mxchat_live_agent_archive_on_end_callback() {
9438 - $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off';
9439 - printf(
9440 - '<input type="checkbox" id="live_agent_archive_on_end_toggle" name="live_agent_archive_on_end_toggle" value="on" %s />',
9441 - checked('on', $value, false)
9442 - );
9443 - 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>';
9444 - 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>';
9445 -}
9446 -
9447 -/**
9448 - * Telegram Integration Callbacks
9449 - */
9450 -public function mxchat_telegram_section_callback() {
9451 - echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
9452 -}
9453 -
9454 -public function mxchat_telegram_status_callback() {
9455 - $fresh_options = get_option('mxchat_options');
9456 - $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
9457 -
9458 - echo '<label class="toggle-switch">';
9459 - echo sprintf(
9460 - '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
9461 - checked($status, 'on', false)
9462 - );
9463 1715 echo '<span class="slider"></span>';
9464 1716 echo '</label>';
9465 - echo '<label for="telegram_status" class="mxchat-status-label">';
9466 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9467 - echo '</label>';
9468 -}
1717 + echo '<p class="description">Enable to keep chat history when users navigate tabs or return to the site within 24 hours.</p>';
9469 1718
9470 -public function mxchat_telegram_notification_message_callback() {
9471 - $message = isset($this->options['telegram_notification_message'])
9472 - ? $this->options['telegram_notification_message']
9473 - : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
9474 -
9475 - printf(
9476 - '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
9477 - esc_textarea($message)
9478 - );
9479 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9480 -}
9481 -
9482 -public function mxchat_telegram_away_message_callback() {
9483 - $message = isset($this->options['telegram_away_message'])
9484 - ? $this->options['telegram_away_message']
9485 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9486 -
9487 - printf(
9488 - '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
9489 - esc_textarea($message)
9490 - );
9491 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
9492 -}
9493 -
9494 -public function mxchat_telegram_bot_token_callback() {
9495 - printf(
9496 - '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
9497 - isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
9498 - );
9499 - 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>';
9500 - echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
9501 -}
9502 -
9503 -public function mxchat_telegram_group_id_callback() {
9504 - printf(
9505 - '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
9506 - isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
9507 - );
9508 - echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
9509 -}
9510 -
9511 -public function mxchat_telegram_webhook_secret_callback() {
9512 - $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
9513 -
9514 - // Auto-generate secret if empty
9515 - if (empty($secret)) {
9516 - $secret = wp_generate_password(64, false, false);
9517 - $options = get_option('mxchat_options', []);
9518 - $options['telegram_webhook_secret'] = $secret;
9519 - update_option('mxchat_options', $options);
9520 - $this->options['telegram_webhook_secret'] = $secret;
1719 + // If not activated, show Pro feature overlay
1720 + if (!$this->is_activated) {
1721 + echo '<div class="pro-feature-overlay">';
1722 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
1723 + echo '</div>';
9521 1724 }
9522 1725
9523 - printf(
9524 - '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
9525 - esc_attr($secret)
9526 - );
9527 - 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>';
9528 - 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>';
1726 + echo '</div>';
9529 1727 }
9530 1728
9531 -/**
9532 - * Webhook Handoff Callbacks (plan d88e22)
9533 - */
9534 -public function mxchat_webhook_handoff_section_callback() {
9535 - echo '<p>' . esc_html__('Send live-agent handoffs to any URL you choose — your helpdesk, an automation flow, a CRM.', 'mxchat') . '</p>';
9536 -}
9537 1729
9538 -public function mxchat_webhook_handoff_status_callback() {
9539 - $fresh_options = get_option('mxchat_options');
9540 - $status = isset($fresh_options['webhook_handoff_status']) ? $fresh_options['webhook_handoff_status'] : 'off';
9541 1730
9542 - echo '<label class="toggle-switch">';
9543 - echo sprintf(
9544 - '<input type="checkbox" id="webhook_handoff_status" name="webhook_handoff_status" value="on" %s />',
9545 - checked($status, 'on', false)
9546 - );
9547 - echo '<span class="slider"></span>';
9548 - echo '</label>';
9549 - echo '<label for="webhook_handoff_status" class="mxchat-status-label">';
9550 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9551 - echo '</label>';
9552 -}
9553 1731
9554 -public function mxchat_webhook_handoff_notification_message_callback() {
9555 - $message = isset($this->options['webhook_handoff_notification_message'])
9556 - ? $this->options['webhook_handoff_notification_message']
9557 - : __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat');
9558 1732
9559 - printf(
9560 - '<textarea id="webhook_handoff_notification_message" name="webhook_handoff_notification_message" rows="3" cols="50">%s</textarea>',
9561 - esc_textarea($message)
9562 - );
9563 - echo '<p class="description">' . esc_html__('Message shown after the handoff is delivered. The chat stays in AI mode — your team follows up separately, so let the visitor know what to expect.', 'mxchat') . '</p>';
9564 -}
1733 + public function mxchat_enqueue_admin_assets() {
1734 + wp_enqueue_style('wp-color-picker');
9565 1735
9566 -public function mxchat_webhook_handoff_away_message_callback() {
9567 - $message = isset($this->options['webhook_handoff_away_message'])
9568 - ? $this->options['webhook_handoff_away_message']
9569 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
1736 + // Get the plugin version or file modification time for cache busting
1737 + $plugin_version = '1.1.7'; // Replace this with your plugin's version
9570 1738
9571 - printf(
9572 - '<textarea id="webhook_handoff_away_message" name="webhook_handoff_away_message" rows="3" cols="50">%s</textarea>',
9573 - esc_textarea($message)
9574 - );
9575 - echo '<p class="description">' . esc_html__('Message shown when this destination is offline or outside its scheduled hours.', 'mxchat') . '</p>';
9576 -}
1739 + // File paths
1740 + $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
1741 + $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
1742 + $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
1743 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
9577 1744
9578 -public function mxchat_webhook_handoff_url_callback() {
9579 - $value = isset($this->options['webhook_handoff_url']) ? $this->options['webhook_handoff_url'] : '';
9580 - printf(
9581 - '<input type="url" id="webhook_handoff_url" name="webhook_handoff_url" value="%s" class="regular-text" placeholder="https://example.com/hooks/mxchat" />',
9582 - esc_attr($value)
9583 - );
9584 - echo '<p class="description">' . esc_html__('Where handoffs are sent as a JSON POST. Must be https and publicly reachable (localhost and private-network hosts are rejected).', 'mxchat') . '</p>';
1745 + // Check if files exist and get modification times
1746 + $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
1747 + $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
1748 + $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
1749 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
9585 1750
9586 - // Surface the last failed delivery right where it gets fixed — a handoff
9587 - // that silently 404s is worse than no handoff. A successful one clears this.
9588 - $webhook_error = get_option('mxchat_webhook_handoff_error');
9589 - if (!empty($webhook_error['error']) && trim((string) $value) !== '' && ($webhook_error['configured'] ?? '') === trim((string) $value)) {
9590 - echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this URL', 'mxchat') . '</strong> — '
9591 - . esc_html(sprintf(
9592 - /* translators: %s: the delivery failure, e.g. an HTTP status or a transport error */
9593 - __('the request failed with "%s". Until this is fixed, the chatbot answers these conversations itself instead of telling visitors a human was notified.', 'mxchat'),
9594 - $webhook_error['error']
9595 - )) . '</p>';
9596 - }
9597 -}
1751 + // Enqueue scripts and styles with corrected paths
1752 + wp_enqueue_script(
1753 + 'mxchat-color-picker',
1754 + plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
1755 + array('wp-color-picker'),
1756 + $color_picker_version,
1757 + true
1758 + );
9598 1759
9599 -public function mxchat_webhook_handoff_secret_callback() {
9600 - printf(
9601 - '<input type="password" id="webhook_handoff_secret" name="webhook_handoff_secret" value="%s" class="regular-text" />',
9602 - isset($this->options['webhook_handoff_secret']) ? esc_attr($this->options['webhook_handoff_secret']) : ''
9603 - );
9604 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'webhook_handoff_secret\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9605 - echo '<p class="description">' . esc_html__('Optional. When set, each POST carries an X-MxChat-Signature header (sha256 HMAC of the body) so your endpoint can verify the sender. The secret itself is never sent.', 'mxchat') . '</p>';
9606 -}
1760 + wp_enqueue_script(
1761 + 'mxchat-embedding-check',
1762 + plugin_dir_url(__FILE__) . '../js/embedding-check.js',
1763 + array(),
1764 + $embedding_check_version,
1765 + true
1766 + );
9607 1767
9608 -public function mxchat_similarity_threshold_callback() {
9609 - // Load from mxchat_options array
9610 - $options = get_option('mxchat_options', []);
1768 + wp_enqueue_script(
1769 + 'mxchat-transcripts-js',
1770 + plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
1771 + array('jquery'),
1772 + $transcripts_js_version,
1773 + true
1774 + );
9611 1775
9612 - // Get value from options array with default of 35
9613 - $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
1776 + wp_enqueue_script(
1777 + 'mxchat-admin-js',
1778 + plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
1779 + array('jquery'),
1780 + $plugin_version,
1781 + true
1782 + );
9614 1783
9615 - echo '<div class="slider-container">';
9616 - echo sprintf(
9617 - '<input type="range"
9618 - id="similarity_threshold"
9619 - name="similarity_threshold"
9620 - min="20"
9621 - max="85"
9622 - step="1"
9623 - value="%s"
9624 - class="range-slider" />',
9625 - esc_attr($threshold)
9626 - );
9627 - echo sprintf(
9628 - '<span id="threshold_value" class="range-value">%s</span>',
9629 - esc_html($threshold)
9630 - );
9631 - echo '</div>';
9632 -}
1784 + wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
1785 + 'ajax_url' => admin_url('admin-ajax.php'),
1786 + 'nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
1787 + ));
9633 1788
9634 -public function mxchat_max_input_length_callback() {
9635 - // Load from mxchat_options array (plan a3fae2 part C).
9636 - $options = get_option('mxchat_options', []);
1789 + wp_enqueue_style(
1790 + 'mxchat-admin-css',
1791 + plugin_dir_url(__FILE__) . '../css/admin-style.css',
1792 + array(),
1793 + $admin_css_version
1794 + );
9637 1795
9638 - // 0 = unlimited (default — preserves current behavior, no cap).
9639 - $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0;
1796 + wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
1797 + 'ajax_url' => admin_url('admin-ajax.php'),
1798 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
1799 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
1800 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
1801 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
1802 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
1803 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
1804 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
1805 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
1806 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
1807 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
1808 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
1809 + 'pre_chat_message' => $this->options['pre_chat_message'] ?? 'Hey there! Ask me anything!',
1810 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9640 1811
9641 - echo sprintf(
9642 - '<input type="number"
9643 - id="max_input_length"
9644 - name="max_input_length"
9645 - min="0"
9646 - max="100000"
9647 - step="1"
9648 - value="%s"
9649 - placeholder="0"
9650 - class="mxch-input mxch-input-sm" />',
9651 - esc_attr($max_input_length)
9652 - );
9653 -}
1812 + // New fields for Loops Integration
1813 + 'loops_api_key' => $this->options['loops_api_key'] ?? '',
1814 + 'loops_mailing_list' => $this->options['loops_mailing_list'] ?? '',
1815 + 'trigger_keywords' => $this->options['trigger_keywords'] ?? '',
1816 + 'triggered_phrase_response' => $this->options['triggered_phrase_response'] ?? 'Would you like to join our mailing list? Please provide your email below.',
1817 + 'email_capture_response' => $this->options['email_capture_response'] ?? 'Thank you for providing your email! You\'ve been added to our list.'
1818 + ));
9654 1819
9655 -public function mxchat_rag_sources_limit_callback() {
9656 - // Load from mxchat_options array
9657 - $options = get_option('mxchat_options', []);
9658 1820
9659 - // Get value from options array with default of 3
9660 - $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
9661 -
9662 - echo '<div class="slider-container">';
9663 - echo sprintf(
9664 - '<input type="range"
9665 - id="rag_sources_limit"
9666 - name="rag_sources_limit"
9667 - min="3"
9668 - max="10"
9669 - step="1"
9670 - value="%s"
9671 - class="range-slider" />',
9672 - esc_attr($rag_sources_limit)
9673 - );
9674 - echo sprintf(
9675 - '<span id="rag_sources_limit_value" class="range-value">%s</span>',
9676 - esc_html($rag_sources_limit)
9677 - );
9678 - echo '</div>';
9679 -}
9680 -
9681 -public function mxchat_rag_chunks_limit_callback() {
9682 - // Load from mxchat_options array
9683 - $options = get_option('mxchat_options', []);
9684 -
9685 - // Get value from options array with default of 15
9686 - $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
9687 -
9688 - echo '<div class="slider-container">';
9689 - echo sprintf(
9690 - '<input type="range"
9691 - id="rag_chunks_limit"
9692 - name="rag_chunks_limit"
9693 - min="8"
9694 - max="20"
9695 - step="1"
9696 - value="%s"
9697 - class="range-slider" />',
9698 - esc_attr($rag_chunks_limit)
9699 - );
9700 - echo sprintf(
9701 - '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
9702 - esc_html($rag_chunks_limit)
9703 - );
9704 - echo '</div>';
9705 -}
9706 -
9707 -/**
9708 - * Add body class on the Onboarding wizard page so CSS-only chrome surgery
9709 - * (collapsing the WP admin sidebar) only applies on this page.
9710 - * Plan: plan-mxchat-20260527-905439.
9711 - */
9712 -public function mxchat_add_onboarding_body_class($classes) {
9713 - if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') {
9714 - $classes .= ' mxchat-onboarding-focused';
9715 1821 }
9716 - return $classes;
9717 -}
9718 1822
9719 -public function mxchat_enqueue_admin_assets($hook_suffix = '') {
9720 - // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY
9721 - // guard here was the strpos() on $_GET['page'] below — which is
9722 - // attacker-controlled — so ANY logged-in user (Subscriber included) could
9723 - // load a page they are legitimately allowed to see, e.g.
9724 - // /wp-admin/profile.php?page=mxchat, and receive every nonce this method
9725 - // localizes. Three of the handlers behind those nonces verified the nonce
9726 - // but checked no capability. Every MxChat menu page is registered
9727 - // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for
9728 - // legitimate users.
9729 - if (!current_user_can('manage_options')) {
9730 - return;
9731 - }
1823 + public function mxchat_sanitize($input) {
1824 + $new_input = array();
9732 1825
9733 - // Get plugin version
9734 - $version = MXCHAT_VERSION;
1826 + if (isset($input['api_key'])) {
1827 + $new_input['api_key'] = sanitize_text_field($input['api_key']);
1828 + }
9735 1829
9736 - // Use file modification time for development (remove in production)
9737 - if (defined('WP_DEBUG') && WP_DEBUG) {
9738 - $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
9739 - }
1830 + if (isset($input['enable_woocommerce_integration'])) {
1831 + $new_input['enable_woocommerce_integration'] = isset($input['enable_woocommerce_integration']) && $input['enable_woocommerce_integration'] === '1' ? '1' : '0';
9740 1832
9741 - $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
9742 - $plugin_url = plugin_dir_url(__FILE__) . '../';
1833 + }
9743 1834
9744 - // Only load on MxChat pages. Prefer the server-derived $hook_suffix that
9745 - // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be
9746 - // forged onto a screen MxChat does not own. Falls back to the legacy
9747 - // $_GET check only when the hook is unavailable (direct/legacy callers).
9748 - if ($hook_suffix !== '') {
9749 - if (strpos($hook_suffix, 'mxchat') === false) {
9750 - return;
1835 + if (isset($input['privacy_toggle'])) {
1836 + $new_input['privacy_toggle'] = $input['privacy_toggle'];
9751 1837 }
9752 - } elseif (strpos($current_page, 'mxchat') === false) {
9753 - return;
9754 - }
9755 1838
9756 - // Always load these on all MxChat pages
9757 - $this->enqueue_core_admin_assets($plugin_url, $version);
9758 - $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
9759 - $this->localize_admin_scripts($current_page);
9760 -}
9761 -private function enqueue_core_admin_assets($plugin_url, $version) {
9762 - // Core admin styles
9763 - wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
9764 - wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
1839 + if (isset($input['complianz_toggle'])) {
1840 + $new_input['complianz_toggle'] = $input['complianz_toggle'];
1841 + }
9765 1842
9766 - // New sidebar navigation styles (for main settings page)
9767 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
1843 + // Handle custom privacy text input
1844 + if (isset($input['privacy_text'])) {
1845 + // Allow basic HTML for links
1846 + $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
1847 + }
9768 1848
9769 - // Core admin scripts
9770 - wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
9771 -}
9772 -private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
9773 - switch ($current_page) {
9774 - case 'mxchat-prompts':
9775 - // Shared shell JS: tab switching, deep-linking and the mobile menu
9776 - // for this page's flat nav (inline copies removed by plan c192a4).
9777 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9778 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9779 - 'copied' => __('Copied', 'mxchat'),
9780 - ));
9781 - // Knowledge processing page assets
9782 - wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
9783 - wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
9784 - // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
9785 - wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
9786 - // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the
9787 - // Testing tab's match-card / chunk-detail components, which are scoped
9788 - // under .mxch-testing-results. Load that stylesheet here so the inspector
9789 - // modal renders identically to the Testing tab.
9790 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version);
9791 - break;
9792 1849
9793 - case 'mxchat-transcripts':
9794 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9795 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9796 - // Load transcripts-specific styles
9797 - wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
9798 - wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
9799 - break;
1850 + if (isset($input['enable_woocommerce_order_access'])) {
1851 + $new_input['enable_woocommerce_order_access'] = isset($input['enable_woocommerce_order_access']) && $input['enable_woocommerce_order_access'] === '1' ? '1' : '0';
9800 1852
9801 - case 'mxchat-actions':
9802 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9803 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9804 - // Load actions-specific styles
9805 - wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
9806 - wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
1853 + }
9807 1854
9808 - // Localize script data for actions page
9809 - $is_activated = get_option('mxchat_pro_license_status') === 'active';
9810 - wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
9811 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9812 - 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
9813 - 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9814 - 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
9815 - 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
9816 - 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
9817 - 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9818 - 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9819 - 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9820 - 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9821 - 'isActivated' => $is_activated,
9822 - 'i18n' => array(
9823 - 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'),
9824 - 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'),
9825 - 'saving' => __('Saving...', 'mxchat'),
9826 - 'saved' => __('Saved successfully!', 'mxchat'),
9827 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9828 - 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
9829 - 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
9830 - )
9831 - ));
9832 - break;
1855 + if (isset($input['system_prompt_instructions'])) {
1856 + $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
1857 + }
9833 1858
9834 - case 'mxchat-activation':
9835 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9836 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9837 - // Load pro page-specific styles
9838 - wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
9839 - // Load pro page JavaScript
9840 - wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
9841 - // Load activation script for license activation/deactivation
9842 - wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
9843 - break;
1859 + if (isset($input['mxchat_pro_email'])) {
1860 + $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
1861 + }
9844 1862
9845 - case 'mxchat-content':
9846 - // Load admin sidebar CSS (shared styles for sidebar navigation)
9847 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9848 - // Load content page-specific styles
9849 - wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
9850 - // Load content page JavaScript
9851 - wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
9852 - break;
1863 + if (isset($input['mxchat_activation_key'])) {
1864 + $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
1865 + }
9853 1866
9854 - case 'mxchat-api-access':
9855 - // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
9856 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9857 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9858 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9859 - 'copied' => __('Copied', 'mxchat'),
9860 - ));
9861 - break;
1867 + if (isset($input['append_to_body'])) {
1868 + $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
1869 + }
9862 1870
9863 - case 'mxchat-max':
9864 - case 'mxchat-onboarding':
9865 - // Onboarding page — uses the shared admin shell PLUS the wizard
9866 - // overlay (plan-905439). admin-onboarding-wizard.css scopes the
9867 - // WP-chrome surgery to body.mxchat-onboarding-focused so it only
9868 - // applies on THIS page. The body class is added below via the
9869 - // admin_body_class filter.
9870 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9871 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9872 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9873 - 'copied' => __('Copied', 'mxchat'),
9874 - ));
9875 - // admin-style.css provides the .mxchat-instructions-modal-* classes
9876 - // the new Behavior step's "View Sample Instructions" modal needs.
9877 - // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay
9878 - // so the wizard's own rules win where they collide. plan-a2e4d6.
9879 - wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version);
9880 - 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);
9881 - wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true);
9882 - break;
9883 - default:
9884 - // Settings page: load the shared shell JS for #hash deep-linking
9885 - // to tabs (plan 4ede16). The page's own inline nav script owns
9886 - // clicks/accordion behaviour; the shell script adds load +
9887 - // hashchange activation and replaceState so plain href="#tab"
9888 - // anchors and shared URLs land on the right tab. Kept inside the
9889 - // default case because the settings page also needs everything
9890 - // below (Testing tab chatbot + streaming assets).
9891 - if ($current_page === 'mxchat-settings') {
9892 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9893 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9894 - 'copied' => __('Copied', 'mxchat'),
9895 - ));
9896 - }
1871 + if (isset($input['top_bar_title'])) {
1872 + $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
1873 + }
9897 1874
9898 - wp_enqueue_script(
9899 - 'mxchat-test-streaming-js',
9900 - $plugin_url . 'js/mxchat-test-streaming.js',
9901 - ['jquery'],
9902 - $version,
9903 - true
9904 - );
1875 + if (isset($input['intro_message'])) {
1876 + $new_input['intro_message'] = sanitize_text_field($input['intro_message']);
1877 + }
9905 1878
9906 - wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
9907 - 'ajax_url' => admin_url('admin-ajax.php'),
9908 - 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
9909 - 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
9910 - ]);
9911 -
9912 - // Testing Tab: Load chatbot assets for the embedded testing chatbot
9913 - wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
9914 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
9915 -
9916 - wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
9917 - wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
9918 -
9919 - // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
9920 - do_action('mxchat_enqueue_testing_tab_assets');
9921 -
9922 - // Localize mxchatChat for the chatbot JS (same settings as frontend)
9923 - $options = get_option('mxchat_options', array());
9924 - $prompts_options = get_option('mxchat_prompts_options', array());
9925 - $theme_options = get_option('mxchat_theme_options', array());
9926 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
9927 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
9928 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
9929 -
9930 - wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
9931 - 'ajax_url' => admin_url('admin-ajax.php'),
9932 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
9933 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
9934 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
9935 - 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
9936 - 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
9937 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9938 - 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
9939 - 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
9940 - 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
9941 - 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
9942 - 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
9943 - 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
9944 - 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
9945 - 'close_button_color' => $options['close_button_color'] ?? '#fff',
9946 - 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
9947 - 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
9948 - 'icon_color' => $options['icon_color'] ?? '#fff',
9949 - 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
9950 - 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
9951 - 'appendWidgetToBody' => 'off',
9952 - 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
9953 - 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
9954 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
9955 - 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
9956 - 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
9957 - 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
9958 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
9959 - 'email_collection_enabled' => 'off', // No email collection in testing
9960 - 'initial_email_state' => null,
9961 - 'skip_email_check' => true,
9962 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
9963 - 'skip_inline_colors' => $skip_inline_colors,
9964 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
9965 - ));
9966 -
9967 - // Localize testing tab script data
9968 - wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
9969 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9970 - 'nonce' => wp_create_nonce('mxchat_test_nonce'),
9971 - 'isAdmin' => true,
9972 - 'testingEnabled' => true
9973 - ));
9974 -
9975 - // Add testing enabled flag for the chatbot to return debug data
9976 - add_action('admin_footer', function() {
9977 - echo '<script>window.mxchatTestingEnabled = true;</script>';
9978 - });
9979 -
9980 - break;
9981 - }
9982 -}
9983 -/**
9984 - * The base mxchatAdmin payload shared by every MxChat admin page.
9985 - *
9986 - * Extracted (plan c192a4) so page-specific re-localizations of the SAME
9987 - * global — the knowledge page prints a second `var mxchatAdmin` via the
9988 - * mxchat-knowledge-processing handle, and last-printed wins — can merge
9989 - * their extra keys on top of this instead of silently narrowing the object
9990 - * that mxchat-admin.js also reads on that page.
9991 - */
9992 -private function mxchat_get_admin_base_localization() {
9993 - return array(
9994 - 'ajax_url' => admin_url('admin-ajax.php'),
9995 - 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
9996 - 'admin_url' => admin_url(),
9997 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
9998 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
9999 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10000 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
10001 - 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
10002 - 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
10003 - 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
10004 - 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
10005 - 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
10006 - 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
10007 - 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
10008 - 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
10009 - 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
10010 - 'is_activated' => $this->is_activated ? '1' : '0',
10011 - 'status_refresh_interval' => 5000,
10012 - 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'),
10013 - 'unsaved_label' => __('Unsaved', 'mxchat'),
10014 - // Live-agent schedule status text (plan 8ccaa2).
10015 - 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'),
10016 - 'i18n_always_available' => __('Always available', 'mxchat'),
10017 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10018 - 'ajaxurl' => admin_url('admin-ajax.php')
10019 - );
10020 -}
10021 -private function localize_admin_scripts($current_page) {
10022 - // Base localization data for main admin script
10023 - $base_data = $this->mxchat_get_admin_base_localization();
10024 -
10025 - // Localize main admin script with base data
10026 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
10027 -
10028 - // Canonical chat-model catalog for the modal picker grid
10029 - // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php
10030 - // automatically appears here.
10031 - if (!class_exists('MxChat_Model_Catalog')) {
10032 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
10033 - }
10034 - wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape());
10035 -
10036 - // Page-specific localizations
10037 - $this->localize_page_specific_scripts($current_page);
10038 -}
10039 -private function localize_page_specific_scripts($current_page) {
10040 - switch ($current_page) {
10041 - case 'mxchat-prompts':
10042 - // Status updater localization
10043 - wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
10044 - 'ajax_url' => admin_url('admin-ajax.php'),
10045 - 'nonce' => wp_create_nonce('mxchat_status_nonce')
10046 - ));
10047 -
10048 - // Content selector localization
10049 - wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
10050 - 'ajaxurl' => admin_url('admin-ajax.php'),
10051 - 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
10052 - 'i18n' => array(
10053 - 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
10054 - 'selectAll' => __('Select All', 'mxchat'),
10055 - 'process' => __('Process Selected', 'mxchat'),
10056 - 'cancel' => __('Cancel', 'mxchat'),
10057 - 'noResults' => __('No content found.', 'mxchat'),
10058 - 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
10059 - 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
10060 - )
10061 - ));
10062 -
10063 - // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's
10064 - // base one) and last-printed wins — so it must carry the FULL base
10065 - // payload plus the knowledge-page extras, or every mxchatAdmin.*
10066 - // key mxchat-admin.js reads on this page comes up undefined
10067 - // (plan c192a4). Extras merge last: status_refresh_interval stays
10068 - // at this page's faster 2000ms cadence.
10069 - wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge(
10070 - $this->mxchat_get_admin_base_localization(),
10071 - array(
10072 - 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
10073 - 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
10074 - 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
10075 - 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10076 - 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
10077 - 'status_refresh_interval' => 2000,
10078 - 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
10079 - )
10080 - ));
10081 - break;
10082 -
10083 - case 'mxchat-activation':
10084 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
10085 - // fixed here by a5b297): this second `var mxchatAdmin` must carry
10086 - // the full base payload plus the page extras.
10087 - wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge(
10088 - $this->mxchat_get_admin_base_localization(),
10089 - array(
10090 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
10091 - )
10092 - ));
10093 - break;
10094 -
10095 - case 'mxchat-content':
10096 - wp_localize_script('mxchat-content-js', 'mxchatContent', array(
10097 - 'ajaxUrl' => admin_url('admin-ajax.php'),
10098 - 'nonce' => wp_create_nonce('mxchat_content_nonce'),
10099 - 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10100 - 'previewUrl' => home_url('/?p='),
10101 - 'isActivated' => $this->is_activated(),
10102 - 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
10103 - 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
10104 - // Whether Search Console is actually LINKED — distinct from hasGSC
10105 - // (add-on active). Reads the same option the add-on's settings
10106 - // card keys off; harmless false when the add-on is absent.
10107 - 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false),
10108 - 'seoOptimize' => array(
10109 - 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
10110 - 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
10111 - 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
10112 - 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
10113 - 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
10114 - 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
10115 - 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
10116 - ),
10117 - 'i18n' => array(
10118 - 'generating' => __('Generating...', 'mxchat'),
10119 - 'planning' => __('Planning content structure...', 'mxchat'),
10120 - 'images' => __('Generating images...', 'mxchat'),
10121 - 'writing' => __('Writing full content...', 'mxchat'),
10122 - 'creating' => __('Creating WordPress post...', 'mxchat'),
10123 - 'done' => __('Content generated successfully!', 'mxchat'),
10124 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
10125 - 'editSuccess' => __('Content updated successfully.', 'mxchat'),
10126 - 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
10127 - )
10128 - ));
10129 - break;
10130 -
10131 - case 'mxchat-transcripts':
10132 - // Get chart data for localization
10133 - $chart_data = $this->get_transcripts_chart_data();
10134 -
10135 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
10136 - // fixed here by a5b297): merge the base payload under the page keys.
10137 - // export_nonce/setting_nonce/ajax_url duplicate base values identically;
10138 - // delete_nonce and translate_nonce are the page-specific adds.
10139 - wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge(
10140 - $this->mxchat_get_admin_base_localization(),
10141 - array(
10142 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
10143 - 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
10144 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
10145 - 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
10146 - )
10147 - ));
10148 -
10149 - // Localize chart data separately - use array_values to ensure proper JSON array encoding
10150 - wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
10151 - 'labels' => array_values($chart_data['labels']),
10152 - 'chats' => array_values($chart_data['chats']),
10153 - 'messages' => array_values($chart_data['messages'])
10154 - ));
10155 - break;
10156 -
10157 - case 'mxchat-settings':
10158 - default:
10159 - // The 'mxchatStyleSettings' localize that used to live here was
10160 - // REMOVED by plan-mxchat-20260731-c63fb6.
10161 - //
10162 - // It targeted the script handle 'mxchat-color-picker', which is
10163 - // registered/enqueued NOWHERE in the plugin — so wp_localize_script()
10164 - // returned false and printed nothing. That accident was the only
10165 - // thing keeping it from being a live secret disclosure: the payload
10166 - // carried loops_api_key, live_agent_secret_key and
10167 - // live_agent_bot_token in full, and this whole method ran for any
10168 - // logged-in user (see the capability gate added to
10169 - // mxchat_enqueue_admin_assets). One future
10170 - // wp_enqueue_script('mxchat-color-picker', ...) would have printed
10171 - // three secrets into page HTML for Subscribers.
10172 - //
10173 - // Nothing consumed the object: a tree-wide grep for
10174 - // 'mxchatStyleSettings' returns only this call site, and js/ names
10175 - // loops_api_key only at mxchat-admin.js:572, as a field-NAME string
10176 - // in an autosave allowlist — not a value read. Removed entirely
10177 - // rather than deleting just the three secret keys, so there is no
10178 - // dead payload left for someone to re-arm.
10179 - break;
10180 - }
10181 -
10182 - // Additional localization that was in the original code
10183 - wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
10184 - 'ajax_url' => admin_url('admin-ajax.php'),
10185 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
10186 - ));
10187 -}
10188 -
10189 -public function mxchat_sanitize($input) {
10190 - $new_input = array();
10191 -
10192 - if (isset($input['api_key'])) {
10193 - $new_input['api_key'] = sanitize_text_field($input['api_key']);
10194 - }
10195 -
10196 - if (isset($input['similarity_threshold'])) {
10197 - $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
10198 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
10199 - }
10200 -
10201 - if (isset($input['rag_sources_limit'])) {
10202 - $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
10203 - $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
10204 - }
10205 -
10206 - if (isset($input['rag_chunks_limit'])) {
10207 - $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
10208 - $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
10209 - }
10210 -
10211 - if (isset($input['xai_api_key'])) {
10212 - $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
10213 - }
10214 -
10215 - if (isset($input['claude_api_key'])) {
10216 - $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
10217 - }
10218 -
10219 - if (isset($input['enable_streaming_toggle'])) {
10220 - $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
10221 - } else {
10222 - // If checkbox not checked, it won't be in $input, so set to 'off'
10223 - $new_input['enable_streaming_toggle'] = 'off';
10224 - }
10225 -
10226 - if (isset($input['enable_web_search'])) {
10227 - $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
10228 - } else {
10229 - // If checkbox not checked, it won't be in $input, so set to 'off'
10230 - $new_input['enable_web_search'] = 'off';
10231 - }
10232 -
10233 - if (isset($input['deepseek_api_key'])) {
10234 - $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
10235 - }
10236 -
10237 - if (isset($input['gemini_api_key'])) {
10238 - $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
10239 - }
10240 -
10241 - if (isset($input['enable_woocommerce_integration'])) {
10242 - $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
10243 - }
10244 -
10245 - if (isset($input['privacy_toggle'])) {
10246 - $new_input['privacy_toggle'] = $input['privacy_toggle'];
10247 - }
10248 -
10249 - if (isset($input['complianz_toggle'])) {
10250 - $new_input['complianz_toggle'] = $input['complianz_toggle'];
10251 - }
10252 -
10253 - // Handle custom privacy text input
10254 - if (isset($input['privacy_text'])) {
10255 - // Allow basic HTML for links
10256 - $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
10257 - }
10258 -
10259 - if (isset($input['system_prompt_instructions'])) {
10260 - $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
10261 - }
10262 -
10263 - if (isset($input['mxchat_pro_email'])) {
10264 - $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
10265 - }
10266 -
10267 - if (isset($input['mxchat_activation_key'])) {
10268 - $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
10269 - }
10270 -
10271 - if (isset($input['append_to_body'])) {
10272 - $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
10273 - }
10274 -
10275 - // Post type visibility settings
10276 - if (isset($input['post_type_visibility_mode'])) {
10277 - $allowed_modes = array('all', 'include', 'exclude');
10278 - $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
10279 - ? $input['post_type_visibility_mode']
10280 - : 'all';
10281 - }
10282 -
10283 - if (isset($input['post_type_visibility_list'])) {
10284 - if (is_array($input['post_type_visibility_list'])) {
10285 - $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
10286 - } else {
10287 - $new_input['post_type_visibility_list'] = array();
1879 + if (isset($input['input_copy'])) {
1880 + $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10288 1881 }
10289 - }
10290 1882
10291 - if (isset($input['contextual_awareness_toggle'])) {
10292 - $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
10293 -}
10294 1883
10295 - if (isset($input['citation_links_toggle'])) {
10296 - $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
10297 -}
10298 -
10299 - if (isset($input['strip_unapproved_links_toggle'])) {
10300 - $new_input['strip_unapproved_links_toggle'] = $input['strip_unapproved_links_toggle'] === 'on' ? 'on' : 'off';
10301 -}
10302 -
10303 - // Satisfaction rating prompt — defaults ON when unchecked (so first save
10304 - // doesn't accidentally disable it). The form posts 'on' when checked;
10305 - // unchecked checkboxes don't post a value at all, so we infer 'off' only
10306 - // when the autosave/PHP request explicitly clears it via empty string.
10307 - if (array_key_exists('satisfaction_rating_enabled', $input)) {
10308 - $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
10309 - }
10310 -
10311 - // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
10312 - // the 4 text strings are sanitized + capped server-side. Blank values are
10313 - // preserved so the integrator falls back to translated defaults.
10314 - if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
10315 - $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
10316 - }
10317 -
10318 - // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default,
10319 - // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out
10320 - // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist,
10321 - // so without this isset-handler the key is stripped on the next save of ANY field
10322 - // (the 2c02ea global-rate-limit footgun).
10323 - if (array_key_exists('max_input_length', $input)) {
10324 - $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length'])));
10325 - }
10326 - if (array_key_exists('satisfaction_rating_question', $input)) {
10327 - $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
10328 - }
10329 - if (array_key_exists('satisfaction_rating_thanks', $input)) {
10330 - $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
10331 - }
10332 - if (array_key_exists('satisfaction_rating_placeholder', $input)) {
10333 - $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
10334 - }
10335 - if (array_key_exists('satisfaction_rating_saved', $input)) {
10336 - $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
10337 - }
10338 -
10339 - if (isset($input['top_bar_title'])) {
10340 - $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
10341 - }
10342 -
10343 - if (isset($input['ai_agent_text'])) {
10344 - $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
1884 + if (isset($input['rate_limit_message'])) {
1885 + $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10345 1886 }
10346 1887
10347 - if (isset($input['enable_email_block'])) {
10348 - $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
10349 - }
1888 + if (isset($input['rate_limit'])) {
1889 + $allowed_limits = array('5', '10', '15', '20', '100');
1890 + $rate_limit = sanitize_text_field($input['rate_limit']);
10350 1891
10351 - if (isset($input['email_blocker_header_content'])) {
10352 - // wp_kses_post() allows standard HTML tags permitted by WordPress
10353 - $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
10354 - }
10355 - if (isset($input['email_blocker_button_text'])) {
10356 - $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
10357 - }
10358 - // Sanitize name field toggle
10359 - if (isset($input['enable_name_field'])) {
10360 - $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
10361 - } else {
10362 - $new_input['enable_name_field'] = 'off';
10363 - }
10364 - // Sanitize name field placeholder
10365 - if (isset($input['name_field_placeholder'])) {
10366 - $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
10367 - }
10368 - // Consent checkbox (b062c4). Both toggles default off — an unchecked box
10369 - // posts nothing, so the else-branch is what makes unticking stick.
10370 - if (isset($input['enable_consent_checkbox'])) {
10371 - $new_input['enable_consent_checkbox'] = ($input['enable_consent_checkbox'] === 'on') ? 'on' : 'off';
10372 - } else {
10373 - $new_input['enable_consent_checkbox'] = 'off';
10374 - }
10375 - if (isset($input['consent_checkbox_label'])) {
10376 - // Shared allowlist with the render path — see MxChat_Utils::sanitize_consent_label().
10377 - $new_input['consent_checkbox_label'] = MxChat_Utils::sanitize_consent_label($input['consent_checkbox_label']);
10378 - }
10379 - if (isset($input['consent_checkbox_required'])) {
10380 - $new_input['consent_checkbox_required'] = ($input['consent_checkbox_required'] === 'on') ? 'on' : 'off';
10381 - } else {
10382 - $new_input['consent_checkbox_required'] = 'off';
10383 - }
10384 - if (isset($input['intro_message'])) {
10385 - $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
10386 - }
10387 -
10388 - if (isset($input['input_copy'])) {
10389 - $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10390 - }
10391 -
10392 - if (isset($input['rate_limit_message'])) {
10393 - $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10394 - }
10395 -
10396 -// Handle the new rate limits format
10397 -if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
10398 - $new_input['rate_limits'] = array();
10399 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10400 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10401 -
10402 - foreach ($input['rate_limits'] as $role_id => $settings) {
10403 - $new_input['rate_limits'][$role_id] = array();
10404 -
10405 - // Sanitize limit
10406 - if (isset($settings['limit'])) {
10407 - $limit = sanitize_text_field($settings['limit']);
10408 - // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive
10409 - // integer (custom value) — mirrors the global branch (plan-2c02ea). Without
10410 - // the custom path the per-role custom input was dropped and reset to the role
10411 - // default on every save (plan-7e23e7).
10412 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10413 - $new_input['rate_limits'][$role_id]['limit'] = $limit;
1892 + if (in_array($rate_limit, $allowed_limits, true)) {
1893 + $new_input['rate_limit'] = $rate_limit;
10414 1894 } else {
10415 - $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
1895 + // Set a default or a fallback value in case of an invalid entry
1896 + $new_input['rate_limit'] = '100';
10416 1897 }
10417 1898 }
10418 1899
10419 - // Preserve the per-role custom value (mirrors the global branch's limit_custom).
10420 - if (isset($settings['limit_custom'])) {
10421 - $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']);
1900 +
1901 + if (isset($input['pre_chat_message'])) {
1902 + $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10422 1903 }
10423 1904
10424 - // Sanitize timeframe
10425 - if (isset($settings['timeframe'])) {
10426 - $timeframe = sanitize_text_field($settings['timeframe']);
10427 - if (in_array($timeframe, $allowed_timeframes, true)) {
10428 - $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
10429 - } else {
10430 - $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
1905 + if (isset($input['model'])) {
1906 + $allowed_models = array(
1907 + 'gpt-4o',
1908 + 'gpt-4o-mini',
1909 + 'gpt-4-turbo',
1910 + 'gpt-4',
1911 + 'gpt-3.5-turbo',
1912 + );
1913 + if (in_array($input['model'], $allowed_models)) {
1914 + $new_input['model'] = sanitize_text_field($input['model']);
10431 1915 }
10432 1916 }
10433 1917
10434 - // Sanitize message
10435 - if (isset($settings['message'])) {
10436 - $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
1918 + // Sanitize new pro features
1919 + if (isset($input['close_button_color'])) {
1920 + $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
10437 1921 }
10438 - }
10439 -}
10440 1922
10441 -// Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea).
10442 -// Mirrors the per-role block above, adapted to the single global shape. Without
10443 -// this branch the whitelist-rebuild dropped rate_limits_global entirely on every
10444 -// save, so the global cap silently fell back to its 'unlimited' default.
10445 -// MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed.
10446 -if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) {
10447 - $g = $input['rate_limits_global'];
10448 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10449 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10450 - $global_out = array();
1923 + if (isset($input['chatbot_bg_color'])) {
1924 + $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
1925 + }
10451 1926
10452 - if (isset($g['limit'])) {
10453 - $limit = sanitize_text_field($g['limit']);
10454 - // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the
10455 - // autosave handler / renderer), OR any positive integer (custom value).
10456 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10457 - $global_out['limit'] = $limit;
10458 - } else {
10459 - $global_out['limit'] = 'unlimited';
1927 + if (isset($input['woocommerce_consumer_key'])) {
1928 + $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10460 1929 }
10461 - }
10462 1930
10463 - if (isset($g['limit_custom'])) {
10464 - $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']);
10465 - }
1931 + if (isset($input['woocommerce_consumer_secret'])) {
1932 + $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
1933 + }
10466 1934
10467 - if (isset($g['timeframe'])) {
10468 - $timeframe = sanitize_text_field($g['timeframe']);
10469 - $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily';
10470 - }
1935 + if (isset($input['user_message_bg_color'])) {
1936 + $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
1937 + }
10471 1938
10472 - if (isset($g['message'])) {
10473 - $global_out['message'] = sanitize_textarea_field($g['message']);
10474 - }
1939 + if (isset($input['user_message_font_color'])) {
1940 + $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
1941 + }
10475 1942
10476 - $new_input['rate_limits_global'] = $global_out;
10477 -}
1943 + if (isset($input['bot_message_bg_color'])) {
1944 + $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
1945 + }
10478 1946
10479 - if (isset($input['pre_chat_message'])) {
10480 - $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10481 - }
1947 + if (isset($input['bot_message_font_color'])) {
1948 + $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
1949 + }
10482 1950
10483 - if (isset($input['voyage_api_key'])) {
10484 - $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
10485 - }
1951 + if (isset($input['top_bar_bg_color'])) {
1952 + $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
1953 + }
10486 1954
10487 - // Add to your sanitize function
10488 - if (isset($input['embedding_model'])) {
10489 - // Catalog refactor (plan-d14e89): allowlist derived from the canonical
10490 - // catalog in includes/class-mxchat-model-catalog.php.
10491 - if (!class_exists('MxChat_Model_Catalog')) {
10492 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1955 + if (isset($input['send_button_font_color'])) {
1956 + $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
10493 1957 }
10494 - $allowed_models = MxChat_Model_Catalog::embedding_model_ids();
10495 - if (in_array($input['embedding_model'], $allowed_models)) {
10496 - $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
1958 +
1959 + if (isset($input['chatbot_background_color'])) {
1960 + $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
10497 1961 }
10498 - }
10499 1962
10500 -if (isset($input['model'])) {
10501 - if ($input['model'] === 'openrouter') {
10502 - $new_input['model'] = 'openrouter';
10503 - } else {
10504 - if (!class_exists('MxChat_Model_Catalog')) {
10505 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
1963 + if (isset($input['icon_color'])) {
1964 + $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
10506 1965 }
10507 - $allowed_models = MxChat_Model_Catalog::chat_model_ids();
10508 1966
10509 - if (in_array($input['model'], $allowed_models)) {
10510 - $new_input['model'] = sanitize_text_field($input['model']);
10511 - } else {
10512 - // Fallback for any deprecated model
10513 - $new_input['model'] = 'gpt-5.6-sol';
1967 + if (isset($input['chat_input_font_color'])) {
1968 + $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
10514 1969 }
10515 - }
10516 -}
10517 -
10518 -if (isset($input['openrouter_selected_model'])) {
10519 - // Just sanitize it, don't validate against a whitelist
10520 - $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
10521 -}
10522 1970
10523 -// ADD THIS:
10524 -if (isset($input['openrouter_selected_model_name'])) {
10525 - $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
10526 -}
10527 -
10528 - if (isset($input['openrouter_api_key'])) {
10529 - $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
10530 - }
1971 + // Sanitize link_target_toggle
1972 + if (isset($input['link_target_toggle'])) {
1973 + $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
1974 + }
10531 1975
10532 - // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
10533 - if (isset($input['custom_provider_base_url'])) {
10534 - $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
10535 - }
10536 - if (isset($input['custom_provider_api_key'])) {
10537 - $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
10538 - }
10539 - if (isset($input['custom_provider_model'])) {
10540 - $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
10541 - }
10542 - if (isset($input['custom_provider_auth_scheme'])) {
10543 - $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
10544 - $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
10545 - }
10546 - if (isset($input['custom_provider_for_embeddings'])) {
10547 - $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
10548 - }
10549 - if (isset($input['custom_provider_for_images'])) {
10550 - $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
10551 - }
10552 - if (isset($input['custom_provider_embedding_model'])) {
10553 - $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
10554 - }
10555 - if (isset($input['custom_provider_api_version'])) {
10556 - $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
10557 - }
10558 -
10559 -
10560 -
10561 - if (isset($input['woocommerce_consumer_key'])) {
10562 - $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10563 - }
10564 -
10565 - if (isset($input['woocommerce_consumer_secret'])) {
10566 - $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
10567 - }
10568 -
10569 -
10570 - // Sanitize link_target_toggle
10571 - if (isset($input['link_target_toggle'])) {
10572 - $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
10573 - }
10574 -
10575 - // Sanitize Loops API Key
1976 + // Sanitize Loops API Key
10576 1977 if (isset($input['loops_api_key'])) {
10577 1978 $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
10578 1979 }
10579 1980
@@ -10580,410 +1981,180 @@
10580 1981 if (isset($input['chat_persistence_toggle'])) {
10581 1982 $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
10582 1983 }
10583 1984
10584 - // No else clause: an absent key stays absent, so the front-end default ('on') applies
10585 - // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here).
10586 - if (isset($input['print_button_enabled'])) {
10587 - $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off';
10588 - }
10589 1985
10590 - // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label.
10591 - // No else on the toggle: an absent key stays absent so the front-end '?? off'
10592 - // default applies, and the full-array autosave rebuild preserves a saved value.
10593 - if (isset($input['reset_chat_enabled'])) {
10594 - $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off';
10595 - }
10596 -
10597 - if (isset($input['reset_chat_label'])) {
10598 - $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']);
10599 - }
10600 -
10601 - if (isset($input['popular_question_1'])) {
10602 - $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
10603 - }
10604 -
10605 - if (isset($input['popular_question_2'])) {
10606 - $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']);
10607 - }
10608 -
10609 - if (isset($input['popular_question_3'])) {
10610 - $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']);
10611 - }
10612 -
10613 - if (isset($input['additional_popular_questions']) && is_array($input['additional_popular_questions'])) {
10614 - $new_input['additional_popular_questions'] = array_map('sanitize_text_field', $input['additional_popular_questions']);
10615 - }
10616 -
10617 1986 // Sanitize Loops Mailing List
10618 1987 if (isset($input['loops_mailing_list'])) {
10619 1988 $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
10620 1989 }
10621 1990
10622 -// Sanitize Triggered Phrase Response
1991 + // Sanitize Trigger Keywords
1992 + if (isset($input['trigger_keywords'])) {
1993 + $new_input['trigger_keywords'] = sanitize_text_field($input['trigger_keywords']);
1994 + }
1995 +
1996 + // Sanitize Triggered Phrase Response
10623 1997 if (isset($input['triggered_phrase_response'])) {
10624 1998 $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
10625 1999 }
2000 +
10626 2001 if (isset($input['email_capture_response'])) {
10627 - $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
2002 + $new_input['email_capture_response'] = sanitize_textarea_field($input['email_capture_response']);
10628 2003 }
10629 2004
10630 - // Sanitize Brave Search Settings
10631 - if (isset($input['brave_api_key'])) {
10632 - $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
2005 + return $new_input;
10633 2006 }
10634 2007
10635 - if (isset($input['brave_image_count'])) {
10636 - $image_count = intval($input['brave_image_count']);
10637 - $new_input['brave_image_count'] = ($image_count >=1 && $image_count <=6) ? $image_count : 4;
10638 - }
10639 2008
10640 - if (isset($input['brave_safe_search'])) {
10641 - $allowed = array('strict', 'off');
10642 - $new_input['brave_safe_search'] = in_array($input['brave_safe_search'], $allowed, true) ? $input['brave_safe_search'] : 'strict';
2009 + // Method to append the chatbot to the body
2010 + public function mxchat_append_chatbot_to_body() {
2011 + $options = get_option('mxchat_options');
2012 + if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
2013 + echo do_shortcode('[mxchat_chatbot floating="yes"]');
2014 + }
10643 2015 }
10644 2016
10645 - if (isset($input['brave_news_count'])) {
10646 - $news_count = intval($input['brave_news_count']);
10647 - $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
10648 - }
10649 2017
10650 - if (isset($input['brave_country'])) {
10651 - $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
10652 - }
10653 2018
10654 - if (isset($input['brave_language'])) {
10655 - $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
10656 - }
2019 +private function mxchat_extract_main_content($html) {
2020 + $dom = new DOMDocument;
2021 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
2022 + @$dom->loadHTML($html);
2023 + libxml_clear_errors();
10657 2024
10658 - if (isset($input['chat_toolbar_toggle'])) {
10659 - $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
10660 - }
2025 + $xpath = new DOMXPath($dom);
10661 2026
10662 - // Sanitize PDF upload button toggle
10663 - if (isset($input['show_pdf_upload_button'])) {
10664 - $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
10665 - } else {
10666 - $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
10667 - }
2027 + // Simplified selectors focusing on common content areas
2028 + $selectors = [
2029 + '//article',
2030 + '//*[@id="content"]',
2031 + '//*[@class="entry-content"]',
2032 + '//main',
2033 + ];
10668 2034
10669 - // Sanitize Word upload button toggle
10670 - if (isset($input['show_word_upload_button'])) {
10671 - $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
10672 - } else {
10673 - $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
10674 - }
10675 -
10676 - if (isset($input['pdf_intent_trigger_text'])) {
10677 - $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
10678 - }
10679 -
10680 - if (isset($input['pdf_intent_success_text'])) {
10681 - $new_input['pdf_intent_success_text'] = sanitize_text_field($input['pdf_intent_success_text']);
10682 - }
10683 -
10684 - if (isset($input['pdf_intent_error_text'])) {
10685 - $new_input['pdf_intent_error_text'] = sanitize_text_field($input['pdf_intent_error_text']);
10686 - }
10687 -
10688 - if (isset($input['pdf_max_pages'])) {
10689 - $new_input['pdf_max_pages'] = intval($input['pdf_max_pages']);
10690 - if ($new_input['pdf_max_pages'] < 1 || $new_input['pdf_max_pages'] > 69) {
10691 - $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
2035 + foreach ($selectors as $selector) {
2036 + $nodes = $xpath->query($selector);
2037 + if ($nodes->length > 0) {
2038 + $content = '';
2039 + foreach ($nodes as $node) {
2040 + $content .= $dom->saveHTML($node);
2041 + }
2042 + return $content;
10692 2043 }
10693 2044 }
10694 2045
10695 - if (isset($input['live_agent_webhook_url'])) {
10696 - $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
10697 - }
10698 - if (isset($input['live_agent_secret_key'])) {
10699 - $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
10700 - }
2046 + // Fallback: Return the entire body content if no specific selector matches
2047 + $body = $dom->getElementsByTagName('body');
2048 + return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
2049 +}
10701 2050
10702 - // Live Agent Integration
10703 - if (isset($input['live_agent_bot_token'])) {
10704 - $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
2051 +public function mxchat_handle_sitemap_submission() {
2052 + // Check if the form was submitted and the user has sufficient permissions
2053 + if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
2054 + return;
10705 2055 }
10706 2056
10707 - if (isset($input['live_agent_shared_channel'])) {
10708 - $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']);
10709 - }
2057 + // Verify the nonce field for security
2058 + check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
10710 2059
10711 - // Default-OFF toggle: absent key stays absent (unchecked box = off).
10712 - if (isset($input['live_agent_archive_on_end_toggle'])) {
10713 - $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off';
10714 - }
2060 + // Sanitize and retrieve the submitted URL
2061 + $submitted_url = esc_url_raw($_POST['sitemap_url']); // Accept either a sitemap URL or a regular URL
10715 2062
10716 - if (isset($input['live_agent_user_ids'])) {
10717 - $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
2063 + // Fetch the content of the submitted URL
2064 + $response = wp_remote_get($submitted_url);
2065 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2066 + set_transient('mxchat_admin_notice_error', 'Failed to fetch the URL. Please check the URL and try again.', 30);
2067 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2068 + exit;
10718 2069 }
10719 2070
10720 - if (isset($input['live_agent_status'])) {
10721 - $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
10722 - }
10723 - if (isset($input['live_agent_away_message'])) {
10724 - $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
10725 - }
10726 - if (isset($input['live_agent_notification_message'])) {
10727 - $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
10728 - }
2071 + $content_type = wp_remote_retrieve_header($response, 'content-type');
2072 + $body_content = wp_remote_retrieve_body($response);
10729 2073
10730 - // Telegram Integration
10731 - if (isset($input['telegram_status'])) {
10732 - $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
10733 - }
10734 - if (isset($input['telegram_bot_token'])) {
10735 - $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
10736 - }
10737 - if (isset($input['telegram_group_id'])) {
10738 - $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
10739 - }
10740 - if (isset($input['telegram_webhook_secret'])) {
10741 - $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
10742 - }
10743 - if (isset($input['telegram_notification_message'])) {
10744 - $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
10745 - }
10746 - if (isset($input['telegram_away_message'])) {
10747 - $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
10748 - }
2074 + // Check if the URL points to a sitemap (XML) or a regular HTML page
2075 + if (strpos($content_type, 'xml') !== false || strpos($body_content, '<urlset') !== false) {
2076 + // Handle Sitemap XML
2077 + $xml = simplexml_load_string($body_content);
2078 + if ($xml === false) {
2079 + set_transient('mxchat_admin_notice_error', 'Invalid sitemap XML. Please provide a valid sitemap.', 30);
2080 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2081 + exit;
2082 + }
10749 2083
10750 - // Webhook Handoff (plan d88e22)
10751 - if (isset($input['webhook_handoff_status'])) {
10752 - $new_input['webhook_handoff_status'] = ($input['webhook_handoff_status'] === 'on') ? 'on' : 'off';
10753 - }
10754 - if (isset($input['webhook_handoff_url'])) {
10755 - // https only — esc_url_raw with an https-only protocol list stores ''
10756 - // for anything else, so a non-https URL can never persist.
10757 - $new_input['webhook_handoff_url'] = esc_url_raw(trim((string) $input['webhook_handoff_url']), array('https'));
10758 - }
10759 - if (isset($input['webhook_handoff_secret'])) {
10760 - $new_input['webhook_handoff_secret'] = sanitize_text_field($input['webhook_handoff_secret']);
10761 - }
10762 - if (isset($input['webhook_handoff_notification_message'])) {
10763 - $new_input['webhook_handoff_notification_message'] = sanitize_textarea_field($input['webhook_handoff_notification_message']);
10764 - }
10765 - if (isset($input['webhook_handoff_away_message'])) {
10766 - $new_input['webhook_handoff_away_message'] = sanitize_textarea_field($input['webhook_handoff_away_message']);
10767 - }
2084 + $embedding_success = true; // Flag to track if all embeddings are successful
10768 2085
10769 - // Sanitize script loading strategy
10770 - if (isset($input['script_loading_strategy'])) {
10771 - $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
10772 - $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
10773 - ? $input['script_loading_strategy']
10774 - : 'default';
10775 - }
2086 + foreach ($xml->url as $url_element) {
2087 + $page_url = (string)$url_element->loc;
10776 2088
10777 - // Sanitize debug mode
10778 - if (isset($input['debug_mode'])) {
10779 - $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
10780 - }
2089 + $page_response = wp_remote_get($page_url);
2090 + if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
2091 + continue;
2092 + }
10781 2093
10782 - // Content Generator Settings
10783 - if (isset($input['content_model'])) {
10784 - $new_input['content_model'] = sanitize_text_field($input['content_model']);
10785 - }
10786 - if (isset($input['content_image_model'])) {
10787 - $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
10788 - }
10789 - if (isset($input['content_image_quality'])) {
10790 - $q = sanitize_text_field($input['content_image_quality']);
10791 - $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
10792 - }
10793 - if (isset($input['content_enable_images'])) {
10794 - $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
10795 - }
10796 - if (isset($input['content_use_placeholders'])) {
10797 - $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
10798 - }
10799 - if (isset($input['content_internal_linking'])) {
10800 - $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
10801 - }
10802 - if (isset($input['content_tool_use'])) {
10803 - $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
10804 - }
10805 - if (isset($input['content_image_count'])) {
10806 - $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count']));
10807 - }
2094 + $page_html = wp_remote_retrieve_body($page_response);
2095 + $page_content = $this->mxchat_extract_main_content($page_html);
2096 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10808 2097
10809 - // SEO Optimize toggle fields
10810 - 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) {
10811 - if (isset($input[$seo_key])) {
10812 - $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
2098 + if (!empty($sanitized_content)) {
2099 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2100 + if (is_array($embedding_vector)) {
2101 + MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $this->options['api_key']);
2102 + } else {
2103 + $embedding_success = false; // Set flag to false if any embedding fails
2104 + }
2105 + }
10813 2106 }
10814 - }
10815 2107
10816 - // Preserve content generator settings when saving from main settings page
10817 - // (where content fields are not in the form submission)
10818 - $existing = get_option('mxchat_options', array());
10819 - 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) {
10820 - if (!isset($new_input[$key]) && isset($existing[$key])) {
10821 - $new_input[$key] = $existing[$key];
2108 + if ($embedding_success) {
2109 + set_transient('mxchat_admin_notice_success', 'Sitemap content successfully submitted!', 30);
2110 + } else {
2111 + set_transient('mxchat_admin_notice_error', 'Some content failed to embed. Please check your API key and try again.', 30);
10822 2112 }
10823 - }
10824 2113
10825 - return $new_input;
10826 -}
2114 + } else {
2115 + // Handle Regular URL (HTML Page)
2116 + $page_content = $this->mxchat_extract_main_content($body_content);
2117 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10827 2118
10828 -/**
10829 - * Log a debug message if debug mode is enabled
10830 - *
10831 - * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
10832 - * @param string $message The log message
10833 - * @param array $data Optional additional data to log
10834 - * @return bool Whether the message was logged
10835 - */
10836 -public static function mxchat_log_debug( $type, $message, $data = array() ) {
10837 - $options = get_option( 'mxchat_options', array() );
10838 -
10839 - // Check if debug mode is enabled
10840 - if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
10841 - return false;
10842 - }
10843 -
10844 - // Get current log
10845 - $log = get_option( 'mxchat_debug_log', array() );
10846 - if ( ! is_array( $log ) ) {
10847 - $log = array();
10848 - }
10849 -
10850 - // Add new entry
10851 - $entry = array(
10852 - 'time' => current_time( 'Y-m-d H:i:s' ),
10853 - 'type' => sanitize_key( $type ),
10854 - 'message' => sanitize_text_field( $message ),
10855 - );
10856 -
10857 - if ( ! empty( $data ) ) {
10858 - $entry['data'] = $data;
10859 - }
10860 -
10861 - // Add to beginning of array (newest first)
10862 - array_unshift( $log, $entry );
10863 -
10864 - // Keep only last 100 entries
10865 - if ( count( $log ) > 100 ) {
10866 - $log = array_slice( $log, 0, 100 );
10867 - }
10868 -
10869 - // Save log
10870 - update_option( 'mxchat_debug_log', $log, false );
10871 -
10872 - return true;
10873 -}
10874 -
10875 -/**
10876 - * Get the debug log entries
10877 - *
10878 - * @return array The debug log entries
10879 - */
10880 -public static function mxchat_get_debug_log() {
10881 - $log = get_option( 'mxchat_debug_log', array() );
10882 - return is_array( $log ) ? $log : array();
10883 -}
10884 -
10885 -/**
10886 - * Clear the debug log
10887 - *
10888 - * @return bool Whether the log was cleared
10889 - */
10890 -public static function mxchat_clear_debug_log() {
10891 - return delete_option( 'mxchat_debug_log' );
10892 -}
10893 -
10894 -/**
10895 - * Export settings as JSON with masked API keys
10896 - *
10897 - * @return array The sanitized settings array
10898 - */
10899 -public static function mxchat_export_settings() {
10900 - $options = get_option( 'mxchat_options', array() );
10901 -
10902 - if ( ! is_array( $options ) ) {
10903 - return array();
10904 - }
10905 -
10906 - // List of API key fields to mask
10907 - $api_key_fields = array(
10908 - 'api_key',
10909 - 'xai_api_key',
10910 - 'claude_api_key',
10911 - 'deepseek_api_key',
10912 - 'voyage_api_key',
10913 - 'gemini_api_key',
10914 - 'openrouter_api_key',
10915 - 'loops_api_key',
10916 - 'brave_api_key',
10917 - 'live_agent_secret_key',
10918 - 'live_agent_bot_token',
10919 - 'telegram_bot_token',
10920 - 'telegram_webhook_secret',
10921 - 'woocommerce_consumer_key',
10922 - 'woocommerce_consumer_secret',
10923 - );
10924 -
10925 - // Mask API keys (show only last 4 characters)
10926 - foreach ( $api_key_fields as $field ) {
10927 - if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
10928 - $value = $options[ $field ];
10929 - if ( strlen( $value ) > 4 ) {
10930 - $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
2119 + if (!empty($sanitized_content)) {
2120 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2121 + if (is_array($embedding_vector)) {
2122 + MxChat_Utils::submit_content_to_db($sanitized_content, $submitted_url, $this->options['api_key']);
2123 + set_transient('mxchat_admin_notice_success', 'URL content successfully submitted!', 30);
10931 2124 } else {
10932 - $options[ $field ] = '****';
2125 + set_transient('mxchat_admin_notice_error', 'Failed to generate embedding for the URL content. Please check your API key and try again.', 30);
10933 2126 }
2127 + } else {
2128 + set_transient('mxchat_admin_notice_error', 'No valid content found on the provided URL.', 30);
10934 2129 }
10935 2130 }
10936 2131
10937 - // Add metadata
10938 - $export = array(
10939 - 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
10940 - 'export_date' => current_time( 'Y-m-d H:i:s' ),
10941 - 'wordpress_version' => get_bloginfo( 'version' ),
10942 - 'php_version' => phpversion(),
10943 - 'settings' => $options,
10944 - );
10945 -
10946 - return $export;
2132 + // Redirect after setting the transient
2133 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2134 + exit;
10947 2135 }
10948 2136
10949 -/**
10950 - * Reset all settings to defaults
10951 - *
10952 - * @return bool Whether the reset was successful
10953 - */
10954 -public static function mxchat_reset_all_settings() {
10955 - // Delete main options
10956 - $deleted = delete_option( 'mxchat_options' );
10957 2137
10958 - // Also clear the debug log
10959 - delete_option( 'mxchat_debug_log' );
10960 2138
10961 - // Log the reset (will create new log since we just cleared it)
10962 - // We need to temporarily enable debug mode to log this
10963 - $temp_options = array( 'debug_mode' => 'on' );
10964 - update_option( 'mxchat_options', $temp_options );
2139 +private function mxchat_sanitize_content_for_api($content) {
2140 + // Remove script, style tags, and HTML comments
2141 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
2142 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
2143 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
10965 2144
10966 - self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
2145 + // Remove all HTML tags and decode HTML entities
2146 + $content = wp_strip_all_tags($content);
2147 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
10967 2148
10968 - // Now delete again to trigger re-initialization
10969 - delete_option( 'mxchat_options' );
2149 + // Trim and normalize whitespace
2150 + $content = trim(preg_replace('/\s+/', ' ', $content));
10970 2151
10971 - return $deleted;
2152 + return $content;
10972 2153 }
10973 2154
10974 - // Method to append the chatbot to the body
10975 - public function mxchat_append_chatbot_to_body() {
10976 - $options = get_option('mxchat_options');
10977 - if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
10978 - echo do_shortcode('[mxchat_chatbot floating="yes"]');
10979 - }
10980 - }
10981 2155
10982 2156
10983 -
10984 -
10985 -
10986 2157 private function mxchat_fetch_loops_mailing_lists($api_key) {
10987 2158 $url = 'https://app.loops.so/api/v1/lists';
10988 2159 $response = wp_remote_get($url, array(
10989 2160 'headers' => array(
@@ -11000,461 +2171,8 @@
11000 2171 $lists = json_decode($body, true);
11001 2172
11002 2173 return isset($lists) && is_array($lists) ? $lists : array();
11003 2174 }
11004 -
11005 -function mxchat_calculate_cosine_similarity($vec1, $vec2) {
11006 - if (empty($vec1) || empty($vec2)) {
11007 - return 0.0;
11008 - }
11009 -
11010 - $dot_product = 0.0;
11011 - $norm_a = 0.0;
11012 - $norm_b = 0.0;
11013 -
11014 - for ($i = 0; $i < count($vec1); $i++) {
11015 - $dot_product += $vec1[$i] * $vec2[$i];
11016 - $norm_a += pow($vec1[$i], 2);
11017 - $norm_b += pow($vec2[$i], 2);
11018 - }
11019 -
11020 - if ($norm_a == 0.0 || $norm_b == 0.0) {
11021 - return 0.0;
11022 - } else {
11023 - return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
11024 - }
11025 -}
11026 -
11027 -/**
11028 - * Validates nonce and deletes all chat prompts
11029 - */
11030 -public function mxchat_handle_delete_all_prompts() {
11031 - //error_log('=== DELETE ALL DEBUG START ===');
11032 -
11033 - // Verify nonce
11034 - if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
11035 - //error_log('DEBUG: Nonce verification failed');
11036 - wp_die(__('Nonce verification failed.', 'mxchat'));
11037 - }
11038 -
11039 - // Check permissions
11040 - if (!current_user_can('manage_options')) {
11041 - //error_log('DEBUG: Permission check failed');
11042 - wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
11043 - }
11044 -
11045 - // Get bot_id and content type filter from POST data
11046 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
11047 - $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
11048 -
11049 - $success = true;
11050 - $error_messages = array();
11051 -
11052 - // Get bot-specific Pinecone configuration
11053 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
11054 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
11055 -
11056 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
11057 -
11058 - if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
11059 - // Delete from Pinecone (with optional content type filter)
11060 - $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
11061 -
11062 - if (!$result['success']) {
11063 - $success = false;
11064 - $error_messages[] = $result['message'];
11065 - }
11066 -
11067 - } else {
11068 - // Delete from WordPress database
11069 - global $wpdb;
11070 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
11071 -
11072 - // Build WHERE conditions
11073 - $where_clauses = array();
11074 - $where_values = array();
11075 -
11076 - // Bot filter
11077 - if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
11078 - $where_clauses[] = 'bot_id = %s';
11079 - $where_values[] = $bot_id;
11080 - }
11081 -
11082 - // Content type filter
11083 - if (!empty($content_type_filter)) {
11084 - $where_clauses[] = 'content_type = %s';
11085 - $where_values[] = $content_type_filter;
11086 - }
11087 -
11088 - if (!empty($where_clauses)) {
11089 - $where_sql = implode(' AND ', $where_clauses);
11090 - $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
11091 - } else {
11092 - // No filters — delete all
11093 - $result = $wpdb->query("DELETE FROM {$table_name}");
11094 - }
11095 -
11096 - if ($result === false) {
11097 - $success = false;
11098 - $error_messages[] = 'Failed to delete from WordPress database';
11099 - }
11100 - }
11101 -
11102 - // Redirect back with a success message and bot_id
11103 - $redirect_url = add_query_arg(array(
11104 - 'page' => 'mxchat-prompts',
11105 - 'bot_id' => $bot_id,
11106 - 'all_deleted' => $success ? 'true' : 'false'
11107 - ), admin_url('admin.php'));
11108 -
11109 - wp_safe_redirect($redirect_url);
11110 - exit;
11111 -}
11112 -
11113 -
11114 -
11115 - /**
11116 - * Handles deletion prompt with nonce validation
11117 - */
11118 - public function mxchat_handle_delete_prompt() {
11119 - // Sanitize and validate nonce
11120 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
11121 - if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
11122 - wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
11123 - }
11124 -
11125 - // Check permissions
11126 - if (!current_user_can('manage_options')) {
11127 - wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
11128 - }
11129 -
11130 - // Get ID and source parameters
11131 - $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
11132 - $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
11133 -
11134 - if (empty($id)) {
11135 - wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
11136 - }
11137 -
11138 - $success = false;
11139 - $error_message = '';
11140 -
11141 - // Resolve per-bot Pinecone settings — the global option is the wrong
11142 - // index entirely when the row belongs to a bot with its own host
11143 - $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default';
11144 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
11145 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
11146 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
11147 -
11148 - // If source is not specified, determine based on Pinecone configuration
11149 - if (empty($source)) {
11150 - $source = $use_pinecone ? 'pinecone' : 'wordpress';
11151 - }
11152 -
11153 - if ($source === 'pinecone' || $use_pinecone) {
11154 - //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
11155 -
11156 - // Handle Pinecone deletion
11157 - if (empty($pinecone_options['mxchat_pinecone_host']) ||
11158 - empty($pinecone_options['mxchat_pinecone_api_key'])) {
11159 - wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
11160 - }
11161 -
11162 - // Delete from Pinecone using the vector ID directly
11163 - $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
11164 - $id,
11165 - $pinecone_options['mxchat_pinecone_api_key'],
11166 - $pinecone_options['mxchat_pinecone_host'],
11167 - $pinecone_options['mxchat_pinecone_namespace'] ?? ''
11168 - );
11169 - if ($result['success']) {
11170 - $success = true;
11171 -
11172 - // Remove from vector cache
11173 - $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
11174 - $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
11175 -
11176 - set_transient('mxchat_admin_notice_success',
11177 - esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
11178 - } else {
11179 - $error_message = $result['message'];
11180 - set_transient('mxchat_admin_notice_error',
11181 - esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
11182 - }
11183 - } else {
11184 - //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
11185 -
11186 - // Handle WordPress database deletion
11187 - global $wpdb;
11188 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
11189 -
11190 - // Clear cache and delete prompt
11191 - wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
11192 -
11193 - $result = $wpdb->delete(
11194 - $table_name,
11195 - array('id' => intval($id)),
11196 - array('%d')
11197 - );
11198 -
11199 - if ($result !== false) {
11200 - $success = true;
11201 - set_transient('mxchat_admin_notice_success',
11202 - esc_html__('Entry deleted successfully.', 'mxchat'), 30);
11203 - } else {
11204 - set_transient('mxchat_admin_notice_error',
11205 - esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
11206 - }
11207 - }
11208 -
11209 - // Redirect back to the prompts page
11210 - wp_safe_redirect(add_query_arg(
11211 - array(
11212 - 'page' => 'mxchat-prompts',
11213 - 'deleted' => $success ? 'true' : 'false'
11214 - ),
11215 - admin_url('admin.php')
11216 - ));
11217 - exit;
11218 - }
11219 -
11220 -
11221 -
11222 -
11223 - /**
11224 - * Averages multiple vectors into a single vector
11225 - */
11226 - private function mxchat_average_vectors($vectors) {
11227 - $vector_length = count($vectors[0]);
11228 - $sum_vector = array_fill(0, $vector_length, 0);
11229 -
11230 - foreach ($vectors as $vector) {
11231 - for ($i = 0; $i < $vector_length; $i++) {
11232 - $sum_vector[$i] += $vector[$i];
11233 - }
11234 - }
11235 -
11236 - // Divide each component by the number of vectors to get the average
11237 - $num_vectors = count($vectors);
11238 - for ($i = 0; $i < $vector_length; $i++) {
11239 - $sum_vector[$i] /= $num_vectors;
11240 - }
11241 -
11242 - return $sum_vector;
11243 - }
11244 -
11245 -
11246 -
11247 -
11248 - /**
11249 - * Generates embeddings from input text for MXChat
11250 - */
11251 - public function mxchat_generate_embedding($text) {
11252 - // Enable detailed logging for debugging
11253 - //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
11254 - //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
11255 -
11256 - $options = get_option('mxchat_options');
11257 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
11258 - //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
11259 -
11260 - // Determine provider and endpoint
11261 - if (strpos($selected_model, 'voyage') === 0) {
11262 - $api_key = $options['voyage_api_key'] ?? '';
11263 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
11264 - $provider_name = 'Voyage AI';
11265 - //error_log('[MXCHAT-EMBED] Using Voyage AI API');
11266 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
11267 - $api_key = $options['gemini_api_key'] ?? '';
11268 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
11269 - $provider_name = 'Google Gemini';
11270 - //error_log('[MXCHAT-EMBED] Using Google Gemini API');
11271 - } else {
11272 - $api_key = $options['api_key'] ?? '';
11273 - $endpoint = 'https://api.openai.com/v1/embeddings';
11274 - $provider_name = 'OpenAI';
11275 - //error_log('[MXCHAT-EMBED] Using OpenAI API');
11276 - }
11277 -
11278 - //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
11279 -
11280 - if (empty($api_key)) {
11281 - $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
11282 - //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
11283 - return $error_message;
11284 - }
11285 -
11286 - // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
11287 - $estimated_tokens = ceil(str_word_count($text) / 0.75);
11288 - //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
11289 -
11290 - if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
11291 - //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
11292 - // Consider truncating text here
11293 - }
11294 -
11295 - // Prepare request body based on provider
11296 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11297 - // Gemini API format
11298 - $request_body = array(
11299 - 'model' => 'models/' . $selected_model,
11300 - 'content' => array(
11301 - 'parts' => array(
11302 - array('text' => $text)
11303 - )
11304 - )
11305 - );
11306 -
11307 - // Set output dimensionality to 1536 for consistency with other models
11308 - $request_body['outputDimensionality'] = 1536;
11309 - } else {
11310 - // OpenAI/Voyage API format
11311 - $request_body = array(
11312 - 'model' => $selected_model,
11313 - 'input' => $text
11314 - );
11315 -
11316 - // Add output_dimension for voyage-3-large model
11317 - if ($selected_model === 'voyage-3-large') {
11318 - $request_body['output_dimension'] = 2048;
11319 - }
11320 - }
11321 -
11322 - //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
11323 -
11324 - // Prepare headers based on provider
11325 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11326 - // Gemini uses API key as query parameter
11327 - $endpoint .= '?key=' . $api_key;
11328 - $headers = array(
11329 - 'Content-Type' => 'application/json'
11330 - );
11331 - } else {
11332 - // OpenAI/Voyage use Bearer token
11333 - $headers = array(
11334 - 'Authorization' => 'Bearer ' . $api_key,
11335 - 'Content-Type' => 'application/json'
11336 - );
11337 - }
11338 -
11339 - // Make API request
11340 - //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
11341 - $response = wp_remote_post($endpoint, array(
11342 - 'body' => wp_json_encode($request_body),
11343 - 'headers' => $headers,
11344 - 'timeout' => 60 // Increased timeout for large inputs
11345 - ));
11346 -
11347 - // Handle wp_remote_post errors
11348 - if (is_wp_error($response)) {
11349 - $error_message = $response->get_error_message();
11350 - //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
11351 - return 'Connection error: ' . $error_message;
11352 - }
11353 -
11354 - // Get and check HTTP response code
11355 - $http_code = wp_remote_retrieve_response_code($response);
11356 - //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
11357 -
11358 - if ($http_code !== 200) {
11359 - $error_body = wp_remote_retrieve_body($response);
11360 - //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
11361 -
11362 - // Try to parse error for more details
11363 - $error_json = json_decode($error_body, true);
11364 - if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
11365 - $error_type = $error_json['error']['type'] ?? 'unknown';
11366 - $error_message = $error_json['error']['message'] ?? 'No message';
11367 - //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
11368 - //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
11369 -
11370 - // Customize error message for common API errors
11371 - if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
11372 - $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
11373 - } elseif ($error_type === 'authentication_error') {
11374 - $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
11375 - }
11376 -
11377 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11378 - return $error_message;
11379 - }
11380 -
11381 - $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
11382 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11383 - return $error_message;
11384 - }
11385 -
11386 - // Parse response body
11387 - $response_body = wp_remote_retrieve_body($response);
11388 - //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
11389 -
11390 - $response_data = json_decode($response_body, true);
11391 -
11392 - if (json_last_error() !== JSON_ERROR_NONE) {
11393 - $error = json_last_error_msg();
11394 - //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
11395 - //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
11396 - return "Failed to parse API response: $error";
11397 - }
11398 -
11399 - // Handle different response formats based on provider
11400 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11401 - // Gemini API response format
11402 - if (isset($response_data['embedding']['values'])) {
11403 - $embedding_dimensions = count($response_data['embedding']['values']);
11404 - //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
11405 -
11406 - // Check if embedding dimensions are as expected (should be 1536)
11407 - if ($embedding_dimensions !== 1536) {
11408 - //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
11409 - }
11410 -
11411 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11412 - return $response_data['embedding']['values'];
11413 - } else {
11414 - //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
11415 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11416 -
11417 - if (isset($response_data['error'])) {
11418 - $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
11419 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11420 - return $error_message;
11421 - }
11422 -
11423 - $error_message = "Invalid Gemini API response format: No embedding found";
11424 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11425 - return $error_message;
11426 - }
11427 - } else {
11428 - // OpenAI/Voyage API response format
11429 - if (isset($response_data['data'][0]['embedding'])) {
11430 - $embedding_dimensions = count($response_data['data'][0]['embedding']);
11431 - //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
11432 -
11433 - // Check if embedding dimensions are as expected
11434 - if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
11435 - ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
11436 - //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
11437 - }
11438 -
11439 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11440 - return $response_data['data'][0]['embedding'];
11441 - } else {
11442 - //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
11443 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11444 -
11445 - if (isset($response_data['error'])) {
11446 - $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
11447 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11448 - return $error_message;
11449 - }
11450 -
11451 - $error_message = "Invalid API response format: No embedding found";
11452 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11453 - return $error_message;
11454 - }
11455 - }
11456 - }
11457 2175
11458 2176
11459 2177
11460 2178 }