PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.5.3
MxChat – AI Chatbot & Content Generation for WordPress v1.5.3
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 +2988 -9680 3.2.191.5.3 View file →
@@ -6,31 +6,13 @@
6 6 class MxChat_Admin {
7 7 private $options;
8 8 private $chat_count;
9 9 private $is_activated;
10 - private $knowledge_manager;
11 10
12 - /**
13 - * Get whether the license is activated
14 - * @return bool
15 - */
16 - public function is_activated() {
17 - return $this->is_activated;
18 - }
19 -
20 - /**
21 - * Get plugin options
22 - * @return array
23 - */
24 - public function get_options() {
25 - return $this->options;
26 - }
27 -
28 - public function __construct($knowledge_manager = null) {
11 + public function __construct() {
29 12 $this->options = get_option('mxchat_options');
30 13 $this->chat_count = get_option('mxchat_chat_count', 0);
31 14 $this->is_activated = $this->is_license_active();
32 - $this->knowledge_manager = $knowledge_manager;
33 15
34 16 // Initialize default options if they are not set
35 17 if (!$this->options) {
36 18 $this->initialize_default_options();
@@ -37,407 +19,97 @@
37 19 }
38 20
39 21 // Add admin menu and initialize settings
40 22 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
41 - // Pro & Extensions registers at priority 30 so it always lands last in
42 - // the sidebar — below API Access (priority 20) and below any other
43 - // submenu that hooks at default priority 10.
44 - add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
45 - // Onboarding visibility — runs LAST so it can remove the submenu after every
46 - // other add_submenu_page() call. The page stays reachable by direct URL.
47 - add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999);
48 23 add_action('admin_init', array($this, 'mxchat_page_init'));
49 - add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
50 24 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
51 - // Add body class for the Onboarding wizard (plan-905439) so the
52 - // chrome-surgery CSS in admin-onboarding-wizard.css can scope its
53 - // WP-sidebar collapse to this page only.
54 - add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class'));
55 25 add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
26 + add_action('admin_post_mxchat_submit_content', array($this, 'mxchat_handle_content_submission'));
56 27 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
57 28 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
58 29 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
59 - add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
30 + add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
60 31 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
61 32 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
62 33 add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
34 + add_action('wp_ajax_mxchat_activate_license', array($this, 'mxchat_handle_activate_license'));
63 35 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
36 + // Add the AJAX handler for logged-in users
37 + add_action('wp_ajax_mxchat_save_inline_prompt', array($this, 'mxchat_save_inline_prompt'));
64 38 add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
39 +
40 + // Define admin_post actions for form submission handling
65 41 add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
66 42 add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
67 - add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
68 - add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
43 + add_action('admin_post_mxchat_update_intent_threshold', array($this, 'mxchat_handle_update_intent_threshold'));
44 + add_action('admin_post_mxchat_stop_processing', array($this, 'mxchat_stop_processing'));
69 45
70 - // Leads tab (inside Transcripts)
71 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
72 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
73 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
74 -
75 - add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
76 - add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
77 - add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
78 - add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
79 - // Self-heal: the cleanup event is otherwise only scheduled at activation or
80 - // when the retention setting CHANGES — if it is ever lost (deactivate cycle,
81 - // cron-option wipe, DB restore) nothing re-registers it and retention goes
82 - // silently inert while the UI still says it is on (plan-bc08a6).
83 - add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled'));
84 -
85 - add_action('admin_init', array($this, 'register_pinecone_settings'));
86 - add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
87 -
88 - add_action('admin_notices', array($this, 'display_admin_notices'));
89 -
90 - add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
91 - add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
92 - add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
93 -
94 - // wp_ajax_mxchat_save_selected_bot is registered (and handled) in
95 - // admin/class-ajax-handler.php — a duplicate registration here pointed
96 - // at a method this class never defined, a load-order-dependent fatal
97 - // waiting to fire (plan 52bcad).
98 - add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
99 - add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
100 -
101 - // Actions page AJAX handlers
102 - add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
103 - add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
104 - add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
105 - add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
106 - add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
107 - add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
108 - add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
109 - add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
110 - add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
111 - add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
112 -
113 - // Slack test connection
114 - add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
115 -
116 - // Translation handlers
117 - add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
118 - add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
119 -
120 - // 3.2.3: Embedding model switch protection
121 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
122 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
123 - add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax'));
124 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
125 - add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice'));
126 46 }
127 47
128 - /**
129 - * Nudge admins to configure a Telegram webhook secret (plan-0c17b5).
130 - *
131 - * Shown only when a Telegram bot token is configured (integration active)
132 - * AND no webhook secret is set. Without a secret the webhook falls back to a
133 - * Telegram source-IP check — safer than the old fail-open, but a real secret
134 - * is the recommended protection. Dismissible; does not block anything.
135 - */
136 - public function mxchat_telegram_secret_notice() {
137 - if (!current_user_can('manage_options')) {
138 - return;
139 - }
140 - $options = get_option('mxchat_options', array());
141 - $has_token = !empty($options['telegram_bot_token']);
142 - $has_secret = !empty($options['telegram_webhook_secret']);
143 - if (!$has_token || $has_secret) {
144 - return;
145 - }
146 - if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') {
147 - return;
148 - }
149 - $settings_url = admin_url('admin.php?page=mxchat-max');
150 - ?>
151 - <div class="notice notice-warning is-dismissible mxchat-telegram-secret-notice">
152 - <p><strong><?php esc_html_e('MxChat: Telegram webhook is running without a secret token', 'mxchat'); ?></strong></p>
153 - <p>
154 - <?php esc_html_e('Your Telegram integration is active but no webhook secret is configured. Requests are currently verified only by origin IP. For full protection, set a webhook secret token in the Telegram settings and re-register your webhook.', 'mxchat'); ?>
155 - </p>
156 - <p>
157 - <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary"><?php esc_html_e('Open Telegram settings', 'mxchat'); ?></a>
158 - </p>
159 - </div>
160 - <script>
161 - (function(){
162 - var n = document.querySelector('.mxchat-telegram-secret-notice');
163 - if (!n) return;
164 - n.addEventListener('click', function(e){
165 - if (e.target && e.target.classList.contains('notice-dismiss')) {
166 - var d = new FormData();
167 - d.append('action', 'mxchat_dismiss_telegram_secret_notice');
168 - d.append('nonce', '<?php echo esc_js(wp_create_nonce('mxchat_dismiss_telegram_secret')); ?>');
169 - fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', { method: 'POST', body: d, credentials: 'same-origin' });
170 - }
171 - });
172 - })();
173 - </script>
174 - <?php
48 + // Method to check if the license is active
49 + private function is_license_active() {
50 + $license_status = get_option('mxchat_license_status', 'inactive');
51 + return $license_status === 'active';
175 52 }
176 53
177 - /**
178 - * AJAX: persist dismissal of the Telegram-secret admin notice (plan-0c17b5).
179 - */
180 - public function mxchat_dismiss_telegram_secret_notice_ajax() {
181 - if (!current_user_can('manage_options')
182 - || !check_ajax_referer('mxchat_dismiss_telegram_secret', 'nonce', false)) {
183 - wp_send_json_error();
184 - }
185 - update_option('mxchat_dismissed_telegram_secret_notice', '1', 'no');
186 - wp_send_json_success();
187 - }
188 -
189 - /**
190 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
191 - * switch. Pure option comparison — no counts, no DB queries beyond the
192 - * cached options. The dialog is shown whenever the user has previously
193 - * embedded with a different model than the one they're switching to.
194 - */
195 - public function mxchat_check_embedding_switch_ajax() {
196 - check_ajax_referer('mxchat_admin_nonce', 'security');
197 - if (!current_user_can('manage_options')) {
198 - wp_send_json_error(__('Unauthorized', 'mxchat'));
199 - }
200 -
201 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
202 - $options = get_option('mxchat_options', array());
203 - if (isset($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
204 - // The standard dropdown is inert while custom embeddings are on —
205 - // whatever value it posts, the next embed uses the custom identity.
206 - $new_model = MxChat_Utils::get_selected_embedding_model($options);
207 - }
208 - $active_model = MxChat_Utils::get_active_embedding_model();
209 -
210 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
211 -
212 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
213 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
214 -
215 - wp_send_json_success(array(
216 - 'is_mismatch' => $is_mismatch,
217 - 'active_model' => $active_model,
218 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
219 - 'new_model' => $new_model,
220 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
221 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
222 - 'active_dims' => $active_dims,
223 - 'new_dims' => $new_dims,
224 - ));
225 - }
226 -
227 - /**
228 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
229 - * pair so the banner reappears on the next switch event.
230 - */
231 - public function mxchat_dismiss_embedding_mismatch_ajax() {
232 - check_ajax_referer('mxchat_admin_nonce', 'security');
233 - if (!current_user_can('manage_options')) {
234 - wp_send_json_error(__('Unauthorized', 'mxchat'));
235 - }
236 -
237 - $options = get_option('mxchat_options', array());
238 - $selected = MxChat_Utils::get_selected_embedding_model($options);
239 - $active = MxChat_Utils::get_active_embedding_model();
240 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
241 - wp_send_json_success();
242 - }
243 -
244 - /**
245 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
246 - * (last used to actually embed something) differs from the currently
247 - * selected model. Pure option comparison — no DB queries on every page
248 - * load. The banner auto-clears once both match again, i.e. after a delete
249 - * + re-embed cycle.
250 - */
251 - public function mxchat_embedding_mismatch_notice() {
252 - if (!current_user_can('manage_options')) {
253 - return;
254 - }
255 -
256 - $options = get_option('mxchat_options', array());
257 - $selected = MxChat_Utils::get_selected_embedding_model($options);
258 - $active = MxChat_Utils::get_active_embedding_model();
259 -
260 - if (empty($active) || empty($selected) || $active === $selected) {
261 - return;
262 - }
263 -
264 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
265 - if ($dismissed === $active . '|' . $selected) {
266 - return;
267 - }
268 -
269 - $active_label = MxChat_Utils::embedding_model_label($active);
270 - $selected_label = MxChat_Utils::embedding_model_label($selected);
271 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
272 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
273 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
274 -
275 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
276 - $actions_url = admin_url('admin.php?page=mxchat-actions');
277 -
278 - ?>
279 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
280 - data-active="<?php echo esc_attr($active); ?>"
281 - data-selected="<?php echo esc_attr($selected); ?>">
282 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
283 - <p>
284 - <?php
285 - printf(
286 - /* translators: 1: previously-used model name, 2: currently-selected model name */
287 - esc_html__('Your knowledge base and actions were embedded with %1$s, but %2$s is now selected. Similarity matching will return inaccurate or empty results until you delete all existing embeddings and re-embed your content with the new model.', 'mxchat'),
288 - '<code>' . esc_html($active_label) . '</code>',
289 - '<code>' . esc_html($selected_label) . '</code>'
290 - );
291 - ?>
292 - </p>
293 - <?php if ($dims_differ) : ?>
294 - <p>
295 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
296 - <?php
297 - printf(
298 - /* translators: 1: old dim count, 2: new dim count */
299 - esc_html__('Existing vectors are %1$d-dimensional but the new model produces %2$d-dimensional vectors. If you use Pinecone, your index will reject queries entirely until re-embedded.', 'mxchat'),
300 - (int) $active_dims,
301 - (int) $selected_dims
302 - );
303 - ?>
304 - </p>
305 - <?php endif; ?>
306 - <p>
307 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
308 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
309 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
310 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
311 - </p>
312 - </div>
313 - <script>
314 - (function($){
315 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
316 - $.post(ajaxurl, {
317 - action: 'mxchat_dismiss_embedding_mismatch',
318 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
319 - });
320 - });
321 - })(jQuery);
322 - </script>
323 - <?php
324 - }
325 -
326 -private function is_license_active() {
327 - $license_status = get_option('mxchat_license_status', 'inactive');
328 - return ($license_status === 'active');
329 -}
330 -
54 + // Initialize default options
331 55 private function initialize_default_options() {
332 56 $default_options = array(
333 57 'api_key' => '',
334 58 'xai_api_key' => '',
335 59 'claude_api_key' => '',
336 - 'deepseek_api_key' => '',
337 - 'voyage_api_key' => '',
338 - 'gemini_api_key' => '',
339 - 'enable_streaming_toggle' => 'off',
340 - 'enable_web_search' => 'off',
341 - 'embedding_model' => 'text-embedding-ada-002',
342 - 'system_prompt_instructions' => 'You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
60 + '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:
61 + - Your name is [Chatbot Name].
62 + - 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.
63 + - Do not make up links to pages. Only use specific links you see in your knowledgebase.
64 + - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
65 + - 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.',
66 + 'model' => 'gpt-4o',
67 + 'rate_limit_logged_in' => '100',
68 + 'rate_limit_logged_out' => '100',
69 + 'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
70 + 'top_bar_title' => 'MxChat',
71 + 'intro_message' => 'Hello! How can I assist you today?',
72 + 'input_copy' => 'How can I assist?',
73 + 'append_to_body' => 'off',
74 + 'close_button_color' => '#fff',
75 + 'chatbot_bg_color' => '#fff',
76 + 'user_message_bg_color' => '#fff',
77 + 'user_message_font_color' => '#212121',
78 + 'bot_message_bg_color' => '#212121',
79 + 'bot_message_font_color' => '#fff',
80 + 'top_bar_bg_color' => '#212121',
81 + 'send_button_font_color' => '#212121',
82 + 'chat_input_font_color' => '#212121',
83 + 'chatbot_background_color' => '#212121',
84 + 'icon_color' => '#fff',
85 + 'enable_woocommerce_integration' => '0',
86 + 'link_target_toggle' => 'off',
87 + 'pre_chat_message' => 'Hey there! Ask me anything!',
343 88
344 - # Response Style - CRITICALLY IMPORTANT
345 - - MAXIMUM LENGTH: 1-3 short sentences per response
346 - - Ultra-concise: Get straight to the answer with no filler
347 - - No introductions like "Sure!" or "I\'d be happy to help"
348 - - No phrases like "based on my knowledge" or "according to information"
349 - - No explanatory text before giving the answer
350 - - No summaries or repetition
351 - - Hyperlink all URLs
352 - - Respond in user\'s language
353 - - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
354 -
355 - # Knowledge Base Requirements - PREVENT HALLUCINATIONS
356 - - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
357 - - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
358 - - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
359 - - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
360 - - Better to admit insufficient information than provide inaccurate answers',
361 - 'model' => esc_html__('gpt-5.6-sol', 'mxchat'),
362 - 'rate_limit_logged_out' => esc_html__('100', 'mxchat'),
363 - 'role_rate_limits' => array(),
364 - 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
365 - 'enable_email_block' => '',
366 - 'email_blocker_header_content' => __("<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>", 'mxchat'),
367 - 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
368 - 'enable_name_field' => 'off', // NEW
369 - 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
370 - 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
371 - 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
372 - 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
373 - 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
374 - 'append_to_body' => esc_html__('off', 'mxchat'),
375 - 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
376 - 'post_type_visibility_list' => array(), // Array of post type slugs
377 - 'contextual_awareness_toggle' => 'off',
378 - 'citation_links_toggle' => 'on',
379 - 'satisfaction_rating_enabled' => 'off',
380 - 'satisfaction_rating_idle_seconds' => 60,
381 - 'satisfaction_rating_question' => '',
382 - 'satisfaction_rating_thanks' => '',
383 - 'satisfaction_rating_placeholder' => '',
384 - 'satisfaction_rating_saved' => '',
385 - 'close_button_color' => esc_html__('#fff', 'mxchat'),
386 - 'chatbot_bg_color' => esc_html__('#fff', 'mxchat'),
387 - 'user_message_bg_color' => esc_html__('#fff', 'mxchat'),
388 - 'user_message_font_color' => esc_html__('#212121', 'mxchat'),
389 - 'bot_message_bg_color' => esc_html__('#212121', 'mxchat'),
390 - 'bot_message_font_color' => esc_html__('#fff', 'mxchat'),
391 - 'top_bar_bg_color' => esc_html__('#212121', 'mxchat'),
392 - 'send_button_font_color' => esc_html__('#212121', 'mxchat'),
393 - 'chat_input_font_color' => esc_html__('#212121', 'mxchat'),
394 - 'chatbot_background_color' => esc_html__('#212121', 'mxchat'),
395 - 'icon_color' => esc_html__('#fff', 'mxchat'),
396 - 'enable_woocommerce_integration' => esc_html__('0', 'mxchat'),
397 - 'link_target_toggle' => esc_html__('off', 'mxchat'),
398 - 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
399 -
400 89 // New fields for Loops Integration
401 90 'loops_api_key' => '',
402 91 'loops_mailing_list' => '',
403 - 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
404 - 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
92 + 'triggered_phrase_response' => 'Would you like to join our mailing list? Please provide your email below.',
93 + 'email_capture_response' => 'Thank you for providing your email! You\'ve been added to our list.',
405 94 'popular_question_1' => '',
406 95 'popular_question_2' => '',
407 96 'popular_question_3' => '',
408 - 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
409 - 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
410 - 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
97 + 'pdf_intent_trigger_text' => "Please provide the URL to the PDF you'd like to discuss.",
98 + 'pdf_intent_success_text' => "I've processed the PDF. What questions do you have about it?",
99 + 'pdf_intent_error_text' => "Sorry, I couldn't process the PDF. Please ensure it's a valid file.",
411 100 'pdf_max_pages' => 69,
412 - 'show_pdf_upload_button' => 'on',
413 - 'show_word_upload_button' => 'on',
414 101
415 - // Live Agent Integration (Slack)
102 + // Live Agent Integration
416 103 'live_agent_webhook_url' => '',
417 104 'live_agent_secret_key' => '',
418 105 'live_agent_bot_token' => '',
419 - 'live_agent_message_bg_color' => esc_html__('#ffffff', 'mxchat'),
420 - 'live_agent_message_font_color' => esc_html__('#333333', 'mxchat'),
421 -
422 - // Telegram Integration
423 - 'telegram_status' => 'off',
424 - 'telegram_bot_token' => '',
425 - 'telegram_group_id' => '',
426 - 'telegram_webhook_secret' => '',
427 - 'telegram_notification_message' => __("I've notified a support agent. Please allow a moment for them to respond. If you'd like to continue with AI, just type \"Switch to AI\" at any time.", 'mxchat'),
428 - 'telegram_away_message' => __("I just checked, and it looks like our support team isn't personally available at the moment. If you'd like, you can leave your email address, and they'll get back to you as soon as possible. In the meantime, you can keep chatting with me — just let me know how I can help!", 'mxchat'),
429 -
430 - 'chat_toolbar_toggle' => esc_html__('off', 'mxchat'),
431 - 'mode_indicator_bg_color' => esc_html__('#767676', 'mxchat'),
432 - 'mode_indicator_font_color' => esc_html__('#ffffff', 'mxchat'),
433 - 'toolbar_icon_color' => esc_html__('#212121', 'mxchat'),
434 -
435 - // Optimization settings
436 - 'script_loading_strategy' => 'default',
437 -
438 - // Debug settings
439 - 'debug_mode' => 'off',
106 + 'live_agent_message_bg_color' => '#ffffff',
107 + 'live_agent_message_font_color' => '#333333',
108 + 'chat_toolbar_toggle' => 'off',
109 + 'mode_indicator_bg_color' => '#767676',
110 + 'mode_indicator_font_color' => '#ffffff',
111 + 'toolbar_icon_color' => '#212121',
440 112 );
441 113
442 114
443 115 // Merge existing options with defaults
@@ -448,687 +120,134 @@
448 120 if ($existing_options !== $merged_options) {
449 121 update_option('mxchat_options', $merged_options);
450 122 }
451 123
452 - // Add default limits for each role
453 - $roles = wp_roles()->get_names();
454 - foreach ($roles as $role_id => $role_name) {
455 - $default_options['role_rate_limits'][$role_id] = esc_html__('100', 'mxchat');
456 - }
457 -
458 - return $default_options;
459 -
460 124 // Update the $this->options property
461 125 $this->options = $merged_options;
462 126 }
463 127
464 -public function mxchat_add_plugin_page() {
465 - // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file).
466 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
467 128
468 - // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu
469 - // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now
470 - // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding).
471 - add_menu_page(
472 - esc_html__('MxChat', 'mxchat'),
473 - esc_html__('MxChat', 'mxchat'),
474 - 'manage_options',
475 - 'mxchat-max',
476 - array($this, 'mxchat_create_dashboard_page'),
477 - 'dashicons-testimonial',
478 - 6
479 - );
480 129
481 - // Onboarding submenu — first child under MxChat (plan-d14e89).
482 - // First registration uses menu_slug === parent slug 'mxchat-max' →
483 - // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the
484 - // first child shows as "Onboarding" instead of a redundant pair.
485 - add_submenu_page(
486 - 'mxchat-max',
487 - esc_html__('MxChat Onboarding', 'mxchat'),
488 - esc_html__('Onboarding', 'mxchat'),
489 - 'manage_options',
490 - 'mxchat-max',
491 - array($this, 'mxchat_create_dashboard_page')
492 - );
493 - // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link
494 - // + legacy redirects still target this slug). Parent === null keeps it
495 - // out of the menu while remaining accessible by URL.
496 - add_submenu_page(
497 - null,
498 - esc_html__('MxChat Onboarding', 'mxchat'),
499 - esc_html__('Onboarding', 'mxchat'),
500 - 'manage_options',
501 - 'mxchat-onboarding',
502 - array($this, 'mxchat_create_dashboard_page')
503 - );
130 + public function mxchat_add_plugin_page() {
131 + // Main menu page
132 + add_menu_page(
133 + 'MxChat Settings',
134 + 'MxChat',
135 + 'manage_options',
136 + 'mxchat-max',
137 + array($this, 'mxchat_create_admin_page'),
138 + 'dashicons-testimonial',
139 + 6
140 + );
504 141
505 - // Settings submenu — same callback as before, just at a new slug.
506 - add_submenu_page(
507 - 'mxchat-max',
508 - esc_html__('MxChat Settings', 'mxchat'),
509 - esc_html__('Settings', 'mxchat'),
510 - 'manage_options',
511 - 'mxchat-settings',
512 - array($this, 'mxchat_create_admin_page')
513 - );
142 + // Submenu page for Knowledge
143 + add_submenu_page(
144 + 'mxchat-max',
145 + 'Prompts',
146 + 'Knowledge',
147 + 'manage_options',
148 + 'mxchat-prompts',
149 + array($this, 'mxchat_create_prompts_page')
150 + );
514 151
515 - // Submenu page for Knowledge
516 - add_submenu_page(
517 - 'mxchat-max',
518 - esc_html__('Prompts', 'mxchat'),
519 - esc_html__('Knowledge', 'mxchat'),
520 - 'manage_options',
521 - 'mxchat-prompts',
522 - array($this, 'mxchat_create_prompts_page')
523 - );
152 + // Submenu page for Chat Transcripts
153 + add_submenu_page(
154 + 'mxchat-max', // Corrected parent slug to match the main menu
155 + 'Chat Transcripts',
156 + 'Transcripts',
157 + 'manage_options',
158 + 'mxchat-transcripts',
159 + array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
160 + );
524 161
162 + // Submenu page for Intents
525 163 add_submenu_page(
526 - 'mxchat-max',
527 - esc_html__('Chat Transcripts', 'mxchat'),
528 - esc_html__('Transcripts', 'mxchat'),
529 - 'manage_options',
530 - 'mxchat-transcripts',
531 - array($this, 'mxchat_create_transcripts_page')
164 + 'mxchat-max', // Parent slug
165 + 'MxChat Intents', // Page title
166 + 'Intents', // Menu title
167 + 'manage_options', // Capability
168 + 'mxchat-intents', // Menu slug
169 + array($this, 'mxchat_intents_page_html') // Callback function
532 170 );
533 171
534 - add_submenu_page(
535 - 'mxchat-max',
536 - esc_html__('MxChat Actions', 'mxchat'),
537 - esc_html__('Actions', 'mxchat'),
538 - 'manage_options',
539 - 'mxchat-actions',
540 - array($this, 'mxchat_actions_page_html')
541 - );
172 + // Submenu page for Activation Key
173 + add_submenu_page(
174 + 'mxchat-max',
175 + 'Pro Upgrade',
176 + 'Pro Upgrade',
177 + 'manage_options',
178 + 'mxchat-activation',
179 + array($this, 'mxchat_create_activation_page')
180 + );
542 181
543 - // Content Generator page
544 - add_submenu_page(
545 - 'mxchat-max',
546 - esc_html__('Content', 'mxchat'),
547 - esc_html__('Content', 'mxchat'),
548 - 'manage_options',
549 - 'mxchat-content',
550 - array($this, 'mxchat_create_content_page')
551 - );
552 182
553 183 }
554 184
555 -/**
556 - * Register the Pro & Extensions submenu on a later admin_menu priority so it
557 - * always renders as the bottom-most item in the MxChat sidebar — below
558 - * configuration pages like API Access (priority 20).
559 - */
560 -public function mxchat_add_pro_extensions_page() {
561 - add_submenu_page(
562 - 'mxchat-max',
563 - esc_html__('Pro & Extensions', 'mxchat'),
564 - esc_html__('Pro & Extensions', 'mxchat'),
565 - 'manage_options',
566 - 'mxchat-activation',
567 - array($this, 'mxchat_create_activation_page')
568 - );
569 -}
570 185
571 -public function mxchat_create_addons_page() {
572 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
573 - $addons_page = new MxChat_Addons();
574 - $addons_page->render_page();
575 -}
576 -
577 -/**
578 - * Render the Content Generator admin page
579 - */
580 -public function mxchat_create_content_page() {
581 - require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
582 - // The Editor Assistant toggle on the Settings tab renders through
583 - // mxchat_render_field_wrapper(), which lives in admin-settings-page.php
584 - // (plan-f7df40 relocation) — load it the same way the settings page does.
585 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
586 - mxchat_render_content_page($this);
587 -}
588 -
589 -/**
590 - * Test actual streaming functionality in the WordPress environment
591 - */
592 -public function mxchat_handle_test_streaming_actual() {
593 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
594 -
595 - // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler
596 - // reads the site's provider keys and spends them on an outbound call, so it
597 - // is billable abuse for any logged-in user who obtained the nonce.
598 - if (!current_user_can('manage_options')) {
599 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
600 - }
601 -
602 - // Check if headers have already been sent
603 - if (headers_sent()) {
604 - wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
186 +public function mxchat_handle_content_submission() {
187 + // Check if the form was submitted and the user has sufficient permissions
188 + if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
605 189 return;
606 190 }
607 191
608 - // Check for required functions
609 - if (!function_exists('curl_init')) {
610 - wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
611 - return;
192 + // Verify the nonce field for security
193 + $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
194 + if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
195 + wp_die('Nonce verification failed.');
612 196 }
613 197
614 - // Get user's selected model and API key
615 - $options = get_option('mxchat_options', []);
616 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
198 + // Sanitize the content input
199 + $article_content = sanitize_textarea_field($_POST['article_content']);
617 200
618 - // Get the provider from the model
619 - $model_parts = explode('-', $selected_model);
620 - $provider = strtolower($model_parts[0]);
201 + // Sanitize the URL input (optional URL)
202 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : ''; // Default to empty if not provided
621 203
622 - // Get the appropriate API key
623 - $api_key = '';
624 - switch ($provider) {
625 - case 'gpt':
626 - case 'o1':
627 - $api_key = $options['api_key'] ?? '';
628 - break;
629 - case 'claude':
630 - $api_key = $options['claude_api_key'] ?? '';
631 - break;
632 - case 'grok':
633 - $api_key = $options['xai_api_key'] ?? '';
634 - break;
635 - case 'deepseek':
636 - $api_key = $options['deepseek_api_key'] ?? '';
637 - break;
638 - case 'gemini':
639 - $api_key = $options['gemini_api_key'] ?? '';
640 - break;
641 - default:
642 - // Default to OpenAI for unknown models
643 - $api_key = $options['api_key'] ?? '';
644 - $provider = 'gpt';
645 - break;
646 - }
204 + // Generate the embedding vector for the content
205 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
647 206
648 - if (empty($api_key)) {
649 - wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
650 - return;
651 - }
207 + global $wpdb;
208 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
652 209
653 - // Test streaming with the selected model and provider
654 - try {
655 - $this->perform_streaming_test($provider, $selected_model, $api_key);
656 - } catch (Exception $e) {
657 - wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
210 + // Check if the 'source_url' column exists in the table and add it if it doesn't
211 + if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
212 + // Use wpdb::query and a prepared statement to avoid SQL injection
213 + $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
658 214 }
659 -}
660 215
661 -/**
662 - * Perform the actual streaming test
663 - */
664 -private function perform_streaming_test($provider, $model, $api_key) {
665 - // Set streaming headers
666 - header('Content-Type: text/event-stream');
667 - header('Cache-Control: no-cache');
668 - header('X-Accel-Buffering: no'); // Disable nginx buffering
216 + if (is_array($embedding_vector)) {
217 + // Serialize the embedding vector before storing it
218 + $embedding_vector_serialized = serialize($embedding_vector);
669 219
670 - // Prepare test message
671 - $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
672 -
673 - // Configure API request based on provider
674 - $url = '';
675 - $headers = [];
676 - $body = [];
677 -
678 - switch ($provider) {
679 - case 'gpt':
680 - case 'o1':
681 - $url = 'https://api.openai.com/v1/chat/completions';
682 - $headers = [
683 - 'Content-Type: application/json',
684 - 'Authorization: Bearer ' . $api_key
685 - ];
686 - $body = [
687 - 'model' => $model,
688 - 'messages' => [['role' => 'user', 'content' => $test_message]],
689 - 'max_tokens' => 50,
690 - 'temperature' => 0.3,
691 - 'stream' => true
692 - ];
693 - break;
694 -
695 - case 'claude':
696 - $url = 'https://api.anthropic.com/v1/messages';
697 - $headers = [
698 - 'Content-Type: application/json',
699 - 'x-api-key: ' . $api_key,
700 - 'anthropic-version: 2023-06-01'
701 - ];
702 - $body = [
703 - 'model' => $model,
704 - 'messages' => [['role' => 'user', 'content' => $test_message]],
705 - 'max_tokens' => 50,
706 - 'temperature' => 0.3,
707 - 'stream' => true
708 - ];
709 - // Claude flagships from Opus 4.7 onward reject the temperature
710 - // param outright (400). Reuse the catalog's decision — this path
711 - // previously sent temperature unconditionally, so the streaming
712 - // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5.
713 - if (class_exists('MxChat_Model_Catalog')
714 - && method_exists('MxChat_Model_Catalog', 'supports_temperature')
715 - && !MxChat_Model_Catalog::supports_temperature($model)) {
716 - unset($body['temperature']);
717 - }
718 - break;
719 -
720 - case 'grok':
721 - $url = 'https://api.x.ai/v1/chat/completions';
722 - $headers = [
723 - 'Content-Type: application/json',
724 - 'Authorization: Bearer ' . $api_key
725 - ];
726 - $body = [
727 - 'model' => $model,
728 - 'messages' => [['role' => 'user', 'content' => $test_message]],
729 - 'max_tokens' => 50,
730 - 'temperature' => 0.3,
731 - 'stream' => true
732 - ];
733 - break;
734 -
735 - case 'deepseek':
736 - $url = 'https://api.deepseek.com/v1/chat/completions';
737 - $headers = [
738 - 'Content-Type: application/json',
739 - 'Authorization: Bearer ' . $api_key
740 - ];
741 - $body = [
742 - 'model' => $model,
743 - 'messages' => [['role' => 'user', 'content' => $test_message]],
744 - 'max_tokens' => 50,
745 - 'temperature' => 0.3,
746 - 'stream' => true,
747 - // DeepSeek V4 defaults to thinking mode ON — reasoning would
748 - // consume the 50-token test budget and return no visible text.
749 - 'thinking' => ['type' => 'disabled']
750 - ];
751 - break;
752 -
753 - default:
754 - echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
755 - flush();
756 - return;
757 - }
758 -
759 - // Initialize cURL
760 - $ch = curl_init();
761 - curl_setopt($ch, CURLOPT_URL, $url);
762 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
763 - curl_setopt($ch, CURLOPT_POST, true);
764 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
765 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
766 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
767 - curl_setopt($ch, CURLOPT_TIMEOUT, 30);
768 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
769 - return $this->process_streaming_test_data($data, $provider);
770 - });
771 -
772 - // Send initial test message
773 - echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
774 - flush();
775 -
776 - $result = curl_exec($ch);
777 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
778 - $curl_error = curl_error($ch);
779 - curl_close($ch);
780 -
781 - if ($curl_error) {
782 - echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
783 - flush();
784 - return;
785 - }
786 -
787 - if ($http_code !== 200) {
788 - echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
789 - flush();
790 - return;
791 - }
792 -
793 - // Send completion signal
794 - echo "data: [DONE]\n\n";
795 - flush();
796 -}
797 -
798 -/**
799 - * Process streaming data for the test
800 - */
801 -private function process_streaming_test_data($data, $provider) {
802 - static $chunk_count = 0;
803 -
804 - $lines = explode("\n", $data);
805 -
806 - foreach ($lines as $line) {
807 - if (trim($line) === '') {
808 - continue;
809 - }
810 -
811 - // Handle different provider formats
812 - if ($provider === 'claude') {
813 - // Claude uses event: and data: format
814 - if (strpos($line, 'data: ') === 0) {
815 - $json_str = substr($line, 6);
816 - $json = json_decode($json_str, true);
817 -
818 - if (isset($json['type']) && $json['type'] === 'content_block_delta') {
819 - if (isset($json['delta']['text'])) {
820 - $chunk_count++;
821 - echo "data: " . json_encode([
822 - 'content' => $json['delta']['text'],
823 - 'test_chunk' => $chunk_count
824 - ]) . "\n\n";
825 - flush();
826 - }
827 - }
828 - }
829 - } else {
830 - // OpenAI, X.AI, DeepSeek format
831 - if (strpos($line, 'data: ') === 0) {
832 - $json_str = substr($line, 6);
833 -
834 - if ($json_str === '[DONE]') {
835 - // Don't echo [DONE] here, let the main function handle it
836 - continue;
837 - }
838 -
839 - $json = json_decode($json_str, true);
840 - if (isset($json['choices'][0]['delta']['content'])) {
841 - $chunk_count++;
842 - echo "data: " . json_encode([
843 - 'content' => $json['choices'][0]['delta']['content'],
844 - 'test_chunk' => $chunk_count
845 - ]) . "\n\n";
846 - flush();
847 - }
848 - }
849 - }
850 - }
851 -
852 - return strlen($data);
853 -}
854 -
855 -/**
856 - * Updated version of your existing test method (keep this as a fallback)
857 - */
858 -public function mxchat_handle_test_streaming() {
859 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
860 -
861 - // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but
862 - // fail here so the alias never becomes a bypass if that call is refactored.
863 - if (!current_user_can('manage_options')) {
864 - wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403);
865 - }
866 -
867 - // Use the actual streaming test instead
868 - $this->mxchat_handle_test_streaming_actual();
869 -}
870 -
871 -
872 -public function register_pinecone_settings() {
873 - register_setting(
874 - 'mxchat_pinecone_addon_options',
875 - 'mxchat_pinecone_addon_options',
876 - array(
877 - 'type' => 'array',
878 - 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
879 - 'default' => array(
880 - 'mxchat_use_pinecone' => '0',
881 - 'mxchat_pinecone_api_key' => '',
882 - 'mxchat_pinecone_host' => '',
883 - 'mxchat_pinecone_index' => '',
884 - 'mxchat_pinecone_environment' => ''
885 - )
886 - )
887 - );
888 -}
889 -
890 -public function sanitize_pinecone_settings($input) {
891 - $sanitized = array();
892 -
893 - $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
894 - $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
895 - $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
896 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
897 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
898 -
899 - // Remove https:// from host if present
900 - $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
901 -
902 - return $sanitized;
903 -}
904 -
905 -public function register_openai_vectorstore_settings() {
906 - register_setting(
907 - 'mxchat_openai_vectorstore_options',
908 - 'mxchat_openai_vectorstore_options',
909 - array(
910 - 'type' => 'array',
911 - 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
912 - 'default' => array(
913 - 'mxchat_use_openai_vectorstore' => '0',
914 - 'mxchat_vectorstore_ids' => '',
915 - 'mxchat_vectorstore_max_results' => 5
916 - )
917 - )
918 - );
919 -}
920 -
921 -public function sanitize_openai_vectorstore_settings($input) {
922 - $sanitized = array();
923 -
924 - $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
925 - $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
926 - $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
927 -
928 - // Ensure max results is within reasonable range
929 - if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
930 - $sanitized['mxchat_vectorstore_max_results'] = 1;
931 - }
932 - if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
933 - $sanitized['mxchat_vectorstore_max_results'] = 20;
934 - }
935 -
936 - return $sanitized;
937 -}
938 -
939 -/**
940 - * AJAX handler to test OpenAI Vector Store connection
941 - */
942 -public function mxchat_test_vectorstore_connection() {
943 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
944 -
945 - if (!current_user_can('manage_options')) {
946 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
947 - return;
948 - }
949 -
950 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
951 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
952 - $mxchat_options = get_option('mxchat_options', array());
953 - $api_key = $mxchat_options['api_key'] ?? '';
954 -
955 - if (empty($api_key)) {
956 - wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
957 - return;
958 - }
959 -
960 - if (empty($vectorstore_ids)) {
961 - wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
962 - return;
963 - }
964 -
965 - // Get the first Vector Store ID for testing
966 - $ids_array = array_map('trim', explode(',', $vectorstore_ids));
967 - $test_id = $ids_array[0];
968 -
969 - // Test by retrieving the Vector Store info
970 - $response = wp_remote_get(
971 - 'https://api.openai.com/v1/vector_stores/' . $test_id,
972 - array(
973 - 'headers' => array(
974 - 'Authorization' => 'Bearer ' . $api_key,
975 - 'Content-Type' => 'application/json',
976 - 'OpenAI-Beta' => 'assistants=v2'
220 + // Insert the content, embedding vector, and source URL into the database, using a prepared statement
221 + $inserted = $wpdb->insert(
222 + $table_name,
223 + array(
224 + 'article_content' => $article_content,
225 + 'embedding_vector' => $embedding_vector_serialized,
226 + 'source_url' => $article_url, // Insert the URL, empty string if not provided
977 227 ),
978 - 'timeout' => 30
979 - )
980 - );
981 -
982 - if (is_wp_error($response)) {
983 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
984 - return;
985 - }
986 -
987 - $status_code = wp_remote_retrieve_response_code($response);
988 - $body = json_decode(wp_remote_retrieve_body($response), true);
989 -
990 - if ($status_code === 200 && isset($body['id'])) {
991 - $file_count = $body['file_counts']['completed'] ?? 0;
992 - $name = $body['name'] ?? $test_id;
993 - wp_send_json_success(array(
994 - 'message' => sprintf(
995 - __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
996 - esc_html($name),
997 - $file_count
228 + array(
229 + '%s', // Format for article_content (string)
230 + '%s', // Format for embedding_vector (serialized string)
231 + '%s', // Format for source_url (string)
998 232 )
999 - ));
1000 - } elseif ($status_code === 404) {
1001 - wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
1002 - } elseif ($status_code === 401) {
1003 - wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
1004 - } else {
1005 - $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
1006 - wp_send_json_error(array('message' => $error_message));
1007 - }
1008 -}
1009 -
1010 -/**
1011 - * AJAX handler to test Slack connection and validate scopes
1012 - */
1013 -public function mxchat_test_slack_connection() {
1014 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
1015 -
1016 - if (!current_user_can('manage_options')) {
1017 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
1018 - return;
1019 - }
1020 -
1021 - $bot_token = $this->options['live_agent_bot_token'] ?? '';
1022 -
1023 - if (empty($bot_token)) {
1024 - wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
1025 - return;
1026 - }
1027 -
1028 - // Test 1: Validate bot token with auth.test
1029 - $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
1030 - 'headers' => array(
1031 - 'Authorization' => 'Bearer ' . $bot_token,
1032 - 'Content-Type' => 'application/json'
1033 - ),
1034 - 'timeout' => 15
1035 - ));
1036 -
1037 - if (is_wp_error($auth_response)) {
1038 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
1039 - return;
1040 - }
1041 -
1042 - $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
1043 -
1044 - if (!isset($auth_body['ok']) || !$auth_body['ok']) {
1045 - $error = $auth_body['error'] ?? 'unknown_error';
1046 - $error_messages = array(
1047 - 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
1048 - 'not_authed' => __('No authentication token provided.', 'mxchat'),
1049 - 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
1050 - 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
1051 233 );
1052 - $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
1053 - wp_send_json_error(array('message' => $message));
1054 - return;
1055 - }
1056 234
1057 - $team_name = $auth_body['team'] ?? 'Unknown Workspace';
1058 - $bot_name = $auth_body['user'] ?? 'Unknown Bot';
235 + if ($inserted === false) {
236 + //error_log('Error inserting content: ' . $wpdb->last_error);
237 + set_transient('mxchat_admin_notice_error', 'Error inserting content into the database. Please try again.', 30);
238 + } else {
239 + set_transient('mxchat_admin_notice_success', 'Content successfully submitted!', 30);
240 + }
1059 241
1060 - // Test 2: Check if we can list channels (tests channels:read scope)
1061 - $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
1062 - 'headers' => array(
1063 - 'Authorization' => 'Bearer ' . $bot_token,
1064 - 'Content-Type' => 'application/json'
1065 - ),
1066 - 'body' => json_encode(array('limit' => 1)),
1067 - 'timeout' => 15
1068 - ));
1069 -
1070 - $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
1071 - $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
1072 -
1073 - // Test 3: Check if we can create channels (tests channels:manage scope)
1074 - // We'll just check the error message without actually creating
1075 - $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
1076 - 'headers' => array(
1077 - 'Authorization' => 'Bearer ' . $bot_token,
1078 - 'Content-Type' => 'application/json'
1079 - ),
1080 - 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
1081 - 'timeout' => 15
1082 - ));
1083 -
1084 - $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
1085 -
1086 - // If channel was created, delete it immediately
1087 - if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
1088 - wp_remote_post('https://slack.com/api/conversations.archive', array(
1089 - 'headers' => array(
1090 - 'Authorization' => 'Bearer ' . $bot_token,
1091 - 'Content-Type' => 'application/json'
1092 - ),
1093 - 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
1094 - 'timeout' => 15
1095 - ));
1096 - $can_create_channels = true;
1097 242 } else {
1098 - $create_error = $create_body['error'] ?? '';
1099 - // name_taken means we have permission but channel exists
1100 - $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
1101 -
1102 - // Check for missing scope errors
1103 - if ($create_error === 'missing_scope') {
1104 - $can_create_channels = false;
1105 - }
243 + //error_log('Embedding generation failed for article content: ' . $article_content);
244 + set_transient('mxchat_admin_notice_error', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
1106 245 }
1107 246
1108 - // Build result message
1109 - $results = array();
1110 - $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
1111 - $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
1112 - $results[] = '';
1113 - $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
1114 - $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
1115 -
1116 - $missing_scopes = array();
1117 - if (!$can_read_channels) $missing_scopes[] = 'channels:read';
1118 - if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
1119 -
1120 - if (!empty($missing_scopes)) {
1121 - wp_send_json_error(array(
1122 - 'message' => implode("\n", $results),
1123 - 'missing_scopes' => $missing_scopes,
1124 - 'partial' => true
1125 - ));
1126 - } else {
1127 - wp_send_json_success(array(
1128 - 'message' => implode("\n", $results)
1129 - ));
1130 - }
247 + // Redirect after setting the transient
248 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
249 + exit;
1131 250 }
1132 251
1133 252 public function mxchat_display_admin_notice() {
1134 253 // Success notice
@@ -1135,9 +254,9 @@
1135 254 if ($message = get_transient('mxchat_admin_notice_success')) {
1136 255 ?>
1137 256 <div class="notice notice-success is-dismissible">
1138 257 <p><?php echo esc_html($message); ?></p>
1139 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
258 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1140 259 </div>
1141 260 <?php
1142 261 delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1143 262 }
@@ -1146,9 +265,9 @@
1146 265 if ($message = get_transient('mxchat_admin_notice_error')) {
1147 266 ?>
1148 267 <div class="notice notice-error is-dismissible">
1149 268 <p><?php echo esc_html($message); ?></p>
1150 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
269 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1151 270 </div>
1152 271 <?php
1153 272 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1154 273 }
@@ -1153,5077 +272,1179 @@
1153 272 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1154 273 }
1155 274 }
1156 275
1157 -public function show_live_agent_disabled_banner() {
1158 - $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1159 276
1160 - if ($show_disabled_notice) {
1161 - ?>
1162 - <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1163 - <div class="mxchat-pro-notification">
1164 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1165 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1166 - <line x1="18" y1="6" x2="6" y2="18"></line>
1167 - <line x1="6" y1="6" x2="18" y2="18"></line>
1168 - </svg>
1169 - </button>
1170 - <div class="mxchat-live-agent-content">
1171 - <h3>🔧 Live Agent Integration Updated!</h3>
1172 - <p>We've temporarily disabled your Live Agent integration due to recent enhancements that have made it much better! You can easily turn it back on by going to <strong>Settings &rarr; Integrations &rarr; Toolbar</strong> and reviewing the new configuration options.</p>
1173 - </div>
1174 - </div>
1175 - </div>
1176 - <?php
1177 - }
1178 -}
1179 -/**
1180 - * Render the Onboarding page. Delegates to the procedural renderer in
1181 - * includes/admin-onboarding-page.php. Wired to both `?page=mxchat-max`
1182 - * (legacy top-level URL) and `?page=mxchat-onboarding` (the canonical
1183 - * Onboarding submenu).
1184 - *
1185 - * When the user has dismissed onboarding and lands on `mxchat-max` (the
1186 - * legacy URL, since the Onboarding submenu has been removed), redirect to
1187 - * Settings instead — the page is "graduated" and we shouldn't dump them
1188 - * back onto it. They can still navigate here directly via the unhide link.
1189 - */
1190 -public function mxchat_create_dashboard_page() {
1191 - require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php';
1192 277
1193 - $current = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1194 - if ($current === 'mxchat-max' && function_exists('mxchat_onboarding_is_dismissed') && mxchat_onboarding_is_dismissed()) {
1195 - wp_safe_redirect(admin_url('admin.php?page=mxchat-settings'));
1196 - exit;
1197 - }
1198 278
1199 - if (function_exists('mxchat_render_onboarding_page')) {
1200 - mxchat_render_onboarding_page();
1201 - return;
1202 - }
1203 - // Defensive: if the include failed to load, fall back to the old Settings page
1204 - // so the top-level menu never lands on an empty screen.
1205 - $this->mxchat_create_admin_page();
1206 -}
1207 279
1208 -/**
1209 - * Hide the Onboarding submenu when the user has dismissed it (either
1210 - * manually or via auto-graduation). The page itself remains routable so
1211 - * the Settings "Show MxChat Onboarding again" link can navigate back to it.
1212 - */
1213 -public function mxchat_apply_onboarding_visibility() {
1214 - if (!function_exists('mxchat_onboarding_is_dismissed')) {
1215 - return;
1216 - }
1217 - if (mxchat_onboarding_is_dismissed()) {
1218 - // The first MxChat child is the same-slug-as-parent registration
1219 - // (slug 'mxchat-max', labelled "Onboarding") added in plan-d14e89.
1220 - // Remove it so the menu opens straight to Settings after dismiss.
1221 - remove_submenu_page('mxchat-max', 'mxchat-max');
1222 - }
1223 -}
1224 -
1225 280 public function mxchat_create_admin_page() {
1226 - $this->add_live_agent_nonce();
1227 - $this->add_theme_migration_nonce();
1228 -
1229 - // Include and render the new sidebar-based settings page
1230 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1231 - mxchat_render_settings_page($this);
1232 -}
1233 -
1234 -public function dismiss_live_agent_notice() {
1235 - // Add debugging
1236 - //error_log('dismiss_live_agent_notice called');
1237 - //error_log('POST data: ' . print_r($_POST, true));
1238 -
1239 - // Verify nonce
1240 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1241 - //error_log('Nonce verification failed');
1242 - wp_die('Security check failed');
1243 - }
1244 -
1245 - // Remove the notice flag
1246 - $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1247 - //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
1248 -
1249 - wp_send_json_success();
1250 -}
1251 -public function add_live_agent_nonce() {
1252 - if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1253 - // Make sure your admin script is enqueued and localize the data
1254 - wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1255 - 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1256 - 'ajaxurl' => admin_url('admin-ajax.php')
1257 - ));
1258 - }
1259 -}
1260 -
1261 -/**
1262 - * Show theme migration notice for Pro users with AI-generated themes
1263 - * Only shown once - dismissible and stored in options
1264 - */
1265 -public function show_theme_migration_banner() {
1266 - // Only show if Pro is activated
1267 - if (!$this->is_activated) {
1268 - return;
1269 - }
1270 -
1271 - // Check if notice should be shown
1272 - $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1273 -
1274 - if ($show_notice) {
1275 - ?>
1276 - <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1277 - <div class="mxchat-pro-notification">
1278 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1279 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1280 - <line x1="18" y1="6" x2="6" y2="18"></line>
1281 - <line x1="6" y1="6" x2="18" y2="18"></line>
1282 - </svg>
1283 - </button>
1284 - <div class="mxchat-theme-migration-content">
1285 - <h3>🎨 AI Theme Migration Required</h3>
1286 - <p>If you're using an AI-generated chatbot theme, you'll need to migrate it to match the new CSS structure. Go to <strong>Theme Settings</strong>, select your theme from the sidebar, and click the <strong>Migrate</strong> button.</p>
1287 - </div>
281 + ?>
282 + <div class="wrap mxchat-admin">
283 + <?php if (!$this->is_activated): ?>
284 + <div class="mxchat-pro-banner">
285 + <p>
286 + Limited-time offer: Get a lifetime MxChat Pro license for just $49.97 until 01.01.25! After that, it switches to an annual license at $99.97/year. Purchase now and be grandfathered into the lifetime deal!
287 + <a href="https://mxchat.ai/" target="_blank">Upgrade to MxChat Pro today!</a>
288 + </p>
289 + </div>
290 + <?php endif; ?>
291 + <h2 class="admin-title">Mx<span class="admin-emphasis">Chat</span></h2>
292 + <h2 class="mxchat-nav-tab-wrapper">
293 + <a href="#chatbot" class="mxchat-nav-tab mxchat-nav-tab-active" data-tab="chatbot">Chatbot</a>
294 + <a href="#embed" class="mxchat-nav-tab" data-tab="embed">Integrations</a>
295 + <a href="#theme" class="mxchat-nav-tab" data-tab="theme">Theme</a>
296 + <a href="#general" class="mxchat-nav-tab" data-tab="general">FAQ</a>
297 + </h2>
298 + <form method="post" action="options.php">
299 + <?php settings_fields('mxchat_option_group'); ?>
300 + <div id="chatbot" class="mxchat-tab-content active">
301 + <?php do_settings_sections('mxchat-chatbot'); ?>
1288 302 </div>
1289 - </div>
1290 - <?php
1291 - }
1292 -}
1293 303
1294 -/**
1295 - * Dismiss theme migration notice via AJAX
1296 - */
1297 -public function dismiss_theme_migration_notice() {
1298 - // Verify nonce
1299 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1300 - wp_die('Security check failed');
1301 - }
1302 304
1303 - // Remove the notice flag
1304 - delete_option('mxchat_show_theme_migration_notice');
1305 305
1306 - wp_send_json_success();
1307 -}
306 +<div id="embed" class="mxchat-tab-content">
307 + <div class="mxchat-settings-section">
308 + <h2>WooCommerce Settings</h2>
309 + <table class="form-table">
310 + <?php do_settings_fields('mxchat-embed', 'mxchat_woocommerce_section'); ?>
311 + </table>
312 + </div>
1308 313
1309 -/**
1310 - * Add nonce for theme migration notice dismiss
1311 - */
1312 -public function add_theme_migration_nonce() {
1313 - if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1314 - wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1315 - 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1316 - 'ajaxurl' => admin_url('admin-ajax.php')
1317 - ));
1318 - }
1319 -}
314 + <div class="section-divider"></div> <!-- Divider -->
1320 315
1321 -public function mxchat_create_transcripts_page() {
1322 - global $wpdb;
1323 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
316 + <div class="mxchat-settings-section">
317 + <h2>Loops Settings</h2>
318 + <table class="form-table">
319 + <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
320 + </table>
321 + </div>
1324 322
1325 - // Get basic stats
1326 - $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1327 - $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
1328 323
1329 - // Count unique users with detailed breakdown
1330 - $total_users = $wpdb->get_var("
1331 - SELECT COUNT(DISTINCT
1332 - CASE
1333 - WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1334 - WHEN user_id != 0 THEN CONCAT('user_', user_id)
1335 - WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1336 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1337 - AND user_identifier NOT LIKE 'Language Learner'
1338 - AND user_identifier NOT LIKE 'Casual Browser'
1339 - AND user_identifier NOT LIKE 'Policy Enforcer'
1340 - AND user_identifier NOT LIKE 'Researcher'
1341 - AND user_identifier NOT LIKE 'Loyalty Member'
1342 - AND user_identifier NOT LIKE 'Gift Buyer'
1343 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1344 - THEN user_identifier
1345 - ELSE session_id
1346 - END
1347 - )
1348 - FROM $table_name
1349 - WHERE role != 'assistant'
1350 - ");
324 + <div class="section-divider"></div> <!-- Divider -->
1351 325
1352 - // Get user type breakdown
1353 - $registered_users = $wpdb->get_var("
1354 - SELECT COUNT(DISTINCT user_email)
1355 - FROM $table_name
1356 - WHERE user_email != '' AND user_email IS NOT NULL
1357 - ");
326 + <!-- Brave Search Settings Section -->
327 + <div class="mxchat-settings-section">
328 + <h2>Brave Search Settings</h2>
329 + <table class="form-table">
330 + <?php do_settings_fields('mxchat-embed', 'mxchat_brave_section'); ?>
331 + </table>
332 + </div>
1358 333
1359 - $guest_users = $wpdb->get_var("
1360 - SELECT COUNT(DISTINCT user_identifier)
1361 - FROM $table_name
1362 - WHERE (user_email = '' OR user_email IS NULL)
1363 - AND role != 'assistant'
1364 - AND user_identifier NOT LIKE 'Tech-Savvy User'
1365 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1366 - AND user_identifier NOT LIKE 'Language Learner'
1367 - AND user_identifier NOT LIKE 'Casual Browser'
1368 - AND user_identifier NOT LIKE 'Policy Enforcer'
1369 - AND user_identifier NOT LIKE 'Researcher'
1370 - AND user_identifier NOT LIKE 'Loyalty Member'
1371 - AND user_identifier NOT LIKE 'Gift Buyer'
1372 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1373 - ");
334 + <div class="section-divider"></div> <!-- Divider -->
1374 335
1375 - // Get agent test messages count
1376 - $agent_tests = $wpdb->get_var("
1377 - SELECT COUNT(DISTINCT session_id)
1378 - FROM $table_name
1379 - WHERE user_identifier IN (
1380 - 'Tech-Savvy User',
1381 - 'Detail-Oriented User',
1382 - 'Language Learner',
1383 - 'Casual Browser',
1384 - 'Policy Enforcer',
1385 - 'Researcher',
1386 - 'Loyalty Member',
1387 - 'Gift Buyer',
1388 - 'Parent or Caregiver'
1389 - )
1390 - ");
1391 - // Get activity metrics
1392 - $today_chats = $wpdb->get_var("
1393 - SELECT COUNT(DISTINCT session_id)
1394 - FROM $table_name
1395 - WHERE DATE(timestamp) = CURDATE()
1396 - ");
1397 -
1398 - $week_chats = $wpdb->get_var("
1399 - SELECT COUNT(DISTINCT session_id)
1400 - FROM $table_name
1401 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1402 - ");
1403 -
1404 - $month_chats = $wpdb->get_var("
1405 - SELECT COUNT(DISTINCT session_id)
1406 - FROM $table_name
1407 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1408 - ");
1409 -
1410 - // Get daily chat data for last 7 days
1411 - $daily_stats = $wpdb->get_results("
1412 - SELECT
1413 - DATE(timestamp) as date,
1414 - COUNT(DISTINCT session_id) as chats,
1415 - COUNT(*) as messages
1416 - FROM $table_name
1417 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1418 - GROUP BY DATE(timestamp)
1419 - ORDER BY date ASC
1420 - ");
1421 -
1422 - // Get average messages per chat
1423 - $avg_messages = $wpdb->get_var("
1424 - SELECT AVG(message_count)
1425 - FROM (
1426 - SELECT session_id, COUNT(*) as message_count
1427 - FROM $table_name
1428 - GROUP BY session_id
1429 - ) as chat_counts
1430 - ");
1431 - $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1432 -
1433 - // Get busiest hour
1434 - $busiest_hour = $wpdb->get_row("
1435 - SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1436 - FROM $table_name
1437 - GROUP BY HOUR(timestamp)
1438 - ORDER BY chat_count DESC
1439 - LIMIT 1
1440 - ");
1441 -
1442 - // Prepare chart data
1443 - $chart_labels = array();
1444 - $chart_chats = array();
1445 - $chart_messages = array();
1446 -
1447 - // Fill last 7 days with data
1448 - for ($i = 6; $i >= 0; $i--) {
1449 - $date = date('Y-m-d', strtotime("-$i days"));
1450 - $day_name = date('D', strtotime("-$i days"));
1451 - $chart_labels[] = $day_name;
1452 -
1453 - $found = false;
1454 - foreach ($daily_stats as $stat) {
1455 - if ($stat->date === $date) {
1456 - $chart_chats[] = (int)$stat->chats;
1457 - $chart_messages[] = (int)$stat->messages;
1458 - $found = true;
1459 - break;
1460 - }
1461 - }
1462 - if (!$found) {
1463 - $chart_chats[] = 0;
1464 - $chart_messages[] = 0;
1465 - }
1466 - }
336 + <!-- Chat with PDF Intent Settings Section -->
337 +<div class="mxchat-settings-section">
338 + <h2>Toolbar Settings & Intents</h2>
339 + <table class="form-table">
340 + <?php do_settings_fields('mxchat-embed', 'mxchat_pdf_intent_section'); ?>
341 + </table>
342 +</div>
1467 343
1468 - // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1469 - $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
344 +<div class="section-divider"></div> <!-- Divider -->
345 +<!-- Live Agent Settings Section -->
346 +<div class="mxchat-settings-section">
347 + <h2>Live Agent Settings</h2>
348 +<p>Visit our <a href="https://mxchat.ai/documentation/#slack_integration" target="_blank">documentation page</a> to set up live agent transfer via Slack.</p>
349 + <table class="form-table">
350 + <?php do_settings_fields('mxchat-embed', 'mxchat_live_agent_section'); ?>
351 + </table>
352 +</div>
1470 353
1471 - // Prepare page data for the template
1472 - $page_data = array(
1473 - 'total_chats' => $total_chats,
1474 - 'total_messages' => $total_messages,
1475 - 'total_users' => $total_users,
1476 - 'registered_users' => $registered_users,
1477 - 'guest_users' => $guest_users,
1478 - 'agent_tests' => $agent_tests,
1479 - 'today_chats' => $today_chats,
1480 - 'week_chats' => $week_chats,
1481 - 'month_chats' => $month_chats,
1482 - 'avg_messages' => $avg_messages,
1483 - 'busiest_hour' => $busiest_hour,
1484 - 'chart_labels' => $chart_labels,
1485 - 'chart_chats' => $chart_chats,
1486 - 'chart_messages' => $chart_messages,
1487 - 'satisfaction_stats' => $satisfaction_stats,
1488 - );
354 +</div>
1489 355
1490 - // Include and render the new template
1491 - require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1492 - mxchat_render_transcripts_page($this, $page_data);
1493 -}
1494 356
1495 -/**
1496 - * Per-bot satisfaction rating rollup over the last $days days. Used by the
1497 - * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1498 - *
1499 - * @param int $days Window in days.
1500 - * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1501 - */
1502 -public function get_satisfaction_rating_stats($days = 30) {
1503 - global $wpdb;
1504 - $table = $wpdb->prefix . 'mxchat_session_ratings';
1505 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1506 - return array();
1507 - }
1508 - $days = max(1, (int) $days);
1509 - $rows = $wpdb->get_results($wpdb->prepare(
1510 - "SELECT bot_id,
1511 - COUNT(*) AS total,
1512 - SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1513 - SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1514 - FROM {$table}
1515 - WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1516 - GROUP BY bot_id
1517 - ORDER BY total DESC",
1518 - $days
1519 - ));
1520 - $out = array();
1521 - foreach ((array) $rows as $row) {
1522 - $total = (int) $row->total;
1523 - $positive = (int) $row->positive;
1524 - $negative = (int) $row->negative;
1525 - $out[] = array(
1526 - 'bot_id' => $row->bot_id ?: 'default',
1527 - 'total' => $total,
1528 - 'positive' => $positive,
1529 - 'negative' => $negative,
1530 - 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1531 - 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1532 - );
1533 - }
1534 - return $out;
1535 -}
1536 357
1537 -/**
1538 - * Get chart data for transcripts page
1539 - * Used by both page render and script localization
1540 - *
1541 - * @return array Chart data with labels, chats, and messages arrays
1542 - */
1543 -private function get_transcripts_chart_data() {
1544 - global $wpdb;
1545 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1546 358
1547 - // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1548 - $daily_stats = $wpdb->get_results("
1549 - SELECT
1550 - DATE(timestamp) as date,
1551 - COUNT(DISTINCT session_id) as chats,
1552 - COUNT(*) as messages
1553 - FROM $table_name
1554 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1555 - GROUP BY DATE(timestamp)
1556 - ORDER BY date ASC
1557 - ");
1558 359
1559 - // Prepare chart data
1560 - $chart_labels = array();
1561 - $chart_chats = array();
1562 - $chart_messages = array();
360 + <div id="theme" class="mxchat-tab-content">
361 + <?php do_settings_sections('mxchat-theme'); ?>
362 + </div>
363 + <div id="general" class="mxchat-tab-content">
364 + <?php do_settings_sections('mxchat-general'); ?>
365 +<p>
366 + If you’re having trouble with setup or getting the responses you need, we encourage you to review our
367 + <a href="https://mxchat.ai/documentation/" target="_blank" rel="noopener noreferrer">documentation</a> or
368 + <a href="https://wordpress.org/support/plugin/mxchat-basic/" target="_blank" rel="noopener noreferrer">create a support ticket</a>.
369 +</p>
370 +<p>
371 + If you like our plugin, please consider <a href="https://wordpress.org/plugins/mxchat-basic/#reviews" target="_blank" rel="noopener noreferrer">leaving us a review</a>.
372 +</p>
1563 373
1564 - // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1565 - for ($i = 6; $i >= 0; $i--) {
1566 - $date = date('Y-m-d', strtotime("-$i days"));
1567 - $day_name = date('D', strtotime("-$i days"));
1568 - $chart_labels[] = $day_name;
1569 -
1570 - $found = false;
1571 - if ($daily_stats) {
1572 - foreach ($daily_stats as $stat) {
1573 - if ($stat->date === $date) {
1574 - $chart_chats[] = (int)$stat->chats;
1575 - $chart_messages[] = (int)$stat->messages;
1576 - $found = true;
1577 - break;
1578 - }
1579 - }
1580 - }
1581 - if (!$found) {
1582 - $chart_chats[] = 0;
1583 - $chart_messages[] = 0;
1584 - }
1585 - }
1586 -
1587 - return array(
1588 - 'labels' => $chart_labels,
1589 - 'chats' => $chart_chats,
1590 - 'messages' => $chart_messages
1591 - );
1592 -}
1593 -
1594 -public function mxchat_transcripts_notification_section_callback() {
1595 - echo '<p>' . esc_html__('Configure email notifications for new chat transcripts. You will receive an email notification when a new chat session begins.', 'mxchat') . '</p>';
1596 -}
1597 -public function mxchat_enable_notifications_callback() {
1598 - $options = get_option('mxchat_transcripts_options', array());
1599 - $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1600 - ?>
1601 - <label for="mxchat_enable_notifications">
1602 - <input type="checkbox" id="mxchat_enable_notifications"
1603 - name="mxchat_transcripts_options[mxchat_enable_notifications]"
1604 - value="1" <?php checked(1, $enabled); ?>>
1605 - <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1606 - </label>
1607 - <p class="description">
1608 - <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
374 +<div class="faq-item">
375 + <h3>How does the Claude API integration work?</h3>
376 + <p>
377 + The Claude API, provided by Anthropic, allows for intelligent, context-aware chatbot responses in MxChat. To use it, you will need both an OpenAI API key and a Claude API key. This is necessary because the system utilizes OpenAI for vector embedding in the Retrieval-Augmented Generation (RAG) process, as Claude does not currently offer an embedding API.
1609 378 </p>
1610 - <?php
1611 -}
1612 -public function mxchat_notification_email_callback() {
1613 - $options = get_option('mxchat_transcripts_options', array());
1614 - $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1615 - ?>
1616 - <?php /* type="text", not "email": the browser rejects a comma-separated list outright (plan 2f131a). Validation is server-side in MxChat_Utils. */ ?>
1617 - <input type="text" id="mxchat_notification_email"
1618 - name="mxchat_transcripts_options[mxchat_notification_email]"
1619 - value="<?php echo esc_attr($email); ?>"
1620 - class="regular-text">
1621 - <p class="description">
1622 - <?php printf(esc_html__('Enter the email address where notifications should be sent. Separate up to %d addresses with commas. Defaults to the admin email address.', 'mxchat'), (int) MxChat_Utils::NOTIFICATION_EMAIL_MAX); ?>
379 + <p>
380 + When using the Claude API, your custom content is sent to Claude for generating responses, while the embeddings are processed through OpenAI. This ensures your chatbot provides accurate and engaging responses while maintaining knowledge relevant to your website.
1623 381 </p>
1624 - <?php
1625 -}
382 + <p>
383 + You can obtain your Claude API key by signing up on the <a href="https://www.anthropic.com/api" target="_blank" rel="noopener">Anthropic API page</a>.
384 + </p>
385 +</div>
1626 386
1627 -public function mxchat_auto_delete_transcripts_callback() {
1628 - $options = get_option('mxchat_transcripts_options', array());
1629 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1630 - ?>
1631 - <select id="mxchat_auto_delete_transcripts"
1632 - name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1633 - <option value="never" <?php selected($interval, 'never'); ?>>
1634 - <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1635 - </option>
1636 - <option value="1week" <?php selected($interval, '1week'); ?>>
1637 - <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1638 - </option>
1639 - <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1640 - <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1641 - </option>
1642 - <option value="1month" <?php selected($interval, '1month'); ?>>
1643 - <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1644 - </option>
1645 - </select>
1646 - <p class="description">
1647 - <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
387 +<div class="faq-item">
388 + <h3>How does the X.AI API integration work?</h3>
389 + <p>
390 + The X.AI API, released on 10.21.24, is currently in beta. To use it, you will need both an OpenAI API key and an X.AI API key. This is because OpenAI handles vector embeddings in the Retrieval-Augmented Generation (RAG) process, as X.AI does not yet provide an embedding API.
1648 391 </p>
1649 - <?php
1650 -}
392 + <p>
393 + Custom content is sent to the X.AI API for generating responses, while OpenAI processes the embeddings. This allows the chatbot to provide advanced responses while maintaining context from your website. You can get your X.AI API key from the <a href="https://docs.x.ai/docs" target="_blank" rel="noopener">X.AI API documentation</a>.
394 + </p>
395 +</div>
1651 396
1652 -/**
1653 - * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1654 - * and deletes transcripts older than the given number of days. Set to 0 to fall
1655 - * back to the dropdown (or "Never" if the dropdown is also Never).
1656 - *
1657 - * Devs can override the final day count via the `mxchat_transcript_retention_days`
1658 - * filter — runs in `cleanup_old_transcripts()` after this option is read.
1659 - *
1660 - * (plan-mxchat-20260509-9b80b1)
1661 - */
1662 -public function mxchat_retention_days_callback() {
1663 - $options = get_option('mxchat_transcripts_options', array());
1664 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1665 - ?>
1666 - <input type="number"
1667 - id="mxchat_retention_days"
1668 - name="mxchat_transcripts_options[mxchat_retention_days]"
1669 - value="<?php echo esc_attr($days); ?>"
1670 - min="0"
1671 - max="3650"
1672 - step="1"
1673 - style="width: 90px;" />
1674 - <p class="description">
1675 - <?php esc_html_e('Number of days to retain transcripts. When set to a value greater than 0, this overrides the dropdown above. Set to 0 to use the dropdown. Maximum 3650 (10 years). A daily wp-cron task removes anything older, cascading to translations and click-tracking rows.', 'mxchat'); ?>
1676 - <br>
1677 - <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1678 - <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
397 +<div class="faq-item">
398 + <h3>Do I need an OpenAI API key to use the chatbot?</h3>
399 + <p>
400 + Yes, you will need an OpenAI API key to power the chatbot. You can obtain an API key by signing up on the <a href="https://platform.openai.com/signup" target="_blank" rel="noopener">OpenAI platform</a>. After signing up, you must add credits to your account—typically, $5 in credits is sufficient to get started.
1679 401 </p>
1680 - <?php
1681 -}
1682 -
1683 -public function mxchat_auto_email_transcript_callback() {
1684 - $options = get_option('mxchat_transcripts_options', array());
1685 - $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1686 - $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1687 - $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1688 - ?>
1689 - <label>
1690 - <input type="checkbox"
1691 - id="mxchat_auto_email_transcript_enabled"
1692 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1693 - value="1"
1694 - <?php checked($enabled, 1); ?>>
1695 - <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1696 - </label>
1697 - <br><br>
1698 - <label for="mxchat_auto_email_transcript_delay">
1699 - <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1700 - </label>
1701 - <select id="mxchat_auto_email_transcript_delay"
1702 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1703 - <option value="15" <?php selected($delay, '15'); ?>>
1704 - <?php esc_html_e('15 minutes', 'mxchat'); ?>
1705 - </option>
1706 - <option value="30" <?php selected($delay, '30'); ?>>
1707 - <?php esc_html_e('30 minutes', 'mxchat'); ?>
1708 - </option>
1709 - <option value="60" <?php selected($delay, '60'); ?>>
1710 - <?php esc_html_e('1 hour', 'mxchat'); ?>
1711 - </option>
1712 - </select>
1713 - <br><br>
1714 - <label>
1715 - <input type="checkbox"
1716 - id="mxchat_auto_email_transcript_require_contact"
1717 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1718 - value="1"
1719 - <?php checked($require_contact, 1); ?>>
1720 - <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1721 - </label>
1722 - <p class="description">
1723 - <?php esc_html_e('Automatically email the full transcript as a .txt file after the specified time has passed since the last user message. The scheduled email will be cancelled if a new message is received.', 'mxchat'); ?>
1724 - <br>
1725 - <?php esc_html_e('When "Only send if visitor provided contact info" is enabled, transcripts will only be emailed if the visitor shared an email address or phone number (including WhatsApp) in the chat.', 'mxchat'); ?>
402 + <p>
403 + Once you have your API key, simply enter it in the chatbot's settings to enable functionality. The chatbot relies on OpenAI’s models for generating responses, so having sufficient credits in your OpenAI account is essential for smooth operation.
1726 404 </p>
1727 - <?php
1728 -}
405 +</div>
1729 406
407 + <div class="faq-item">
408 + <h3>How do I add the chatbot to my site?</h3>
409 + <p>
410 + 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.
411 + </p>
412 + </div>
1730 413
414 + <div class="faq-item">
415 + <h3>How does the chatbot use my content to generate responses?</h3>
416 + <p>
417 + 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.
418 + </p>
419 + </div>
1731 420
1732 -public function sanitize_transcripts_options($input) {
1733 - $sanitized = array();
421 + <div class="faq-item">
422 + <h3>Why does the chatbot sometimes make up links or information?</h3>
423 + <p>
424 + 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.
425 + </p>
426 + </div>
1734 427
1735 - $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
428 + <div class="faq-item">
429 + <h3>How do intents work in MxChat?</h3>
430 + <p>
431 + Intents allow MxChat to recognize user requests and trigger specific actions, such as capturing emails or displaying product information. This helps provide a more interactive and responsive experience. For a detailed explanation of each intent, please refer to our <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">Intents Documentation</a>.
432 + </p>
433 + </div>
1736 434
1737 - if (isset($input['mxchat_notification_email'])) {
1738 - // Same list rule as the Transcripts autosave path (plan 2f131a). These two
1739 - // paths disagreeing is how the original bug survived: this one DID call
1740 - // is_email(), but on sanitize_email()'s output — which is valid even when
1741 - // the input was two addresses mashed into one. See MxChat_Utils.
1742 - $parsed = MxChat_Utils::parse_notification_emails($input['mxchat_notification_email']);
1743 - if ($parsed['error'] !== '') {
1744 - add_settings_error(
1745 - 'mxchat_transcripts_options',
1746 - 'invalid_email',
1747 - $parsed['error'],
1748 - 'error'
1749 - );
1750 - // Keep whatever was already stored. Do NOT fall back to admin_email:
1751 - // that fallback belongs to a genuinely EMPTY field, and using it here
1752 - // would quietly redirect notifications away from the address on screen.
1753 - $existing = get_option('mxchat_transcripts_options', array());
1754 - if (is_array($existing) && isset($existing['mxchat_notification_email'])) {
1755 - $sanitized['mxchat_notification_email'] = $existing['mxchat_notification_email'];
1756 - }
1757 - } else {
1758 - $sanitized['mxchat_notification_email'] = implode(', ', $parsed['emails']);
1759 - }
1760 - }
1761 435
1762 - // Sanitize auto-delete setting
1763 - $valid_intervals = array('never', '1week', '2weeks', '1month');
1764 - if (isset($input['mxchat_auto_delete_transcripts'])) {
1765 - $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1766 - ? $input['mxchat_auto_delete_transcripts']
1767 - : 'never';
1768 - } else {
1769 - $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1770 - }
436 + <div class="faq-item">
437 + <h3>How does the Complianz integration work?</h3>
438 + <p>
439 + 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.
440 + </p>
441 + </div>
1771 442
1772 - // Sanitize custom retention-days override (plan-9b80b1).
1773 - if (isset($input['mxchat_retention_days'])) {
1774 - $days = (int) $input['mxchat_retention_days'];
1775 - $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1776 - } else {
1777 - $sanitized['mxchat_retention_days'] = 0;
1778 - }
443 + <div class="faq-item">
444 + <h3>How does the WooCommerce integration work?</h3>
445 + <p>
446 + 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.
447 + </p>
448 + </div>
1779 449
1780 - // Get old values to check if auto-delete or retention-days changed.
1781 - $old_options = get_option('mxchat_transcripts_options');
1782 - $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1783 - $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
450 + <div class="faq-item">
451 + <h3>Why isn't my chatbot responding as expected?</h3>
452 + <p>
453 + 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.
454 + </p>
455 + <p>
456 + We’re dedicated to your success and ready to guide you in aligning the AI's behavior to meet your goals.
457 + </p>
458 + </div>
1784 459
1785 - // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1786 - // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1787 - // reason to keep the daily cron registered.
1788 - $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1789 - $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1790 - if ($interval_changed || $retention_changed) {
1791 - $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1792 - $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1793 - }
460 + <div class="faq-item">
461 + <h3>What is Loops, and how do I get an API key?</h3>
462 + <p>
463 + 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.
464 + </p>
465 + </div>
1794 466
1795 - // Sanitize auto-email transcript settings
1796 - $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
1797 467
1798 - $valid_delays = array('15', '30', '60');
1799 - if (isset($input['mxchat_auto_email_transcript_delay'])) {
1800 - $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1801 - ? $input['mxchat_auto_email_transcript_delay']
1802 - : '30';
1803 - } else {
1804 - $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1805 - }
1806 -
1807 - // Sanitize require contact info setting
1808 - $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1809 -
1810 - return $sanitized;
468 + </div>
469 + <?php submit_button(); ?>
470 + </form>
471 + </div>
472 + <?php
1811 473 }
1812 474
1813 -/**
1814 - * Schedule or unschedule the transcript cleanup cron job
1815 - */
1816 -public function schedule_transcript_cleanup($interval) {
1817 - // Clear any existing scheduled event
1818 - $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1819 - if ($timestamp) {
1820 - wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1821 - }
1822 475
1823 - // Schedule new event whenever retention is active. "active" is the canonical
1824 - // value passed by sanitize_transcripts_options when either the dropdown != never
1825 - // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1826 - // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1827 - if ($interval !== 'never') {
1828 - // Schedule to run daily at 3 AM
1829 - $next_run = strtotime('tomorrow 3:00 AM');
1830 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1831 - }
1832 -}
476 + public function mxchat_create_transcripts_page() {
477 + ?>
478 + <div class="wrap mxchat-admin">
479 + <h2><?php esc_html_e('Chat Transcripts', 'mxchat'); ?></h2>
480 + <form id="mxchat-delete-form" method="post">
481 + <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
482 + <div class="mxchat-controls">
483 + <label for="mxchat-select-all-transcripts" class="mxchat-select-all-label">
484 + <input type="checkbox" id="mxchat-select-all-transcripts" /> <?php esc_html_e('Select All', 'mxchat'); ?>
485 + </label>
486 + <input type="submit" value="<?php esc_attr_e('Delete Selected', 'mxchat'); ?>" class="button delete-chats-button" />
487 + </div>
488 + <div id="mxchat-transcripts">
489 + <!-- Transcripts will be loaded here -->
490 + </div>
491 + </form>
492 + </div>
493 + <?php
494 + }
1833 495
1834 -/**
1835 - * Self-heal guard: keep the cleanup cron in sync with the retention setting.
1836 - *
1837 - * Runs on admin_init. Cost when nothing is wrong: one get_option() (cached) and
1838 - * one wp_next_scheduled() (reads the cached cron option) — no writes. It only
1839 - * schedules when retention is active but the event is missing, and only
1840 - * unschedules when retention is off but the event survived. Both directions
1841 - * reuse schedule_transcript_cleanup() so there is exactly one scheduling path.
1842 - * Legacy dropdown values (1week/2weeks/1month) count as active, matching the
1843 - * helper's own semantics. Deliberately not gated on DISABLE_WP_CRON: scheduling
1844 - * writes the cron option regardless of how cron is executed, so a server-side
1845 - * cron runner still picks the event up.
1846 - */
1847 -public function ensure_transcript_cleanup_scheduled() {
1848 - $options = get_option('mxchat_transcripts_options', array());
1849 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1850 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1851 - $active = ($interval !== 'never') || ($days > 0);
1852 - $scheduled = (bool) wp_next_scheduled('mxchat_cleanup_old_transcripts');
1853 496
1854 - if ($active && !$scheduled) {
1855 - $this->schedule_transcript_cleanup('active');
1856 - } elseif (!$active && $scheduled) {
1857 - $this->schedule_transcript_cleanup('never');
1858 - }
1859 -}
1860 497
1861 -/**
1862 - * Delete old transcripts based on the configured interval
1863 - */
1864 -public function cleanup_old_transcripts() {
1865 - $options = get_option('mxchat_transcripts_options', array());
1866 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1867 - $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1868 498
1869 - // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
1870 - $days = 0;
1871 - if ($custom_days > 0) {
1872 - $days = $custom_days;
1873 - } else {
1874 - switch ($interval) {
1875 - case '1week': $days = 7; break;
1876 - case '2weeks': $days = 14; break;
1877 - case '1month': $days = 30; break;
1878 - case 'never':
1879 - default:
1880 - $days = 0;
1881 - }
1882 - }
1883 -
1884 - // Devs can override the final day count programmatically.
1885 - $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
1886 -
1887 - if ($days <= 0) {
1888 - return; // Retention disabled — bail.
1889 - }
1890 -
499 +public function mxchat_create_prompts_page() {
1891 500 global $wpdb;
1892 - $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1893 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1894 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
501 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1895 502
1896 - // Defensive: if the main table doesn't exist (fresh-ish install), bail.
1897 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
1898 - return;
503 + // Display success message if all prompts were deleted
504 + if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
505 + echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p></div>';
1899 506 }
1900 507
1901 - $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
508 + // Set up pagination and search query
509 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
510 + $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
511 + $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
512 + $per_page = 10;
513 + $offset = ($current_page - 1) * $per_page;
1902 514
1903 - // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
1904 - // the cron will pick up where it left off on the next tick (within hours).
1905 - $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
1906 -
1907 - $sessions_to_delete = $wpdb->get_col(
1908 - $wpdb->prepare(
1909 - "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
1910 - $cutoff_date,
1911 - $batch_cap
1912 - )
1913 - );
1914 -
1915 - if (empty($sessions_to_delete)) {
1916 - return;
515 + // Modify query to handle search input
516 + $sql_search = "";
517 + if ($search_query) {
518 + $sql_search = $wpdb->prepare("WHERE article_content LIKE %s", '%' . $wpdb->esc_like($search_query) . '%');
1917 519 }
1918 520
1919 - $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
521 + // Retrieve total number of prompts, considering search filter
522 + $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} {$sql_search}");
523 + $total_pages = ceil($total_prompts / $per_page);
1920 524
1921 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1922 - // $placeholders is a server-built list of literal "%s" tokens.
1923 - $deleted_transcripts = (int) $wpdb->query(
525 + // Retrieve prompts from the database
526 + $prompts = $wpdb->get_results(
1924 527 $wpdb->prepare(
1925 - "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
1926 - $sessions_to_delete
528 + "SELECT * FROM {$table_name} {$sql_search} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
529 + $per_page,
530 + $offset
1927 531 )
1928 532 );
1929 533
1930 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
1931 - $wpdb->query(
1932 - $wpdb->prepare(
1933 - "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
1934 - $sessions_to_delete
1935 - )
1936 - );
1937 - }
534 + ?>
1938 535
1939 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
1940 - $wpdb->query(
1941 - $wpdb->prepare(
1942 - "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
1943 - $sessions_to_delete
1944 - )
1945 - );
1946 - }
1947 - // phpcs:enable
536 + <div class="wrap mxchat-admin">
537 + <div class="mxchat-grid-container">
538 + <!-- Submit Content Form -->
539 + <div class="mxchat-grid-item full-width">
540 + <h2>Submit Content</h2>
541 + <form id="mxchat-content-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
542 + <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
543 + <div class="mxchat-form-group">
544 + <label for="article_content">Article Content:</label>
545 + <textarea name="article_content" id="article_content" required></textarea>
546 + </div>
547 + <div class="mxchat-form-group">
548 + <label for="article_url">Article URL (Optional):</label>
549 + <input type="url" name="article_url" id="article_url" placeholder="Enter related URL for the content">
550 + </div>
551 + <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
552 + </form>
553 + <div id="mxchat-content-loading" class="mxchat-content-spinner" style="display: none;"></div>
554 + <div id="mxchat-content-loading-text" class="mxchat-loading-text">Submitting content, please wait...</div>
555 + </div>
1948 556
1949 - update_option('mxchat_retention_last_swept_at', time(), false);
1950 - update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
1951 -}
1952 557
1953 -public function export_chat_transcripts() {
1954 - if (!current_user_can('manage_options')) {
1955 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1956 - }
558 + <div class="mxchat-grid-item">
559 + <h2><?php esc_html_e('Submit Sitemap, URL, or PDF URL', 'mxchat'); ?></h2>
1957 560
1958 - check_ajax_referer('mxchat_export_transcripts', 'security');
561 + <?php
562 + // Check for any active processing
563 + $pdf_url = get_transient('mxchat_last_pdf_url');
564 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
565 + $pdf_status = $pdf_url ? $this->get_pdf_processing_status($pdf_url) : false;
566 + $sitemap_status = $sitemap_url ? $this->get_sitemap_processing_status($sitemap_url) : false;
1959 567
1960 - global $wpdb;
1961 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
568 + // Clear old completed statuses
569 + if ($pdf_status && $pdf_status['status'] === 'complete') {
570 + delete_transient('mxchat_last_pdf_url');
571 + $pdf_status = false;
572 + }
573 + if ($sitemap_status && $sitemap_status['status'] === 'complete') {
574 + delete_transient('mxchat_last_sitemap_url');
575 + $sitemap_status = false;
576 + }
1962 577
1963 - // Get all transcripts ordered by session and timestamp
1964 - $results = $wpdb->get_results(
1965 - "SELECT session_id, user_email, user_identifier, role, message, timestamp
1966 - FROM {$table_name}
1967 - ORDER BY session_id, timestamp ASC"
1968 - );
578 + $is_processing = ($pdf_status && $pdf_status['status'] === 'processing') ||
579 + ($sitemap_status && $sitemap_status['status'] === 'processing');
580 + ?>
1969 581
1970 - if (empty($results)) {
1971 - wp_send_json_error(array('message' => 'No transcripts found.'));
1972 - wp_die();
1973 - }
582 + <?php if (!$is_processing) : ?>
583 + <form id="mxchat-sitemap-form" method="post" class="mxchat-sitemap-form"
584 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_sitemap')); ?>">
1974 585
1975 - // Set headers for CSV download
1976 - header('Content-Type: text/csv');
1977 - header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
1978 - header('Pragma: no-cache');
1979 - header('Expires: 0');
586 + <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
1980 587
1981 - // Create output stream
1982 - $output = fopen('php://output', 'w');
588 + <div class="mxchat-search-group">
589 + <input type="url"
590 + name="sitemap_url"
591 + id="sitemap_url"
592 + placeholder="<?php esc_attr_e('Enter URL (Sitemap, PDF, or webpage)', 'mxchat'); ?>"
593 + required
594 + aria-label="<?php esc_attr_e('URL Input', 'mxchat'); ?>"
595 + />
596 + <input type="submit"
597 + name="submit_sitemap"
598 + value="<?php esc_attr_e('Submit', 'mxchat'); ?>"
599 + class="button button-primary"
600 + />
601 + </div>
602 + </form>
603 + <?php endif; ?>
1983 604
1984 - // Add UTF-8 BOM for proper Excel encoding
1985 - fputs($output, "\xEF\xBB\xBF");
605 + <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"
606 + aria-hidden="true"></div>
607 + <div id="mxchat-loading-text" class="screen-reader-text" style="display: none;">
608 + <?php esc_html_e('Loading information into database, please wait...', 'mxchat'); ?>
609 + </div>
1986 610
1987 - // Add CSV headers
1988 - fputcsv($output, array(
1989 - 'Session ID',
1990 - 'Email',
1991 - 'User Identifier',
1992 - 'Role',
1993 - 'Message',
1994 - 'Timestamp'
1995 - ));
611 + <?php if ($pdf_status && $pdf_status['status'] !== 'complete') : ?>
612 + <div class="mxchat-process-status pdf" role="alert" aria-live="polite">
613 + <h3><?php esc_html_e('PDF Processing Status (Refresh page for update)', 'mxchat'); ?></h3>
614 + <p>
615 + <?php
616 + printf(
617 + /* translators: 1: Current pages, 2: Total pages, 3: Percentage complete */
618 + esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'),
619 + absint($pdf_status['processed_pages']),
620 + absint($pdf_status['total_pages']),
621 + absint($pdf_status['percentage'])
622 + );
623 + ?>
624 + </p>
625 + <p>
626 + <?php
627 + printf(
628 + /* translators: %s: Current status */
629 + esc_html__('Status: %s', 'mxchat'),
630 + esc_html(ucfirst($pdf_status['status']))
631 + );
632 + ?>
633 + </p>
634 + <p>
635 + <?php
636 + printf(
637 + /* translators: %s: Time since last update */
638 + esc_html__('Last update: %s', 'mxchat'),
639 + esc_html($pdf_status['last_update'])
640 + );
641 + ?>
642 + </p>
643 + </div>
644 + <?php endif; ?>
1996 645
1997 - // Add data rows
1998 - foreach ($results as $row) {
1999 - fputcsv($output, array(
2000 - $row->session_id,
2001 - $row->user_email,
2002 - $row->user_identifier,
2003 - $row->role,
2004 - $row->message,
2005 - $row->timestamp
2006 - ));
2007 - }
646 + <?php if ($sitemap_status && $sitemap_status['status'] !== 'complete') : ?>
647 + <div class="mxchat-process-status sitemap" role="alert" aria-live="polite">
648 + <h3><?php esc_html_e('Sitemap Processing Status (Refresh page for update)', 'mxchat'); ?></h3>
649 + <p>
650 + <?php
651 + printf(
652 + /* translators: 1: Processed URLs, 2: Total URLs, 3: Percentage complete */
653 + esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'),
654 + absint($sitemap_status['processed_urls']),
655 + absint($sitemap_status['total_urls']),
656 + absint($sitemap_status['percentage'])
657 + );
658 + ?>
659 + </p>
660 + <p>
661 + <?php
662 + printf(
663 + /* translators: %s: Current status */
664 + esc_html__('Status: %s', 'mxchat'),
665 + esc_html(ucfirst($sitemap_status['status']))
666 + );
667 + ?>
668 + </p>
669 + <p>
670 + <?php
671 + printf(
672 + /* translators: %s: Time since last update */
673 + esc_html__('Last update: %s', 'mxchat'),
674 + esc_html($sitemap_status['last_update'])
675 + );
676 + ?>
677 + </p>
678 + </div>
679 + <?php endif; ?>
2008 680
2009 - fclose($output);
2010 - wp_die();
2011 -}
681 + <?php if ($is_processing) : ?>
682 + <form id="mxchat-stop-form" method="post" class="mxchat-stop-form"
683 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
2012 684
2013 -// ============================================================================
2014 -// Leads tab (inside Transcripts)
2015 -//
2016 -// Leads are derived from existing data — no dedicated table. Primary source:
2017 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
2018 -// source: the mxchat_sessions table's visitor_email/visitor_name columns
2019 -// (plus any unmigrated legacy `mxchat_email_{sid}` wp_options rows) for
2020 -// "orphan" leads who submitted the pre-chat form but never chatted.
2021 -// ============================================================================
685 + <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
2022 686
2023 -/**
2024 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
2025 - */
2026 -public function mxchat_fetch_leads() {
2027 - if (!current_user_can('manage_options')) {
2028 - wp_send_json_error(['message' => 'Insufficient permissions']);
2029 - wp_die();
2030 - }
687 + <input type="submit"
688 + name="stop_processing"
689 + value="<?php esc_attr_e('Stop Processing', 'mxchat'); ?>"
690 + class="button button-secondary"
691 + />
692 + </form>
693 +<?php endif; ?>
2031 694
2032 - global $wpdb;
2033 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
695 + </div>
2034 696
2035 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
2036 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
2037 - $offset = ($page - 1) * $per_page;
2038 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
2039 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
2040 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
2041 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
2042 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
2043 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
697 + <!-- Search Knowledge Form -->
698 + <div class="mxchat-grid-item">
699 + <h2>Search Knowledge</h2>
700 + <form method="get" id="knowledge-search">
701 + <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
702 + <input type="hidden" name="page" value="mxchat-prompts" />
703 + <div class="mxchat-search-group">
704 + <input type="text" name="search" placeholder="Search Knowledge" value="<?php echo esc_attr($search_query); ?>" />
705 + <input type="submit" value="Search" class="button button-primary" />
706 + </div>
707 + </form>
708 + </div>
709 + </div>
2044 710
2045 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
2046 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
711 + <!-- Table navigation with Delete All Button -->
712 + <div class="tablenav">
713 + <div class="tablenav-pages">
714 + <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
2047 715
2048 - // Base WHERE for transcripts leads.
2049 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
2050 - $where_params = [];
716 + <!-- Delete All Prompts Button -->
717 + <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_all_prompts')); ?>" style="display: inline;" onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete all prompts? This action cannot be undone.', 'mxchat'); ?>');">
718 + <?php wp_nonce_field('mxchat_delete_all_prompts_action', 'mxchat_delete_all_prompts_nonce'); ?>
719 + <input type="submit" name="delete_all_prompts" value="<?php esc_attr_e('Delete All Knowledge', 'mxchat'); ?>" class="button mxchat-delete-all" />
720 + </form>
2051 721
2052 - if ($date_cutoff) {
2053 - $where_clauses[] = 'timestamp >= %s';
2054 - $where_params[] = $date_cutoff;
2055 - }
2056 - if ($page_filter && $has_page_url_column) {
2057 - $where_clauses[] = 'originating_page_url = %s';
2058 - $where_params[] = $page_filter;
2059 - }
2060 - if ($search !== '') {
2061 - $like = '%' . $wpdb->esc_like($search) . '%';
2062 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
2063 - $where_params[] = $like;
2064 - $where_params[] = $like;
2065 - }
2066 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
722 + <?php
723 + // Display pagination links
724 + $page_links = paginate_links(array(
725 + 'base' => add_query_arg(array('paged' => '%#%', 'search' => urlencode($search_query), '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')), admin_url('admin.php?page=mxchat-prompts')),
726 + 'format' => '',
727 + 'prev_text' => __('&laquo; Previous'),
728 + 'next_text' => __('Next &raquo;'),
729 + 'total' => $total_pages,
730 + 'current' => $current_page,
731 + ));
2067 732
2068 - // Aggregate query grouped by email.
2069 - $select_sql = $has_page_url_column
2070 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2071 - COUNT(DISTINCT session_id) AS conversation_count"
2072 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
2073 - COUNT(DISTINCT session_id) AS conversation_count";
733 + if ($page_links) {
734 + echo '<div class="tablenav-pages">' . wp_kses_post($page_links) . '</div>';
735 + }
736 + ?>
737 + </div>
738 + </div>
2074 739
2075 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
2076 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
740 + <!-- Prompts Table -->
741 + <table class="mxchat-table">
742 + <thead>
743 + <tr>
744 + <th>ID</th>
745 + <th>Article Content</th>
746 + <th>URL</th>
747 + <th>Actions</th>
748 + </tr>
749 + </thead>
750 + <tbody>
751 + <?php if ($prompts) : ?>
752 + <?php foreach ($prompts as $prompt) : ?>
753 + <tr id="prompt-<?php echo esc_attr($prompt->id); ?>">
754 + <td><?php echo esc_html($prompt->id); ?></td>
755 + <td class="mxchat_article_content_dashboard">
756 + <span class="content-view"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></span>
757 + <textarea class="content-edit" style="display:none;"><?php echo esc_textarea($prompt->article_content); ?></textarea>
758 + </td>
759 + <td class="mxchat_article_url_dashboard">
760 + <span class="url-view">
761 + <?php if (!empty($prompt->source_url)) : ?>
762 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
763 + <?php else : ?>
764 + N/A
765 + <?php endif; ?>
766 + </span>
767 + <input type="url" class="url-edit" value="<?php echo esc_attr($prompt->source_url); ?>" style="display:none;" />
768 + </td>
769 + <td>
770 + <button class="button edit-button" data-id="<?php echo esc_attr($prompt->id); ?>">Edit</button>
771 + <button class="button save-button" data-id="<?php echo esc_attr($prompt->id); ?>" style="display:none;">Save</button>
772 + <a href="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_prompt&id=' . esc_attr($prompt->id) . '&_wpnonce=' . wp_create_nonce('mxchat_delete_prompt_nonce'))); ?>" class="button delete-button">Delete</a>
773 + </td>
774 + </tr>
775 + <?php endforeach; ?>
776 + <?php else : ?>
777 + <tr>
778 + <td colspan="4"><?php esc_html_e('No prompts found.', 'mxchat'); ?></td>
779 + </tr>
780 + <?php endif; ?>
781 + </tbody>
782 + </table>
783 + </div>
784 + <?php
785 +}
2077 786
2078 - $transcripts_sql = $wpdb->prepare(
2079 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
2080 - array_merge($where_params, [$per_page, $offset])
2081 - );
2082 - $transcript_rows = $wpdb->get_results($transcripts_sql);
2083 787
2084 - // Count of unique transcript-based leads under the same filters.
2085 - $count_sql = $wpdb->prepare(
2086 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
2087 - $where_params
2088 - );
2089 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
2090 -
2091 - // Hydrate each row: name, latest_session_id, top page.
2092 - $leads = [];
2093 - foreach ($transcript_rows as $row) {
2094 - $detail = $has_page_url_column
2095 - ? $wpdb->get_row($wpdb->prepare(
2096 - "SELECT session_id, user_name, originating_page_url, originating_page_title
2097 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2098 - $row->user_email
2099 - ))
2100 - : $wpdb->get_row($wpdb->prepare(
2101 - "SELECT session_id, user_name FROM {$table}
2102 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2103 - $row->user_email
2104 - ));
2105 -
2106 - $leads[] = [
2107 - 'email' => $row->user_email,
2108 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2109 - 'conversation_count' => (int) $row->conversation_count,
2110 - 'last_seen' => $row->last_seen,
2111 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
2112 - 'first_seen' => $row->first_seen,
2113 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
2114 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2115 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
2116 - 'is_orphan' => false,
2117 - 'status' => 'active',
2118 - ];
788 +// Delete All Prompts
789 +public function mxchat_handle_delete_all_prompts() {
790 + // Verify nonce
791 + if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
792 + wp_die(__('Nonce verification failed.', 'mxchat'));
2119 793 }
2120 794
2121 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
2122 - // status filter below. Deduplication priority when the same email appears in multiple
2123 - // sources: transcripts > chat_deleted > orphan.
2124 - $transcripts_emails_seen = array_flip(array_map(
2125 - function ($r) { return strtolower($r['email']); },
2126 - $leads
2127 - ));
2128 -
2129 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
2130 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
2131 - $chat_deleted_leads_all = [];
2132 - if ($status === 'all' || $status === 'chat_deleted') {
2133 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
2134 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
2135 - $chat_deleted_leads_all = array_values(array_filter(
2136 - $chat_deleted_leads_all,
2137 - function ($row) use ($transcripts_emails_seen) {
2138 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2139 - }
2140 - ));
2141 - foreach ($chat_deleted_leads_all as $row) {
2142 - $transcripts_emails_seen[strtolower($row['email'])] = true;
2143 - }
2144 - }
2145 -
2146 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
2147 - // when a date filter is active.
2148 - $orphan_leads_all = [];
2149 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
2150 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
2151 - $orphan_leads_all = array_values(array_filter(
2152 - $orphan_leads_all,
2153 - function ($row) use ($transcripts_emails_seen) {
2154 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
2155 - }
2156 - ));
2157 - }
2158 -
2159 - // Apply status filter to the transcripts-derived list.
2160 - if ($status === 'orphan' || $status === 'chat_deleted') {
2161 - $leads = [];
2162 - $transcripts_lead_count = 0;
2163 - }
2164 -
2165 - // Stitch the current page from the three buckets in priority order.
2166 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
2167 - $remaining_slots = $per_page - count($leads);
2168 -
2169 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
2170 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
2171 - if ($start < count($chat_deleted_leads_all)) {
2172 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
2173 - $remaining_slots = $per_page - count($leads);
2174 - }
2175 - }
2176 -
2177 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
2178 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
2179 - $start = max(0, ($page - 1) * $per_page - $before);
2180 - if ($start < count($orphan_leads_all)) {
2181 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
2182 - }
2183 - }
2184 -
2185 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
2186 -
2187 - // Stats strip: always computed over full dataset, unaffected by filters.
2188 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
2189 -
2190 - // Top pages: top 5 by distinct emails captured.
2191 - $top_pages = [];
2192 - if ($has_page_url_column) {
2193 - $top_pages_rows = $wpdb->get_results(
2194 - "SELECT originating_page_url AS url,
2195 - MAX(originating_page_title) AS title,
2196 - COUNT(DISTINCT user_email) AS lead_count
2197 - FROM {$table}
2198 - WHERE user_email IS NOT NULL AND user_email != ''
2199 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
2200 - GROUP BY originating_page_url
2201 - ORDER BY lead_count DESC, url ASC
2202 - LIMIT 5"
2203 - );
2204 - foreach ($top_pages_rows as $p) {
2205 - $top_pages[] = [
2206 - 'url' => $p->url,
2207 - 'title' => $p->title ?: $p->url,
2208 - 'lead_count' => (int) $p->lead_count,
2209 - ];
2210 - }
2211 - }
2212 -
2213 - wp_send_json([
2214 - 'success' => true,
2215 - 'leads' => $leads,
2216 - 'page' => $page,
2217 - 'per_page' => $per_page,
2218 - 'total_count' => $total_count,
2219 - 'total_pages' => $total_pages,
2220 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
2221 - 'showing_end' => min($offset + $per_page, $total_count),
2222 - 'stats' => $stats,
2223 - 'top_pages' => $top_pages,
2224 - ]);
2225 - wp_die();
2226 -}
2227 -
2228 -/**
2229 - * Delete one or more leads by email. Removes every transcripts row for that
2230 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2231 - * mxchat_history_{sid}) and any orphan option entries matching the email.
2232 - */
2233 -public function mxchat_delete_leads() {
795 + // Check permissions
2234 796 if (!current_user_can('manage_options')) {
2235 - wp_send_json_error(['message' => 'Insufficient permissions']);
2236 - wp_die();
797 + wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
2237 798 }
2238 - check_ajax_referer('mxchat_delete_leads', 'security');
2239 799
2240 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2241 - $emails = [];
2242 - foreach ($emails_raw as $e) {
2243 - $clean = sanitize_email((string) $e);
2244 - if ($clean) {
2245 - $emails[] = $clean;
2246 - }
2247 - }
2248 - if (empty($emails)) {
2249 - wp_send_json_error(['message' => 'No emails provided']);
2250 - wp_die();
2251 - }
2252 -
2253 - $summary = self::mxchat_wipe_leads_by_email($emails);
2254 -
2255 - wp_send_json([
2256 - 'success' => true,
2257 - 'deleted_leads' => count($emails),
2258 - 'deleted_sessions' => $summary['deleted_sessions'],
2259 - 'deleted_rows' => $summary['deleted_rows'],
2260 - ]);
2261 - wp_die();
2262 -}
2263 -
2264 -/**
2265 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2266 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2267 - *
2268 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2269 - * Input emails must already be sanitized with sanitize_email().
2270 - */
2271 -private static function mxchat_wipe_leads_by_email(array $emails) {
2272 800 global $wpdb;
2273 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2274 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2275 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
801 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2276 802
2277 - $deleted_sessions = 0;
2278 - $deleted_rows = 0;
2279 - $emails_lc = array_map('strtolower', $emails);
803 + // Delete all prompts from the table
804 + $wpdb->query("DELETE FROM {$table_name}");
2280 805
2281 - foreach ($emails as $email) {
2282 - $session_ids = $wpdb->get_col($wpdb->prepare(
2283 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2284 - $email
2285 - ));
806 + // Clear relevant cache
807 + wp_cache_delete('all_prompts', 'mxchat_prompts');
2286 808
2287 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2288 - if ($rows_removed !== false) {
2289 - $deleted_rows += (int) $rows_removed;
2290 - }
809 + // Redirect back with a success message
810 + $redirect_url = add_query_arg(array(
811 + 'page' => 'mxchat-prompts',
812 + 'all_deleted' => 'true'
813 + ), admin_url('admin.php'));
2291 814
2292 - foreach ($session_ids as $sid) {
2293 - $deleted_sessions++;
2294 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2295 - delete_option('mxchat_history_' . $sid);
2296 - delete_option('mxchat_email_' . $sid);
2297 - delete_option('mxchat_name_' . $sid);
2298 - delete_option('mxchat_agent_name_' . $sid);
2299 - delete_option('mxchat_lead_del_email_' . $sid);
2300 - delete_option('mxchat_lead_del_name_' . $sid);
2301 - delete_option('mxchat_lead_del_ts_' . $sid);
2302 - if (class_exists('MxChat_Session_Store')) {
2303 - MxChat_Session_Store::delete_session($sid); // b64b77
2304 - }
2305 - if ($has_translations) {
2306 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2307 - }
2308 - }
2309 - }
815 + wp_safe_redirect($redirect_url);
816 + exit;
817 +}
2310 818
2311 - // Table-side twin of the option sweep below (5658f2): orphan pre-chat
2312 - // captures now live in the sessions table's identity columns.
2313 - if (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'find_by_email')) {
2314 - foreach ($emails as $email) {
2315 - foreach (MxChat_Session_Store::find_by_email($email) as $sid) {
2316 - MxChat_Session_Store::delete_session($sid);
2317 - }
2318 - }
819 +// Single Prompt Deletion
820 +public function mxchat_handle_delete_prompt() {
821 + // Sanitize and validate nonce
822 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
823 + if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
824 + wp_die('Nonce verification failed.');
2319 825 }
2320 826
2321 - // Clean up any lingering option entries (unmigrated orphan pre-chat captures +
2322 - // chat_deleted preservations) whose stored value matches one of the emails being wiped.
2323 - $lingering = $wpdb->get_results(
2324 - "SELECT option_name, option_value FROM {$wpdb->options}
2325 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2326 - );
2327 - foreach ($lingering as $opt) {
2328 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2329 - continue;
2330 - }
2331 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2332 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2333 - delete_option('mxchat_lead_del_email_' . $sid);
2334 - delete_option('mxchat_lead_del_name_' . $sid);
2335 - delete_option('mxchat_lead_del_ts_' . $sid);
2336 - } else {
2337 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2338 - delete_option('mxchat_email_' . $sid);
2339 - delete_option('mxchat_name_' . $sid);
2340 - }
2341 - }
2342 -
2343 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2344 -
2345 - return [
2346 - 'deleted_sessions' => $deleted_sessions,
2347 - 'deleted_rows' => $deleted_rows,
2348 - ];
2349 -}
2350 -
2351 -/**
2352 - * Stream a leads CSV. scope=all exports every lead under current filters is not
2353 - * supported to keep semantics simple; caller either exports all leads or a
2354 - * specific set of selected emails.
2355 - */
2356 -public function mxchat_export_leads() {
827 + // Check permissions
2357 828 if (!current_user_can('manage_options')) {
2358 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
829 + wp_die('You do not have sufficient permissions to delete prompts.');
2359 830 }
2360 - check_ajax_referer('mxchat_export_leads', 'security');
2361 831
2362 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2363 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2364 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2365 -
2366 - $emails_in_clean = [];
2367 - foreach ($emails_in as $e) {
2368 - $clean = sanitize_email((string) $e);
2369 - if ($clean) {
2370 - $emails_in_clean[] = $clean;
2371 - }
832 + // Validate and sanitize ID parameter
833 + $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
834 + if ($id <= 0) {
835 + wp_die('Invalid prompt ID.');
2372 836 }
2373 837
2374 838 global $wpdb;
2375 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2376 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
839 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2377 840
2378 - // Collect leads from transcripts.
2379 - $transcripts_sql = "SELECT user_email AS email,
2380 - MAX(timestamp) AS last_seen,
2381 - COUNT(DISTINCT session_id) AS conversation_count
2382 - FROM {$table}
2383 - WHERE user_email IS NOT NULL AND user_email != ''";
2384 - $params = [];
2385 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2386 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2387 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2388 - $params = $emails_in_clean;
2389 - }
2390 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
841 + // Clear cache and delete prompt
842 + wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
843 + $wpdb->delete($table_name, array('id' => $id), array('%d'));
2391 844
2392 - $rows = !empty($params)
2393 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2394 - : $wpdb->get_results($transcripts_sql);
2395 -
2396 - // Hydrate each row with name + top page.
2397 - $export_rows = [];
2398 - foreach ($rows as $row) {
2399 - $detail = $has_page_url_column
2400 - ? $wpdb->get_row($wpdb->prepare(
2401 - "SELECT user_name, originating_page_url FROM {$table}
2402 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2403 - $row->email
2404 - ))
2405 - : $wpdb->get_row($wpdb->prepare(
2406 - "SELECT user_name FROM {$table}
2407 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2408 - $row->email
2409 - ));
2410 - $export_rows[] = [
2411 - 'email' => $row->email,
2412 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2413 - 'conversation_count' => (int) $row->conversation_count,
2414 - 'last_seen' => $row->last_seen,
2415 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2416 - ];
2417 - }
2418 -
2419 - // Include orphan + chat_deleted leads when exporting all.
2420 - if ($scope === 'all') {
2421 - $transcripts_emails_lc = array_flip(array_map(
2422 - function ($r) { return strtolower($r['email']); },
2423 - $export_rows
2424 - ));
2425 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2426 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2427 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2428 - $export_rows[] = [
2429 - 'email' => $cd['email'],
2430 - 'name' => $cd['name'],
2431 - 'conversation_count' => 0,
2432 - 'last_seen' => $cd['last_seen'],
2433 - 'top_page_url' => '',
2434 - ];
2435 - }
2436 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2437 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2438 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2439 - $export_rows[] = [
2440 - 'email' => $orphan['email'],
2441 - 'name' => $orphan['name'],
2442 - 'conversation_count' => 0,
2443 - 'last_seen' => '',
2444 - 'top_page_url' => '',
2445 - ];
2446 - }
2447 - }
2448 -
2449 - if (empty($export_rows)) {
2450 - wp_send_json_error(['message' => 'No leads to export.']);
2451 - wp_die();
2452 - }
2453 -
2454 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2455 - header('Content-Type: text/csv');
2456 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2457 - header('Pragma: no-cache');
2458 - header('Expires: 0');
2459 -
2460 - $output = fopen('php://output', 'w');
2461 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2462 -
2463 - if ($fields_mode === 'email_only') {
2464 - fputcsv($output, ['Email']);
2465 - foreach ($export_rows as $r) {
2466 - fputcsv($output, [$r['email']]);
2467 - }
2468 - } else {
2469 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page']);
2470 - foreach ($export_rows as $r) {
2471 - fputcsv($output, [
2472 - $r['email'],
2473 - $r['name'],
2474 - $r['conversation_count'],
2475 - $r['last_seen'],
2476 - $r['top_page_url'],
2477 - ]);
2478 - }
2479 - }
2480 -
2481 - fclose($output);
2482 - wp_die();
845 + wp_safe_redirect(add_query_arg(array('page' => 'mxchat-prompts', 'deleted' => 'true'), admin_url('admin.php')));
846 + exit;
2483 847 }
2484 848
2485 -/**
2486 - * Stats strip payload (independent of filters).
2487 - */
2488 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2489 - global $wpdb;
2490 849
2491 - $total_transcripts_emails = (int) $wpdb->get_var(
2492 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2493 - WHERE user_email IS NOT NULL AND user_email != ''"
2494 - );
2495 850
2496 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2497 - "SELECT COUNT(*) FROM (
2498 - SELECT user_email FROM {$table}
2499 - WHERE user_email IS NOT NULL AND user_email != ''
2500 - GROUP BY user_email
2501 - HAVING MIN(timestamp) >= %s
2502 - ) AS new_leads",
2503 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2504 - ));
2505 851
2506 - $total_convos = (int) $wpdb->get_var(
2507 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2508 - WHERE user_email IS NOT NULL AND user_email != ''"
2509 - );
852 + public function mxchat_generate_embedding($text) {
853 + $options = get_option('mxchat_options');
854 + $api_key = $options['api_key'] ?? 'default_api_key';
2510 855
2511 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2512 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
856 + $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
857 + 'body' => wp_json_encode(array(
858 + 'model' => 'text-embedding-ada-002',
859 + 'input' => $text
860 + )),
861 + 'headers' => array(
862 + 'Authorization' => 'Bearer ' . $api_key,
863 + 'Content-Type' => 'application/json'
864 + ),
865 + ));
2513 866
2514 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2515 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2516 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2517 -
2518 - $avg = $total_transcripts_emails > 0
2519 - ? round($total_convos / $total_transcripts_emails, 1)
2520 - : 0;
2521 -
2522 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2523 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2524 - // inflate this number.
2525 - $orphan_pct = $total_leads > 0
2526 - ? (int) round(($orphan_count / $total_leads) * 100)
2527 - : 0;
2528 -
2529 - return [
2530 - 'total_leads' => $total_leads,
2531 - 'new_this_week' => $new_this_week,
2532 - 'avg_convos' => $avg,
2533 - 'orphan_pct' => $orphan_pct,
2534 - 'orphan_count' => $orphan_count,
2535 - 'chat_deleted_count' => $chat_deleted_count,
2536 - ];
2537 -}
2538 -
2539 -/**
2540 - * Collect leads who had a conversation that an admin later deleted (preserved via
2541 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2542 - * original last-seen timestamp so they still sort and filter sensibly.
2543 - *
2544 - * @param string $search Optional email/name substring filter.
2545 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2546 - * @return array
2547 - */
2548 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2549 - global $wpdb;
2550 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2551 -
2552 - $rows = $wpdb->get_results(
2553 - "SELECT option_name, option_value FROM {$wpdb->options}
2554 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2555 - );
2556 - if (empty($rows)) {
2557 - return [];
2558 - }
2559 -
2560 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2561 - // they've come back and chatted, so they're active leads again.
2562 - $emails_in_transcripts = array_map(
2563 - 'strtolower',
2564 - (array) $wpdb->get_col(
2565 - "SELECT DISTINCT user_email FROM {$table}
2566 - WHERE user_email IS NOT NULL AND user_email != ''"
2567 - )
2568 - );
2569 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2570 -
2571 - $needle = strtolower(trim((string) $search));
2572 - $by_email = [];
2573 -
2574 - foreach ($rows as $opt) {
2575 - $email = sanitize_email(trim((string) $opt->option_value));
2576 - if (!$email) {
2577 - continue;
867 + if (is_wp_error($response)) {
868 + return null;
2578 869 }
2579 - if (isset($emails_in_transcripts[strtolower($email)])) {
2580 - continue;
2581 - }
2582 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2583 - if (!$sid) {
2584 - continue;
2585 - }
2586 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2587 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2588 870
2589 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2590 - continue;
2591 - }
2592 - if ($needle !== '') {
2593 - $hay = strtolower($email . ' ' . $name);
2594 - if (strpos($hay, $needle) === false) {
2595 - continue;
2596 - }
2597 - }
2598 -
2599 - $key = strtolower($email);
2600 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2601 - $by_email[$key] = [
2602 - 'email' => $email,
2603 - 'name' => $name,
2604 - 'conversation_count' => 0,
2605 - 'last_seen' => $ts,
2606 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2607 - 'first_seen' => $ts,
2608 - 'latest_session_id' => '',
2609 - 'top_page_url' => '',
2610 - 'top_page_title' => '',
2611 - 'is_orphan' => false,
2612 - 'status' => 'chat_deleted',
2613 - ];
2614 - }
871 + $response_data = json_decode(wp_remote_retrieve_body($response), true);
872 + return $response_data['data'][0]['embedding'] ?? null;
2615 873 }
2616 874
2617 - // Newest chat_deleted first.
2618 - usort($by_email, function ($a, $b) {
2619 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2620 - });
2621 - return array_values($by_email);
2622 -}
2623 -
2624 -/**
2625 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2626 - */
2627 -private static function mxchat_count_chat_deleted_leads() {
2628 - global $wpdb;
2629 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2630 -
2631 - $emails = $wpdb->get_col(
2632 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2633 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2634 - );
2635 - if (empty($emails)) {
2636 - return 0;
2637 - }
2638 -
2639 - $transcripts_emails = array_map(
2640 - 'strtolower',
2641 - (array) $wpdb->get_col(
2642 - "SELECT DISTINCT user_email FROM {$table}
2643 - WHERE user_email IS NOT NULL AND user_email != ''"
2644 - )
2645 - );
2646 - $transcripts_emails = array_flip($transcripts_emails);
2647 -
2648 - $count = 0;
2649 - $seen = [];
2650 - foreach ($emails as $raw) {
2651 - $email = strtolower(trim((string) $raw));
2652 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2653 - continue;
875 + public function mxchat_delete_chat_history() {
876 + if (!current_user_can('manage_options')) {
877 + echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
878 + wp_die();
2654 879 }
2655 - $seen[$email] = true;
2656 - $count++;
2657 - }
2658 - return $count;
2659 -}
2660 880
2661 -/**
2662 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2663 - * Returned rows have no conversation_count, no timestamp.
2664 - *
2665 - * @param string $search Optional email/name substring filter.
2666 - * @return array
2667 - */
2668 -private static function mxchat_collect_orphan_leads($search = '') {
2669 - global $wpdb;
2670 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
881 + check_ajax_referer('mxchat_delete_chat_history', 'security');
2671 882
2672 - // Primary source since 5658f2: the sessions table's identity columns.
2673 - // The legacy option scan stays for installs still mid-migration.
2674 - $store_rows = (class_exists('MxChat_Session_Store') && method_exists('MxChat_Session_Store', 'identity_rows'))
2675 - ? MxChat_Session_Store::identity_rows()
2676 - : [];
883 + global $wpdb;
884 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2677 885
2678 - $option_rows = $wpdb->get_results(
2679 - "SELECT option_name, option_value FROM {$wpdb->options}
2680 - WHERE option_name LIKE 'mxchat_email_%'"
2681 - );
2682 - if (empty($option_rows) && empty($store_rows)) {
2683 - return [];
2684 - }
886 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
887 + foreach ($_POST['delete_session_ids'] as $session_id) {
888 + $session_id_sanitized = sanitize_text_field($session_id);
2685 889
2686 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2687 - $session_ids_with_rows = $wpdb->get_col(
2688 - "SELECT DISTINCT session_id FROM {$table}
2689 - WHERE user_email IS NOT NULL AND user_email != ''"
2690 - );
2691 - $session_ids_with_rows = array_flip($session_ids_with_rows);
890 + // Clear relevant cache before deletion
891 + $cache_key = 'chat_session_' . $session_id_sanitized;
892 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
2692 893
2693 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2694 - $emails_in_transcripts = array_map(
2695 - 'strtolower',
2696 - (array) $wpdb->get_col(
2697 - "SELECT DISTINCT user_email FROM {$table}
2698 - WHERE user_email IS NOT NULL AND user_email != ''"
2699 - )
2700 - );
2701 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2702 -
2703 - $orphans_by_email = [];
2704 - $needle = strtolower(trim((string) $search));
2705 -
2706 - // Normalize both sources into [sid, email, name] candidates. Table rows
2707 - // first — a session can only live in one home, and dedup-by-email below
2708 - // handles any overlap either way.
2709 - $candidates = [];
2710 - foreach ($store_rows as $row) {
2711 - $candidates[] = [
2712 - 'sid' => (string) $row['session_id'],
2713 - 'email' => (string) $row['visitor_email'],
2714 - 'name' => is_string($row['visitor_name'] ?? null) ? $row['visitor_name'] : '',
2715 - ];
2716 - }
2717 - foreach ($option_rows as $opt) {
2718 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2719 - $name_option = $sid ? get_option('mxchat_name_' . $sid, '') : '';
2720 - $candidates[] = [
2721 - 'sid' => (string) $sid,
2722 - 'email' => (string) $opt->option_value,
2723 - 'name' => is_string($name_option) ? $name_option : '',
2724 - ];
2725 - }
2726 -
2727 - foreach ($candidates as $cand) {
2728 - $email = sanitize_email(trim($cand['email']));
2729 - if (!$email) {
2730 - continue;
2731 - }
2732 - $sid = $cand['sid'];
2733 - if (!$sid) {
2734 - continue;
2735 - }
2736 - // Exclude leads who have any transcripts rows (they appear in the main list).
2737 - if (isset($emails_in_transcripts[strtolower($email)])) {
2738 - continue;
2739 - }
2740 - if (isset($session_ids_with_rows[$sid])) {
2741 - continue;
2742 - }
2743 -
2744 - $name = trim($cand['name']);
2745 -
2746 - if ($needle !== '') {
2747 - $hay = strtolower($email . ' ' . $name);
2748 - if (strpos($hay, $needle) === false) {
2749 - continue;
894 + // Perform the deletion
895 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
2750 896 }
2751 - }
2752 897
2753 - $key = strtolower($email);
2754 - if (!isset($orphans_by_email[$key])) {
2755 - $orphans_by_email[$key] = [
2756 - 'email' => $email,
2757 - 'name' => $name,
2758 - 'conversation_count' => 0,
2759 - 'last_seen' => '',
2760 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2761 - 'first_seen' => '',
2762 - 'latest_session_id' => '',
2763 - 'top_page_url' => '',
2764 - 'top_page_title' => '',
2765 - 'is_orphan' => true,
2766 - 'status' => 'orphan',
2767 - ];
2768 - }
2769 - }
898 + // Optionally, clear a general cache if you have one
899 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2770 900
2771 - return array_values($orphans_by_email);
2772 -}
2773 -
2774 -/**
2775 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2776 - */
2777 -private static function mxchat_leads_date_cutoff($date_range) {
2778 - switch ($date_range) {
2779 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2780 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2781 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2782 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2783 - case 'all':
2784 - default: return '';
2785 - }
2786 -}
2787 -
2788 -/**
2789 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2790 - */
2791 -private static function mxchat_leads_format_relative($timestamp) {
2792 - if (!$timestamp) {
2793 - return '';
2794 - }
2795 - $ts = strtotime($timestamp . ' UTC');
2796 - if (!$ts) {
2797 - return '';
2798 - }
2799 - $diff = time() - $ts;
2800 - if ($diff < 60) return __('just now', 'mxchat');
2801 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2802 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2803 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2804 - return wp_date('M j', $ts);
2805 -}
2806 -
2807 -/**
2808 - * Handle translation of chat messages via AJAX
2809 - */
2810 -public function mxchat_translate_messages() {
2811 - if (!current_user_can('manage_options')) {
2812 - wp_send_json_error(['error' => 'Insufficient permissions']);
2813 - wp_die();
2814 - }
2815 -
2816 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2817 - $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
2818 - $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
2819 - $messages = json_decode($messages_json, true);
2820 -
2821 - if (empty($session_id)) {
2822 - wp_send_json_error(['error' => 'No session ID provided']);
2823 - wp_die();
2824 - }
2825 -
2826 - if (empty($messages) || !is_array($messages)) {
2827 - wp_send_json_error(['error' => 'No messages to translate']);
2828 - wp_die();
2829 - }
2830 -
2831 - // Language names for prompting
2832 - $languages = [
2833 - 'en' => 'English',
2834 - 'es' => 'Spanish',
2835 - 'fr' => 'French',
2836 - 'de' => 'German',
2837 - 'it' => 'Italian',
2838 - 'pt' => 'Portuguese',
2839 - 'nl' => 'Dutch',
2840 - 'ru' => 'Russian',
2841 - 'zh' => 'Chinese',
2842 - 'ja' => 'Japanese',
2843 - 'ko' => 'Korean',
2844 - 'ar' => 'Arabic',
2845 - 'hi' => 'Hindi',
2846 - 'tr' => 'Turkish',
2847 - 'pl' => 'Polish',
2848 - 'vi' => 'Vietnamese',
2849 - 'th' => 'Thai',
2850 - 'id' => 'Indonesian',
2851 - 'sv' => 'Swedish',
2852 - 'da' => 'Danish'
2853 - ];
2854 -
2855 - $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
2856 -
2857 - // Build combined text for translation (numbered for parsing)
2858 - $numbered_messages = [];
2859 - foreach ($messages as $i => $msg) {
2860 - $content = isset($msg['content']) ? trim($msg['content']) : '';
2861 - if (!empty($content)) {
2862 - $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
901 + echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
902 + } else {
903 + echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
2863 904 }
2864 - }
2865 905
2866 - if (empty($numbered_messages)) {
2867 - wp_send_json_error(['error' => 'No valid messages to translate']);
2868 906 wp_die();
2869 907 }
2870 908
2871 - $combined_text = implode("\n\n", $numbered_messages);
2872 909
2873 - // Prepare the translation prompt
2874 - $system_prompt = "You are a translator. Translate the following messages to {$target_lang_name}. Keep the [MSG#] and [/MSG#] tags exactly as they are - only translate the content between them. Maintain the original formatting, line breaks, and any HTML tags. Return ONLY the translated messages with the tags, no explanations.";
910 +public function mxchat_save_inline_prompt() {
911 + // Check for nonce security
912 + check_ajax_referer('mxchat_save_inline_nonce');
2875 913
2876 - // Get user's selected model and determine provider
2877 - $options = get_option('mxchat_options', []);
2878 - $selected_model = $options['model'] ?? 'gpt-5.6-sol';
2879 -
2880 - // Check if using OpenRouter
2881 - if ($selected_model === 'openrouter') {
2882 - $provider = 'openrouter';
2883 - $selected_model = $options['openrouter_selected_model'] ?? '';
2884 - $api_key = $options['openrouter_api_key'] ?? '';
2885 -
2886 - if (empty($selected_model)) {
2887 - wp_send_json_error(['error' => 'No OpenRouter model selected']);
2888 - wp_die();
2889 - }
2890 - } else {
2891 - // Determine provider from model name
2892 - $model_parts = explode('-', $selected_model);
2893 - $provider = strtolower($model_parts[0]);
2894 -
2895 - // Get the appropriate API key based on provider
2896 - $api_key = '';
2897 - switch ($provider) {
2898 - case 'gpt':
2899 - case 'o1':
2900 - $api_key = $options['api_key'] ?? '';
2901 - break;
2902 - case 'claude':
2903 - $api_key = $options['claude_api_key'] ?? '';
2904 - break;
2905 - case 'grok':
2906 - $api_key = $options['xai_api_key'] ?? '';
2907 - break;
2908 - case 'deepseek':
2909 - $api_key = $options['deepseek_api_key'] ?? '';
2910 - break;
2911 - case 'gemini':
2912 - $api_key = $options['gemini_api_key'] ?? '';
2913 - break;
2914 - default:
2915 - // Default to OpenAI
2916 - $api_key = $options['api_key'] ?? '';
2917 - $provider = 'gpt';
2918 - break;
2919 - }
2920 - }
2921 -
2922 - if (empty($api_key)) {
2923 - wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
2924 - wp_die();
2925 - }
2926 -
2927 - // Make API request based on provider
2928 - $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
2929 -
2930 - if (is_wp_error($response)) {
2931 - wp_send_json_error(['error' => $response->get_error_message()]);
2932 - wp_die();
2933 - }
2934 -
2935 - // Parse the response to extract translated messages
2936 - $translations = [];
2937 - foreach ($messages as $msg) {
2938 - $index = $msg['index'];
2939 - $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
2940 - if (preg_match($pattern, $response, $matches)) {
2941 - $translations[] = [
2942 - 'index' => $index,
2943 - 'translated' => trim($matches[1])
2944 - ];
2945 - }
2946 - }
2947 -
2948 - // Save translations to database
2949 - if (!empty($translations)) {
2950 - $this->save_transcript_translation($session_id, $target_lang, $translations);
2951 - }
2952 -
2953 - wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
2954 - wp_die();
2955 -}
2956 -
2957 -/**
2958 - * Save transcript translation to database
2959 - */
2960 -private function save_transcript_translation($session_id, $language_code, $translations) {
2961 - global $wpdb;
2962 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
2963 -
2964 - // Check if table exists, create if not
2965 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
2966 - mxchat_create_translations_table();
2967 - }
2968 -
2969 - $now = current_time('mysql');
2970 - $translations_json = wp_json_encode($translations);
2971 -
2972 - // Use REPLACE to insert or update
2973 - $wpdb->query($wpdb->prepare(
2974 - "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
2975 - VALUES (%s, %s, %s, %s, %s)",
2976 - $session_id,
2977 - $language_code,
2978 - $translations_json,
2979 - $now,
2980 - $now
2981 - ));
2982 -}
2983 -
2984 -/**
2985 - * Get saved translation for a session
2986 - */
2987 -public function mxchat_get_transcript_translation() {
914 + // Verify permissions
2988 915 if (!current_user_can('manage_options')) {
2989 - wp_send_json_error(['error' => 'Insufficient permissions']);
2990 - wp_die();
916 + wp_send_json_error('Permission denied.');
917 + return;
2991 918 }
2992 919
2993 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2994 -
2995 - if (empty($session_id)) {
2996 - wp_send_json_error(['error' => 'No session ID provided']);
2997 - wp_die();
2998 - }
2999 -
3000 920 global $wpdb;
3001 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
921 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3002 922
3003 - // Check if table exists
3004 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
3005 - wp_send_json(['success' => true, 'has_translation' => false]);
3006 - wp_die();
3007 - }
923 + // Validate and sanitize input data
924 + $prompt_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
925 + $article_content = isset($_POST['article_content']) ? sanitize_textarea_field($_POST['article_content']) : '';
926 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : '';
3008 927
3009 - // Get the most recent translation for this session
3010 - $result = $wpdb->get_row($wpdb->prepare(
3011 - "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
3012 - $session_id
3013 - ));
928 + if ($prompt_id > 0 && !empty($article_content)) {
929 + // Re-generate the embedding vector for the updated content
930 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
3014 931
3015 - if ($result) {
3016 - $translations = json_decode($result->translations, true);
3017 - wp_send_json([
3018 - 'success' => true,
3019 - 'has_translation' => true,
3020 - 'language' => $result->language_code,
3021 - 'translations' => $translations
3022 - ]);
3023 - } else {
3024 - wp_send_json(['success' => true, 'has_translation' => false]);
3025 - }
3026 - wp_die();
3027 -}
932 + if (is_array($embedding_vector)) {
933 + // Serialize the embedding vector before storing it
934 + $embedding_vector_serialized = serialize($embedding_vector);
3028 935
3029 -/**
3030 - * Translate text using the user's selected provider and model
3031 - */
3032 -private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
3033 - switch ($provider) {
3034 - case 'claude':
3035 - return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
3036 - case 'grok':
3037 - return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
3038 - case 'deepseek':
3039 - return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
3040 - case 'gemini':
3041 - return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
3042 - case 'openrouter':
3043 - return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
3044 - case 'gpt':
3045 - case 'o1':
3046 - default:
3047 - return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
3048 - }
3049 -}
3050 -
3051 -/**
3052 - * Translate text using OpenAI API
3053 - */
3054 -private function translate_with_openai($api_key, $model, $system_prompt, $text) {
3055 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
3056 - 'timeout' => 60,
3057 - 'headers' => [
3058 - 'Authorization' => 'Bearer ' . $api_key,
3059 - 'Content-Type' => 'application/json'
3060 - ],
3061 - 'body' => wp_json_encode([
3062 - 'model' => $model,
3063 - 'messages' => [
3064 - ['role' => 'system', 'content' => $system_prompt],
3065 - ['role' => 'user', 'content' => $text]
3066 - ],
3067 - 'temperature' => 0.3
3068 - ])
3069 - ]);
3070 -
3071 - if (is_wp_error($response)) {
3072 - return $response;
3073 - }
3074 -
3075 - $body = json_decode(wp_remote_retrieve_body($response), true);
3076 -
3077 - if (isset($body['error'])) {
3078 - return new WP_Error('api_error', $body['error']['message']);
3079 - }
3080 -
3081 - if (isset($body['choices'][0]['message']['content'])) {
3082 - return $body['choices'][0]['message']['content'];
3083 - }
3084 -
3085 - return new WP_Error('api_error', 'Invalid API response');
3086 -}
3087 -
3088 -/**
3089 - * Translate text using Claude API
3090 - */
3091 -private function translate_with_claude($api_key, $model, $system_prompt, $text) {
3092 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3093 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3094 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3095 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3096 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
3097 - 'timeout' => 60,
3098 - 'headers' => [
3099 - 'x-api-key' => $api_key,
3100 - 'anthropic-version' => '2023-06-01',
3101 - 'Content-Type' => 'application/json'
3102 - ],
3103 - 'body' => wp_json_encode([
3104 - 'model' => $model,
3105 - 'max_tokens' => 4096,
3106 - // Prompt-cache breakpoint (plan 1ff43b): the translate instruction
3107 - // repeats across every message in a batch, so cache reads bill at
3108 - // 0.1x. Below the model's minimum prefix it silently no-ops.
3109 - 'system' => trim((string) $system_prompt) === '' ? $system_prompt : [
3110 - ['type' => 'text', 'text' => $system_prompt, 'cache_control' => ['type' => 'ephemeral']]
3111 - ],
3112 - 'messages' => [
3113 - ['role' => 'user', 'content' => $text]
3114 - ]
3115 - ])
3116 - ]);
3117 -
3118 - if (is_wp_error($response)) {
3119 - return $response;
3120 - }
3121 -
3122 - $body = json_decode(wp_remote_retrieve_body($response), true);
3123 -
3124 - if (isset($body['error'])) {
3125 - return new WP_Error('api_error', $body['error']['message']);
3126 - }
3127 -
3128 - if (isset($body['content'][0]['text'])) {
3129 - return $body['content'][0]['text'];
3130 - }
3131 -
3132 - return new WP_Error('api_error', 'Invalid API response');
3133 -}
3134 -
3135 -/**
3136 - * Translate text using xAI (Grok) API
3137 - */
3138 -private function translate_with_xai($api_key, $model, $system_prompt, $text) {
3139 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
3140 - 'timeout' => 60,
3141 - 'headers' => [
3142 - 'Authorization' => 'Bearer ' . $api_key,
3143 - 'Content-Type' => 'application/json'
3144 - ],
3145 - 'body' => wp_json_encode([
3146 - 'model' => $model,
3147 - 'messages' => [
3148 - ['role' => 'system', 'content' => $system_prompt],
3149 - ['role' => 'user', 'content' => $text]
3150 - ],
3151 - 'temperature' => 0.3
3152 - ])
3153 - ]);
3154 -
3155 - if (is_wp_error($response)) {
3156 - return $response;
3157 - }
3158 -
3159 - $body = json_decode(wp_remote_retrieve_body($response), true);
3160 -
3161 - if (isset($body['error'])) {
3162 - return new WP_Error('api_error', $body['error']['message']);
3163 - }
3164 -
3165 - if (isset($body['choices'][0]['message']['content'])) {
3166 - return $body['choices'][0]['message']['content'];
3167 - }
3168 -
3169 - return new WP_Error('api_error', 'Invalid API response');
3170 -}
3171 -
3172 -/**
3173 - * Translate text using DeepSeek API
3174 - */
3175 -private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
3176 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
3177 - 'timeout' => 60,
3178 - 'headers' => [
3179 - 'Authorization' => 'Bearer ' . $api_key,
3180 - 'Content-Type' => 'application/json'
3181 - ],
3182 - 'body' => wp_json_encode([
3183 - 'model' => $model,
3184 - 'messages' => [
3185 - ['role' => 'system', 'content' => $system_prompt],
3186 - ['role' => 'user', 'content' => $text]
3187 - ],
3188 - 'temperature' => 0.3,
3189 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
3190 - // slow responses); translation wants non-thinking.
3191 - 'thinking' => ['type' => 'disabled']
3192 - ])
3193 - ]);
3194 -
3195 - if (is_wp_error($response)) {
3196 - return $response;
3197 - }
3198 -
3199 - $body = json_decode(wp_remote_retrieve_body($response), true);
3200 -
3201 - if (isset($body['error'])) {
3202 - return new WP_Error('api_error', $body['error']['message']);
3203 - }
3204 -
3205 - if (isset($body['choices'][0]['message']['content'])) {
3206 - return $body['choices'][0]['message']['content'];
3207 - }
3208 -
3209 - return new WP_Error('api_error', 'Invalid API response');
3210 -}
3211 -
3212 -/**
3213 - * Translate text using Google Gemini API
3214 - */
3215 -private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
3216 - if ($model === 'gemini-3-pro-preview') {
3217 - $model = 'gemini-3.1-pro-preview';
3218 - }
3219 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
3220 -
3221 - $response = wp_remote_post($url, [
3222 - 'timeout' => 60,
3223 - 'headers' => [
3224 - 'Content-Type' => 'application/json'
3225 - ],
3226 - 'body' => wp_json_encode([
3227 - 'contents' => [
3228 - [
3229 - 'parts' => [
3230 - ['text' => $system_prompt . "\n\n" . $text]
3231 - ]
3232 - ]
3233 - ],
3234 - 'generationConfig' => [
3235 - 'temperature' => 0.3
3236 - ]
3237 - ])
3238 - ]);
3239 -
3240 - if (is_wp_error($response)) {
3241 - return $response;
3242 - }
3243 -
3244 - $body = json_decode(wp_remote_retrieve_body($response), true);
3245 -
3246 - if (isset($body['error'])) {
3247 - return new WP_Error('api_error', $body['error']['message']);
3248 - }
3249 -
3250 - if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
3251 - return $body['candidates'][0]['content']['parts'][0]['text'];
3252 - }
3253 -
3254 - return new WP_Error('api_error', 'Invalid API response');
3255 -}
3256 -
3257 -/**
3258 - * Translate text using OpenRouter API
3259 - */
3260 -private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
3261 - $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
3262 - 'timeout' => 60,
3263 - 'headers' => [
3264 - 'Authorization' => 'Bearer ' . $api_key,
3265 - 'Content-Type' => 'application/json',
3266 - 'HTTP-Referer' => home_url(),
3267 - 'X-Title' => 'MxChat Translation'
3268 - ],
3269 - 'body' => wp_json_encode([
3270 - 'model' => $model,
3271 - 'messages' => [
3272 - ['role' => 'system', 'content' => $system_prompt],
3273 - ['role' => 'user', 'content' => $text]
3274 - ],
3275 - 'temperature' => 0.3
3276 - ])
3277 - ]);
3278 -
3279 - if (is_wp_error($response)) {
3280 - return $response;
3281 - }
3282 -
3283 - $body = json_decode(wp_remote_retrieve_body($response), true);
3284 -
3285 - if (isset($body['error'])) {
3286 - return new WP_Error('api_error', $body['error']['message']);
3287 - }
3288 -
3289 - if (isset($body['choices'][0]['message']['content'])) {
3290 - return $body['choices'][0]['message']['content'];
3291 - }
3292 -
3293 - return new WP_Error('api_error', 'Invalid API response');
3294 -}
3295 -
3296 -public function mxchat_fetch_chat_history() {
3297 - global $wpdb;
3298 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3299 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3300 -
3301 - if (!current_user_can('manage_options')) {
3302 - wp_send_json_error(['message' => 'Insufficient permissions']);
3303 - wp_die();
3304 - }
3305 -
3306 - $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3307 - $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3308 - $offset = ($page - 1) * $per_page;
3309 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3310 - $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3311 - $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3312 - if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3313 - $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3314 - $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3315 - $ratings_join = '';
3316 - $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3317 - if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3318 - // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3319 - $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3320 - $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3321 - }
3322 -
3323 - // Build search condition
3324 - $search_condition = '';
3325 - $search_params = [];
3326 - if (!empty($search)) {
3327 - $search_condition = "WHERE (
3328 - session_id LIKE %s
3329 - OR user_email LIKE %s
3330 - OR user_name LIKE %s
3331 - OR user_identifier LIKE %s
3332 - OR message LIKE %s
3333 - )";
3334 - $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3335 - }
3336 -
3337 - // Get total count
3338 - $count_query = !empty($search)
3339 - ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3340 - : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3341 - $total_sessions = (int) $wpdb->get_var($count_query);
3342 -
3343 - // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3344 - // and order by rating value (NULLs last) with recency as tiebreaker.
3345 - if ($ratings_join) {
3346 - $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3347 - } else {
3348 - $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3349 - }
3350 - $session_query = !empty($search)
3351 - ? $wpdb->prepare(
3352 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3353 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3354 - array_merge($search_params, [$per_page, $offset])
3355 - )
3356 - : $wpdb->prepare(
3357 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3358 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3359 - $per_page, $offset
3360 - );
3361 - $session_ids = $wpdb->get_col($session_query);
3362 -
3363 - $total_pages = ceil($total_sessions / $per_page);
3364 -
3365 - if (empty($session_ids)) {
3366 - wp_send_json([
3367 - 'success' => true,
3368 - 'sessions' => [],
3369 - 'page' => $page,
3370 - 'total_pages' => 0,
3371 - 'total_sessions' => 0,
3372 - 'showing_start' => 0,
3373 - 'showing_end' => 0
3374 - ]);
3375 - wp_die();
3376 - }
3377 -
3378 - // Check for optional columns/tables
3379 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3380 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3381 -
3382 - // Batch-fetch session ratings for this page (plan-a5b006).
3383 - $ratings_map = array();
3384 - if ($rating_table_exists && !empty($session_ids)) {
3385 - $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3386 - $rating_rows = $wpdb->get_results($wpdb->prepare(
3387 - "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3388 - $session_ids
3389 - ));
3390 - foreach ($rating_rows as $row) {
3391 - $ratings_map[$row->session_id] = array(
3392 - 'value' => (int) $row->rating_value,
3393 - 'feedback' => (string) $row->rating_feedback,
936 + // Update the prompt in the database
937 + $updated = $wpdb->update(
938 + $table_name,
939 + array(
940 + 'article_content' => $article_content,
941 + 'embedding_vector' => $embedding_vector_serialized,
942 + 'source_url' => $article_url,
943 + ),
944 + array('id' => $prompt_id),
945 + array('%s', '%s', '%s'),
946 + array('%d')
3394 947 );
3395 - }
3396 - }
3397 948
3398 - // Build session list data
3399 - $sessions = [];
3400 - foreach ($session_ids as $session_id) {
3401 - // Get session metadata
3402 - $session_data = $originating_columns_exist
3403 - ? $wpdb->get_row($wpdb->prepare(
3404 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3405 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3406 - $session_id
3407 - ))
3408 - : $wpdb->get_row($wpdb->prepare(
3409 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3410 - WHERE session_id = %s LIMIT 1",
3411 - $session_id
3412 - ));
3413 -
3414 - // Get message count and latest timestamp
3415 - $message_stats = $wpdb->get_row($wpdb->prepare(
3416 - "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3417 - $session_id
3418 - ));
3419 -
3420 - // Get first user message as preview
3421 - $first_user_msg = $wpdb->get_var($wpdb->prepare(
3422 - "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3423 - $session_id
3424 - ));
3425 - $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3426 -
3427 - // Build display name
3428 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3429 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3430 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3431 -
3432 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3433 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3434 -
3435 - // Format time - show relative for recent, date for older
3436 - $timestamp = strtotime($message_stats->latest . ' UTC');
3437 - $now = time();
3438 - $diff = $now - $timestamp;
3439 - if ($diff < 3600) {
3440 - $time_display = floor($diff / 60) . 'm ago';
3441 - } elseif ($diff < 86400) {
3442 - $time_display = floor($diff / 3600) . 'h ago';
3443 - } elseif ($diff < 604800) {
3444 - $time_display = floor($diff / 86400) . 'd ago';
949 + if ($updated !== false) {
950 + wp_send_json_success();
951 + } else {
952 + wp_send_json_error('Database update failed.');
953 + }
3445 954 } else {
3446 - $time_display = wp_date('M j', $timestamp);
955 + wp_send_json_error('Embedding generation failed.');
3447 956 }
3448 -
3449 - // Get initials for avatar
3450 - $initials = strtoupper(substr($display_name, 0, 2));
3451 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3452 - $parts = explode(' ', $display_name);
3453 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3454 - }
3455 -
3456 - $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3457 - $rating_value = $rating_entry ? $rating_entry['value'] : null;
3458 - $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3459 -
3460 - $sessions[] = [
3461 - 'session_id' => $session_id,
3462 - 'display_name' => $display_name,
3463 - 'display_sub' => $display_sub,
3464 - 'initials' => $initials,
3465 - 'preview' => $preview,
3466 - 'message_count' => (int) $message_stats->count,
3467 - 'time_display' => $time_display,
3468 - 'timestamp' => $message_stats->latest,
3469 - 'rating_value' => $rating_value,
3470 - 'rating_feedback' => $rating_feedback,
3471 - ];
957 + } else {
958 + wp_send_json_error('Invalid data.');
3472 959 }
3473 -
3474 - wp_send_json([
3475 - 'success' => true,
3476 - 'sessions' => $sessions,
3477 - 'page' => $page,
3478 - 'total_pages' => $total_pages,
3479 - 'total_sessions' => $total_sessions,
3480 - 'showing_start' => $offset + 1,
3481 - 'showing_end' => min($offset + $per_page, $total_sessions)
3482 - ]);
3483 - wp_die();
3484 960 }
3485 961
3486 -/**
3487 - * Fetch single conversation details for split-panel view
3488 - */
3489 -public function mxchat_fetch_conversation() {
962 +public function mxchat_fetch_chat_history() {
3490 963 global $wpdb;
3491 964 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3492 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3493 965
3494 966 if (!current_user_can('manage_options')) {
3495 - wp_send_json_error(['message' => 'Insufficient permissions']);
967 + echo esc_html__('You do not have sufficient permissions to view this page.', 'mxchat');
3496 968 wp_die();
3497 969 }
3498 970
3499 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
3500 - if (empty($session_id)) {
3501 - wp_send_json_error(['message' => 'No session ID provided']);
3502 - wp_die();
3503 - }
971 + $chat_transcripts = $wpdb->get_results(
972 + $wpdb->prepare("SELECT * FROM {$table_name} ORDER BY timestamp ASC")
973 + );
3504 974
3505 - // Check for optional columns/tables
3506 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3507 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3508 -
3509 - // Get session metadata
3510 - $session_data = $originating_columns_exist
3511 - ? $wpdb->get_row($wpdb->prepare(
3512 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3513 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3514 - $session_id
3515 - ))
3516 - : $wpdb->get_row($wpdb->prepare(
3517 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3518 - WHERE session_id = %s LIMIT 1",
3519 - $session_id
3520 - ));
3521 -
3522 - if (!$session_data) {
3523 - wp_send_json_error(['message' => 'Session not found']);
975 + if (empty($chat_transcripts)) {
976 + echo esc_html__('No chat history available.', 'mxchat');
3524 977 wp_die();
3525 978 }
3526 979
3527 - // Get clicked URLs
3528 - $clicked_urls = [];
3529 - if ($url_table_exists) {
3530 - $url_clicks = $wpdb->get_results($wpdb->prepare(
3531 - "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3532 - WHERE session_id = %s ORDER BY click_timestamp ASC",
3533 - $session_id
3534 - ));
3535 - foreach ($url_clicks as $click) {
3536 - $clicked_urls[] = $click->clicked_url;
3537 - }
3538 - }
980 + ob_start();
981 + $current_session_id = '';
3539 982
3540 - // Get all messages
3541 - $messages = $wpdb->get_results($wpdb->prepare(
3542 - "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3543 - $session_id
3544 - ));
983 + echo '<div class="mxchat-transcript">';
3545 984
3546 - // Build user info
3547 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3548 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3549 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3550 -
3551 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3552 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3553 -
3554 - // Get initials
3555 - $initials = strtoupper(substr($display_name, 0, 2));
3556 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3557 - $parts = explode(' ', $display_name);
3558 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3559 - }
3560 -
3561 - // Page info
3562 - $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3563 - $page_title = '';
3564 - if ($page_url) {
3565 - $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3566 - }
3567 -
3568 - // Format messages for output
3569 - $formatted_messages = [];
3570 - foreach ($messages as $msg) {
3571 - $is_user = ($msg->role === 'user');
3572 - // Live-agent replies (Slack/Telegram handoff) persist with role 'agent'.
3573 - // Kept OUT of $is_bot so the RAG Sources link below stays bot-only.
3574 - $is_agent = ($msg->role === 'agent');
3575 - $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3576 -
3577 - $content = wp_kses(
3578 - stripslashes($msg->message),
3579 - [
3580 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3581 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3582 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3583 - 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3584 - 'img' => ['src' => [], 'alt' => [], 'class' => []],
3585 - 'h3' => ['class' => []],
3586 - 'h4' => ['class' => []],
3587 - 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
3588 - 'select' => ['class' => [], 'data-attribute' => []],
3589 - 'option' => ['value' => []],
3590 - 'span' => ['class' => []],
3591 - 'del' => [], 'ins' => [],
3592 - ]
3593 - );
3594 - $formatted_content = $this->format_transcript_message($content);
3595 -
3596 - $has_rag = $is_bot && !empty($msg->rag_context);
3597 -
3598 - $formatted_messages[] = [
3599 - 'id' => $msg->id,
3600 - 'role' => $msg->role,
3601 - 'is_user' => $is_user,
3602 - 'is_agent' => $is_agent,
3603 - 'is_bot' => $is_bot,
3604 - 'content' => $formatted_content,
3605 - 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
3606 - 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
3607 - 'has_rag' => $has_rag
3608 - ];
3609 - }
3610 -
3611 - // First message timestamp for "started" display
3612 - $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
3613 -
3614 - // Pull rating_feedback for this session (if any) so the details drawer can show it.
3615 - $rating_feedback = '';
3616 - $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
3617 - if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
3618 - $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
3619 - "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
3620 - $session_id
3621 - ));
3622 - }
3623 -
3624 - wp_send_json([
3625 - 'success' => true,
3626 - 'session_id' => $session_id,
3627 - 'user' => [
3628 - 'name' => $display_name,
3629 - 'sub' => $display_sub,
3630 - 'initials' => $initials,
3631 - 'email' => $user_email,
3632 - 'identifier' => $user_identifier
3633 - ],
3634 - 'page' => [
3635 - 'url' => $page_url,
3636 - 'title' => $page_title
3637 - ],
3638 - 'clicked_urls' => $clicked_urls,
3639 - 'messages' => $formatted_messages,
3640 - 'message_count' => count($messages),
3641 - 'started' => $started,
3642 - 'rating_feedback' => $rating_feedback
3643 - ]);
3644 - wp_die();
3645 -}
3646 -
3647 -
3648 -/**
3649 - * ALTERNATIVE: Simpler helper method using string replacement
3650 - */
3651 -private function highlight_clicked_links($message_content, $clicked_urls) {
3652 - if (empty($clicked_urls)) {
3653 - return wp_kses(
3654 - $message_content,
3655 - [
3656 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3657 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3658 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3659 - ]
3660 - );
3661 - }
3662 -
3663 - // First apply standard sanitization
3664 - $message_content = wp_kses(
3665 - $message_content,
3666 - [
3667 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3668 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3669 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3670 - ]
3671 - );
3672 -
3673 - // Process each clicked URL
3674 - foreach ($clicked_urls as $clicked_url) {
3675 - // Try multiple patterns to catch different link formats
3676 - $patterns = [
3677 - // Standard link format
3678 - '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
3679 - // Link with trailing slash
3680 - '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
3681 - // Encoded entities version
3682 - '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
3683 - ];
3684 -
3685 - foreach ($patterns as $pattern) {
3686 - if (preg_match($pattern, $message_content)) {
3687 - $message_content = preg_replace_callback(
3688 - $pattern,
3689 - function($matches) {
3690 - $full_match = $matches[0];
3691 - $attributes = $matches[1];
3692 -
3693 - // Check if it already has the class
3694 - if (strpos($full_match, 'mxchat-clicked-link') !== false) {
3695 - return $full_match;
3696 - }
3697 -
3698 - // Check if class attribute exists
3699 - if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
3700 - // Add to existing class
3701 - $new_attributes = preg_replace(
3702 - '/class=["\']([^"\']*)["\']/',
3703 - 'class="$1 mxchat-clicked-link"',
3704 - $attributes
3705 - );
3706 - } else {
3707 - // Add new class attribute
3708 - $new_attributes = $attributes . ' class="mxchat-clicked-link"';
3709 - }
3710 -
3711 - // Add title if not present
3712 - if (strpos($new_attributes, 'title=') === false) {
3713 - $new_attributes .= ' title="User clicked this link"';
3714 - }
3715 -
3716 - return '<a' . $new_attributes . '>';
3717 - },
3718 - $message_content
3719 - );
3720 -
3721 - // If we found and replaced, break out of the patterns loop
3722 - break;
985 + foreach ($chat_transcripts as $transcript) {
986 + if ($current_session_id !== $transcript->session_id) {
987 + if ($current_session_id !== '') {
988 + echo '</div></div>';
3723 989 }
990 + $current_session_id = sanitize_text_field($transcript->session_id);
991 + echo '<div class="mxchat-session">';
992 + echo '<div class="mxchat-session-header">';
993 + echo '<input type="checkbox" name="delete_session_ids[]" value="' . esc_attr($transcript->session_id) . '"> ';
994 + echo esc_html($current_session_id);
995 + echo '</div>';
996 + echo '<div class="mxchat-messages">';
3724 997 }
3725 - }
3726 998
3727 - return $message_content;
3728 -}
999 + $formatted_timestamp = date_i18n('g:i a', strtotime($transcript->timestamp));
1000 +$role = $transcript->role;
1001 +$message_class = '';
3729 1002
3730 -public function mxchat_create_prompts_page() {
3731 - //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
3732 -
3733 - global $wpdb;
3734 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3735 -
3736 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3737 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
3738 -
3739 - // Display success message if all prompts were deleted
3740 - if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
3741 - echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button></div>';
3742 - }
3743 -
3744 - // Set up pagination, search query, and content type filter
3745 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
3746 - $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
3747 - $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
3748 - $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
3749 - $per_page = 25;
3750 -
3751 - //error_log('DEBUG: Search query: ' . $search_query);
3752 - //error_log('DEBUG: Content type filter: ' . $content_type_filter);
3753 - //error_log('DEBUG: Current page: ' . $current_page);
3754 - //error_log('DEBUG: Per page: ' . $per_page);
3755 -
3756 - // ================================
3757 - // MULTI-BOT CONFIGURATION
3758 - // ================================
3759 -
3760 - // Check for multi-bot and set up bot selection
3761 - if (class_exists('MxChat_Multi_Bot_Manager')) {
3762 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
3763 - $available_bots = $multi_bot_manager->get_available_bots();
3764 -
3765 - // Get saved bot selection (user-specific first, then site-wide default)
3766 - $user_id = get_current_user_id();
3767 - $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
3768 - if (empty($saved_bot_id)) {
3769 - $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
3770 - }
3771 -
3772 - // Allow URL override but default to saved selection
3773 - $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
3774 - $multibot_active = true;
1003 +// Check if it's an automated test message
1004 +if (strpos($transcript->user_identifier, 'Curious Customer') !== false ||
1005 + strpos($transcript->user_identifier, 'Technical Expert') !== false ||
1006 + strpos($transcript->user_identifier, 'Feature Explorer') !== false) {
1007 + $message_class = 'user-message';
1008 + $display_role = $transcript->user_identifier; // Show the agent type
1009 +} else if ($role === 'user' || filter_var($transcript->user_identifier, FILTER_VALIDATE_IP)) {
1010 + $message_class = 'user-message';
1011 + // Format display role (IP address or email)
1012 + if (!empty($transcript->user_email)) {
1013 + $display_role = sanitize_email($transcript->user_email);
3775 1014 } else {
3776 - $current_bot_id = 'default';
3777 - $multibot_active = false;
3778 - }
3779 -
3780 - // ================================
3781 - // DATA SOURCE CONFIGURATION
3782 - // ================================
3783 -
3784 - // Get bot-specific Pinecone settings
3785 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
3786 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3787 - $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
3788 -
3789 - // Get OpenAI Vector Store settings
3790 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
3791 - $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
3792 -
3793 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3794 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
3795 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
3796 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
3797 -
3798 - if ($use_pinecone && !empty($pinecone_api_key)) {
3799 - //error_log('DEBUG: Using PINECONE data source with bot-specific config');
3800 - // PINECONE DATA SOURCE
3801 - $data_source = 'pinecone';
3802 -
3803 - // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
3804 - // UPDATED 2.5.6: Added content_type_filter parameter
3805 - $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
3806 -
3807 - // TEMPORARY DEBUG - Add this right after the fetch call
3808 - //error_log('=== DEBUG: Bot switching issue ===');
3809 - //error_log('Current bot ID: ' . $current_bot_id);
3810 - //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3811 - //error_log('Records returned: ' . count($records['data'] ?? []));
3812 - //error_log('Total records: ' . ($records['total'] ?? 0));
3813 -
3814 - // Check first few records to see their bot_id
3815 - if (!empty($records['data'])) {
3816 - foreach (array_slice($records['data'], 0, 3) as $i => $record) {
3817 - $record_bot_id = $record->bot_id ?? 'NOT_SET';
3818 - //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
3819 - }
3820 - }
3821 - //error_log('=== END DEBUG ===');
3822 -
3823 - $total_records = $records['total'] ?? 0;
3824 - $prompts = $records['data'] ?? array();
3825 - $total_in_database = $records['total_in_database'] ?? 0;
3826 - $showing_recent_only = $records['showing_recent_only'] ?? false;
3827 -
3828 - $total_pages = ceil($total_records / $per_page);
3829 -
3830 - } else {
3831 - //error_log('DEBUG: Using WORDPRESS DB data source');
3832 - // WORDPRESS DB DATA SOURCE (your existing logic)
3833 - $data_source = 'wordpress';
3834 -
3835 - // Initialize these variables for WordPress DB
3836 - $total_in_database = 0;
3837 - $showing_recent_only = false;
3838 -
3839 - $offset = ($current_page - 1) * $per_page;
3840 -
3841 - // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
3842 - $where_clauses = array();
3843 - $where_values = array();
3844 -
3845 - if ($search_query) {
3846 - $where_clauses[] = "article_content LIKE %s";
3847 - $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
3848 - }
3849 -
3850 - if ($content_type_filter) {
3851 - $where_clauses[] = "content_type = %s";
3852 - $where_values[] = $content_type_filter;
3853 - }
3854 -
3855 - $sql_where = "";
3856 - if (!empty($where_clauses)) {
3857 - $sql_where = "WHERE " . implode(" AND ", $where_clauses);
3858 - }
3859 -
3860 - // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
3861 - // This ensures pagination shows X entries per page, not X chunks
3862 - // Entries with empty source_url are counted individually
3863 - if (!empty($where_values)) {
3864 - // Count unique source_urls + count of rows with empty source_url
3865 - $count_query = $wpdb->prepare(
3866 - "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
3867 - (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
3868 - array_merge($where_values, $where_values)
3869 - );
1015 + $user_identifier = sanitize_text_field($transcript->user_identifier);
1016 + if (filter_var($user_identifier, FILTER_VALIDATE_IP)) {
1017 + $display_role = preg_replace('/\.\d+$/', '.xxx', $user_identifier);
3870 1018 } else {
3871 - $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
3872 - (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
1019 + $display_role = $user_identifier;
3873 1020 }
3874 - $total_records = $wpdb->get_var($count_query);
3875 - $total_pages = ceil($total_records / $per_page);
3876 -
3877 - // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
3878 - // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
3879 - if (!empty($where_values)) {
3880 - $urls_query = $wpdb->prepare(
3881 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
3882 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3883 - array_merge($where_values, array($per_page, $offset))
3884 - );
3885 - } else {
3886 - $urls_query = $wpdb->prepare(
3887 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
3888 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3889 - $per_page, $offset
3890 - );
3891 - }
3892 - $page_urls = $wpdb->get_results($urls_query);
3893 -
3894 - // Step 2: Fetch all rows for these source_urls
3895 - $prompts = array();
3896 - if (!empty($page_urls)) {
3897 - // Build URL order map to preserve newest-first ordering from step 1
3898 - $url_order_map = array();
3899 - $url_list = array();
3900 - $has_empty_url = false;
3901 - $order_index = 0;
3902 - foreach ($page_urls as $url_row) {
3903 - if (empty($url_row->source_url)) {
3904 - $has_empty_url = true;
3905 - $url_order_map['__empty__'] = $order_index++;
3906 - } else {
3907 - $url_list[] = $url_row->source_url;
3908 - $url_order_map[$url_row->source_url] = $order_index++;
3909 - }
3910 - }
3911 -
3912 - // Build query to fetch all rows for these URLs
3913 - $url_conditions = array();
3914 - $url_values = array();
3915 -
3916 - if (!empty($url_list)) {
3917 - $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
3918 - $url_conditions[] = "source_url IN ($placeholders)";
3919 - $url_values = array_merge($url_values, $url_list);
3920 - }
3921 -
3922 - if ($has_empty_url) {
3923 - $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
3924 - }
3925 -
3926 - if (!empty($url_conditions)) {
3927 - $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
3928 -
3929 - // Add original filters back
3930 - if (!empty($where_clauses)) {
3931 - $url_where .= " AND " . implode(" AND ", $where_clauses);
3932 - $url_values = array_merge($url_values, $where_values);
3933 - }
3934 -
3935 - if (!empty($url_values)) {
3936 - $prompts_query = $wpdb->prepare(
3937 - "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
3938 - $url_values
3939 - );
3940 - } else {
3941 - $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
3942 - }
3943 -
3944 - $prompts = $wpdb->get_results($prompts_query);
3945 -
3946 - // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
3947 - usort($prompts, function($a, $b) use ($url_order_map) {
3948 - $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
3949 - $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
3950 - $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
3951 - $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
3952 -
3953 - // First sort by URL order (newest URLs first)
3954 - if ($order_a !== $order_b) {
3955 - return $order_a - $order_b;
3956 - }
3957 -
3958 - // Within same URL, sort by timestamp DESC (newest chunks first)
3959 - return strtotime($b->timestamp) - strtotime($a->timestamp);
3960 - });
3961 - }
3962 - }
3963 1021 }
3964 -
3965 - // ================================
3966 - // PAGINATION GENERATION
3967 - // ================================
3968 -
3969 - // Generate pagination links
3970 - if ($total_pages > 1) {
3971 - // Build a clean base URL with only necessary parameters
3972 - $pagination_args = array('page' => 'mxchat-prompts');
3973 -
3974 - // Preserve bot_id parameter if multi-bot is active
3975 - if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
3976 - $pagination_args['bot_id'] = $current_bot_id;
3977 - }
3978 -
3979 - // Preserve search query and nonce if present
3980 - if ($search_query) {
3981 - $pagination_args['search'] = $search_query;
3982 - if (!empty($nonce)) {
3983 - $pagination_args['_wpnonce'] = $nonce;
3984 - }
3985 - }
3986 -
3987 - // Preserve content type filter if present
3988 - if ($content_type_filter) {
3989 - $pagination_args['content_type'] = $content_type_filter;
3990 - }
3991 -
3992 - // Build clean base URL
3993 - $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
3994 -
3995 - $page_links = paginate_links(array(
3996 - 'base' => $base_url . '%_%',
3997 - 'format' => '&paged=%#%',
3998 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
3999 - 'next_text' => __('Next &raquo;', 'mxchat'),
4000 - 'total' => $total_pages,
4001 - 'current' => $current_page,
4002 - 'type' => 'plain',
4003 - ));
4004 - } else {
4005 - $page_links = '';
4006 - }
4007 -
4008 - // ================================
4009 - // PROCESSING STATUS RETRIEVAL
4010 - // ================================
4011 -
4012 - // Retrieve processing statuses using queue-based method
4013 - $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
4014 - $pdf_status = $processing_statuses['pdf_status'];
4015 - $sitemap_status = $processing_statuses['sitemap_status'];
4016 - $is_processing = $processing_statuses['is_processing'];
4017 -
4018 - //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
4019 -
4020 - // ================================
4021 - // RENDER PAGE WITH NEW SIDEBAR LAYOUT
4022 - // ================================
4023 -
4024 - // Include the new knowledge page template
4025 - require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
4026 -
4027 - // Package all page data for the render function
4028 - $page_data = array(
4029 - 'prompts' => $prompts,
4030 - 'total_records' => $total_records,
4031 - 'total_pages' => $total_pages,
4032 - 'current_page' => $current_page,
4033 - 'per_page' => $per_page,
4034 - 'page_links' => $page_links,
4035 - 'search_query' => $search_query,
4036 - 'content_type_filter' => $content_type_filter,
4037 - 'data_source' => $data_source,
4038 - 'use_pinecone' => $use_pinecone,
4039 - 'use_vectorstore' => $use_vectorstore,
4040 - 'multibot_active' => $multibot_active,
4041 - 'current_bot_id' => $current_bot_id,
4042 - 'pdf_status' => $pdf_status,
4043 - 'sitemap_status' => $sitemap_status,
4044 - 'is_processing' => $is_processing,
4045 - 'total_in_database' => $total_in_database ?? 0,
4046 - 'showing_recent_only' => $showing_recent_only ?? false,
4047 - );
4048 -
4049 - // Render the new sidebar-based page
4050 - mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
1022 +} elseif ($role === 'agent') {
1023 + $message_class = 'agent-message';
1024 + $display_role = 'Agent';
1025 +} else {
1026 + $message_class = 'bot-message';
1027 + $display_role = 'Bot';
4051 1028 }
4052 1029
4053 -/**
4054 - * Get bot-specific Pinecone configuration
4055 - * Used in the knowledge retrieval functions
4056 - */
4057 -private function get_bot_pinecone_config($bot_id = 'default') {
4058 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
4059 -
4060 - // If default bot or multi-bot add-on not active, use default Pinecone config
4061 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
4062 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
4063 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
4064 - $config = array(
4065 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
4066 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
4067 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
4068 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
4069 - );
4070 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
4071 - return $config;
1030 +echo '<div class="mxchat-message ' . esc_attr($message_class) . '">';
1031 +echo '<div class="mxchat-message-header">' . esc_html($display_role) . '</div>';
1032 + echo '<div class="mxchat-message-content">' . wp_kses_post($transcript->message) . '</div>';
1033 + echo '<div class="mxchat-timestamp">' . esc_html($formatted_timestamp) . '</div>';
1034 + echo '</div>';
4072 1035 }
4073 -
4074 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
4075 -
4076 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
4077 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
4078 -
4079 - if (!empty($bot_pinecone_config)) {
4080 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
4081 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
4082 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
4083 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
4084 - } else {
4085 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
4086 - }
4087 -
4088 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
4089 -}
4090 1036
4091 -public function mxchat_delete_chat_history() {
4092 - if (!current_user_can('manage_options')) {
4093 - echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4094 - wp_die();
4095 - }
4096 - check_ajax_referer('mxchat_delete_chat_history', 'security');
1037 + echo '</div></div></div>';
4097 1038
4098 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
4099 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
4100 - wp_die();
4101 - }
4102 -
4103 - global $wpdb;
4104 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4105 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
4106 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
4107 -
4108 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
4109 - // across the whole table). Default false: the chat rows go away but the lead is
4110 - // preserved as a separate "chat deleted" lead in the Leads tab.
4111 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
4112 -
4113 - $deleted_count = 0;
4114 - $preserved_as_deleted_leads = 0;
4115 - $emails_to_fully_wipe = [];
4116 -
4117 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
4118 - $session_id_sanitized = MxChat_Utils::sanitize_session_id($session_id);
4119 - if ($session_id_sanitized === '') {
4120 - continue;
4121 - }
4122 -
4123 - // Capture the lead info attached to this session *before* we delete the rows.
4124 - $lead_row = $wpdb->get_row($wpdb->prepare(
4125 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
4126 - FROM {$table_name}
4127 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
4128 - GROUP BY user_email, user_name
4129 - ORDER BY last_ts DESC LIMIT 1",
4130 - $session_id_sanitized
4131 - ));
4132 -
4133 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
4134 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
4135 -
4136 - if ($has_translations) {
4137 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
4138 - }
4139 -
4140 - delete_option('mxchat_history_' . $session_id_sanitized);
4141 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
4142 - if (class_exists('MxChat_Session_Store')) {
4143 - MxChat_Session_Store::delete_session($session_id_sanitized); // b64b77
4144 - }
4145 -
4146 - if ($lead_row && !empty($lead_row->user_email)) {
4147 - if ($also_delete_lead) {
4148 - // Full-wipe requested — queue the email so that all their sessions and
4149 - // related options get swept below. Also clear this session's pre-chat
4150 - // capture options (they're no longer meaningful).
4151 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
4152 - delete_option('mxchat_email_' . $session_id_sanitized);
4153 - delete_option('mxchat_name_' . $session_id_sanitized);
4154 - } else {
4155 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
4156 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
4157 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
4158 - if (!empty($lead_row->user_name)) {
4159 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
4160 - }
4161 - if (!empty($lead_row->last_ts)) {
4162 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
4163 - }
4164 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
4165 - delete_option('mxchat_email_' . $session_id_sanitized);
4166 - delete_option('mxchat_name_' . $session_id_sanitized);
4167 - $preserved_as_deleted_leads++;
4168 - }
4169 - } else {
4170 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
4171 - delete_option('mxchat_email_' . $session_id_sanitized);
4172 - delete_option('mxchat_name_' . $session_id_sanitized);
4173 - }
4174 -
4175 - $deleted_count++;
4176 - }
4177 -
4178 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
4179 - // chat_deleted preservation) for each affected email. Reuses the same internal
4180 - // helper as the Leads-tab Delete button for consistency.
4181 - if (!empty($emails_to_fully_wipe)) {
4182 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
4183 - }
4184 -
4185 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
4186 -
4187 - echo wp_json_encode([
4188 - 'success' => sprintf(
4189 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
4190 - $deleted_count
4191 - ),
4192 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
4193 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
4194 - ]);
1039 + $output = ob_get_clean();
1040 + echo $output;
4195 1041 wp_die();
4196 1042 }
4197 1043
4198 -/**
4199 - * Format transcript message content with markdown processing
4200 - * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
4201 - */
4202 -private function format_transcript_message($text) {
4203 - if (empty($text)) {
4204 - return '';
4205 - }
4206 1044
4207 - // Normalize line endings and clean up excessive whitespace
4208 - $text = str_replace("\r\n", "\n", $text);
4209 - $text = str_replace("\r", "\n", $text);
4210 -
4211 - // Clean up existing <br> tags that may have been saved (legacy data)
4212 - // Convert <br>, <br/>, <br /> back to newlines for consistent processing
4213 - $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
4214 -
4215 - // Collapse 3+ consecutive newlines to just 2 (paragraph break)
4216 - $text = preg_replace('/\n{3,}/', "\n\n", $text);
4217 -
4218 - // Process markdown headers (# Header)
4219 - $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
4220 - $level = strlen($matches[1]);
4221 - $content = esc_html(trim($matches[2]));
4222 - return "<h{$level}>{$content}</h{$level}>";
4223 - }, $text);
4224 -
4225 - // Process code blocks with triple backticks
4226 - $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
4227 - $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
4228 - $code = esc_html($matches[2]);
4229 - return "<pre><code{$language}>{$code}</code></pre>";
4230 - }, $text);
4231 -
4232 - // Process inline code with single backticks
4233 - $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
4234 -
4235 - // Process bold text **text** or __text__
4236 - $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
4237 - $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
4238 -
4239 - // Process italic text *text* or _text_ (but not if part of URL)
4240 - $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
4241 - $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
4242 -
4243 - // Process markdown links [text](url)
4244 - $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
4245 - $link_text = esc_html($matches[1]);
4246 - $url = esc_url($matches[2]);
4247 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
4248 - }, $text);
4249 -
4250 - // Process citation-style brackets [URL]
4251 - $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
4252 - $url = esc_url($matches[1]);
4253 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
4254 - }, $text);
4255 -
4256 - // Process standalone URLs (not already in links or img src)
4257 - $text = preg_replace_callback(
4258 - '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
4259 - function($matches) {
4260 - $url = esc_url($matches[1]);
4261 - // Truncate display URL if too long
4262 - $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
4263 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
4264 - },
4265 - $text
4266 - );
4267 -
4268 - // Process mailto links
4269 - $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
4270 - $link_text = esc_html($matches[1]);
4271 - $mailto = esc_url($matches[2]);
4272 - return "<a href=\"{$mailto}\">{$link_text}</a>";
4273 - }, $text);
4274 -
4275 - // Convert paragraphs: split by double newlines, wrap in <p> tags
4276 - // This creates proper paragraph structure instead of excessive <br> tags
4277 - $paragraphs = preg_split('/\n\n+/', $text);
4278 -
4279 - // Filter out empty paragraphs but preserve content like "0"
4280 - $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
4281 - return $p !== '';
4282 - }));
4283 -
4284 - if (empty($paragraphs)) {
4285 - // No content after filtering
4286 - return '';
4287 - } elseif (count($paragraphs) > 1) {
4288 - // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
4289 - $formatted_paragraphs = array_map(function($p) {
4290 - return nl2br($p);
4291 - }, $paragraphs);
4292 - $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4293 - } else {
4294 - // Single paragraph - just convert newlines to <br>
4295 - $text = nl2br($paragraphs[0]);
4296 - }
4297 -
4298 - return $text;
4299 -}
4300 -
4301 -/**
4302 - * AJAX handler to fetch RAG context for a specific message
4303 - * Used by the transcript viewer to show retrieved documents
4304 - */
4305 -public function mxchat_get_rag_context() {
4306 - // Check permissions
4307 - if (!current_user_can('manage_options')) {
4308 - wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4309 - wp_die();
4310 - }
4311 -
4312 - // Validate message ID
4313 - if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4314 - wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4315 - wp_die();
4316 - }
4317 -
4318 - $message_id = absint($_POST['message_id']);
4319 -
4320 - global $wpdb;
4321 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4322 -
4323 - // Fetch the RAG context for this message
4324 - $result = $wpdb->get_row($wpdb->prepare(
4325 - "SELECT rag_context FROM {$table_name} WHERE id = %d",
4326 - $message_id
4327 - ));
4328 -
4329 - if (!$result || empty($result->rag_context)) {
4330 - wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4331 - wp_die();
4332 - }
4333 -
4334 - // Decode the JSON data
4335 - $rag_context = json_decode($result->rag_context, true);
4336 -
4337 - if (json_last_error() !== JSON_ERROR_NONE) {
4338 - wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4339 - wp_die();
4340 - }
4341 -
4342 - wp_send_json_success($rag_context);
4343 - wp_die();
4344 -}
4345 -
4346 -public function display_admin_notices() {
4347 - // Check if we're on a MXChat admin page
4348 - $screen = get_current_screen();
4349 - if (!$screen || strpos($screen->base, 'mxchat') === false) {
4350 - return;
4351 - }
4352 -
4353 - $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4354 -
4355 - // Check for error notices
4356 - $error_notice = get_transient('mxchat_admin_notice_error');
4357 - if ($error_notice) {
4358 - echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4359 - delete_transient('mxchat_admin_notice_error');
4360 - }
4361 -
4362 - // Check for success notices
4363 - $success_notice = get_transient('mxchat_admin_notice_success');
4364 - if ($success_notice) {
4365 - echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4366 - delete_transient('mxchat_admin_notice_success');
4367 - }
4368 -
4369 - // Check for info notices
4370 - $info_notice = get_transient('mxchat_admin_notice_info');
4371 - if ($info_notice) {
4372 - echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4373 - delete_transient('mxchat_admin_notice_info');
4374 - }
4375 -}
4376 -
4377 -
4378 1045 public function mxchat_create_activation_page() {
4379 - // Include the new Pro & Extensions page template
4380 - require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
1046 + $license_status = get_option('mxchat_license_status', 'inactive');
1047 + $license_error = get_option('mxchat_license_error', '');
1048 + ?>
1049 + <div class="wrap mxchat-admin">
1050 + <h2>MxChat Pro: Activation</h2>
1051 + <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
1052 + <div class="error notice">
1053 + <p><?php echo esc_html($license_error); ?></p>
1054 + </div>
1055 + <?php endif; ?>
4381 1056
4382 - // Get addons configuration from the MxChat_Addons class
4383 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4384 - $addons_instance = new MxChat_Addons();
4385 - $addons_config = $addons_instance->get_addons_config();
1057 + <form id="mxchat-activation-form" style="<?php echo $license_status === 'active' ? 'display: none;' : ''; ?>">
1058 + <table class="form-table">
1059 + <tr valign="top">
1060 + <th scope="row">Email Address</th>
1061 + <td>
1062 + <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" required />
1063 + </td>
1064 + </tr>
1065 + <tr valign="top">
1066 + <th scope="row">Activation Key</th>
1067 + <td>
1068 + <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" required />
1069 + </td>
1070 + </tr>
1071 + </table>
1072 + <?php if ($license_status !== 'active'): ?>
1073 + <button type="submit" id="activate_license_button" class="button button-primary"><?php esc_html_e('Activate License', 'mxchat'); ?></button>
1074 + <div id="mxchat-activation-spinner" class="mxchat-activation-spinner" style="display: none;"></div>
1075 + <?php endif; ?>
1076 + </form>
4386 1077
4387 - // Render the consolidated Pro & Extensions page
4388 - mxchat_render_pro_page($this, $addons_config);
1078 + <!-- License Status Display -->
1079 + <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
1080 + </div>
1081 + <?php
4389 1082 }
4390 1083
4391 -/**
4392 - * Check if current activation is linked to a domain
4393 - * This checks YOUR website's database, not the user's local database
4394 - */
4395 -public function is_current_activation_linked($domain) {
4396 - $license_key = get_option('mxchat_activation_key');
4397 - $email = get_option('mxchat_pro_email');
4398 -
4399 - if (empty($license_key) || empty($email)) {
4400 - return false;
4401 - }
4402 -
4403 - // Check with YOUR website's API
4404 - $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4405 - 'body' => array(
4406 - 'license_key' => $license_key,
4407 - 'email' => $email,
4408 - 'domain' => $domain
4409 - ),
4410 - 'timeout' => 10,
4411 - 'sslverify' => false
4412 - ));
4413 -
4414 - if (is_wp_error($response)) {
4415 - return false;
4416 - }
4417 -
4418 - $body = json_decode(wp_remote_retrieve_body($response), true);
4419 - return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
4420 -}
4421 -
4422 -
4423 -public function mxchat_actions_page_html() {
4424 - if (!current_user_can('manage_options')) {
1084 +public function mxchat_intents_page_html() {
1085 + if ( ! current_user_can( 'manage_options' ) ) {
4425 1086 return;
4426 1087 }
4427 1088
1089 + // Fetch existing intents with pagination and filtering
4428 1090 global $wpdb;
4429 1091 $table_name = $wpdb->prefix . 'mxchat_intents';
1092 + $page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
1093 + $per_page = 20;
1094 + $offset = ( $page - 1 ) * $per_page;
4430 1095
4431 - // Get stats for dashboard
4432 - $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4433 - $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4434 - $disabled_actions = $total_actions - $enabled_actions;
1096 + // Build the WHERE clause based on filters
1097 + $where = '1=1';
1098 + $search_term = isset( $_GET['s'] ) ? trim( $_GET['s'] ) : '';
1099 + $callback_filter = isset( $_GET['callback_filter'] ) ? sanitize_text_field( $_GET['callback_filter'] ) : '';
4435 1100
4436 - // Get unique action types count
4437 - $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
4438 -
4439 - // Get action type distribution
4440 - $type_distribution_raw = $wpdb->get_results("SELECT callback_function, COUNT(*) as count FROM $table_name GROUP BY callback_function ORDER BY count DESC LIMIT 10");
4441 - $available_callbacks = $this->mxchat_get_available_callbacks();
4442 - $callback_groups = $this->mxchat_get_available_callbacks(true, true);
4443 -
4444 - $action_type_distribution = array();
4445 - foreach ($type_distribution_raw as $row) {
4446 - $label = isset($available_callbacks[$row->callback_function]['label'])
4447 - ? $available_callbacks[$row->callback_function]['label']
4448 - : $row->callback_function;
4449 - $action_type_distribution[$label] = $row->count;
1101 + if ( $search_term ) {
1102 + $search_term_like = '%' . $wpdb->esc_like( $search_term ) . '%';
1103 + $where .= $wpdb->prepare( ' AND (intent_label LIKE %s OR phrases LIKE %s)', $search_term_like, $search_term_like );
4450 1104 }
4451 1105
4452 - // Native function-calling (AI Tools) data — plan-mxchat-20260617-a41dee.
4453 - // The AI Tools checklist reads from MxChat_Tool_Registry, the SAME single
4454 - // source the chat-time function-calling loop reads, so the two never drift.
4455 - if (!class_exists('MxChat_Tool_Registry')) {
4456 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-tool-registry.php';
1106 + if ( $callback_filter ) {
1107 + $where .= $wpdb->prepare( ' AND callback_function = %s', $callback_filter );
4457 1108 }
4458 - if (!class_exists('MxChat_Model_Catalog')) {
4459 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
4460 - }
4461 - $fc_options = get_option('mxchat_options', array());
4462 - $fc_current_model = isset($fc_options['model']) ? $fc_options['model'] : 'gpt-5.6-sol';
4463 - $fc_model_capable = class_exists('MxChat_Model_Catalog')
4464 - ? MxChat_Model_Catalog::supports_tools($fc_current_model) : true;
4465 - $active_tab = (isset($_GET['tab']) && $_GET['tab'] === 'ai-tools') ? 'ai-tools' : 'dashboard';
4466 1109
4467 - // Enrich each AI Tool with the dashicon its callback already uses on the
4468 - // Trigger Phrases "Choose what it does" grid, so the AI Tools cards/modal
4469 - // share the same iconography (plan 8bbf98 part 4). View-layer only — the
4470 - // registry's model-facing data is untouched. Default admin-generic.
4471 - $fc_tools = MxChat_Tool_Registry::available_tools();
4472 - foreach ($fc_tools as &$fc_tool_ref) {
4473 - $fc_cb_ref = $fc_tool_ref['callback'];
4474 - $fc_tool_ref['icon'] = isset($available_callbacks[$fc_cb_ref]['icon'])
4475 - ? $available_callbacks[$fc_cb_ref]['icon']
4476 - : 'admin-generic';
4477 - }
4478 - unset($fc_tool_ref);
1110 + // Get total count for pagination
1111 + $total_intents = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name WHERE $where" );
1112 + $total_pages = ceil( $total_intents / $per_page );
4479 1113
4480 - // Count of ACTIVE tools — drives the AI Tools sidebar nav badge, mirroring
4481 - // $total_actions for Trigger Phrases. A tool in the list = active (plan
4482 - // d450a7), so the badge shows the same number the list pane shows (plan 5f7409).
4483 - $total_tools = count(array_filter($fc_tools, function ($t) {
4484 - return !empty($t['enabled']);
4485 - }));
1114 + // Fetch intents with pagination and filters
1115 + $intents = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE $where LIMIT %d OFFSET %d", $per_page, $offset ) );
4486 1116
4487 - // Brave-key dependency check (plan 183856): Web Search + Image Search run on
4488 - // the Brave Search API. If either is enabled as a tool but no brave_api_key is
4489 - // configured, surface a graceful "key not set" notice so the admin isn't met
4490 - // with a silently no-firing tool.
4491 - $fc_brave_missing = false;
4492 - $brave_key = isset($fc_options['brave_api_key']) ? trim($fc_options['brave_api_key']) : '';
4493 - if ($brave_key === '') {
4494 - foreach ($fc_tools as $fc_t) {
4495 - if (!empty($fc_t['enabled']) && isset($fc_t['requires_key']) && $fc_t['requires_key'] === 'brave_api_key') {
4496 - $fc_brave_missing = true;
4497 - break;
4498 - }
4499 - }
4500 - }
1117 + // Get available callback functions with 'pro_only' flag
1118 + $available_callbacks = $this->mxchat_get_available_callbacks();
1119 + ?>
4501 1120
4502 - // Prepare page data
4503 - $page_data = array(
4504 - 'total_actions' => $total_actions,
4505 - 'enabled_actions' => $enabled_actions,
4506 - 'disabled_actions' => $disabled_actions,
4507 - 'action_types_count' => $action_types_count,
4508 - 'action_type_distribution' => $action_type_distribution,
4509 - 'available_callbacks' => $available_callbacks,
4510 - 'callback_groups' => $callback_groups,
4511 - // AI Tools section
4512 - 'active_tab' => $active_tab,
4513 - 'fc_enabled' => MxChat_Tool_Registry::is_enabled(),
4514 - 'total_tools' => $total_tools,
4515 - 'fc_tools' => $fc_tools,
4516 - 'fc_current_model' => $fc_current_model,
4517 - 'fc_model_capable' => $fc_model_capable,
4518 - 'fc_brave_missing' => $fc_brave_missing,
4519 - 'fc_saved' => isset($_GET['mxchat_fc_saved']),
4520 - );
4521 -
4522 - // Include and render the new template
4523 - require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4524 - mxchat_render_actions_page($this, $page_data);
4525 -}
4526 -
4527 -/**
4528 - * LEGACY HTML - Preserved below for reference, to be removed in future update
4529 - */
4530 -function mxchat_actions_page_legacy_html() {
4531 - // This function is deprecated and no longer used
4532 - // The new template is in includes/admin-actions-page.php
4533 - ?>
4534 - <div class="wrap mxchat-wrapper">
4535 - <!-- Hero Section -->
4536 - <div class="mxchat-hero">
4537 - <h1 class="mxchat-main-title">
4538 - <span class="mxchat-gradient-text">Actions</span> Manager
4539 - </h1>
4540 - <p class="mxchat-hero-subtitle">
4541 - <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
1121 + <div class="wrap mxchat-admin">
1122 + <!-- Add Intent Form -->
1123 + <form id="mxchat-add-intent-form" method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
1124 + <input type="hidden" name="action" value="mxchat_add_intent">
1125 + <?php wp_nonce_field( 'mxchat_add_intent_nonce' ); ?>
1126 + <h2><?php esc_html_e( 'Add New Intent', 'mxchat' ); ?></h2>
1127 + <p class="description">
1128 + <?php esc_html_e( 'We highly encourage users to quickly read our ', 'mxchat' ); ?>
1129 + <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">
1130 + <?php esc_html_e( 'documentation', 'mxchat' ); ?>
1131 + </a>
1132 + <?php esc_html_e( ' to better understand intents. Some intents require setup in the Integration tab.', 'mxchat' ); ?>
4542 1133 </p>
4543 - </div>
4544 1134
4545 - <!-- Actions Header with Search and Filter -->
4546 - <div class="mxchat-actions-header">
4547 - <div class="mxchat-actions-filters">
4548 - <form method="get" class="mxchat-search-form">
4549 - <input type="hidden" name="page" value="mxchat-actions">
4550 - <div class="mxchat-search-group">
4551 - <span class="dashicons dashicons-search"></span>
4552 - <input type="text" name="s" class="mxchat-search-input"
4553 - placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
4554 - value="<?php echo esc_attr($search_term); ?>">
4555 - </div>
4556 - <select name="callback_filter" class="mxchat-action-filter">
4557 - <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
4558 - <?php foreach ($available_callbacks as $function => $callback_data) :
4559 - $label = $callback_data['label']; ?>
4560 - <option value="<?php echo esc_attr($function); ?>"
4561 - <?php selected($callback_filter, $function); ?>>
4562 - <?php echo esc_html($label); ?>
4563 - </option>
4564 - <?php endforeach; ?>
4565 - </select>
4566 - <button type="submit" class="mxchat-button-secondary">
4567 - <?php esc_html_e('Filter', 'mxchat'); ?>
4568 - </button>
4569 - </form>
1135 + <div class="mxchat-form-group">
1136 + <label for="intent_label"><?php esc_html_e( 'Intent Label (For your reference only)', 'mxchat' ); ?></label>
1137 + <input name="intent_label" type="text" id="intent_label" class="regular-text" required
1138 + placeholder="Example Email Capture: Newsletter Signup">
4570 1139 </div>
4571 - <div class="mxchat-actions-controls">
4572 - <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
4573 - <span class="dashicons dashicons-plus-alt"></span>
4574 - <?php esc_html_e('Add New Action', 'mxchat'); ?>
4575 - </button>
1140 + <div class="mxchat-form-group">
1141 + <label for="phrases"><?php esc_html_e( 'Phrases (comma-separated)', 'mxchat' ); ?></label>
1142 + <textarea name="phrases" id="phrases" rows="5" class="large-text" required
1143 + placeholder="Example Email Capture: sign me up, subscribe me, I want to join, add me to the newsletter, send me updates, keep me informed"></textarea>
4576 1144 </div>
4577 - </div>
4578 -
4579 - <!-- Actions Grid Layout - All actions in a single grid -->
4580 - <div class="mxchat-actions-grid">
4581 - <div class="mxchat-cards-container">
4582 - <?php if (!empty($actions)) : ?>
4583 - <?php foreach ($actions as $action) :
4584 - $callback_function = $action->callback_function;
4585 - $callback_label = isset($available_callbacks[$callback_function]['label'])
4586 - ? $available_callbacks[$callback_function]['label']
4587 - : $callback_function;
4588 - $threshold_value = isset($action->similarity_threshold)
4589 - ? round($action->similarity_threshold * 100)
4590 - : 85;
4591 -
4592 - // Check if this is a form action
4593 - $is_form_action = strpos($action->intent_label, 'Form ') === 0;
4594 -
4595 - // Get action status (enabled/disabled) - default to true if column doesn't exist
4596 - $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
4597 -
4598 - // Get enabled bots for display
4599 - $enabled_bots = [];
4600 - if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
4601 - $enabled_bots = json_decode($action->enabled_bots, true);
4602 - if (!is_array($enabled_bots)) {
4603 - $enabled_bots = ['default'];
4604 - }
4605 - } else {
4606 - $enabled_bots = ['default']; // Backward compatibility
4607 - }
4608 - ?>
4609 - <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
4610 - <div class="mxchat-card-header">
4611 - <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
4612 - <div class="mxchat-card-toggle">
4613 - <label class="mxchat-switch">
4614 - <input type="checkbox" class="mxchat-action-toggle"
4615 - data-action-id="<?php echo esc_attr($action->id); ?>"
4616 - <?php checked($is_enabled); ?>>
4617 - <span class="mxchat-slider round"></span>
4618 - </label>
4619 - </div>
4620 - </div>
4621 -
4622 - <div class="mxchat-card-body">
4623 - <div class="mxchat-card-description">
4624 - <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
4625 - <?php echo esc_html($callback_label); ?>
4626 - </div>
4627 -
4628 - <div class="mxchat-card-phrases">
4629 - <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
4630 - <div class="mxchat-phrases-preview">
4631 - <?php
4632 - // Check if the helper function exists, otherwise use a simple substring
4633 - if (method_exists($this, 'get_trimmed_phrases')) {
4634 - echo esc_html($this->get_trimmed_phrases($action->phrases));
4635 - } else {
4636 - echo esc_html(strlen($action->phrases) > 100 ?
4637 - substr($action->phrases, 0, 97) . '...' :
4638 - $action->phrases);
4639 - }
4640 - ?>
4641 - </div>
4642 - </div>
4643 -
4644 - <div class="mxchat-threshold-control">
4645 - <div class="mxchat-threshold-label">
4646 - <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
4647 - <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
4648 - </div>
4649 - </div>
4650 -
4651 - <!-- Bot Availability Display (Read-only) -->
4652 - <div class="mxchat-card-bots">
4653 - <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
4654 - <div class="mxchat-bot-badges">
4655 - <?php
4656 - foreach ($enabled_bots as $bot_id) {
4657 - if ($bot_id === 'default') {
4658 - echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
4659 - } else {
4660 - // Try to get bot name from multi-bot manager
4661 - if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
4662 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4663 - $available_bots = $multi_bot_manager->get_available_bots();
4664 - $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
4665 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
4666 - } else {
4667 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
4668 - }
4669 - }
4670 - }
4671 - ?>
4672 - </div>
4673 - </div>
4674 - </div>
4675 -
4676 - <div class="mxchat-card-footer">
4677 - <?php
4678 - // Check if it's a form action
4679 - $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
4680 -
4681 - // Check if it's a recommendation flow action
4682 - $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
4683 -
4684 - if ($is_form_action) {
4685 - $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
4686 - ?>
4687 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
4688 - class="mxchat-button-primary">
4689 - <span class="dashicons dashicons-feedback"></span>
4690 - <?php esc_html_e('Edit Form', 'mxchat'); ?>
4691 - </a>
4692 - <?php } elseif ($is_flow_action) {
4693 - ?>
4694 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
4695 - class="mxchat-button-primary">
4696 - <span class="dashicons dashicons-list-view"></span>
4697 - <?php esc_html_e('Manage Flows', 'mxchat'); ?>
4698 - </a>
4699 - <?php } else { ?>
4700 - <button type="button"
4701 - class="mxchat-button-secondary mxchat-edit-button"
4702 - data-action-id="<?php echo esc_attr($action->id); ?>"
4703 - data-phrases="<?php echo esc_attr($action->phrases); ?>"
4704 - data-label="<?php echo esc_attr($action->intent_label); ?>"
4705 - data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
4706 - data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
4707 - data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
4708 - <span class="dashicons dashicons-edit"></span>
4709 - <?php esc_html_e('Edit', 'mxchat'); ?>
4710 - </button>
4711 - <form method="post"
4712 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
4713 - class="mxchat-delete-form"
4714 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
4715 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
4716 - <input type="hidden" name="action" value="mxchat_delete_intent">
4717 - <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
4718 - <button type="submit" class="mxchat-button-text mxchat-delete-button">
4719 - <span class="dashicons dashicons-trash"></span>
4720 - <?php esc_html_e('Delete', 'mxchat'); ?>
4721 - </button>
4722 - </form>
4723 - <?php } ?>
4724 - </div>
4725 - </div>
1145 + <div class="mxchat-form-group">
1146 + <label for="callback_function"><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></label>
1147 + <select name="callback_function" id="callback_function" required>
1148 + <option value=""><?php esc_html_e( 'Select a Callback', 'mxchat' ); ?></option>
1149 + <?php foreach ( $available_callbacks as $function => $callback_data ) : ?>
1150 + <?php
1151 + $label = $callback_data['label'];
1152 + $pro_only = $callback_data['pro_only'];
1153 + $disabled = ( ! $this->is_activated && $pro_only ) ? 'disabled' : '';
1154 + $label_suffix = ( ! $this->is_activated && $pro_only ) ? ' (Pro Only)' : '';
1155 + ?>
1156 + <option value="<?php echo esc_attr( $function ); ?>" <?php echo $disabled; ?>>
1157 + <?php echo esc_html( $label . $label_suffix ); ?>
1158 + </option>
4726 1159 <?php endforeach; ?>
4727 - <?php else : ?>
4728 - <!-- If no actions found -->
4729 - <div class="mxchat-no-actions">
4730 - <div class="mxchat-empty-state">
4731 - <span class="dashicons dashicons-format-chat"></span>
4732 - <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4733 - <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4734 - <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4735 - <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4736 - </button>
4737 - </div>
4738 - </div>
4739 - <?php endif; ?>
1160 + </select>
4740 1161 </div>
1162 + <button type="submit" class="button button-primary submit-content-button">
1163 + <?php esc_html_e( 'Add Intent', 'mxchat' ); ?>
1164 + </button>
1165 + <div id="mxchat-intent-loading" style="display: none;"></div>
1166 + <div id="mxchat-intent-loading-text" style="display: none;">
1167 + <?php esc_html_e( 'Saving intent, please wait...', 'mxchat' ); ?>
4741 1168 </div>
4742 1169
4743 - <?php if ($total_pages > 1) : ?>
4744 - <div class="mxchat-pagination">
4745 - <?php
4746 - echo paginate_links(array(
4747 - 'base' => add_query_arg('paged', '%#%'),
4748 - 'format' => '',
4749 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4750 - 'next_text' => __('Next &raquo;', 'mxchat'),
4751 - 'total' => $total_pages,
4752 - 'current' => $page
4753 - ));
4754 - ?>
4755 - </div>
4756 - <?php endif; ?>
1170 + </form>
4757 1171
4758 -<!-- Add/Edit Action Modal with Step-Based Approach -->
4759 -<!-- Complete Modal HTML with Defined Groups Variable -->
4760 -<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
4761 - <div class="mxchat-modal-content">
4762 - <span class="mxchat-modal-close">&times;</span>
4763 -
4764 - <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4765 - <!-- Dynamic nonce field -->
4766 - <div id="action-nonce-container">
4767 - <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
1172 + <!-- Filter Form -->
1173 + <form method="get" action="">
1174 + <input type="hidden" name="page" value="mxchat-intents">
1175 + <div class="mxchat-search-group">
1176 + <input type="text" name="s" id="mxchat-intent-search" placeholder="<?php esc_attr_e( 'Search Intents', 'mxchat' ); ?>" value="<?php echo esc_attr( $search_term ); ?>">
1177 + <select name="callback_filter" id="mxchat-callback-filter">
1178 + <option value=""><?php esc_html_e( 'All Callbacks', 'mxchat' ); ?></option>
1179 + <?php foreach ( $available_callbacks as $function => $callback_data ) : ?>
1180 + <?php $label = $callback_data['label']; ?>
1181 + <option value="<?php echo esc_attr( $function ); ?>" <?php selected( $callback_filter, $function ); ?>><?php echo esc_html( $label ); ?></option>
1182 + <?php endforeach; ?>
1183 + </select>
1184 + <button type="submit" class="button"><?php esc_html_e( 'Filter', 'mxchat' ); ?></button>
4768 1185 </div>
4769 - <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4770 - <input type="hidden" name="intent_id" id="edit_action_id" value="">
4771 - <input type="hidden" name="callback_function" id="callback_function" value="">
1186 + </form>
4772 1187
4773 - <!-- Step 1: Action Type Selection -->
4774 - <div id="mxchat-action-step-1" class="mxchat-action-step active">
4775 - <div class="mxchat-step-indicator">
4776 - <div class="mxchat-step-number">1</div>
4777 - <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4778 - </div>
4779 -
4780 - <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4781 - <div class="mxchat-action-type-search">
4782 - <span class="dashicons dashicons-search"></span>
4783 - <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4784 - </div>
4785 -
4786 - <?php
4787 - // Get the callbacks - IMPORTANT: Define the $groups variable here
4788 - $groups = $this->mxchat_get_available_callbacks(true, true);
4789 - ?>
4790 -
4791 - <div class="mxchat-action-type-categories">
4792 - <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
1188 + <!-- Intents Table -->
1189 + <table class="wp-list-table mxchat-intents-table widefat fixed striped">
1190 + <thead>
1191 + <tr>
1192 + <th><?php esc_html_e( 'Intent Label', 'mxchat' ); ?></th>
1193 + <th><?php esc_html_e( 'Phrases', 'mxchat' ); ?></th>
1194 + <th><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></th>
1195 + <th><?php esc_html_e( 'Similarity Threshold', 'mxchat' ); ?></th>
1196 + <th><?php esc_html_e( 'Actions', 'mxchat' ); ?></th>
1197 + </tr>
1198 + </thead>
1199 + <tbody>
1200 + <?php if ( $intents ) : ?>
1201 + <?php foreach ( $intents as $intent ) : ?>
4793 1202 <?php
4794 - // Get unique categories from the defined groups
4795 - foreach ($groups as $group_label => $group_callbacks) :
4796 - $category_slug = sanitize_title($group_label);
1203 + $callback_function = $intent->callback_function;
1204 + $callback_label = isset( $available_callbacks[ $callback_function ]['label'] ) ? $available_callbacks[ $callback_function ]['label'] : $callback_function;
1205 + $threshold_value = isset( $intent->similarity_threshold ) ? round( $intent->similarity_threshold * 100 ) : 85;
4797 1206 ?>
4798 - <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4799 - <?php endforeach; ?>
4800 - </div>
4801 -
4802 - <div class="mxchat-action-types-grid">
4803 - <?php
4804 - // Generate action cards from available callbacks
4805 - foreach ($groups as $group_label => $group_callbacks) :
4806 - $category_slug = sanitize_title($group_label);
4807 -
4808 - foreach ($group_callbacks as $function => $data) :
4809 - $label = $data['label'];
4810 - $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4811 - $description = isset($data['description']) ? $data['description'] : '';
4812 - $is_addon = isset($data['addon']) && $data['addon'] !== false;
4813 - $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4814 - $is_installed = isset($data['installed']) ? $data['installed'] : true;
4815 - $is_promo = !empty($data['addon_promo']) && !$is_installed;
4816 -
4817 - // Determine card status and styling
4818 - $card_class = 'mxchat-action-type-card';
4819 - $icon_class = 'mxchat-action-type-icon';
4820 - $status_badge = '';
4821 -
4822 - if ($is_promo) {
4823 - // Promotional card — not selectable, just informational
4824 - $card_class .= ' not-installed mxchat-promo-card';
4825 - $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4826 - } elseif ($is_addon && !$is_installed) {
4827 - // Add-on not installed
4828 - $card_class .= ' not-installed';
4829 - $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4830 - }
4831 -
4832 - // Default description if none provided
4833 - if (empty($description)) {
4834 - $description = sprintf(
4835 - esc_html__('Use the %s action in your chatbot', 'mxchat'),
4836 - $label
4837 - );
4838 - }
4839 - ?>
4840 - <div class="<?php echo esc_attr($card_class); ?>"
4841 - data-category="<?php echo esc_attr($category_slug); ?>"
4842 - <?php if (!$is_promo) : ?>
4843 - data-value="<?php echo esc_attr($function); ?>"
4844 - data-label="<?php echo esc_attr($label); ?>"
4845 - <?php endif; ?>
4846 - data-pro="false"
4847 - data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4848 - data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
4849 - <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
4850 - <div class="<?php echo esc_attr($icon_class); ?>">
4851 - <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4852 - </div>
4853 - <div class="mxchat-action-type-info">
4854 - <h4><?php echo esc_html($label); ?></h4>
4855 - <p><?php echo esc_html($description); ?></p>
4856 - <?php if (!empty($status_badge)) : ?>
4857 - <?php echo $status_badge; ?>
4858 - <?php endif; ?>
4859 -
4860 - <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
4861 - <div class="mxchat-addon-info">
4862 - <?php echo esc_html(sprintf(
4863 - __('Requires %s', 'mxchat'),
4864 - $addon_name
4865 - )); ?>
4866 - — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
4867 - </div>
4868 - <?php endif; ?>
4869 - </div>
4870 - </div>
4871 - <?php endforeach;
4872 - endforeach; ?>
4873 - </div>
4874 - </div>
4875 -
4876 - <div class="mxchat-modal-actions">
4877 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4878 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4879 - </button>
4880 - </div>
4881 - </div>
4882 -
4883 - <!-- Step 2: Action Configuration -->
4884 - <div id="mxchat-action-step-2" class="mxchat-action-step">
4885 - <div class="mxchat-step-indicator">
4886 - <div class="mxchat-step-number">2</div>
4887 - <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4888 - </div>
4889 -
4890 - <div class="mxchat-selected-action">
4891 - <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
4892 - <span class="dashicons dashicons-arrow-left-alt"></span>
4893 - <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
4894 - </button>
4895 - <div class="mxchat-selected-action-info">
4896 - <div id="selected-action-icon" class="mxchat-action-type-icon">
4897 - <span class="dashicons dashicons-admin-generic"></span>
4898 - </div>
4899 - <div class="mxchat-selected-action-details">
4900 - <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
4901 - <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
4902 - </div>
4903 - </div>
4904 - </div>
4905 -
4906 - <div class="mxchat-form-group">
4907 - <label for="intent_label">
4908 - <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
4909 - </label>
4910 - <input name="intent_label" type="text" id="intent_label" required
4911 - class="mxchat-intent-input"
4912 - placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
4913 - </div>
4914 -
4915 - <div class="mxchat-form-group">
4916 - <label for="phrases">
4917 - <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
4918 - </label>
4919 - <textarea name="phrases" id="action_phrases" rows="5" required
4920 - class="mxchat-intent-textarea"
4921 - placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
4922 - </div>
4923 -
4924 - <div class="mxchat-form-group">
4925 - <label for="similarity_threshold">
4926 - <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
4927 - <span class="mxchat-threshold-value-display">85%</span>
4928 - </label>
4929 - <div class="mxchat-slider-group modal-slider">
4930 - <input type="range"
4931 - name="similarity_threshold"
4932 - id="similarity_threshold"
4933 - min="10"
4934 - max="95"
4935 - value="85"
4936 - class="mxchat-intent-slider"
4937 - oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
4938 - </div>
4939 - <div class="mxchat-threshold-hint">
4940 - <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
4941 - </div>
4942 - </div>
4943 -
4944 - <!-- Bot Selection Section -->
4945 - <div class="mxchat-form-group">
4946 - <label for="enabled_bots">
4947 - <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
4948 - </label>
4949 - <div class="mxchat-bot-selector">
4950 - <div class="mxchat-bot-option">
4951 - <label class="mxchat-checkbox-label">
4952 - <input type="checkbox"
4953 - name="enabled_bots[]"
4954 - value="default"
4955 - id="bot_default"
4956 - checked="checked">
4957 - <span class="mxchat-checkmark"></span>
4958 - <?php esc_html_e('Default Bot', 'mxchat'); ?>
4959 - </label>
4960 - </div>
4961 -
4962 - <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
4963 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4964 - $available_bots = $multi_bot_manager->get_available_bots();
4965 -
4966 - foreach ($available_bots as $bot_id => $bot_name) :
4967 - if ($bot_id === 'default') continue; // Skip default, already shown above
4968 - ?>
4969 - <div class="mxchat-bot-option">
4970 - <label class="mxchat-checkbox-label">
4971 - <input type="checkbox"
4972 - name="enabled_bots[]"
4973 - value="<?php echo esc_attr($bot_id); ?>"
4974 - id="bot_<?php echo esc_attr($bot_id); ?>">
4975 - <span class="mxchat-checkmark"></span>
4976 - <?php echo esc_html($bot_name); ?>
4977 - </label>
4978 - </div>
4979 - <?php
4980 - endforeach;
4981 - endif; ?>
4982 - </div>
4983 - </div>
4984 -
4985 - <div class="mxchat-modal-actions">
4986 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4987 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4988 - </button>
4989 - <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
4990 - <?php esc_html_e('Save Action', 'mxchat'); ?>
4991 - </button>
4992 - </div>
4993 - </div>
4994 - </form>
1207 + <tr>
1208 + <td><?php echo esc_html( $intent->intent_label ); ?></td>
1209 + <td><?php echo esc_html( $intent->phrases ); ?></td>
1210 + <td><?php echo esc_html( $callback_label ); ?></td>
1211 + <!-- Similarity Threshold Column -->
1212 + <td>
1213 + <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
1214 + <?php wp_nonce_field( 'mxchat_update_intent_threshold_nonce' ); ?>
1215 + <input type="hidden" name="action" value="mxchat_update_intent_threshold">
1216 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
1217 + <input type="range" name="intent_threshold" id="intent_threshold_<?php echo esc_attr( $intent->id ); ?>" min="70" max="95" value="<?php echo esc_attr( $threshold_value ); ?>" oninput="document.getElementById('threshold_output_<?php echo esc_attr( $intent->id ); ?>').value = this.value + '%'">
1218 + <output id="threshold_output_<?php echo esc_attr( $intent->id ); ?>"><?php echo esc_html( $threshold_value ); ?>%</output>
1219 + </td>
1220 + <!-- Actions Column -->
1221 + <td>
1222 + <button type="submit" class="button button-primary mxchat-save-button">
1223 + <?php esc_html_e( 'Save', 'mxchat' ); ?>
1224 + </button>
1225 + </form>
1226 + <!-- Delete Form -->
1227 + <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" onsubmit="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this intent?', 'mxchat' ); ?>');">
1228 + <?php wp_nonce_field( 'mxchat_delete_intent_nonce' ); ?>
1229 + <input type="hidden" name="action" value="mxchat_delete_intent">
1230 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
1231 + <button type="submit" class="button mxchat-delete-all">
1232 + <?php esc_html_e( 'Delete', 'mxchat' ); ?>
1233 + </button>
1234 + </form>
1235 + </td>
1236 + </tr>
1237 + <?php endforeach; ?>
1238 + <?php else : ?>
1239 + <tr>
1240 + <td colspan="5"><?php esc_html_e( 'No intents found.', 'mxchat' ); ?></td>
1241 + </tr>
1242 + <?php endif; ?>
1243 + </tbody>
1244 + </table>
4995 1245 </div>
4996 -</div>
4997 -
4998 -<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
4999 - <div class="mxchat-action-loading-spinner"></div>
5000 - <div class="mxchat-action-loading-text">
5001 - <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
5002 - </div>
5003 -</div>
5004 - </div><!-- .mxchat-wrapper -->
5005 1246 <?php
5006 1247 }
5007 -private function get_trimmed_phrases($phrases, $max_length = 100) {
5008 - if (strlen($phrases) <= $max_length) {
5009 - return $phrases;
5010 - }
5011 1248
5012 - $trimmed = substr($phrases, 0, $max_length);
5013 - $last_comma = strrpos($trimmed, ',');
5014 1249
5015 - if ($last_comma !== false) {
5016 - $trimmed = substr($trimmed, 0, $last_comma);
5017 - }
5018 -
5019 - return $trimmed . '...';
5020 -}
5021 -public function mxchat_add_enabled_column_to_intents() {
5022 - global $wpdb;
5023 - $table_name = $wpdb->prefix . 'mxchat_intents';
5024 -
5025 - // Check if the column already exists
5026 - $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
5027 -
5028 - if (empty($columns)) {
5029 - // Add the column with default value of 1 (enabled)
5030 - $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
5031 - }
5032 -}
5033 -
5034 -public function mxchat_handle_delete_intent() {
1250 +public function mxchat_handle_update_intent_threshold() {
5035 1251 if ( ! current_user_can( 'manage_options' ) ) {
5036 1252 wp_die( esc_html__('Unauthorized user', 'mxchat') );
5037 1253 }
5038 1254
5039 - check_admin_referer('mxchat_delete_intent_nonce');
1255 + check_admin_referer('mxchat_update_intent_threshold_nonce');
5040 1256
5041 - if (isset($_POST['intent_id'])) {
1257 + if (isset($_POST['intent_id'], $_POST['intent_threshold'])) {
5042 1258 global $wpdb;
5043 1259 $table_name = $wpdb->prefix . 'mxchat_intents';
5044 1260 $intent_id = intval($_POST['intent_id']);
1261 + $threshold_percentage = max(70, min(95, intval($_POST['intent_threshold'])));
1262 + $similarity_threshold = $threshold_percentage / 100;
5045 1263
5046 - $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
1264 + $wpdb->update(
1265 + $table_name,
1266 + ['similarity_threshold' => $similarity_threshold],
1267 + ['id' => $intent_id],
1268 + ['%f'],
1269 + ['%d']
1270 + );
5047 1271 }
5048 1272
5049 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
1273 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
5050 1274 exit;
5051 1275 }
5052 -public function mxchat_handle_edit_intent() {
5053 - // Security checks (nonce and permissions)
5054 - if (!current_user_can('manage_options')) {
5055 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5056 - }
5057 - check_admin_referer('mxchat_edit_intent');
5058 1276
5059 - // Get POST data
5060 - $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
5061 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5062 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5063 - $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
5064 - $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
5065 1277
5066 - // Handle enabled_bots
5067 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5068 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5069 -
5070 - // Ensure default is always included for backward compatibility
5071 - if (!in_array('default', $enabled_bots)) {
5072 - $enabled_bots[] = 'default';
1278 +public function mxchat_handle_add_intent() {
1279 + if ( ! current_user_can( 'manage_options' ) ) {
1280 + wp_die( esc_html__('Unauthorized user', 'mxchat') );
5073 1281 }
5074 -
5075 - $enabled_bots_json = json_encode($enabled_bots);
5076 1282
5077 - // Validate inputs
5078 - if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
5079 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5080 - return;
5081 - }
1283 + check_admin_referer('mxchat_add_intent_nonce');
5082 1284
5083 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5084 - if (empty($phrases_array)) {
5085 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5086 - return;
5087 - }
5088 -
5089 - // Generate embeddings with improved error handling
5090 - $vectors = [];
5091 - $failed_phrases = [];
5092 -
5093 - foreach ($phrases_array as $phrase) {
5094 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5095 - if (is_array($embedding_vector)) {
5096 - $vectors[] = $embedding_vector;
5097 - } else {
5098 - $failed_phrases[] = $phrase;
5099 - }
5100 - }
5101 -
5102 - if (!empty($failed_phrases)) {
5103 - $this->handle_embedding_error(
5104 - sprintf(
5105 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5106 - implode(', ', $failed_phrases)
5107 - )
5108 - );
5109 - return;
5110 - }
5111 -
5112 - if (empty($vectors)) {
5113 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5114 - return;
5115 - }
5116 -
5117 - $combined_vector = $this->mxchat_average_vectors($vectors);
5118 - $serialized_vector = maybe_serialize($combined_vector);
5119 -
5120 - // Update the database
5121 1285 global $wpdb;
5122 1286 $table_name = $wpdb->prefix . 'mxchat_intents';
5123 1287
5124 - $result = $wpdb->update(
5125 - $table_name,
5126 - array(
5127 - 'intent_label' => $intent_label,
5128 - 'phrases' => implode(', ', $phrases_array),
5129 - 'embedding_vector' => $serialized_vector,
5130 - 'similarity_threshold' => $similarity_threshold,
5131 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
5132 - ),
5133 - array('id' => $intent_id),
5134 - array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
5135 - array('%d') // Where format: integer
5136 - );
5137 -
5138 - if (false === $result) {
5139 - $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
5140 - return;
5141 - }
5142 -
5143 - // Set success message and redirect
5144 - set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
5145 -
5146 - $redirect_url = add_query_arg(
5147 - array(
5148 - 'page' => 'mxchat-actions'
5149 - ),
5150 - admin_url('admin.php')
5151 - );
5152 - wp_safe_redirect($redirect_url);
5153 - exit;
5154 -}
5155 -public function mxchat_handle_add_intent() {
5156 - if (!current_user_can('manage_options')) {
5157 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
5158 - }
5159 - check_admin_referer('mxchat_add_intent_nonce');
5160 - global $wpdb;
5161 - $table_name = $wpdb->prefix . 'mxchat_intents';
5162 -
5163 - // Sanitize and get form data
5164 1288 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5165 1289 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5166 1290 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5167 -
5168 - // Get similarity threshold from form (convert percentage to decimal)
5169 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5170 -
5171 - // Handle enabled_bots
5172 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
5173 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
5174 -
5175 - // Ensure default is always included for backward compatibility with existing actions
5176 - if (!in_array('default', $enabled_bots)) {
5177 - $enabled_bots[] = 'default';
5178 - }
5179 -
5180 - $enabled_bots_json = json_encode($enabled_bots);
5181 -
5182 - // Validate required fields
1291 + $default_threshold = 0.85;
1292 +
5183 1293 if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
5184 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
5185 - return;
1294 + wp_die( esc_html__('Invalid input. Please ensure all fields are filled out.', 'mxchat') );
5186 1295 }
5187 -
5188 - // Validate callback function
1296 +
5189 1297 $available_callbacks = $this->mxchat_get_available_callbacks();
1298 +
5190 1299 if (!array_key_exists($callback_function, $available_callbacks)) {
5191 - $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
5192 - return;
1300 + wp_die( esc_html__('Invalid callback function selected.', 'mxchat') );
5193 1301 }
5194 -
5195 - // Check if this is an add-on promotional placeholder (not a real action)
5196 - if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
5197 - $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
5198 - $this->handle_embedding_error(sprintf(
5199 - __('This action requires the %s to be installed and activated.', 'mxchat'),
5200 - $addon_name
5201 - ));
5202 - return;
1302 +
1303 + $is_pro_only = $available_callbacks[$callback_function]['pro_only'];
1304 + if ($is_pro_only && !$this->is_activated) {
1305 + wp_die( esc_html__('This callback function is available in the Pro version only.', 'mxchat') );
5203 1306 }
5204 -
5205 - // Process phrases
1307 +
5206 1308 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
1309 +
5207 1310 if (empty($phrases_array)) {
5208 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
5209 - return;
1311 + wp_die( esc_html__('Please enter at least one valid phrase.', 'mxchat') );
5210 1312 }
5211 -
5212 - // Generate embeddings with improved error handling
1313 +
5213 1314 $vectors = [];
5214 - $failed_phrases = [];
5215 1315 foreach ($phrases_array as $phrase) {
5216 1316 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
5217 1317 if (is_array($embedding_vector)) {
5218 1318 $vectors[] = $embedding_vector;
5219 1319 } else {
5220 - $failed_phrases[] = $phrase;
1320 + wp_die( esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase) );
5221 1321 }
5222 1322 }
5223 -
5224 - // Check for embedding failures
5225 - if (!empty($failed_phrases)) {
5226 - $this->handle_embedding_error(
5227 - sprintf(
5228 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
5229 - implode(', ', $failed_phrases)
5230 - )
5231 - );
5232 - return;
5233 - }
5234 -
5235 - if (empty($vectors)) {
5236 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
5237 - return;
5238 - }
5239 -
5240 - // Create combined vector and insert into database
5241 - $combined_vector = $this->mxchat_average_vectors($vectors);
5242 - $serialized_vector = maybe_serialize($combined_vector);
5243 -
5244 - $result = $wpdb->insert($table_name, [
5245 - 'intent_label' => $intent_label,
5246 - 'phrases' => implode(', ', $phrases_array),
5247 - 'embedding_vector' => $serialized_vector,
5248 - 'callback_function' => $callback_function,
5249 - 'similarity_threshold' => $similarity_threshold,
5250 - 'enabled_bots' => $enabled_bots_json, // NEW field
5251 - ]);
5252 -
5253 - if ($result === false) {
5254 - $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
5255 - return;
5256 - }
5257 -
5258 - // Set success message and redirect
5259 - set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
5260 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
5261 - exit;
5262 -}
5263 1323
1324 + if (!empty($vectors)) {
1325 + $combined_vector = $this->mxchat_average_vectors($vectors);
1326 + $serialized_vector = maybe_serialize($combined_vector);
5264 1327
1328 + $result = $wpdb->insert($table_name, [
1329 + 'intent_label' => $intent_label,
1330 + 'phrases' => implode(', ', $phrases_array),
1331 + 'embedding_vector' => $serialized_vector,
1332 + 'callback_function' => $callback_function,
1333 + 'similarity_threshold' => $default_threshold,
1334 + ]);
5265 1335
5266 -
5267 -private function handle_embedding_error($message, $redirect = true) {
5268 - // Store the error message in the existing transient
5269 - set_transient('mxchat_admin_notice_error', $message, 60);
5270 -
5271 - if ($redirect) {
5272 - // Redirect back to the actions page
5273 - $redirect_url = add_query_arg(
5274 - array(
5275 - 'page' => 'mxchat-actions'
5276 - ),
5277 - admin_url('admin.php')
5278 - );
5279 - wp_safe_redirect($redirect_url);
5280 - exit;
5281 - }
5282 -}
5283 -
5284 -/**
5285 - * AJAX handler to fetch actions list for the new split-panel UI
5286 - */
5287 -public function mxchat_fetch_actions_list() {
5288 - check_ajax_referer('mxchat_actions_nonce', 'security');
5289 -
5290 - if (!current_user_can('manage_options')) {
5291 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5292 - }
5293 -
5294 - global $wpdb;
5295 - $table_name = $wpdb->prefix . 'mxchat_intents';
5296 -
5297 - $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
5298 - $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
5299 - $offset = ($page - 1) * $per_page;
5300 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
5301 - $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
5302 - $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
5303 -
5304 - // Build WHERE clause
5305 - $where = '1=1';
5306 - $params = array();
5307 -
5308 - if ($search) {
5309 - $search_like = '%' . $wpdb->esc_like($search) . '%';
5310 - $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
5311 - $params[] = $search_like;
5312 - $params[] = $search_like;
5313 - }
5314 -
5315 - if ($callback_filter) {
5316 - $where .= ' AND callback_function = %s';
5317 - $params[] = $callback_filter;
5318 - }
5319 -
5320 - // Get total count
5321 - $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
5322 - if (!empty($params)) {
5323 - $count_query = $wpdb->prepare($count_query, $params);
5324 - }
5325 - $total_actions = $wpdb->get_var($count_query);
5326 -
5327 - // Get actions
5328 - $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
5329 - $all_params = array_merge($params, array($per_page, $offset));
5330 - $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
5331 -
5332 - // Get available callbacks for labels/icons
5333 - $available_callbacks = $this->mxchat_get_available_callbacks();
5334 -
5335 - // Prefetch individual phrase counts for all fetched actions
5336 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5337 - $phrase_counts = array();
5338 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5339 - $action_ids = wp_list_pluck($actions, 'id');
5340 - if (!empty($action_ids)) {
5341 - $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5342 - $count_results = $wpdb->get_results($wpdb->prepare(
5343 - "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
5344 - $action_ids
5345 - ));
5346 - foreach ($count_results as $row) {
5347 - $phrase_counts[$row->intent_id] = intval($row->cnt);
5348 - }
5349 - }
5350 - }
5351 -
5352 - // Format actions for response
5353 - $formatted_actions = array();
5354 - foreach ($actions as $action) {
5355 - $callback_data = isset($available_callbacks[$action->callback_function])
5356 - ? $available_callbacks[$action->callback_function]
5357 - : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5358 -
5359 - $enabled_bots = json_decode($action->enabled_bots, true);
5360 - if (!is_array($enabled_bots)) {
5361 - $enabled_bots = array('default');
5362 - }
5363 -
5364 - $formatted_actions[] = array(
5365 - 'id' => intval($action->id),
5366 - 'label' => $action->intent_label,
5367 - 'phrases' => $action->phrases,
5368 - 'callback_function' => $action->callback_function,
5369 - 'callback_label' => $callback_data['label'],
5370 - 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5371 - 'threshold' => round($action->similarity_threshold * 100),
5372 - 'enabled' => (bool) $action->enabled,
5373 - 'enabled_bots' => $enabled_bots,
5374 - 'has_legacy_vector' => !empty($action->embedding_vector),
5375 - 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5376 - );
5377 - }
5378 -
5379 - $total_pages = ceil($total_actions / $per_page);
5380 - $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5381 - $showing_end = min($offset + $per_page, $total_actions);
5382 -
5383 - wp_send_json_success(array(
5384 - 'actions' => $formatted_actions,
5385 - 'page' => $page,
5386 - 'per_page' => $per_page,
5387 - 'total_actions' => intval($total_actions),
5388 - 'total_pages' => $total_pages,
5389 - 'showing_start' => $showing_start,
5390 - 'showing_end' => $showing_end,
5391 - ));
5392 -}
5393 -
5394 -/**
5395 - * AJAX handler to toggle action enabled status
5396 - */
5397 -public function mxchat_toggle_action_status() {
5398 - check_ajax_referer('mxchat_actions_nonce', 'security');
5399 -
5400 - if (!current_user_can('manage_options')) {
5401 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5402 - }
5403 -
5404 - $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5405 - $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
5406 -
5407 - if (!$action_id) {
5408 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5409 - }
5410 -
5411 - global $wpdb;
5412 - $table_name = $wpdb->prefix . 'mxchat_intents';
5413 -
5414 - $result = $wpdb->update(
5415 - $table_name,
5416 - array('enabled' => $enabled ? 1 : 0),
5417 - array('id' => $action_id),
5418 - array('%d'),
5419 - array('%d')
5420 - );
5421 -
5422 - if ($result === false) {
5423 - wp_send_json_error(__('Failed to update action status', 'mxchat'));
5424 - }
5425 -
5426 - wp_send_json_success(array('enabled' => (bool) $enabled));
5427 -}
5428 -
5429 -/**
5430 - * AJAX handler to bulk delete actions
5431 - */
5432 -public function mxchat_bulk_delete_actions() {
5433 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5434 -
5435 - if (!current_user_can('manage_options')) {
5436 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5437 - }
5438 -
5439 - $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5440 -
5441 - if (empty($action_ids)) {
5442 - wp_send_json_error(__('No actions selected', 'mxchat'));
5443 - }
5444 -
5445 - global $wpdb;
5446 - $table_name = $wpdb->prefix . 'mxchat_intents';
5447 -
5448 - $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5449 - $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5450 - $result = $wpdb->query($query);
5451 -
5452 - if ($result === false) {
5453 - wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5454 - }
5455 -
5456 - // Also delete individual phrases for these intents
5457 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5458 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5459 - $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5460 - }
5461 -
5462 - wp_send_json_success(array('deleted' => $result));
5463 -}
5464 -
5465 -/**
5466 - * AJAX handler to add a new intent/action
5467 - */
5468 -public function mxchat_add_intent_ajax() {
5469 - check_ajax_referer('mxchat_add_intent_nonce', 'security');
5470 -
5471 - if (!current_user_can('manage_options')) {
5472 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5473 - }
5474 -
5475 - global $wpdb;
5476 - $table_name = $wpdb->prefix . 'mxchat_intents';
5477 -
5478 - // Sanitize input
5479 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5480 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5481 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5482 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5483 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5484 -
5485 - // Validate
5486 - // Check if using new individual phrases mode or legacy mode
5487 - $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5488 - $use_individual = !empty($individual_phrases);
5489 -
5490 - // Validate required fields (phrases not required when using individual mode)
5491 - if (empty($intent_label) || empty($callback_function)) {
5492 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5493 - }
5494 - if (!$use_individual && empty($phrases_input)) {
5495 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5496 - }
5497 -
5498 - // Ensure default bot is included
5499 - if (!in_array('default', $enabled_bots)) {
5500 - $enabled_bots[] = 'default';
5501 - }
5502 - $enabled_bots_json = json_encode($enabled_bots);
5503 -
5504 - if ($use_individual) {
5505 - // New mode: individual phrases each get their own vector
5506 - // Insert the intent row with empty legacy fields
5507 - $result = $wpdb->insert(
5508 - $table_name,
5509 - array(
5510 - 'intent_label' => $intent_label,
5511 - 'phrases' => '',
5512 - 'embedding_vector' => '',
5513 - 'similarity_threshold' => $similarity_threshold,
5514 - 'callback_function' => $callback_function,
5515 - 'enabled' => 1,
5516 - 'enabled_bots' => $enabled_bots_json,
5517 - )
5518 - );
5519 -
5520 1336 if ($result === false) {
5521 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
1337 + wp_die( esc_html__('Database error: ', 'mxchat') . esc_html($wpdb->last_error) );
5522 1338 }
5523 -
5524 - $intent_id = $wpdb->insert_id;
5525 -
5526 - // Insert each phrase individually with its own embedding
5527 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5528 - $failed_phrases = array();
5529 - foreach ($individual_phrases as $phrase) {
5530 - $phrase = trim($phrase);
5531 - if (empty($phrase)) continue;
5532 -
5533 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5534 - if (is_wp_error($embedding_vector)) {
5535 - $failed_phrases[] = $phrase;
5536 - continue;
5537 - }
5538 -
5539 - $wpdb->insert(
5540 - $phrases_table,
5541 - array(
5542 - 'intent_id' => $intent_id,
5543 - 'phrase' => $phrase,
5544 - 'embedding_vector' => maybe_serialize($embedding_vector),
5545 - )
5546 - );
5547 - }
5548 -
5549 - $response = array('id' => $intent_id);
5550 - if (!empty($failed_phrases)) {
5551 - $response['failed_phrases'] = $failed_phrases;
5552 - }
5553 - wp_send_json_success($response);
5554 -
5555 1339 } else {
5556 - // Legacy mode: combine all phrases into one embedding (backwards compatible)
5557 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5558 - if (empty($phrases_array)) {
5559 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5560 - }
5561 -
5562 - // Generate embedding (combine phrases into single string for embedding)
5563 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5564 - if (is_wp_error($embedding_vector)) {
5565 - // Fallback: store without embedding
5566 - $serialized_vector = null;
5567 - } else {
5568 - $serialized_vector = maybe_serialize($embedding_vector);
5569 - }
5570 -
5571 - // Insert
5572 - $result = $wpdb->insert(
5573 - $table_name,
5574 - array(
5575 - 'intent_label' => $intent_label,
5576 - 'phrases' => implode(', ', $phrases_array),
5577 - 'embedding_vector' => $serialized_vector,
5578 - 'similarity_threshold' => $similarity_threshold,
5579 - 'callback_function' => $callback_function,
5580 - 'enabled' => 1,
5581 - 'enabled_bots' => $enabled_bots_json,
5582 - )
5583 - );
5584 -
5585 - if ($result === false) {
5586 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5587 - }
5588 -
5589 - wp_send_json_success(array('id' => $wpdb->insert_id));
1340 + wp_die( esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat') );
5590 1341 }
5591 -}
5592 1342
5593 -/**
5594 - * AJAX handler to edit an existing intent/action
5595 - */
5596 -public function mxchat_edit_intent_ajax() {
5597 - check_ajax_referer('mxchat_edit_intent', 'security');
5598 -
5599 - if (!current_user_can('manage_options')) {
5600 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5601 - }
5602 -
5603 - global $wpdb;
5604 - $table_name = $wpdb->prefix . 'mxchat_intents';
5605 -
5606 - // Sanitize input
5607 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5608 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5609 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5610 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5611 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5612 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5613 -
5614 - // Validate
5615 - if (!$intent_id || empty($intent_label)) {
5616 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5617 - }
5618 -
5619 - // Check if phrases are managed individually (empty phrases_input means individual mode)
5620 - $uses_individual_phrases = empty($phrases_input);
5621 -
5622 - if ($uses_individual_phrases) {
5623 - // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
5624 - $update_data = array(
5625 - 'intent_label' => $intent_label,
5626 - 'similarity_threshold' => $similarity_threshold,
5627 - 'callback_function' => $callback_function,
5628 - 'enabled_bots' => json_encode($enabled_bots),
5629 - );
5630 - } else {
5631 - // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
5632 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5633 - if (empty($phrases_array)) {
5634 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5635 - }
5636 -
5637 - // Generate new embedding (combine phrases into single string for embedding)
5638 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5639 - if (is_wp_error($embedding_vector)) {
5640 - // Keep existing embedding
5641 - $update_data = array(
5642 - 'intent_label' => $intent_label,
5643 - 'phrases' => implode(', ', $phrases_array),
5644 - 'similarity_threshold' => $similarity_threshold,
5645 - 'callback_function' => $callback_function,
5646 - 'enabled_bots' => json_encode($enabled_bots),
5647 - );
5648 - } else {
5649 - $serialized_vector = maybe_serialize($embedding_vector);
5650 - $update_data = array(
5651 - 'intent_label' => $intent_label,
5652 - 'phrases' => implode(', ', $phrases_array),
5653 - 'embedding_vector' => $serialized_vector,
5654 - 'similarity_threshold' => $similarity_threshold,
5655 - 'callback_function' => $callback_function,
5656 - 'enabled_bots' => json_encode($enabled_bots),
5657 - );
5658 - }
5659 - }
5660 -
5661 - // Ensure default bot is included
5662 - if (!in_array('default', $enabled_bots)) {
5663 - $enabled_bots[] = 'default';
5664 - }
5665 - $update_data['enabled_bots'] = json_encode($enabled_bots);
5666 -
5667 - $result = $wpdb->update(
5668 - $table_name,
5669 - $update_data,
5670 - array('id' => $intent_id),
5671 - null,
5672 - array('%d')
5673 - );
5674 -
5675 - if ($result === false) {
5676 - wp_send_json_error(__('Failed to update action.', 'mxchat'));
5677 - }
5678 -
5679 - wp_send_json_success(array('updated' => true));
1343 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
1344 + exit;
5680 1345 }
5681 1346
5682 -/**
5683 - * AJAX handler to delete a single intent/action
5684 - */
5685 -public function mxchat_delete_intent_ajax() {
5686 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5687 1347
5688 - if (!current_user_can('manage_options')) {
5689 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5690 - }
5691 1348
5692 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5693 1349
5694 - if (!$intent_id) {
5695 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5696 - }
5697 1350
5698 - global $wpdb;
5699 - $table_name = $wpdb->prefix . 'mxchat_intents';
5700 1351
5701 - $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
5702 -
5703 - if ($result === false) {
5704 - wp_send_json_error(__('Failed to delete action', 'mxchat'));
5705 - }
5706 -
5707 - // Also delete individual phrases for this intent
5708 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5709 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5710 - $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
5711 - }
5712 -
5713 - wp_send_json_success(array('deleted' => true));
1352 +private function mxchat_get_available_callbacks() {
1353 + return [
1354 + 'mxchat_handle_email_capture' => [
1355 + 'label' => 'Email Capture',
1356 + 'pro_only' => false,
1357 + ],
1358 + 'mxchat_handle_product_inquiry' => [
1359 + 'label' => 'Show Product Card',
1360 + 'pro_only' => true,
1361 + ],
1362 + 'mxchat_handle_order_history' => [
1363 + 'label' => 'Order History',
1364 + 'pro_only' => true,
1365 + ],
1366 + 'mxchat_generate_image' => [
1367 + 'label' => 'Generate Image',
1368 + 'pro_only' => true,
1369 + ],
1370 + 'mxchat_handle_search_request' => [
1371 + 'label' => 'Brave Web Search',
1372 + 'pro_only' => false,
1373 + ],
1374 + 'mxchat_handle_image_search_request' => [
1375 + 'label' => 'Brave Image Search',
1376 + 'pro_only' => false,
1377 + ],
1378 + 'mxchat_handle_add_to_cart_intent' => [
1379 + 'label' => 'Add to Cart',
1380 + 'pro_only' => true,
1381 + ],
1382 + 'mxchat_handle_checkout_intent' => [
1383 + 'label' => 'Proceed to Checkout',
1384 + 'pro_only' => true,
1385 + ],
1386 + 'mxchat_handle_pdf_discussion' => [
1387 + 'label' => 'Chat with PDF',
1388 + 'pro_only' => true,
1389 + ],
1390 + 'mxchat_handle_product_recommendations' => [
1391 + 'label' => 'Product Recommendations',
1392 + 'pro_only' => true,
1393 + ],
1394 + 'mxchat_live_agent_handover' => [
1395 + 'label' => 'Live Agent',
1396 + 'pro_only' => true,
1397 + ],
1398 + 'mxchat_handle_switch_to_chatbot_intent' => [
1399 + 'label' => 'Back to Chatbot',
1400 + 'pro_only' => true,
1401 + ],
1402 + ];
5714 1403 }
5715 1404
5716 -/**
5717 - * AJAX handler to add a single phrase with its own embedding to an intent
5718 - */
5719 -public function mxchat_add_phrase_ajax() {
5720 - check_ajax_referer('mxchat_add_phrase_nonce', 'security');
5721 1405
5722 - if (!current_user_can('manage_options')) {
5723 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5724 - }
1406 +private function mxchat_average_vectors($vectors) {
1407 + $vector_length = count($vectors[0]);
1408 + $sum_vector = array_fill(0, $vector_length, 0);
5725 1409
5726 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5727 - $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
5728 -
5729 - if (!$intent_id || empty($phrase)) {
5730 - wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
1410 + foreach ($vectors as $vector) {
1411 + for ($i = 0; $i < $vector_length; $i++) {
1412 + $sum_vector[$i] += $vector[$i];
1413 + }
5731 1414 }
5732 1415
5733 - // Verify the intent exists
5734 - global $wpdb;
5735 - $intents_table = $wpdb->prefix . 'mxchat_intents';
5736 - $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
5737 - if (!$intent) {
5738 - wp_send_json_error(__('Action not found.', 'mxchat'));
1416 + // Divide each component by the number of vectors to get the average
1417 + $num_vectors = count($vectors);
1418 + for ($i = 0; $i < $vector_length; $i++) {
1419 + $sum_vector[$i] /= $num_vectors;
5739 1420 }
5740 1421
5741 - // Generate embedding for this single phrase
5742 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5743 - if (is_wp_error($embedding_vector)) {
5744 - wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
5745 - }
5746 -
5747 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5748 - $result = $wpdb->insert(
5749 - $phrases_table,
5750 - array(
5751 - 'intent_id' => $intent_id,
5752 - 'phrase' => $phrase,
5753 - 'embedding_vector' => maybe_serialize($embedding_vector),
5754 - )
5755 - );
5756 -
5757 - if ($result === false) {
5758 - wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
5759 - }
5760 -
5761 - wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
1422 + return $sum_vector;
5762 1423 }
5763 1424
5764 -/**
5765 - * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
5766 - */
5767 -public function mxchat_delete_phrase_ajax() {
5768 - check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
5769 -
5770 - if (!current_user_can('manage_options')) {
5771 - wp_send_json_error(__('Unauthorized', 'mxchat'));
1425 +public function mxchat_handle_delete_intent() {
1426 + if ( ! current_user_can( 'manage_options' ) ) {
1427 + wp_die( esc_html__('Unauthorized user', 'mxchat') );
5772 1428 }
5773 1429
5774 - $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
5775 - if (!$phrase_id) {
5776 - wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
5777 - }
1430 + check_admin_referer('mxchat_delete_intent_nonce');
5778 1431
5779 - global $wpdb;
5780 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5781 - $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
1432 + if (isset($_POST['intent_id'])) {
1433 + global $wpdb;
1434 + $table_name = $wpdb->prefix . 'mxchat_intents';
1435 + $intent_id = intval($_POST['intent_id']);
5782 1436
5783 - if ($result === false) {
5784 - wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
1437 + $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5785 1438 }
5786 1439
5787 - wp_send_json_success(array('deleted' => true));
1440 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
1441 + exit;
5788 1442 }
5789 1443
5790 -/**
5791 - * AJAX handler to fetch individual phrases for an intent
5792 - */
5793 -public function mxchat_get_phrases_ajax() {
5794 - check_ajax_referer('mxchat_get_phrases_nonce', 'security');
5795 1444
5796 - if (!current_user_can('manage_options')) {
5797 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5798 - }
5799 -
5800 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5801 - if (!$intent_id) {
5802 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5803 - }
5804 -
5805 - global $wpdb;
5806 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5807 -
5808 - $phrases = array();
5809 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5810 - $phrases = $wpdb->get_results($wpdb->prepare(
5811 - "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
5812 - $intent_id
5813 - ));
5814 - }
5815 -
5816 - wp_send_json_success(array('phrases' => $phrases));
5817 -}
5818 -
5819 -/**
5820 - * AJAX handler to clear legacy phrases and embedding from the main intents table
5821 - */
5822 -public function mxchat_delete_legacy_phrases_ajax() {
5823 - check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
5824 -
5825 - if (!current_user_can('manage_options')) {
5826 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5827 - }
5828 -
5829 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5830 - if (!$intent_id) {
5831 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5832 - }
5833 -
5834 - global $wpdb;
5835 - $table_name = $wpdb->prefix . 'mxchat_intents';
5836 -
5837 - $result = $wpdb->update(
5838 - $table_name,
5839 - array('phrases' => '', 'embedding_vector' => ''),
5840 - array('id' => $intent_id),
5841 - array('%s', '%s'),
5842 - array('%d')
5843 - );
5844 -
5845 - if ($result === false) {
5846 - wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
5847 - }
5848 -
5849 - wp_send_json_success(array('cleared' => true));
5850 -}
5851 -
5852 -/**
5853 - * Enhanced get_available_callbacks function with form action exclusion
5854 - *
5855 - * @param bool $grouped Whether to return callbacks grouped by category
5856 - * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
5857 - * @return array Callbacks data with icons, descriptions and availability status
5858 - */
5859 -private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
5860 - // Load WordPress plugin functions if needed
5861 - if (!function_exists('get_plugins')) {
5862 - require_once ABSPATH . 'wp-admin/includes/plugin.php';
5863 - }
5864 -
5865 - // Get active plugins
5866 - $active_plugins = get_option('active_plugins', array());
5867 -
5868 - // Functions to exclude from the action selector only if Pro is activated
5869 - // If user doesn't have Pro, show these so they can see what they're missing
5870 - $excluded_when_pro_active_functions = array(
5871 - 'mxchat_handle_form_collection' // Forms add-on action
5872 - );
5873 -
5874 - // Always excluded functions (regardless of Pro status)
5875 - $always_excluded_functions = array();
5876 -
5877 - // Combine exclusion lists based on Pro activation status
5878 - $excluded_functions = $always_excluded_functions;
5879 - if ($this->is_activated) {
5880 - // Only exclude add-on managed functions if Pro is active
5881 - $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
5882 - }
5883 -
5884 - // Define add-on plugin files and their corresponding action functions
5885 - $addon_plugins = array(
5886 - 'mxchat-woo/mxchat-woo.php' => array(
5887 - 'functions' => array(
5888 - 'mxchat_handle_product_recommendations',
5889 - 'mxchat_handle_order_history',
5890 - 'mxchat_show_product_card',
5891 - 'mxchat_add_to_cart',
5892 - 'mxchat_checkout_redirect',
5893 - 'mxchat_handle_featured_products'
5894 - ),
5895 - 'name' => __('WooCommerce Add-on', 'mxchat'),
5896 - 'pro_required' => true
5897 - ),
5898 - 'mxchat-perplexity/mxchat-perplexity.php' => array(
5899 - 'functions' => array('mxchat_perplexity_research'),
5900 - 'name' => __('Perplexity Add-on', 'mxchat'),
5901 - 'pro_required' => true
5902 - ),
5903 - 'mxchat-forms/mxchat-forms.php' => array(
5904 - 'functions' => array('mxchat_handle_form_collection'),
5905 - 'name' => __('Forms Add-on', 'mxchat'),
5906 - 'pro_required' => true
5907 - ),
5908 - // Add other add-ons and their functions here
5909 - );
5910 -
5911 - // Get the functions that are provided by active add-ons
5912 - $addon_provided_functions = array();
5913 - $addon_function_mapping = array(); // Maps functions to their add-on info
5914 -
5915 - // Check which add-ons are active
5916 - foreach ($addon_plugins as $plugin_file => $addon_info) {
5917 - $is_active = in_array($plugin_file, $active_plugins);
5918 -
5919 - // For each function in this addon
5920 - foreach ($addon_info['functions'] as $function) {
5921 - // Consider a function installed only if:
5922 - // 1. The add-on is active AND
5923 - // 2. Either it doesn't require Pro OR Pro is activated
5924 - $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
5925 -
5926 - // If the add-on is installed, mark this function as provided by an add-on
5927 - if ($is_installed) {
5928 - $addon_provided_functions[] = $function;
5929 - }
5930 -
5931 - // Store addon info for this function regardless of installation status
5932 - $addon_function_mapping[$function] = array(
5933 - 'addon' => basename(dirname($plugin_file)),
5934 - 'addon_name' => $addon_info['name'],
5935 - 'pro_required' => $addon_info['pro_required'],
5936 - 'is_active' => $is_active,
5937 - 'is_installed' => $is_installed
5938 - );
5939 - }
5940 - }
5941 -
5942 - // Core callbacks - always available in the base plugin
5943 - $core_callbacks = array(
5944 - 'mxchat_handle_email_capture' => array(
5945 - 'label' => __('Loops Email Capture', 'mxchat'),
5946 - 'pro_only' => false,
5947 - 'group' => __('Customer Engagement', 'mxchat'),
5948 - 'icon' => 'email-alt',
5949 - 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
5950 - 'addon' => false, // Not from an add-on
5951 - 'installed' => true // Always installed with base plugin
5952 - ),
5953 - 'mxchat_handle_search_request' => array(
5954 - 'label' => __('Brave Web Search', 'mxchat'),
5955 - 'pro_only' => false,
5956 - 'group' => __('Search Features', 'mxchat'),
5957 - 'icon' => 'search',
5958 - 'description' => __('Let users search the web directly from the chat (requires a Brave Search API key)', 'mxchat'),
5959 - 'addon' => false,
5960 - 'installed' => true
5961 - ),
5962 - 'mxchat_handle_image_search_request' => array(
5963 - 'label' => __('Brave Image Search', 'mxchat'),
5964 - 'pro_only' => false,
5965 - 'group' => __('Search Features', 'mxchat'),
5966 - 'icon' => 'format-image',
5967 - 'description' => __('Search and display images in the chat conversation (requires a Brave Search API key)', 'mxchat'),
5968 - 'addon' => false,
5969 - 'installed' => true
5970 - ),
5971 - // Pro core features - check is_activated property
5972 - 'mxchat_generate_image' => array(
5973 - 'label' => __('Generate Image (OpenAI)', 'mxchat'),
5974 - 'pro_only' => false,
5975 - 'group' => __('Other Features', 'mxchat'),
5976 - 'icon' => 'art',
5977 - 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
5978 - 'addon' => false,
5979 - 'installed' => true
5980 - ),
5981 - 'mxchat_generate_gemini_image' => array(
5982 - 'label' => __('Generate Image (Gemini)', 'mxchat'),
5983 - 'pro_only' => false,
5984 - 'group' => __('Other Features', 'mxchat'),
5985 - 'icon' => 'art',
5986 - 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
5987 - 'addon' => false,
5988 - 'installed' => true
5989 - ),
5990 - 'mxchat_handle_pdf_discussion' => array(
5991 - 'label' => __('Chat with PDF', 'mxchat'),
5992 - 'pro_only' => false,
5993 - 'group' => __('Other Features', 'mxchat'),
5994 - 'icon' => 'media-document',
5995 - 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
5996 - 'addon' => false,
5997 - 'installed' => true
5998 - ),
5999 - 'mxchat_live_agent_handover' => array(
6000 - 'label' => __('Slack Live Agent', 'mxchat'),
6001 - 'pro_only' => false,
6002 - 'group' => __('Customer Engagement', 'mxchat'),
6003 - 'icon' => 'admin-users',
6004 - 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
6005 - 'addon' => false,
6006 - 'installed' => true
6007 - ),
6008 - 'mxchat_telegram_live_agent_handover' => array(
6009 - 'label' => __('Telegram Live Agent', 'mxchat'),
6010 - 'pro_only' => false,
6011 - 'group' => __('Customer Engagement', 'mxchat'),
6012 - 'icon' => 'format-chat',
6013 - 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
6014 - 'addon' => false,
6015 - 'installed' => true
6016 - ),
6017 - 'mxchat_handle_switch_to_chatbot_intent' => array(
6018 - 'label' => __('Back to Chatbot', 'mxchat'),
6019 - 'pro_only' => false,
6020 - 'group' => __('Customer Engagement', 'mxchat'),
6021 - 'icon' => 'backup',
6022 - 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
6023 - 'addon' => false,
6024 - 'installed' => true
6025 - ),
6026 - );
6027 -
6028 - // Add-on callbacks with placeholders - only include if the add-on is NOT active
6029 - // These are promotional/informational only — not selectable as real actions
6030 - $addon_callbacks = array(
6031 - // WooCommerce Add-on
6032 - 'mxchat_handle_product_recommendations' => array(
6033 - 'label' => __('Product Recommendations', 'mxchat'),
6034 - 'pro_only' => false,
6035 - 'addon_promo' => true,
6036 - 'group' => __('WooCommerce Features', 'mxchat'),
6037 - 'icon' => 'cart',
6038 - 'description' => __('Suggest products based on customer preferences', 'mxchat'),
6039 - ),
6040 - 'mxchat_handle_order_history' => array(
6041 - 'label' => __('Order History', 'mxchat'),
6042 - 'pro_only' => false,
6043 - 'addon_promo' => true,
6044 - 'group' => __('WooCommerce Features', 'mxchat'),
6045 - 'icon' => 'clipboard',
6046 - 'description' => __('Allow customers to check their order status', 'mxchat'),
6047 - ),
6048 - 'mxchat_show_product_card' => array(
6049 - 'label' => __('Show Product Card', 'mxchat'),
6050 - 'pro_only' => false,
6051 - 'addon_promo' => true,
6052 - 'group' => __('WooCommerce Features', 'mxchat'),
6053 - 'icon' => 'products',
6054 - 'description' => __('Display product information in the chat', 'mxchat'),
6055 - ),
6056 - 'mxchat_add_to_cart' => array(
6057 - 'label' => __('Add to Cart', 'mxchat'),
6058 - 'pro_only' => false,
6059 - 'addon_promo' => true,
6060 - 'group' => __('WooCommerce Features', 'mxchat'),
6061 - 'icon' => 'plus-alt',
6062 - 'description' => __('Add products to cart directly from chat', 'mxchat'),
6063 - ),
6064 - 'mxchat_checkout_redirect' => array(
6065 - 'label' => __('Proceed to Checkout', 'mxchat'),
6066 - 'pro_only' => false,
6067 - 'addon_promo' => true,
6068 - 'group' => __('WooCommerce Features', 'mxchat'),
6069 - 'icon' => 'arrow-right-alt',
6070 - 'description' => __('Redirect customer to checkout page', 'mxchat'),
6071 - ),
6072 - 'mxchat_handle_featured_products' => array(
6073 - 'label' => __('Featured Products Showcase', 'mxchat'),
6074 - 'pro_only' => false,
6075 - 'addon_promo' => true,
6076 - 'group' => __('WooCommerce Features', 'mxchat'),
6077 - 'icon' => 'star-filled',
6078 - 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
6079 - ),
6080 -
6081 - // Perplexity Add-on
6082 - 'mxchat_perplexity_research' => array(
6083 - 'label' => __('Perplexity Research', 'mxchat'),
6084 - 'pro_only' => false,
6085 - 'addon_promo' => true,
6086 - 'group' => __('Search Features', 'mxchat'),
6087 - 'icon' => 'book-alt',
6088 - 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
6089 - ),
6090 -
6091 - // Forms Add-on
6092 - 'mxchat_handle_form_collection' => array(
6093 - 'label' => __('Form Collection', 'mxchat'),
6094 - 'pro_only' => false,
6095 - 'addon_promo' => true,
6096 - 'group' => __('Form Features', 'mxchat'),
6097 - 'icon' => 'feedback',
6098 - 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
6099 - ),
6100 - );
6101 -
6102 - // Enhance add-on callbacks with installation status and addon info
6103 - foreach ($addon_callbacks as $function => $data) {
6104 - if (isset($addon_function_mapping[$function])) {
6105 - $addon_info = $addon_function_mapping[$function];
6106 -
6107 - $addon_callbacks[$function]['addon'] = $addon_info['addon'];
6108 - $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6109 - $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
6110 -
6111 - // Set pro_only based on add-on configuration
6112 - $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6113 - } else {
6114 - $addon_callbacks[$function]['addon'] = 'unknown';
6115 - $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
6116 - $addon_callbacks[$function]['installed'] = false;
6117 - }
6118 - }
6119 -
6120 - // Initialize callbacks with core features
6121 - $callbacks = $core_callbacks;
6122 -
6123 - // Get callbacks from active add-ons
6124 - $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
6125 -
6126 - // Add placeholder callbacks only for add-ons that aren't active
6127 - if ($include_all) {
6128 - foreach ($addon_callbacks as $function => $data) {
6129 - // Skip placeholders for functions provided by active add-ons
6130 - if (in_array($function, $addon_provided_functions)) {
6131 - continue;
6132 - }
6133 -
6134 - // Skip excluded functions
6135 - if (in_array($function, $excluded_functions)) {
6136 - continue;
6137 - }
6138 -
6139 - // Add the placeholder
6140 - $callbacks[$function] = $data;
6141 - }
6142 - }
6143 -
6144 - // Add callbacks from active add-ons (will override placeholders)
6145 - foreach ($active_addon_callbacks as $function => $data) {
6146 - // Skip excluded functions
6147 - if (in_array($function, $excluded_functions)) {
6148 - continue;
6149 - }
6150 -
6151 - // Always include callbacks from add-ons
6152 - $callbacks[$function] = $data;
6153 -
6154 - // Ensure they have the proper add-on info
6155 - if (isset($addon_function_mapping[$function])) {
6156 - $addon_info = $addon_function_mapping[$function];
6157 - $callbacks[$function]['addon'] = $addon_info['addon'];
6158 - $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
6159 - $callbacks[$function]['installed'] = $addon_info['is_installed'];
6160 - $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
6161 - }
6162 - }
6163 -
6164 - // Just before returning callbacks, sort them to prioritize free features
6165 - if (!$grouped) {
6166 - // Create temporary arrays for sorting
6167 - $free_callbacks = array();
6168 - $pro_callbacks = array();
6169 -
6170 - // Split callbacks into free and pro
6171 - foreach ($callbacks as $key => $data) {
6172 - if (isset($data['pro_only']) && $data['pro_only']) {
6173 - $pro_callbacks[$key] = $data;
6174 - } else {
6175 - $free_callbacks[$key] = $data;
6176 - }
6177 - }
6178 -
6179 - // Merge with free callbacks first
6180 - $callbacks = array_merge($free_callbacks, $pro_callbacks);
6181 - }
6182 -
6183 - // Return grouped structure if requested
6184 - if ($grouped) {
6185 - $grouped_callbacks = array();
6186 - foreach ($callbacks as $key => $data) {
6187 - $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
6188 -
6189 - // Ensure we carry forward all the new fields in grouped mode
6190 - $callback_data = array(
6191 - 'label' => $data['label'],
6192 - 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
6193 - 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
6194 - 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
6195 - 'addon' => isset($data['addon']) ? $data['addon'] : false,
6196 - 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
6197 - 'installed' => isset($data['installed']) ? $data['installed'] : true
6198 - );
6199 -
6200 - $grouped_callbacks[$group_label][$key] = $callback_data;
6201 - }
6202 -
6203 - // Sort within each group to prioritize free features
6204 - foreach ($grouped_callbacks as $group => $items) {
6205 - $free_items = array();
6206 - $pro_items = array();
6207 -
6208 - foreach ($items as $key => $data) {
6209 - if (isset($data['pro_only']) && $data['pro_only']) {
6210 - $pro_items[$key] = $data;
6211 - } else {
6212 - $free_items[$key] = $data;
6213 - }
6214 - }
6215 -
6216 - $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
6217 - }
6218 -
6219 - return $grouped_callbacks;
6220 - }
6221 -
6222 - return $callbacks;
6223 -}
6224 -
6225 1445 public function mxchat_page_init() {
1446 + // Register settings
6226 1447 register_setting(
6227 1448 'mxchat_option_group',
6228 1449 'mxchat_options',
6229 1450 array($this, 'mxchat_sanitize')
@@ -6234,201 +1455,70 @@
6234 1455 'mxchat_similarity_threshold',
6235 1456 array(
6236 1457 'type' => 'number',
6237 1458 'sanitize_callback' => function($value) {
6238 - $value = absint($value);
6239 - return min(max($value, 20), 95);
1459 + $value = absint($value); // Ensure it's an integer
1460 + return min(max($value, 70), 85); // Enforce range
6240 1461 },
6241 1462 'default' => 80,
6242 1463 )
6243 1464 );
6244 1465
1466 +
6245 1467 // Chatbot Settings Section
6246 1468 add_settings_section(
6247 1469 'mxchat_chatbot_section',
6248 - esc_html__('Chatbot Settings', 'mxchat'),
1470 + 'Chatbot Settings',
6249 1471 null,
6250 1472 'mxchat-chatbot'
6251 1473 );
6252 1474
6253 - // API Keys Settings Section
6254 - add_settings_section(
6255 - 'mxchat_api_keys_section',
6256 - esc_html__('API Keys', 'mxchat'),
6257 - array($this, 'mxchat_api_keys_section_callback'),
6258 - 'mxchat-api-keys'
6259 - );
6260 -
6261 - // OpenAI API Key
6262 - add_settings_field(
6263 - 'api_key',
6264 - esc_html__('OpenAI API Key', 'mxchat'),
6265 - array($this, 'api_key_callback'),
6266 - 'mxchat-api-keys',
6267 - 'mxchat_api_keys_section'
6268 - );
6269 -
6270 - // X.AI API Key
6271 - add_settings_field(
6272 - 'xai_api_key',
6273 - esc_html__('X.AI API Key', 'mxchat'),
6274 - array($this, 'xai_api_key_callback'),
6275 - 'mxchat-api-keys',
6276 - 'mxchat_api_keys_section'
6277 - );
6278 -
6279 - // Claude API Key
6280 - add_settings_field(
6281 - 'claude_api_key',
6282 - esc_html__('Claude API Key', 'mxchat'),
6283 - array($this, 'claude_api_key_callback'),
6284 - 'mxchat-api-keys',
6285 - 'mxchat_api_keys_section'
6286 - );
6287 -
6288 - // DeepSeek API Key
6289 - add_settings_field(
6290 - 'deepseek_api_key',
6291 - esc_html__('DeepSeek API Key', 'mxchat'),
6292 - array($this, 'deepseek_api_key_callback'),
6293 - 'mxchat-api-keys',
6294 - 'mxchat_api_keys_section'
6295 - );
6296 -
6297 - // Google Gemini API Key
6298 - add_settings_field(
6299 - 'gemini_api_key',
6300 - esc_html__('Google Gemini API Key', 'mxchat'),
6301 - array($this, 'gemini_api_key_callback'),
6302 - 'mxchat-api-keys',
6303 - 'mxchat_api_keys_section'
6304 - );
6305 -
6306 - // Voyage AI API Key
6307 - add_settings_field(
6308 - 'voyage_api_key',
6309 - esc_html__('Voyage AI API Key', 'mxchat'),
6310 - array($this, 'voyage_api_key_callback'),
6311 - 'mxchat-api-keys',
6312 - 'mxchat_api_keys_section'
6313 - );
6314 -
6315 - // OpenRouter API Key
6316 - add_settings_field(
6317 - 'openrouter_api_key',
6318 - esc_html__('OpenRouter API Key', 'mxchat'),
6319 - array($this, 'openrouter_api_key_callback'),
6320 - 'mxchat-api-keys',
6321 - 'mxchat_api_keys_section'
6322 - );
6323 -
6324 - // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6325 - add_settings_field(
6326 - 'custom_provider',
6327 - esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
6328 - array($this, 'custom_provider_callback'),
6329 - 'mxchat-api-keys',
6330 - 'mxchat_api_keys_section'
6331 - );
6332 -
6333 - // Loops API Key
6334 - add_settings_field(
6335 - 'loops_api_key',
6336 - esc_html__('Loops API Key', 'mxchat'),
6337 - array($this, 'mxchat_loops_api_key_callback'),
6338 - 'mxchat-api-keys',
6339 - 'mxchat_api_keys_section'
6340 - );
6341 -
6342 - // Brave Search API Key
6343 - add_settings_field(
6344 - 'brave_api_key',
6345 - __('Brave API Key', 'mxchat'),
6346 - array($this, 'mxchat_brave_api_key_callback'),
6347 - 'mxchat-api-keys',
6348 - 'mxchat_api_keys_section'
6349 - );
6350 -
6351 1475 // Similarity Threshold Slider
6352 1476 add_settings_field(
6353 1477 'similarity_threshold', // Field ID
6354 - esc_html__('Similarity Threshold', 'mxchat'), // Field title
1478 + 'Similarity Threshold', // Field title
6355 1479 array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6356 1480 'mxchat-chatbot', // Page
6357 1481 'mxchat_chatbot_section' // Section
6358 1482 );
6359 1483
6360 - // RAG Sources Limit Slider
1484 + // Existing fields...
6361 1485 add_settings_field(
6362 - 'rag_sources_limit', // Field ID
6363 - esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6364 - array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6365 - 'mxchat-chatbot', // Page
6366 - 'mxchat_chatbot_section' // Section
6367 - );
6368 -
6369 - // RAG Chunks Limit Slider
6370 - add_settings_field(
6371 - 'rag_chunks_limit', // Field ID
6372 - esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6373 - array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6374 - 'mxchat-chatbot', // Page
6375 - 'mxchat_chatbot_section' // Section
6376 - );
6377 -
6378 - add_settings_field(
6379 - 'append_to_body',
6380 - esc_html__('Auto-Display Chatbot', 'mxchat'),
6381 - array($this, 'mxchat_append_to_body_callback'),
1486 + 'api_key',
1487 + 'OpenAI API Key',
1488 + array($this, 'api_key_callback'),
6382 1489 'mxchat-chatbot',
6383 1490 'mxchat_chatbot_section'
6384 1491 );
6385 1492
6386 1493 add_settings_field(
6387 - 'contextual_awareness_toggle',
6388 - esc_html__('Contextual Awareness', 'mxchat'),
6389 - array($this, 'mxchat_contextual_awareness_callback'),
6390 - 'mxchat-chatbot',
6391 - 'mxchat_chatbot_section'
1494 + 'xai_api_key',
1495 + 'X.AI API Key',
1496 + array($this, 'xai_api_key_callback'),
1497 + 'mxchat-chatbot',
1498 + 'mxchat_chatbot_section'
6392 1499 );
6393 1500
6394 1501 add_settings_field(
6395 - 'citation_links_toggle',
6396 - esc_html__('Citation Links', 'mxchat'),
6397 - array($this, 'mxchat_citation_links_toggle_callback'),
1502 + 'claude_api_key',
1503 + 'Claude API Key',
1504 + array($this, 'claude_api_key_callback'),
6398 1505 'mxchat-chatbot',
6399 1506 'mxchat_chatbot_section'
6400 1507 );
6401 1508
6402 - // Satisfaction rating toggle (plan-a5b006).
1509 +
6403 1510 add_settings_field(
6404 - 'satisfaction_rating_enabled',
6405 - esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6406 - array($this, 'mxchat_satisfaction_rating_toggle_callback'),
1511 + 'system_prompt_instructions',
1512 + 'AI Instructions',
1513 + array($this, 'system_prompt_instructions_callback'),
6407 1514 'mxchat-chatbot',
6408 1515 'mxchat_chatbot_section'
6409 1516 );
6410 1517
6411 - // Satisfaction rating customization (plan-141a12, plan-29caac):
6412 - // the 5 customization fields are now inline-rendered inside
6413 - // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6414 -
6415 1518 add_settings_field(
6416 - 'enable_streaming_toggle',
6417 - esc_html__('Enable Streaming', 'mxchat'),
6418 - array($this, 'enable_streaming_toggle_callback'),
6419 - 'mxchat-chatbot',
6420 - 'mxchat_chatbot_section', // Same section as your working toggle
6421 - array(
6422 - 'class' => 'mxchat-setting-row streaming-setting',
6423 - 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6424 - )
6425 - );
6426 -
6427 -
6428 - add_settings_field(
6429 1519 'model',
6430 - esc_html__('Chat Model', 'mxchat'),
1520 + 'Model',
6431 1521 array($this, 'mxchat_model_callback'),
6432 1522 'mxchat-chatbot',
6433 1523 'mxchat_chatbot_section'
6434 1524 );
@@ -6433,27 +1523,10 @@
6433 1523 'mxchat_chatbot_section'
6434 1524 );
6435 1525
6436 1526 add_settings_field(
6437 - 'embedding_model',
6438 - esc_html__('Embedding Model', 'mxchat'),
6439 - array($this, 'embedding_model_callback'),
6440 - 'mxchat-chatbot',
6441 - 'mxchat_chatbot_section'
6442 - );
6443 -
6444 - add_settings_field(
6445 - 'system_prompt_instructions',
6446 - esc_html__('AI Instructions (Behavior)', 'mxchat'),
6447 - array($this, 'system_prompt_instructions_callback'),
6448 - 'mxchat-chatbot',
6449 - 'mxchat_chatbot_section'
6450 - );
6451 -
6452 -
6453 - add_settings_field(
6454 1527 'top_bar_title',
6455 - esc_html__('Top Bar Title', 'mxchat'),
1528 + 'Top Bar Title',
6456 1529 array($this, 'mxchat_top_bar_title_callback'),
6457 1530 'mxchat-chatbot',
6458 1531 'mxchat_chatbot_section'
6459 1532 );
@@ -6458,82 +1531,66 @@
6458 1531 'mxchat_chatbot_section'
6459 1532 );
6460 1533
6461 1534 add_settings_field(
6462 - 'ai_agent_text',
6463 - esc_html__('AI Agent Text', 'mxchat'),
6464 - array($this, 'mxchat_ai_agent_text_callback'),
1535 + 'intro_message',
1536 + 'Introductory Message',
1537 + array($this, 'mxchat_intro_message_callback'),
6465 1538 'mxchat-chatbot',
6466 1539 'mxchat_chatbot_section'
6467 1540 );
6468 1541
6469 1542 add_settings_field(
6470 - 'enable_email_block',
6471 - esc_html__('Require Email To Chat', 'mxchat'),
6472 - array($this, 'enable_email_block_callback'),
1543 + 'input_copy',
1544 + 'Input Copy',
1545 + array($this, 'mxchat_input_copy_callback'),
6473 1546 'mxchat-chatbot',
6474 1547 'mxchat_chatbot_section'
6475 1548 );
6476 1549
6477 1550 add_settings_field(
6478 - 'email_blocker_header_content',
6479 - esc_html__('Require Email Chat Content', 'mxchat'),
6480 - array($this, 'email_blocker_header_content_callback'),
1551 + 'rate_limit_logged_in',
1552 + __('Rate Limit for Logged-in Users', 'mxchat'),
1553 + array($this, 'mxchat_rate_limit_logged_in_callback'),
6481 1554 'mxchat-chatbot',
6482 1555 'mxchat_chatbot_section'
6483 1556 );
6484 1557
6485 1558 add_settings_field(
6486 - 'email_blocker_button_text',
6487 - esc_html__('Require Email Chat Button Text', 'mxchat'),
6488 - [$this, 'email_blocker_button_text_callback'],
1559 + 'rate_limit_logged_out',
1560 + __('Rate Limit for Logged-out Users', 'mxchat'),
1561 + array($this, 'mxchat_rate_limit_logged_out_callback'),
6489 1562 'mxchat-chatbot',
6490 1563 'mxchat_chatbot_section'
6491 1564 );
6492 1565
6493 1566 add_settings_field(
6494 - 'enable_name_field',
6495 - esc_html__('Require Name Field', 'mxchat'),
6496 - array($this, 'enable_name_field_callback'),
1567 + 'rate_limit_message',
1568 + 'Rate Limit Message',
1569 + array($this, 'mxchat_rate_limit_message_callback'),
6497 1570 'mxchat-chatbot',
6498 1571 'mxchat_chatbot_section'
6499 1572 );
6500 1573
6501 1574 add_settings_field(
6502 - 'name_field_placeholder',
6503 - esc_html__('Name Field Placeholder', 'mxchat'),
6504 - array($this, 'name_field_placeholder_callback'),
1575 + 'pre_chat_message',
1576 + 'Pre-Chat Message',
1577 + array($this, 'mxchat_pre_chat_message_callback'),
6505 1578 'mxchat-chatbot',
6506 1579 'mxchat_chatbot_section'
6507 1580 );
6508 1581
6509 - add_settings_field(
6510 - 'intro_message',
6511 - esc_html__('Introductory Message', 'mxchat'),
6512 - array($this, 'mxchat_intro_message_callback'),
1582 + add_settings_field(
1583 + 'append_to_body',
1584 + 'Append Chat Widget to Body',
1585 + array($this, 'mxchat_append_to_body_callback'),
6513 1586 'mxchat-chatbot',
6514 1587 'mxchat_chatbot_section'
6515 1588 );
6516 1589
6517 - add_settings_field(
6518 - 'input_copy',
6519 - esc_html__('Input Copy', 'mxchat'),
6520 - array($this, 'mxchat_input_copy_callback'),
6521 - 'mxchat-chatbot',
6522 - 'mxchat_chatbot_section'
6523 - );
6524 -
6525 - add_settings_field(
6526 - 'pre_chat_message',
6527 - esc_html__('Chat Teaser Pop-up', 'mxchat'),
6528 - array($this, 'mxchat_pre_chat_message_callback'),
6529 - 'mxchat-chatbot',
6530 - 'mxchat_chatbot_section'
6531 - );
6532 -
6533 - add_settings_field(
1590 + add_settings_field(
6534 1591 'privacy_toggle',
6535 - esc_html__('Toggle Privacy Notice', 'mxchat'),
1592 + 'Toggle Privacy Notice',
6536 1593 array($this, 'mxchat_privacy_toggle_callback'),
6537 1594 'mxchat-chatbot',
6538 1595 'mxchat_chatbot_section'
6539 1596 );
@@ -6539,9 +1596,9 @@
6539 1596 );
6540 1597
6541 1598 add_settings_field(
6542 1599 'complianz_toggle',
6543 - esc_html__('Enable Complianz', 'mxchat'),
1600 + 'Enable Complianz',
6544 1601 array($this, 'mxchat_complianz_toggle_callback'),
6545 1602 'mxchat-chatbot',
6546 1603 'mxchat_chatbot_section'
6547 1604 );
@@ -6547,9 +1604,9 @@
6547 1604 );
6548 1605
6549 1606 add_settings_field(
6550 1607 'link_target_toggle',
6551 - esc_html__('Open Links in a New Tab', 'mxchat'),
1608 + 'Open Links in a New Tab',
6552 1609 array($this, 'mxchat_link_target_toggle_callback'),
6553 1610 'mxchat-chatbot',
6554 1611 'mxchat_chatbot_section'
6555 1612 );
@@ -6554,114 +1611,125 @@
6554 1611 'mxchat_chatbot_section'
6555 1612 );
6556 1613
6557 1614 add_settings_field(
6558 - 'chat_persistence_toggle',
6559 - esc_html__('Enable Chat Persistence', 'mxchat'),
6560 - array($this, 'mxchat_chat_persistence_toggle_callback'),
6561 - 'mxchat-chatbot',
6562 - 'mxchat_chatbot_section'
1615 + 'chat_persistence_toggle',
1616 + 'Enable Chat Persistence',
1617 + array($this, 'mxchat_chat_persistence_toggle_callback'),
1618 + 'mxchat-chatbot',
1619 + 'mxchat_chatbot_section'
6563 1620 );
6564 1621
6565 1622 add_settings_field(
6566 - 'print_button_enabled',
6567 - esc_html__('Show Download Transcript Button', 'mxchat'),
6568 - array($this, 'mxchat_print_button_toggle_callback'),
6569 - 'mxchat-chatbot',
6570 - 'mxchat_chatbot_section'
6571 - );
1623 + 'popular_question_1',
1624 + 'Popular Question 1',
1625 + array($this, 'mxchat_popular_question_1_callback'),
1626 + 'mxchat-chatbot',
1627 + 'mxchat_chatbot_section'
1628 +);
6572 1629
6573 - add_settings_field(
6574 - 'reset_chat_enabled',
6575 - esc_html__('Show Start-New-Chat Button', 'mxchat'),
6576 - array($this, 'mxchat_reset_chat_toggle_callback'),
6577 - 'mxchat-chatbot',
6578 - 'mxchat_chatbot_section'
6579 - );
1630 +add_settings_field(
1631 + 'popular_question_2',
1632 + 'Popular Question 2',
1633 + array($this, 'mxchat_popular_question_2_callback'),
1634 + 'mxchat-chatbot',
1635 + 'mxchat_chatbot_section'
1636 +);
6580 1637
6581 - add_settings_field(
6582 - 'reset_chat_label',
6583 - esc_html__('Start-New-Chat Button Label', 'mxchat'),
6584 - array($this, 'mxchat_reset_chat_label_callback'),
6585 - 'mxchat-chatbot',
6586 - 'mxchat_chatbot_section'
6587 - );
1638 +add_settings_field(
1639 + 'popular_question_3',
1640 + 'Popular Question 3',
1641 + array($this, 'mxchat_popular_question_3_callback'),
1642 + 'mxchat-chatbot',
1643 + 'mxchat_chatbot_section'
1644 +);
6588 1645
6589 - add_settings_field(
6590 - 'popular_question_1',
6591 - esc_html__('Quick Question 1', 'mxchat'),
6592 - array($this, 'mxchat_popular_question_1_callback'),
6593 - 'mxchat-chatbot',
6594 - 'mxchat_chatbot_section'
6595 - );
1646 +add_settings_field(
1647 + 'additional_popular_questions',
1648 + 'Additional Popular Questions',
1649 + array($this, 'mxchat_additional_popular_questions_callback'),
1650 + 'mxchat-chatbot',
1651 + 'mxchat_chatbot_section'
1652 +);
6596 1653
6597 - add_settings_field(
6598 - 'popular_question_2',
6599 - esc_html__('Quick Question 2', 'mxchat'),
6600 - array($this, 'mxchat_popular_question_2_callback'),
6601 - 'mxchat-chatbot',
6602 - 'mxchat_chatbot_section'
6603 - );
6604 1654
6605 - add_settings_field(
6606 - 'popular_question_3',
6607 - esc_html__('Quick Question 3', 'mxchat'),
6608 - array($this, 'mxchat_popular_question_3_callback'),
6609 - 'mxchat-chatbot',
6610 - 'mxchat_chatbot_section'
6611 - );
1655 +// WooCommerce Settings Section
1656 +add_settings_section(
1657 + 'mxchat_woocommerce_section',
1658 + 'WooCommerce Settings',
1659 + null,
1660 + 'mxchat-embed'
1661 +);
6612 1662
6613 - add_settings_field(
6614 - 'additional_popular_questions',
6615 - esc_html__('Additional Quick Questions', 'mxchat'),
6616 - array($this, 'mxchat_additional_popular_questions_callback'),
6617 - 'mxchat-chatbot',
6618 - 'mxchat_chatbot_section'
6619 - );
1663 +// Loops Settings Section
1664 +add_settings_section(
1665 + 'mxchat_loops_section',
1666 + 'Loops Settings',
1667 + null,
1668 + 'mxchat-embed'
1669 +);
6620 1670
1671 +// WooCommerce Settings Fields
1672 +add_settings_field(
1673 + 'enable_woocommerce_integration',
1674 + 'Automatically Embed Products',
1675 + array($this, 'mxchat_enable_woocommerce_integration_callback'),
1676 + 'mxchat-embed',
1677 + 'mxchat_woocommerce_section'
1678 +);
6621 1679
6622 - add_settings_field(
6623 - 'rate_limits',
6624 - __('Rate Limits Settings', 'mxchat'),
6625 - array($this, 'mxchat_rate_limits_callback'),
6626 - 'mxchat-chatbot',
6627 - 'mxchat_chatbot_section'
6628 - );
6629 1680
6630 - // Loops Settings Section
6631 - add_settings_section(
6632 - 'mxchat_loops_section',
6633 - esc_html__('Loops Settings', 'mxchat'),
6634 - null,
6635 - 'mxchat-embed'
6636 - );
1681 +add_settings_field(
1682 + 'woocommerce_consumer_key',
1683 + 'WooCommerce Consumer Key',
1684 + array($this, 'mxchat_woocommerce_consumer_key_callback'),
1685 + 'mxchat-embed',
1686 + 'mxchat_woocommerce_section'
1687 +);
6637 1688
6638 - // Loops Settings Fields (API Key moved to API Keys tab)
6639 - add_settings_field(
6640 - 'loops_mailing_list',
6641 - esc_html__('Loops Mailing List', 'mxchat'),
6642 - array($this, 'mxchat_loops_mailing_list_callback'),
6643 - 'mxchat-embed',
6644 - 'mxchat_loops_section'
6645 - );
1689 +add_settings_field(
1690 + 'woocommerce_consumer_secret',
1691 + 'WooCommerce Consumer Secret',
1692 + array($this, 'mxchat_woocommerce_consumer_secret_callback'),
1693 + 'mxchat-embed',
1694 + 'mxchat_woocommerce_section'
1695 +);
6646 1696
6647 - add_settings_field(
6648 - 'triggered_phrase_response',
6649 - esc_html__('Triggered Phrase Response', 'mxchat'),
6650 - array($this, 'mxchat_triggered_phrase_response_callback'),
6651 - 'mxchat-embed',
6652 - 'mxchat_loops_section'
6653 - );
1697 +// Loops Settings Fields
1698 +add_settings_field(
1699 + 'loops_api_key',
1700 + 'Loops API Key',
1701 + array($this, 'mxchat_loops_api_key_callback'),
1702 + 'mxchat-embed',
1703 + 'mxchat_loops_section'
1704 +);
6654 1705
6655 - add_settings_field(
6656 - 'email_capture_response',
6657 - esc_html__('Email Capture Response', 'mxchat'),
6658 - array($this, 'mxchat_email_capture_response_callback'),
6659 - 'mxchat-embed',
6660 - 'mxchat_loops_section'
6661 - );
1706 +add_settings_field(
1707 + 'loops_mailing_list',
1708 + 'Loops Mailing List',
1709 + array($this, 'mxchat_loops_mailing_list_callback'),
1710 + 'mxchat-embed',
1711 + 'mxchat_loops_section'
1712 +);
6662 1713
6663 - // Brave Search Settings Fields
1714 +add_settings_field(
1715 + 'triggered_phrase_response',
1716 + 'Triggered Phrase Response',
1717 + array($this, 'mxchat_triggered_phrase_response_callback'),
1718 + 'mxchat-embed',
1719 + 'mxchat_loops_section'
1720 +);
1721 +
1722 +add_settings_field(
1723 + 'email_capture_response',
1724 + 'Email Capture Response',
1725 + array($this, 'mxchat_email_capture_response_callback'),
1726 + 'mxchat-embed',
1727 + 'mxchat_loops_section'
1728 +);
1729 +
1730 +
1731 + // Brave Search Settings Fields
6664 1732 add_settings_section(
6665 1733 'mxchat_brave_section',
6666 1734 __('Brave Search Settings', 'mxchat'),
6667 1735 array($this, 'mxchat_brave_section_callback'),
@@ -6667,10 +1735,17 @@
6667 1735 array($this, 'mxchat_brave_section_callback'),
6668 1736 'mxchat-embed'
6669 1737 );
6670 1738
6671 - // Brave API Key moved to API Keys tab
6672 1739 add_settings_field(
1740 + 'brave_api_key',
1741 + __('Brave API Key', 'mxchat'),
1742 + array($this, 'mxchat_brave_api_key_callback'),
1743 + 'mxchat-embed',
1744 + 'mxchat_brave_section'
1745 + );
1746 +
1747 + add_settings_field(
6673 1748 'brave_image_count',
6674 1749 __('Number of Images to Return', 'mxchat'),
6675 1750 array($this, 'mxchat_brave_image_count_callback'),
6676 1751 'mxchat-embed',
@@ -6708,545 +1783,384 @@
6708 1783 'mxchat-embed',
6709 1784 'mxchat_brave_section'
6710 1785 );
6711 1786
1787 +
6712 1788 // Chat with PDF Intent Settings Fields
6713 - add_settings_section(
6714 - 'mxchat_pdf_intent_section',
6715 - __('Toolbar Settings & Intents', 'mxchat'),
6716 - array($this, 'mxchat_pdf_intent_section_callback'),
6717 - 'mxchat-embed'
6718 - );
1789 +add_settings_section(
1790 + 'mxchat_pdf_intent_section',
1791 + __('Toolbar Settings & Intents', 'mxchat'),
1792 + array($this, 'mxchat_pdf_intent_section_callback'),
1793 + 'mxchat-embed'
1794 +);
6719 1795
6720 - add_settings_field(
6721 - 'chat_toolbar_toggle',
6722 - __('Show Chat Toolbar', 'mxchat'),
6723 - array($this, 'mxchat_chat_toolbar_toggle_callback'),
6724 - 'mxchat-embed',
6725 - 'mxchat_pdf_intent_section'
6726 - );
1796 +add_settings_field(
1797 + 'chat_toolbar_toggle',
1798 + __('Show Chat Toolbar', 'mxchat'),
1799 + array($this, 'mxchat_chat_toolbar_toggle_callback'),
1800 + 'mxchat-embed',
1801 + 'mxchat_pdf_intent_section'
1802 +);
6727 1803
6728 - // PDF Upload Button Toggle
6729 - add_settings_field(
6730 - 'show_pdf_upload_button',
6731 - __('Show PDF Upload Button', 'mxchat'),
6732 - array($this, 'mxchat_show_pdf_upload_button_callback'),
6733 - 'mxchat-embed',
6734 - 'mxchat_pdf_intent_section'
6735 - );
6736 1804
6737 - // Word Upload Button Toggle
6738 - add_settings_field(
6739 - 'show_word_upload_button',
6740 - __('Show Word Upload Button', 'mxchat'),
6741 - array($this, 'mxchat_show_word_upload_button_callback'),
6742 - 'mxchat-embed',
6743 - 'mxchat_pdf_intent_section'
6744 - );
1805 +add_settings_field(
1806 + 'pdf_intent_trigger_text',
1807 + __('Intent Trigger Text', 'mxchat'),
1808 + array($this, 'mxchat_pdf_intent_trigger_text_callback'),
1809 + 'mxchat-embed',
1810 + 'mxchat_pdf_intent_section'
1811 +);
6745 1812
6746 - add_settings_field(
6747 - 'pdf_intent_trigger_text',
6748 - __('Intent Trigger Text', 'mxchat'),
6749 - array($this, 'mxchat_pdf_intent_trigger_text_callback'),
6750 - 'mxchat-embed',
6751 - 'mxchat_pdf_intent_section'
6752 - );
1813 +add_settings_field(
1814 + 'pdf_intent_success_text',
1815 + __('Success Text', 'mxchat'),
1816 + array($this, 'mxchat_pdf_intent_success_text_callback'),
1817 + 'mxchat-embed',
1818 + 'mxchat_pdf_intent_section'
1819 +);
6753 1820
6754 - add_settings_field(
6755 - 'pdf_intent_success_text',
6756 - __('Success Text', 'mxchat'),
6757 - array($this, 'mxchat_pdf_intent_success_text_callback'),
6758 - 'mxchat-embed',
6759 - 'mxchat_pdf_intent_section'
6760 - );
1821 +add_settings_field(
1822 + 'pdf_intent_error_text',
1823 + __('Error Text', 'mxchat'),
1824 + array($this, 'mxchat_pdf_intent_error_text_callback'),
1825 + 'mxchat-embed',
1826 + 'mxchat_pdf_intent_section'
1827 +);
6761 1828
6762 - add_settings_field(
6763 - 'pdf_intent_error_text',
6764 - __('Error Text', 'mxchat'),
6765 - array($this, 'mxchat_pdf_intent_error_text_callback'),
6766 - 'mxchat-embed',
6767 - 'mxchat_pdf_intent_section'
6768 - );
1829 +// Add PDF Maximum Pages Field
1830 +add_settings_field(
1831 + 'pdf_max_pages',
1832 + __('Maximum PDF Pages', 'mxchat'),
1833 + array($this, 'mxchat_pdf_max_pages_callback'),
1834 + 'mxchat-embed',
1835 + 'mxchat_pdf_intent_section'
1836 +);
6769 1837
6770 - // Add PDF Maximum Pages Field
6771 - add_settings_field(
6772 - 'pdf_max_pages',
6773 - __('Maximum Document Pages', 'mxchat'),
6774 - array($this, 'mxchat_pdf_max_pages_callback'),
6775 - 'mxchat-embed',
6776 - 'mxchat_pdf_intent_section'
6777 - );
6778 1838
6779 - // Live Agent Settings Fields
1839 +
1840 +
1841 +// Live Agent Settings Fields
1842 +add_settings_section(
1843 + 'mxchat_live_agent_section',
1844 + __('Live Agent Settings', 'mxchat'),
1845 + array($this, 'mxchat_live_agent_section_callback'),
1846 + 'mxchat-embed'
1847 +);
1848 +
1849 +// Live Agent Status Fields (add at top of live agent settings)
1850 +add_settings_field(
1851 + 'live_agent_status',
1852 + __('Live Agent Status', 'mxchat'),
1853 + array($this, 'mxchat_live_agent_status_callback'),
1854 + 'mxchat-embed',
1855 + 'mxchat_live_agent_section'
1856 +);
1857 +
1858 +add_settings_field(
1859 + 'live_agent_notification_message',
1860 + __('Notification Message', 'mxchat'),
1861 + array($this, 'mxchat_live_agent_notification_message_callback'),
1862 + 'mxchat-embed',
1863 + 'mxchat_live_agent_section'
1864 +);
1865 +
1866 +add_settings_field(
1867 + 'live_agent_away_message',
1868 + __('Away Message', 'mxchat'),
1869 + array($this, 'mxchat_live_agent_away_message_callback'),
1870 + 'mxchat-embed',
1871 + 'mxchat_live_agent_section'
1872 +);
1873 +
1874 +add_settings_field(
1875 + 'live_agent_webhook_url',
1876 + __('Slack Webhook URL', 'mxchat'),
1877 + array($this, 'mxchat_live_agent_webhook_url_callback'),
1878 + 'mxchat-embed',
1879 + 'mxchat_live_agent_section'
1880 +);
1881 +
1882 +add_settings_field(
1883 + 'live_agent_secret_key',
1884 + __('Slack Secret Key', 'mxchat'),
1885 + array($this, 'mxchat_live_agent_secret_key_callback'),
1886 + 'mxchat-embed',
1887 + 'mxchat_live_agent_section'
1888 +);
1889 +
1890 +// Live Agent Integration Fields
1891 +add_settings_field(
1892 + 'live_agent_bot_token',
1893 + __('Slack Bot OAuth Token', 'mxchat'),
1894 + array($this, 'mxchat_live_agent_bot_token_callback'),
1895 + 'mxchat-embed',
1896 + 'mxchat_live_agent_section'
1897 +);
1898 +
1899 +
1900 + // Theme Settings Section
6780 1901 add_settings_section(
6781 - 'mxchat_live_agent_section',
6782 - __('Live Agent Settings', 'mxchat'),
6783 - array($this, 'mxchat_live_agent_section_callback'),
6784 - 'mxchat-embed'
1902 + 'mxchat_theme_section',
1903 + 'Theme Settings',
1904 + null,
1905 + 'mxchat-theme'
6785 1906 );
6786 1907
6787 - // Live Agent Status Fields (add at top of live agent settings)
6788 1908 add_settings_field(
6789 - 'live_agent_status',
6790 - __('Live Agent Status', 'mxchat'),
6791 - array($this, 'mxchat_live_agent_status_callback'),
6792 - 'mxchat-embed',
6793 - 'mxchat_live_agent_section'
1909 + 'close_button_color',
1910 + 'Close Button & Title Color',
1911 + array($this, 'mxchat_close_button_color_callback'),
1912 + 'mxchat-theme',
1913 + 'mxchat_theme_section'
6794 1914 );
6795 1915
6796 - // Slack availability schedule (plans 8ccaa2 + 99d7a4). Each handoff channel
6797 - // owns an independent schedule rendered under its own Integrations tab; this
6798 - // one governs Slack only. Same callback as Telegram's, parameterized.
6799 1916 add_settings_field(
6800 - 'live_agent_schedule_slack',
6801 - __('Availability Schedule', 'mxchat'),
6802 - array($this, 'mxchat_live_agent_schedule_callback'),
6803 - 'mxchat-embed',
6804 - 'mxchat_live_agent_section',
6805 - array('channel' => 'slack')
1917 + 'chatbot_bg_color',
1918 + 'Chatbot Background Color',
1919 + array($this, 'mxchat_chatbot_bg_color_callback'),
1920 + 'mxchat-theme',
1921 + 'mxchat_theme_section'
6806 1922 );
6807 1923
6808 1924 add_settings_field(
6809 - 'live_agent_notification_message',
6810 - __('Notification Message', 'mxchat'),
6811 - array($this, 'mxchat_live_agent_notification_message_callback'),
6812 - 'mxchat-embed',
6813 - 'mxchat_live_agent_section'
1925 + 'user_message_bg_color',
1926 + 'User Message Background Color',
1927 + array($this, 'mxchat_user_message_bg_color_callback'),
1928 + 'mxchat-theme',
1929 + 'mxchat_theme_section'
6814 1930 );
6815 1931
6816 1932 add_settings_field(
6817 - 'live_agent_away_message',
6818 - __('Away Message', 'mxchat'),
6819 - array($this, 'mxchat_live_agent_away_message_callback'),
6820 - 'mxchat-embed',
6821 - 'mxchat_live_agent_section'
1933 + 'user_message_font_color',
1934 + 'User Message Font Color',
1935 + array($this, 'mxchat_user_message_font_color_callback'),
1936 + 'mxchat-theme',
1937 + 'mxchat_theme_section'
6822 1938 );
6823 1939
6824 1940 add_settings_field(
6825 - 'live_agent_user_ids',
6826 - __('Slack Agent User IDs', 'mxchat'),
6827 - array($this, 'mxchat_live_agent_user_ids_callback'),
6828 - 'mxchat-embed',
6829 - 'mxchat_live_agent_section'
1941 + 'bot_message_bg_color',
1942 + 'Bot Message Background Color',
1943 + array($this, 'mxchat_bot_message_bg_color_callback'),
1944 + 'mxchat-theme',
1945 + 'mxchat_theme_section'
6830 1946 );
6831 1947
6832 - // Shared handoff channel (plan 9f7756): route every handoff into one
6833 - // pre-existing channel as threads instead of creating chat-* channels.
6834 1948 add_settings_field(
6835 - 'live_agent_shared_channel',
6836 - __('Shared Handoff Channel', 'mxchat'),
6837 - array($this, 'mxchat_live_agent_shared_channel_callback'),
6838 - 'mxchat-embed',
6839 - 'mxchat_live_agent_section'
1949 + 'bot_message_font_color',
1950 + 'Bot Message Font Color',
1951 + array($this, 'mxchat_bot_message_font_color_callback'),
1952 + 'mxchat-theme',
1953 + 'mxchat_theme_section'
6840 1954 );
6841 1955
6842 - // Auto-archive per-conversation chat- channels on !endchat (plan 7458a7).
6843 - // Default OFF; never touches the shared handoff channel.
6844 1956 add_settings_field(
6845 - 'live_agent_archive_on_end_toggle',
6846 - __('Archive Channel When Chat Ends', 'mxchat'),
6847 - array($this, 'mxchat_live_agent_archive_on_end_callback'),
6848 - 'mxchat-embed',
6849 - 'mxchat_live_agent_section'
1957 + 'top_bar_bg_color',
1958 + 'Top Bar Background Color',
1959 + array($this, 'mxchat_top_bar_bg_color_callback'),
1960 + 'mxchat-theme',
1961 + 'mxchat_theme_section'
6850 1962 );
6851 1963
6852 1964 add_settings_field(
6853 - 'live_agent_webhook_url',
6854 - __('Slack Webhook URL', 'mxchat'),
6855 - array($this, 'mxchat_live_agent_webhook_url_callback'),
6856 - 'mxchat-embed',
6857 - 'mxchat_live_agent_section'
1965 + 'send_button_font_color',
1966 + 'Send Button Color',
1967 + array($this, 'mxchat_send_button_font_color_callback'),
1968 + 'mxchat-theme',
1969 + 'mxchat_theme_section'
6858 1970 );
6859 1971
6860 1972 add_settings_field(
6861 - 'live_agent_secret_key',
6862 - __('Slack Secret Key', 'mxchat'),
6863 - array($this, 'mxchat_live_agent_secret_key_callback'),
6864 - 'mxchat-embed',
6865 - 'mxchat_live_agent_section'
1973 + 'chat_input_font_color',
1974 + 'Chat Input Font Color',
1975 + array($this, 'mxchat_chat_input_font_color_callback'),
1976 + 'mxchat-theme',
1977 + 'mxchat_theme_section'
6866 1978 );
6867 1979
6868 - // Live Agent Integration Fields
6869 1980 add_settings_field(
6870 - 'live_agent_bot_token',
6871 - __('Slack Bot OAuth Token', 'mxchat'),
6872 - array($this, 'mxchat_live_agent_bot_token_callback'),
6873 - 'mxchat-embed',
6874 - 'mxchat_live_agent_section'
1981 + 'chatbot_background_color',
1982 + 'Floating Widget Background Color',
1983 + array($this, 'mxchat_chatbot_background_color_callback'),
1984 + 'mxchat-theme',
1985 + 'mxchat_theme_section'
6875 1986 );
6876 1987
6877 - // Telegram Integration Section
6878 - add_settings_section(
6879 - 'mxchat_telegram_section',
6880 - __('Telegram Settings', 'mxchat'),
6881 - array($this, 'mxchat_telegram_section_callback'),
6882 - 'mxchat-embed'
1988 + add_settings_field(
1989 + 'icon_color',
1990 + 'Chatbot Icon Color',
1991 + array($this, 'mxchat_icon_color_callback'),
1992 + 'mxchat-theme',
1993 + 'mxchat_theme_section'
6883 1994 );
6884 1995
6885 1996 add_settings_field(
6886 - 'telegram_status',
6887 - __('Live Agent Status', 'mxchat'),
6888 - array($this, 'mxchat_telegram_status_callback'),
6889 - 'mxchat-embed',
6890 - 'mxchat_telegram_section'
1997 + 'custom_icon',
1998 + 'Custom Chatbot Icon (PNG)',
1999 + array($this, 'mxchat_custom_icon_callback'),
2000 + 'mxchat-theme',
2001 + 'mxchat_theme_section'
6891 2002 );
6892 2003
6893 - // Telegram availability schedule (plan 99d7a4) — independent of Slack's,
6894 - // rendered right under the Telegram status toggle it extends.
6895 - add_settings_field(
6896 - 'live_agent_schedule_telegram',
6897 - __('Availability Schedule', 'mxchat'),
6898 - array($this, 'mxchat_live_agent_schedule_callback'),
6899 - 'mxchat-embed',
6900 - 'mxchat_telegram_section',
6901 - array('channel' => 'telegram')
6902 - );
6903 2004
6904 2005 add_settings_field(
6905 - 'telegram_notification_message',
6906 - __('Notification Message', 'mxchat'),
6907 - array($this, 'mxchat_telegram_notification_message_callback'),
6908 - 'mxchat-embed',
6909 - 'mxchat_telegram_section'
2006 + 'live_agent_message_bg_color',
2007 + 'Live Agent Background Color',
2008 + array($this, 'mxchat_live_agent_message_bg_color_callback'),
2009 + 'mxchat-theme',
2010 + 'mxchat_theme_section'
6910 2011 );
6911 2012
6912 2013 add_settings_field(
6913 - 'telegram_away_message',
6914 - __('Away Message', 'mxchat'),
6915 - array($this, 'mxchat_telegram_away_message_callback'),
6916 - 'mxchat-embed',
6917 - 'mxchat_telegram_section'
2014 + 'live_agent_message_font_color',
2015 + 'Live Agent Font Color',
2016 + array($this, 'mxchat_live_agent_message_font_color_callback'),
2017 + 'mxchat-theme',
2018 + 'mxchat_theme_section'
6918 2019 );
6919 2020
2021 + // Mode Indicator Background Color
6920 2022 add_settings_field(
6921 - 'telegram_bot_token',
6922 - __('Telegram Bot Token', 'mxchat'),
6923 - array($this, 'mxchat_telegram_bot_token_callback'),
6924 - 'mxchat-embed',
6925 - 'mxchat_telegram_section'
2023 + 'mode_indicator_bg_color',
2024 + 'Mode Indicator Background Color',
2025 + array($this, 'mxchat_mode_indicator_bg_color_callback'),
2026 + 'mxchat-theme',
2027 + 'mxchat_theme_section'
6926 2028 );
6927 2029
2030 + // Mode Indicator Font Color
6928 2031 add_settings_field(
6929 - 'telegram_group_id',
6930 - __('Telegram Group ID', 'mxchat'),
6931 - array($this, 'mxchat_telegram_group_id_callback'),
6932 - 'mxchat-embed',
6933 - 'mxchat_telegram_section'
2032 + 'mode_indicator_font_color',
2033 + 'Mode Indicator Font Color',
2034 + array($this, 'mxchat_mode_indicator_font_color_callback'),
2035 + 'mxchat-theme',
2036 + 'mxchat_theme_section'
6934 2037 );
6935 2038
6936 2039 add_settings_field(
6937 - 'telegram_webhook_secret',
6938 - __('Webhook Secret Token', 'mxchat'),
6939 - array($this, 'mxchat_telegram_webhook_secret_callback'),
6940 - 'mxchat-embed',
6941 - 'mxchat_telegram_section'
2040 + 'toolbar_icon_color',
2041 + 'Toolbar Icon Color',
2042 + array($this, 'mxchat_toolbar_icon_color_callback'),
2043 + 'mxchat-theme',
2044 + 'mxchat_theme_section'
6942 2045 );
6943 2046
6944 2047 // General Settings Section
6945 2048 add_settings_section(
6946 2049 'mxchat_general_section',
6947 - esc_html__('YouTube Tutorials', 'mxchat'),
2050 + 'Frequently Asked Questions (FAQ)',
6948 2051 null,
6949 2052 'mxchat-general'
6950 2053 );
6951 -}
6952 2054
6953 -public function mxchat_prompts_page_init() {
6954 - register_setting(
6955 - 'mxchat_prompts_options',
6956 - 'mxchat_prompts_options',
6957 - array(
6958 - 'type' => 'array',
6959 - 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
6960 - 'default' => array(
6961 - 'mxchat_auto_sync_posts' => 0,
6962 - 'mxchat_auto_sync_pages' => 0,
6963 - 'mxchat_use_pinecone' => 0,
6964 - 'mxchat_pinecone_api_key' => '',
6965 - 'mxchat_pinecone_environment' => '',
6966 - 'mxchat_pinecone_index' => '',
6967 - 'mxchat_pinecone_host' => '',
6968 - ),
6969 - 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
6970 - )
6971 - );
6972 2055
6973 - add_action('admin_notices', array($this, 'sync_settings_notice'));
6974 -}
6975 2056
6976 -public function mxchat_transcripts_page_init() {
6977 - register_setting(
6978 - 'mxchat_transcripts_options',
6979 - 'mxchat_transcripts_options',
6980 - array(
6981 - 'type' => 'array',
6982 - 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
6983 - 'default' => array(
6984 - 'mxchat_enable_notifications' => 0,
6985 - 'mxchat_notification_email' => get_option('admin_email'),
6986 - 'mxchat_auto_delete_transcripts' => 'never',
6987 - ),
6988 - 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
6989 - )
6990 - );
6991 2057
6992 - add_settings_section(
6993 - 'mxchat_transcripts_notification_section',
6994 - esc_html__('Chat Notification Settings', 'mxchat'),
6995 - array($this, 'mxchat_transcripts_notification_section_callback'),
6996 - 'mxchat-transcripts'
6997 - );
6998 2058
6999 - add_settings_field(
7000 - 'mxchat_enable_notifications',
7001 - esc_html__('Enable Chat Notifications', 'mxchat'),
7002 - array($this, 'mxchat_enable_notifications_callback'),
7003 - 'mxchat-transcripts',
7004 - 'mxchat_transcripts_notification_section'
7005 - );
7006 2059
7007 - add_settings_field(
7008 - 'mxchat_notification_email',
7009 - esc_html__('Notification Email Address', 'mxchat'),
7010 - array($this, 'mxchat_notification_email_callback'),
7011 - 'mxchat-transcripts',
7012 - 'mxchat_transcripts_notification_section'
7013 - );
2060 +}
7014 2061
7015 - add_settings_field(
7016 - 'mxchat_auto_delete_transcripts',
7017 - esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
7018 - array($this, 'mxchat_auto_delete_transcripts_callback'),
7019 - 'mxchat-transcripts',
7020 - 'mxchat_transcripts_notification_section'
7021 - );
2062 +public function mxchat_handle_activate_license() {
2063 + check_ajax_referer('mxchat_activate_license_nonce', 'security');
7022 2064
7023 - add_settings_field(
7024 - 'mxchat_retention_days',
7025 - esc_html__('Custom Retention (Days)', 'mxchat'),
7026 - array($this, 'mxchat_retention_days_callback'),
7027 - 'mxchat-transcripts',
7028 - 'mxchat_transcripts_notification_section'
7029 - );
2065 + $license_key = isset($_POST['mxchat_activation_key']) ? sanitize_text_field($_POST['mxchat_activation_key']) : '';
2066 + $customer_email = isset($_POST['mxchat_pro_email']) ? sanitize_email($_POST['mxchat_pro_email']) : '';
7030 2067
7031 - add_settings_field(
7032 - 'mxchat_auto_email_transcript',
7033 - esc_html__('Auto-Email Full Transcript', 'mxchat'),
7034 - array($this, 'mxchat_auto_email_transcript_callback'),
7035 - 'mxchat-transcripts',
7036 - 'mxchat_transcripts_notification_section'
7037 - );
7038 -}
2068 + if (empty($license_key) || empty($customer_email)) {
2069 + wp_send_json_error('Email or License Key is missing');
2070 + }
7039 2071
2072 + $product_id = 'MxChatPRO';
7040 2073
7041 -/**
7042 - * Sanitize all prompts options
7043 - *
7044 - * @param array $input The unsanitized options array
7045 - * @return array The sanitized options array
7046 - */
7047 -public function sanitize_prompts_options($input) {
7048 - // Log the incoming input.
7049 - //error_log('Sanitizing inputs: ' . print_r($input, true));
2074 + $response = wp_remote_get("http://mxchat.ai/?wc-api=software-api&request=activation&email={$customer_email}&license_key={$license_key}&product_id={$product_id}");
7050 2075
7051 - $sanitized = array();
2076 + if (is_wp_error($response)) {
2077 + wp_send_json_error('Activation failed due to a server error');
2078 + }
7052 2079
7053 - // Boolean options
7054 - $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
7055 - $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
7056 -$sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
2080 + $body = wp_remote_retrieve_body($response);
2081 + $data = json_decode($body);
7057 2082
7058 - // API Key: if less than 32 characters, flag as invalid.
7059 - $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
7060 - if (!empty($api_key) && strlen($api_key) < 32) {
7061 - add_settings_error(
7062 - 'mxchat_prompts_options',
7063 - 'invalid_api_key',
7064 - __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
7065 - );
7066 - $existing_options = get_option('mxchat_prompts_options', array());
7067 - $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
2083 + if ($data && isset($data->activated) && $data->activated) {
2084 + update_option('mxchat_license_status', 'active');
2085 + update_option('mxchat_pro_email', $customer_email);
2086 + update_option('mxchat_activation_key', $license_key);
2087 + wp_send_json_success();
7068 2088 } else {
7069 - $sanitized['mxchat_pinecone_api_key'] = $api_key;
2089 + $error_message = isset($data->error) ? $data->error : 'Activation failed';
2090 + update_option('mxchat_license_status', 'inactive');
2091 + update_option('mxchat_license_error', $error_message);
2092 + wp_send_json_error($error_message);
7070 2093 }
2094 +}
7071 2095
7072 - // Environment and Index Name
7073 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
7074 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
2096 +public function mxchat_rate_limit_logged_in_callback() {
2097 + $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' option
2098 + $selected_rate_limit = isset($this->options['rate_limit_logged_in']) ? $this->options['rate_limit_logged_in'] : '100';
7075 2099
7076 - // Host: Remove protocol and validate format.
7077 - $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
7078 - $host = preg_replace('#^https?://#', '', $host);
7079 - //error_log('Host after removing protocol: ' . $host);
7080 - if (!empty($host)) {
7081 - if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
7082 - add_settings_error(
7083 - 'mxchat_prompts_options',
7084 - 'invalid_host',
7085 - __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
7086 - );
7087 - $existing_options = get_option('mxchat_prompts_options', array());
7088 - $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
7089 - } else {
7090 - $sanitized['mxchat_pinecone_host'] = $host;
7091 - }
7092 - } else {
7093 - $sanitized['mxchat_pinecone_host'] = '';
2100 + echo '<div class="pro-feature-wrapper active">';
2101 + echo '<select id="rate_limit_logged_in" name="mxchat_options[rate_limit_logged_in]">';
2102 + foreach ($rate_limits as $limit) {
2103 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7094 2104 }
7095 -
7096 - //error_log('Final sanitized array: ' . print_r($sanitized, true));
7097 -
7098 - return $sanitized;
2105 + echo '</select>';
2106 + echo '<p class="description">Set the rate limit for logged-in users.</p>';
2107 + echo '</div>';
7099 2108 }
7100 2109
7101 -public function sync_settings_notice() {
7102 - // Only show notice on our plugin page
7103 - if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
7104 - return;
7105 - }
2110 +public function mxchat_rate_limit_logged_out_callback() {
2111 + $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' option
2112 + $selected_rate_limit = isset($this->options['rate_limit_logged_out']) ? $this->options['rate_limit_logged_out'] : '10';
7106 2113
7107 - // Check if settings were updated
7108 - if (isset($_GET['settings-updated'])) {
7109 -
7110 - ?>
7111 - <div class="notice notice-success is-dismissible">
7112 - <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
7113 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
7114 - </div>
7115 - <?php
7116 -
2114 + echo '<div class="pro-feature-wrapper active">';
2115 + echo '<select id="rate_limit_logged_out" name="mxchat_options[rate_limit_logged_out]">';
2116 + foreach ($rate_limits as $limit) {
2117 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7117 2118 }
2119 + echo '</select>';
2120 + echo '<p class="description">Set the rate limit for logged-out users.</p>';
2121 + echo '</div>';
7118 2122 }
7119 -// Add this sanitization function to your class
7120 -public function sanitize_sync_setting($input) {
7121 - return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
7122 -}
7123 2123
7124 -public function mxchat_rate_limits_callback() {
7125 - $all_options = get_option('mxchat_options', []);
7126 2124
7127 - // Define available rate limits
7128 - $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7129 -
7130 - // Define available timeframes
7131 - $timeframes = array(
7132 - 'hourly' => __('Per Hour', 'mxchat'),
7133 - 'daily' => __('Per Day', 'mxchat'),
7134 - 'weekly' => __('Per Week', 'mxchat'),
7135 - 'monthly' => __('Per Month', 'mxchat')
2125 +public function mxchat_rate_limit_message_callback() {
2126 + // Remove the is_activated check and make it always enabled
2127 + echo '<div class="pro-feature-wrapper active">';
2128 + printf(
2129 + '<textarea id="rate_limit_message" name="mxchat_options[rate_limit_message]" rows="3" cols="50">%s</textarea>',
2130 + isset($this->options['rate_limit_message']) ? esc_textarea($this->options['rate_limit_message']) : 'Rate limit exceeded. Please try again later.'
7136 2131 );
7137 -
7138 - // Get all roles plus a "logged_out" pseudo-role
7139 - $roles = wp_roles()->get_names();
7140 - $roles['logged_out'] = __('Logged Out Users', 'mxchat');
7141 -
7142 - // Start the wrapper
7143 - echo '<div class="pro-feature-wrapper active">';
7144 - echo '<div class="mxchat-rate-limits-container">';
7145 -
7146 - echo '<p class="description" style="margin-bottom: 20px;">' .
7147 - esc_html__('Set message limits for each user role and customize the experience when users reach those limits. You can use {limit}, {timeframe}, {count}, and {remaining} as placeholders.', 'mxchat') .
7148 - '</p>';
7149 -
7150 - // Add markdown link documentation
7151 - echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
7152 - echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
7153 - echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
7154 - echo '<ul style="margin-left: 20px;">';
7155 - echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
7156 - echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
7157 - echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
7158 - echo '</ul>';
7159 2132 echo '</div>';
2133 +}
7160 2134
7161 - // Output the controls for each role
7162 - foreach ($roles as $role_id => $role_name) {
7163 - // Get saved options or defaults
7164 - $default_limit = ($role_id === 'logged_out') ? '10' : '100';
7165 - $default_timeframe = 'daily';
7166 - $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
7167 2135
7168 - $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
7169 - ? $all_options['rate_limits'][$role_id]['limit']
7170 - : $default_limit;
2136 +public function mxchat_enable_woocommerce_integration_callback() {
2137 + $checked = isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1' ? 'checked' : '';
2138 + $disabled = $this->is_activated ? '' : 'disabled';
2139 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7171 2140
7172 - $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
7173 - ? $all_options['rate_limits'][$role_id]['timeframe']
7174 - : $default_timeframe;
2141 + echo '<div class="' . esc_attr($class) . '">';
2142 + echo '<label class="toggle-switch">';
2143 + echo '<input type="checkbox" id="enable_woocommerce_integration" name="mxchat_options[enable_woocommerce_integration]" value="1" ' . $checked . ' ' . $disabled . '>';
2144 + echo '<span class="slider"></span>';
2145 + echo '</label>';
7175 2146
7176 - $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
7177 - ? $all_options['rate_limits'][$role_id]['message']
7178 - : $default_message;
7179 -
7180 - // Output the row
7181 - echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
7182 -
7183 - // Role label
7184 - echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
7185 -
7186 - // Controls section
7187 - echo '<div class="mxchat-rate-limit-controls-wrapper">';
7188 -
7189 - // Rate limit and timeframe controls
7190 - echo '<div class="mxchat-rate-limit-controls">';
7191 -
7192 - // Limit dropdown
7193 - echo '<div>';
7194 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
7195 - echo '<select
7196 - id="rate_limits_' . esc_attr($role_id) . '_limit"
7197 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
7198 - class="mxchat-autosave-field">';
7199 - foreach ($rate_limits as $limit) {
7200 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
7201 - }
7202 - echo '</select>';
2147 + if (!$this->is_activated) {
2148 + echo '<div class="pro-feature-overlay">';
2149 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
7203 2150 echo '</div>';
2151 + }
7204 2152
7205 - // Timeframe dropdown
7206 - echo '<div>';
7207 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
7208 - echo '<select
7209 - id="rate_limits_' . esc_attr($role_id) . '_timeframe"
7210 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
7211 - class="mxchat-autosave-field">';
7212 - foreach ($timeframes as $value => $label) {
7213 - echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
7214 - }
7215 - echo '</select>';
7216 - echo '</div>';
2153 + echo '</div>';
2154 +}
7217 2155
7218 - echo '</div>'; // End controls
7219 2156
7220 - // Custom message textarea
7221 - echo '<div class="mxchat-rate-limit-message">';
7222 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
7223 - echo '<textarea
7224 - id="rate_limits_' . esc_attr($role_id) . '_message"
7225 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
7226 - class="mxchat-autosave-field"
7227 - placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
7228 - esc_textarea($custom_message) .
7229 - '</textarea>';
7230 - echo '<p class="description">' .
7231 - esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
7232 - '</p>';
7233 - echo '</div>'; // End message
7234 2157
7235 - echo '</div>'; // End controls wrapper
7236 2158
7237 - echo '</div>'; // End row
7238 - }
7239 -
7240 - echo '</div>'; // End container
7241 -
7242 - echo '</div>'; // End pro-feature-wrapper
7243 -}
7244 -
7245 -private function mxchat_add_option_field($id, $title, $callback = '') {
2159 + private function mxchat_add_option_field($id, $title, $callback = '') {
7246 2160 add_settings_field(
7247 2161 $id,
7248 - __($title, 'mxchat'),
2162 + $title,
7249 2163 $callback ? array($this, $callback) : array($this, $id . '_callback'),
7250 2164 'mxchat-max',
7251 2165 'mxchat_setting_section_id',
7252 2166 $id === 'model' ? ['label_for' => 'model'] : []
@@ -7252,572 +2166,202 @@
7252 2166 $id === 'model' ? ['label_for' => 'model'] : []
7253 2167 );
7254 2168 }
7255 2169
7256 -// API Keys Section Callback
7257 -public function mxchat_api_keys_section_callback() {
7258 - echo '<p>' . esc_html__('Manage all your API keys in one place. Add the API keys for the services you want to use with your chatbot.', 'mxchat') . '</p>';
7259 -}
7260 2170
7261 -// OpenAI API Key
7262 -public function api_key_callback() {
7263 - $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
7264 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2171 + public function api_key_callback() {
2172 + $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
2173 + echo '<input type="password" id="api_key" name="mxchat_options[api_key]" value="' . $apiKey . '" class="regular-text" />';
2174 + echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
2175 + }
7265 2176
7266 - echo '<div class="api-key-wrapper">';
7267 - echo '<input type="text" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7268 - echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7269 - echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
7270 - echo $this->mxchat_provider_key_test_button('openai', 'api_key');
7271 - echo '</div>';
7272 -}
2177 + public function xai_api_key_callback() {
2178 + // Check if the feature is activated (paid feature)
2179 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
2180 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
7273 2181
7274 -// X.AI API Key
7275 -public function xai_api_key_callback() {
7276 - $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
7277 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2182 + // Render the input field for the X.AI API key
2183 + echo '<div class="' . esc_attr($class) . '">';
2184 + printf(
2185 + '<input type="password" id="xai_api_key" name="mxchat_options[xai_api_key]" value="%s" class="regular-text" %s />',
2186 + isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '',
2187 + $disabled
2188 + );
2189 + echo '<button type="button" id="toggleXaiApiKeyVisibility">Show</button>';
7278 2190
7279 - echo '<div class="api-key-wrapper">';
7280 - echo '<input type="text" id="xai_api_key" name="xai_api_key" value="' . $xaiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7281 - echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7282 - echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
7283 - echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key');
7284 - echo '</div>';
7285 -}
7286 -// Claude API Key
7287 -public function claude_api_key_callback() {
7288 - $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
7289 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2191 + // If the feature is not activated, show the overlay with a "Pro Only" message
2192 + if (!$this->is_activated) {
2193 + echo '<div class="pro-feature-overlay">';
2194 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2195 + echo '</div>';
2196 + }
7290 2197
7291 - echo '<div class="api-key-wrapper">';
7292 - echo '<input type="text" id="claude_api_key" name="claude_api_key" value="' . $claudeApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7293 - echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7294 - echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
7295 - echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key');
7296 - echo '</div>';
7297 -}
2198 + echo '</div>';
2199 + }
7298 2200
7299 -// DeepSeek API Key
7300 -public function deepseek_api_key_callback() {
7301 - $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
7302 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2201 + public function claude_api_key_callback() {
2202 + // Check if the feature is activated (paid feature)
2203 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
2204 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
7303 2205
7304 - echo '<div class="api-key-wrapper">';
7305 - echo '<input type="text" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7306 - echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7307 - echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
7308 - echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key');
7309 - echo '</div>';
7310 -}
2206 + // Render the input field for the Claude API key
2207 + echo '<div class="' . esc_attr($class) . '">';
2208 + printf(
2209 + '<input type="password" id="claude_api_key" name="mxchat_options[claude_api_key]" value="%s" class="regular-text" %s />',
2210 + isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '',
2211 + $disabled
2212 + );
2213 + echo '<button type="button" id="toggleClaudeApiKeyVisibility">Show</button>';
7311 2214
7312 -// Gemini API Key
7313 -public function gemini_api_key_callback() {
7314 - $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
7315 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2215 + // If the feature is not activated, show the overlay with a "Pro Only" message
2216 + if (!$this->is_activated) {
2217 + echo '<div class="pro-feature-overlay">';
2218 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2219 + echo '</div>';
2220 + }
7316 2221
7317 - echo '<div class="api-key-wrapper">';
7318 - echo '<input type="text" id="gemini_api_key" name="gemini_api_key" value="' . $geminiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7319 - echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7320 - echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
7321 - echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key');
7322 - echo '</div>';
7323 -}
2222 + echo '</div>';
2223 + }
7324 2224
2225 + public function mxchat_woocommerce_consumer_key_callback() {
2226 + $disabled = $this->is_activated ? '' : 'disabled';
2227 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7325 2228
7326 -// OpenRouter API Key
7327 -public function openrouter_api_key_callback() {
7328 - $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
7329 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2229 + echo '<div class="' . esc_attr($class) . '">';
2230 + printf(
2231 + '<input type="text" id="woocommerce_consumer_key" name="mxchat_options[woocommerce_consumer_key]" value="%s" class="regular-text" %s />',
2232 + isset($this->options['woocommerce_consumer_key']) ? esc_attr($this->options['woocommerce_consumer_key']) : '',
2233 + $disabled
2234 + );
7330 2235
7331 - echo '<div class="api-key-wrapper">';
7332 - echo '<input type="text" id="openrouter_api_key" name="openrouter_api_key" value="' . $openrouterApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7333 - echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7334 - echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
7335 - echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key');
7336 - echo '</div>';
7337 -}
2236 + if (!$this->is_activated) {
2237 + echo '<div class="pro-feature-overlay">';
2238 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2239 + echo '</div>';
2240 + }
7338 2241
7339 -/**
7340 - * Renders a "Test key" button + result target next to a built-in provider key
7341 - * field, and emits the shared delegated click handler ONCE (static guard). The
7342 - * button carries data-target = the key field id so the owner can test the value
7343 - * they just typed (test-before-save); the AJAX handler falls back to the saved
7344 - * key when the field is empty. Styled with the WP `button` class to match the
7345 - * adjacent Custom-provider "Test Connection" button on this same page.
7346 - * plan-mxchat-20260623-c41f74.
7347 - */
7348 -public function mxchat_provider_key_test_button($provider, $target_id) {
7349 - static $script_emitted = false;
7350 - $nonce = wp_create_nonce('mxchat_test_provider_key');
7351 - $html = '<div class="mxchat-key-test" style="margin-top:8px;">'
7352 - . '<button type="button" class="button mxchat-test-provider-key" data-provider="' . esc_attr($provider) . '" data-target="' . esc_attr($target_id) . '" data-nonce="' . esc_attr($nonce) . '">' . esc_html__('Test key', 'mxchat') . '</button>'
7353 - . '<span class="mxchat-test-provider-key-result" style="margin-left:10px;font-size:13px;vertical-align:middle;"></span>'
7354 - . '</div>';
7355 - if (!$script_emitted) {
7356 - $script_emitted = true;
7357 - $html .= $this->mxchat_provider_key_test_script();
7358 - }
7359 - return $html;
7360 -}
2242 + echo '</div>';
2243 + }
7361 2244
7362 -/**
7363 - * One-time delegated click handler shared by every .mxchat-test-provider-key
7364 - * button. Posts the typed key value + provider to mxchat_test_provider_key and
7365 - * renders the success/error message inline. Mirrors the Custom-provider test.
7366 - */
7367 -private function mxchat_provider_key_test_script() {
7368 - $t_testing = esc_js(__('Testing...', 'mxchat'));
7369 - $t_valid = esc_js(__('Key is valid.', 'mxchat'));
7370 - $t_failed = esc_js(__('Failed', 'mxchat'));
7371 - $t_req = esc_js(__('Request failed', 'mxchat'));
7372 - return '<script>(function(){'
7373 - . 'if (window.__mxchatProviderKeyTestWired) { return; }'
7374 - . 'window.__mxchatProviderKeyTestWired = true;'
7375 - . 'document.addEventListener("click", function(e){'
7376 - . 'var btn = e.target && e.target.closest ? e.target.closest(".mxchat-test-provider-key") : null;'
7377 - . 'if (!btn) { return; }'
7378 - . 'e.preventDefault();'
7379 - . 'var field = btn.getAttribute("data-target") ? document.getElementById(btn.getAttribute("data-target")) : null;'
7380 - . 'var out = btn.parentNode ? btn.parentNode.querySelector(".mxchat-test-provider-key-result") : null;'
7381 - . 'if (out) { out.textContent = "' . $t_testing . '"; out.style.color = "#646970"; }'
7382 - . 'btn.disabled = true;'
7383 - . 'var fd = new FormData();'
7384 - . 'fd.append("action", "mxchat_test_provider_key");'
7385 - . 'fd.append("_wpnonce", btn.getAttribute("data-nonce"));'
7386 - . 'fd.append("provider", btn.getAttribute("data-provider") || "");'
7387 - . 'fd.append("key", field ? field.value : "");'
7388 - . 'fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })'
7389 - . '.then(function(r){ return r.json(); })'
7390 - . '.then(function(j){'
7391 - . 'if (out) {'
7392 - . 'if (j && j.success) { out.textContent = "✓ " + ((j.data && j.data.message) ? j.data.message : "' . $t_valid . '"); out.style.color = "#00a32a"; }'
7393 - . 'else { out.textContent = "⚠ " + ((j && j.data && j.data.message) ? j.data.message : "' . $t_failed . '"); out.style.color = "#d63638"; }'
7394 - . '}'
7395 - . 'btn.disabled = false;'
7396 - . '})'
7397 - . '.catch(function(){ if (out) { out.textContent = "⚠ ' . $t_req . '"; out.style.color = "#d63638"; } btn.disabled = false; });'
7398 - . '});'
7399 - . '})();</script>';
7400 -}
2245 + public function mxchat_woocommerce_consumer_secret_callback() {
2246 + $disabled = $this->is_activated ? '' : 'disabled';
2247 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7401 2248
7402 -// Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
7403 -public function custom_provider_callback() {
7404 - $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
7405 - $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
7406 - $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
7407 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
7408 - $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
7409 - $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
7410 - $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
7411 - $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
7412 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7413 - $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
2249 + echo '<div class="' . esc_attr($class) . '">';
2250 + printf(
2251 + '<input type="password" id="woocommerce_consumer_secret" name="mxchat_options[woocommerce_consumer_secret]" value="%s" class="regular-text" %s />',
2252 + isset($this->options['woocommerce_consumer_secret']) ? esc_attr($this->options['woocommerce_consumer_secret']) : '',
2253 + $disabled
2254 + );
2255 + echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';
7414 2256
7415 - echo '<style>
7416 - .mxchat-cp { max-width: 680px; }
7417 - .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
7418 - .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
7419 - .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
7420 - .mxchat-cp .mxchat-cp-row > input[type="text"],
7421 - .mxchat-cp .mxchat-cp-row > input[type="password"],
7422 - .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
7423 - .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
7424 - .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
7425 - .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
7426 - .mxchat-cp .mxchat-cp-azure { margin: 0 0 18px; padding: 12px 14px; background: #f6f7ff; border: 1px solid #dfe1f5; border-left: 3px solid #7873f5; border-radius: 6px; max-width: 480px; }
7427 - .mxchat-cp .mxchat-cp-azure > .mxchat-cp-azure-title { display: block; font-weight: 600; color: #1d2327; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; margin: 0 0 8px; }
7428 - .mxchat-cp .mxchat-cp-azure ol { margin: 0; padding: 0 0 0 18px; color: #50575e; font-size: 12px; line-height: 1.7; }
7429 - .mxchat-cp .mxchat-cp-azure code { background: #eceefb; padding: 1px 5px; border-radius: 3px; font-size: 11px; }
7430 - </style>';
2257 + if (!$this->is_activated) {
2258 + echo '<div class="pro-feature-overlay">';
2259 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2260 + echo '</div>';
2261 + }
7431 2262
7432 - echo '<div class="api-key-wrapper mxchat-cp">';
7433 - echo '<p class="mxchat-cp-intro">' . esc_html__('Point MxChat at any OpenAI-compatible /v1/chat/completions endpoint: Ollama, LM Studio, vLLM, llama.cpp, LocalAI, Azure OpenAI, etc. Then select "Custom (OpenAI-compatible)" in the model picker.', 'mxchat') . '</p>';
2263 + echo '</div>';
2264 + }
7434 2265
7435 - // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout
7436 - // so admins can configure Azure without piecing it together from each field's hint.
7437 - echo '<div class="mxchat-cp-azure">';
7438 - echo '<span class="mxchat-cp-azure-title">' . esc_html__('Azure OpenAI quick start', 'mxchat') . '</span>';
7439 - echo '<ol>';
7440 - echo '<li>' . wp_kses(__('<strong>Base URL</strong> → <code>https://&lt;resource&gt;.openai.azure.com/openai/deployments/&lt;deployment&gt;</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7441 - echo '<li>' . wp_kses(__('<strong>API Key</strong> → your Azure OpenAI key (required)', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7442 - echo '<li>' . wp_kses(__('<strong>Auth Scheme</strong> → <code>api-key header (Azure OpenAI)</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7443 - echo '<li>' . wp_kses(__('<strong>API Version</strong> → required for Azure, e.g. <code>2024-08-01-preview</code>', 'mxchat'), array('strong' => array(), 'code' => array())) . '</li>';
7444 - echo '</ol>';
7445 - echo '</div>';
2266 + public function mxchat_loops_api_key_callback() {
2267 + $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7446 2268
7447 - echo '<div class="mxchat-cp-row">';
7448 - echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
7449 - echo '<input type="text" id="custom_provider_base_url" name="custom_provider_base_url" value="' . $base_url . '" class="regular-text mxchat-autosave-field" placeholder="http://localhost:11434/v1" autocomplete="off" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7450 - echo '<p class="description">' . esc_html__('Examples: Ollama http://localhost:11434/v1 · LM Studio http://localhost:1234/v1 · vLLM http://gpu:8000/v1 · Azure https://<resource>.openai.azure.com/openai/deployments/<deployment>', 'mxchat') . '</p>';
7451 - echo '</div>';
2269 + echo '<div class="api-key-wrapper">';
2270 + printf(
2271 + '<input type="password" id="loops_api_key" name="mxchat_options[loops_api_key]" value="%s" class="regular-text" />',
2272 + $loops_api_key
2273 + );
2274 + echo '<button type="button" id="toggleLoopsApiKeyVisibility">Show</button>';
2275 + echo '</div>';
2276 + echo '<p class="description">Enter your Loops API Key here. (See FAQ for details)</p>';
2277 + }
7452 2278
7453 - echo '<div class="mxchat-cp-row">';
7454 - echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
7455 - echo '<input type="password" id="custom_provider_api_key" name="custom_provider_api_key" value="' . $api_key . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7456 - echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
7457 - echo '</div>';
2279 + public function mxchat_loops_mailing_list_callback() {
2280 + // Retrieve Loops API key and lists
2281 + $loops_api_key = isset($this->options['loops_api_key']) ? $this->options['loops_api_key'] : '';
2282 + $selected_list = isset($this->options['loops_mailing_list']) ? $this->options['loops_mailing_list'] : '';
7458 2283
7459 - echo '<div class="mxchat-cp-row">';
7460 - echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
7461 - echo '<input type="text" id="custom_provider_model" name="custom_provider_model" value="' . $model_name . '" class="regular-text mxchat-autosave-field" placeholder="llama3.2" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7462 - echo '<p class="description">' . esc_html__('The model identifier the upstream server expects (e.g. llama3.2, mistral, gpt-oss). For Azure this is the deployment ID — leave empty if the Base URL already includes /deployments/<deployment>.', 'mxchat') . '</p>';
7463 - echo '</div>';
2284 + if ($loops_api_key) {
2285 + // Fetch lists from Loops API
2286 + $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7464 2287
7465 - echo '<div class="mxchat-cp-row">';
7466 - echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
7467 - echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7468 - echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
7469 - echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
7470 - echo '</select>';
7471 - echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
7472 - echo '</div>';
7473 -
7474 - echo '<div class="mxchat-cp-row">';
7475 - echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
7476 - echo '<input type="text" id="custom_provider_api_version" name="custom_provider_api_version" value="' . $api_version . '" class="regular-text mxchat-autosave-field" placeholder="2024-08-01-preview" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7477 - echo '<p class="description">' . esc_html__('Appended as ?api-version=... on the request URL. Required for Azure OpenAI; leave empty for non-Azure providers.', 'mxchat') . '</p>';
7478 - echo '</div>';
7479 -
7480 - // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
7481 - echo '<div class="mxchat-cp-row">';
7482 - echo '<label style="font-weight:600; display:block; margin:0 0 6px; color:#1d2327; font-size:13px;">' . esc_html__('Extended routing (opt-in)', 'mxchat') . '</label>';
7483 - echo '<label style="display:block; margin:0 0 6px; font-weight:400;"><input type="checkbox" id="custom_provider_for_embeddings" name="custom_provider_for_embeddings" value="on"' . checked($use_embed, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for embeddings', 'mxchat') . '</label>';
7484 - echo '<label style="display:block; margin:0 0 0; font-weight:400;"><input type="checkbox" id="custom_provider_for_images" name="custom_provider_for_images" value="on"' . checked($use_images, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for image generation', 'mxchat') . '</label>';
7485 - echo '<p class="description">' . esc_html__('When off, embeddings and image generation continue to use OpenAI (current behavior). Turn on only if your endpoint exposes OpenAI-compatible /embeddings or /images/generations routes (e.g. Ollama, vLLM, LocalAI).', 'mxchat') . '</p>';
7486 - echo '</div>';
7487 -
7488 - echo '<div class="mxchat-cp-row">';
7489 - echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
7490 - echo '<input type="text" id="custom_provider_embedding_model" name="custom_provider_embedding_model" value="' . $embed_model . '" class="regular-text mxchat-autosave-field" placeholder="nomic-embed-text" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
7491 - echo '<p class="description">' . esc_html__('Only used when "Use custom provider for embeddings" is on. The embedding model name is separate from the chat model name above (e.g. Ollama embedding models: nomic-embed-text, mxbai-embed-large). Leave blank to fall back to the chat model name.', 'mxchat') . '</p>';
7492 - echo '</div>';
7493 -
7494 - echo '<div class="mxchat-cp-test">';
7495 - echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
7496 - echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
7497 - echo '</div>';
7498 -
7499 - echo '<script>(function(){
7500 - var btn = document.getElementById("mxchat-test-custom-provider");
7501 - if (!btn || btn._wired) { return; } btn._wired = true;
7502 - btn.addEventListener("click", function(){
7503 - var out = document.getElementById("mxchat-test-custom-provider-result");
7504 - out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
7505 - out.style.color = "#646970";
7506 - var fd = new FormData();
7507 - fd.append("action", "mxchat_test_custom_provider");
7508 - fd.append("_wpnonce", btn.getAttribute("data-nonce"));
7509 - fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
7510 - .then(function(r){ return r.json(); })
7511 - .then(function(j){
7512 - if (j && j.success) {
7513 - out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
7514 - out.style.color = "#00a32a";
7515 - } else {
7516 - out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
7517 - out.style.color = "#d63638";
2288 + if ($lists) {
2289 + echo '<select id="loops_mailing_list" name="mxchat_options[loops_mailing_list]">';
2290 + foreach ($lists as $list) {
2291 + echo '<option value="' . esc_attr($list['id']) . '" ' . selected($selected_list, $list['id'], false) . '>' . esc_html($list['name']) . '</option>';
7518 2292 }
7519 - })
7520 - .catch(function(){
7521 - out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
7522 - out.style.color = "#d63638";
7523 - });
7524 - });
7525 - })();</script>';
2293 + echo '</select>';
2294 + } else {
2295 + echo '<p class="description">No lists found. Please verify your API Key.</p>';
2296 + }
2297 + } else {
2298 + echo '<p class="description">Enter a valid Loops API Key to load mailing lists.</p>';
2299 + }
2300 + }
7526 2301
7527 - echo '</div>';
7528 -}
2302 + public function mxchat_triggered_phrase_response_callback() {
2303 + $triggered_response = isset($this->options['triggered_phrase_response']) ? $this->options['triggered_phrase_response'] : '';
2304 + echo '<textarea id="triggered_phrase_response" name="mxchat_options[triggered_phrase_response]" rows="3" cols="50">' . esc_textarea($triggered_response) . '</textarea>';
2305 + echo '<p class="description">Enter the chatbot response when a trigger keyword is detected, prompting the user to share their email.</p>';
2306 + }
7529 2307
7530 -// Voyage API Key
7531 -public function voyage_api_key_callback() {
7532 - $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
7533 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2308 + public function mxchat_email_capture_response_callback() {
2309 + $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.';
2310 + echo '<textarea id="email_capture_response" name="mxchat_options[email_capture_response]" rows="3" cols="50">' . esc_textarea($email_capture_response) . '</textarea>';
2311 + echo '<p class="description">Enter the message to send when a user provides their email.</p>';
2312 + }
7534 2313
7535 - echo '<div class="api-key-wrapper">';
7536 - echo '<input type="text" id="voyage_api_key" name="voyage_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7537 - echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7538 - echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
7539 - echo '</div>';
7540 -}
7541 2314
7542 -public function mxchat_loops_api_key_callback() {
7543 - $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7544 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7545 -
7546 - echo '<div class="api-key-wrapper">';
7547 - echo sprintf(
7548 - '<input type="text" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
7549 - $loops_api_key,
7550 - $nonce
7551 - );
7552 - echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7553 - echo '</div>';
7554 - // Cross-reference back to where the list is chosen, so the two screens point
7555 - // at each other (plan-mxchat-20260802-907a63).
7556 - echo '<p class="description">' . wp_kses(
7557 - sprintf(
7558 - /* translators: %s: link to the Loops integration tab. */
7559 - __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'),
7560 - '<a href="#integrations-loops">' . esc_html__('Integrations, Loops', 'mxchat') . '</a>'
7561 - ),
7562 - self::mxchat_loops_pointer_allowed_html()
7563 - ) . '</p>';
7564 -}
7565 -public function mxchat_loops_mailing_list_callback() {
7566 - // Add error handling and type checking
7567 - $loops_api_key = '';
7568 - $selected_list = '';
7569 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7570 -
7571 - // Safely get the API key
7572 - if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
7573 - $loops_api_key = $this->options['loops_api_key'];
2315 + public function mxchat_pre_chat_message_callback() {
2316 + printf(
2317 + '<textarea id="pre_chat_message" name="mxchat_options[pre_chat_message]" rows="5" cols="50">%s</textarea>',
2318 + isset($this->options['pre_chat_message']) ? esc_textarea($this->options['pre_chat_message']) : ''
2319 + );
7574 2320 }
7575 2321
7576 - // Safely get the selected list
7577 - if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
7578 - $selected_list = $this->options['loops_mailing_list'];
2322 + // Callback for AI Instructions textarea
2323 + public function system_prompt_instructions_callback() {
2324 + printf(
2325 + '<textarea id="system_prompt_instructions" name="mxchat_options[system_prompt_instructions]" rows="5" cols="50">%s</textarea>',
2326 + isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''
2327 + );
7579 2328 }
7580 2329
7581 - if (!empty($loops_api_key)) {
7582 - $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7583 - if (is_array($lists) && !empty($lists)) {
7584 - echo '<div class="mxchat-field-wrapper">';
7585 - echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7586 -
7587 - // Add a default "Select a list" option
7588 - echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
7589 -
7590 - foreach ($lists as $list) {
7591 - if (is_array($list) && isset($list['id']) && isset($list['name'])) {
7592 - echo sprintf(
7593 - '<option value="%s" %s>%s</option>',
7594 - esc_attr($list['id']),
7595 - selected($selected_list, $list['id'], false),
7596 - esc_html($list['name'])
7597 - );
7598 - }
7599 - }
7600 - echo '</select>';
7601 - echo '</div>';
7602 - echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
7603 - } else {
7604 - echo '<p class="description">' . wp_kses(
7605 - self::mxchat_loops_api_key_pointer(
7606 - /* translators: %s: link to the API Keys tab. */
7607 - __('No lists found. Please check your Loops API key under %s.', 'mxchat')
7608 - ),
7609 - self::mxchat_loops_pointer_allowed_html()
7610 - ) . '</p>';
7611 - }
7612 - } else {
7613 - echo '<p class="description">' . wp_kses(
7614 - self::mxchat_loops_api_key_pointer(
7615 - /* translators: %s: link to the API Keys tab. */
7616 - __('Enter your Loops API key under %s to load mailing lists.', 'mxchat')
7617 - ),
7618 - self::mxchat_loops_pointer_allowed_html()
7619 - ) . '</p>';
7620 - }
7621 -}
7622 -
7623 -/**
7624 - * Build the "API Keys" pointer used by the Loops mailing-list field.
7625 - *
7626 - * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API
7627 - * Keys tab, but this field's copy still read as though the input were beside
7628 - * it, so users had nowhere to go. Both live on the SAME screen
7629 - * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this
7630 - * dropdown under Integrations > Loops — so the pointer is an in-page tab
7631 - * switch, not a cross-page link.
7632 - *
7633 - * A plain href="#api-keys" is all it takes: the shared admin shell
7634 - * (js/admin-sidebar.js) honours section-naming hashes on load AND on
7635 - * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old
7636 - * data-target workaround on these pointer anchors is gone.
7637 - *
7638 - * @param string $template Translatable string containing one %s placeholder.
7639 - * @return string
7640 - */
7641 -private static function mxchat_loops_api_key_pointer($template) {
7642 - return sprintf(
7643 - $template,
7644 - '<a href="#api-keys">' . esc_html__('API Keys', 'mxchat') . '</a>'
7645 - );
7646 -}
7647 -
7648 -/**
7649 - * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook.
7650 - */
7651 -private static function mxchat_loops_pointer_allowed_html() {
7652 - return array(
7653 - 'a' => array(
7654 - 'href' => array(),
7655 - 'data-target' => array(),
2330 +public function mxchat_model_callback() {
2331 + $models = array(
2332 + 'X.AI Models' => array(
2333 + 'grok-beta' => 'grok-beta (Early Beta)'
7656 2334 ),
2335 + 'Claude Models' => array(
2336 + 'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet (Most Intelligent)',
2337 + 'claude-3-opus-20240229' => 'Claude 3 Opus (Highly Complex Tasks)',
2338 + 'claude-3-sonnet-20240229' => 'Claude 3 Sonnet (Balanced)',
2339 + 'claude-3-haiku-20240307' => 'Claude 3 Haiku (Fastest)'
2340 + ),
2341 + 'OpenAI Models' => array(
2342 + 'gpt-4o' => 'GPT-4o (Recommended)',
2343 + 'gpt-4o-mini' => 'GPT-4o Mini (Fast and Lightweight)',
2344 + 'gpt-4-turbo' => 'GPT-4 Turbo (High-Performance)',
2345 + 'gpt-4' => 'GPT-4 (High Intelligence)',
2346 + 'gpt-3.5-turbo' => 'GPT-3.5 Turbo (Affordable and Fast)'
2347 + )
7657 2348 );
7658 -}
7659 -public function mxchat_triggered_phrase_response_callback() {
7660 - $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
7661 - $triggered_response = isset($this->options['triggered_phrase_response'])
7662 - ? $this->options['triggered_phrase_response']
7663 - : $default_response;
7664 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7665 2349
7666 - echo '<div class="mxchat-field-wrapper">';
7667 - echo sprintf(
7668 - '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7669 - $nonce,
7670 - esc_textarea($triggered_response)
7671 - );
7672 - echo '</div>';
7673 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '</p>';
7674 -}
2350 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';
7675 2351
7676 -public function mxchat_email_capture_response_callback() {
7677 - $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
7678 - $email_capture_response = isset($this->options['email_capture_response'])
7679 - ? $this->options['email_capture_response']
7680 - : $default_response;
7681 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2352 + echo '<select id="model" name="mxchat_options[model]">';
7682 2353
7683 - echo '<div class="mxchat-field-wrapper">';
7684 - echo sprintf(
7685 - '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7686 - $nonce,
7687 - esc_textarea($email_capture_response)
7688 - );
7689 - echo '</div>';
7690 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '</p>';
7691 -}
7692 -public function mxchat_pre_chat_message_callback() {
7693 - // Load the entire 'mxchat_options' array
7694 - $all_options = get_option('mxchat_options', []);
7695 -
7696 - // Retrieve the saved message or use the default value
7697 - $default_message = __('Hey there! Ask me anything!', 'mxchat');
7698 - $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
7699 -
7700 - // Output the textarea
7701 - printf(
7702 - '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
7703 - esc_textarea($pre_chat_message)
7704 - );
7705 -}
7706 -
7707 -// Callback for AI Instructions textarea
7708 -public function system_prompt_instructions_callback() {
7709 - // Retrieve the current value of the system prompt instructions
7710 - $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
7711 - // Render the textarea field
7712 - printf(
7713 - '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
7714 - $instructions
7715 - );
7716 - // Personalization hint
7717 - echo '<p class="description" style="margin-top: 8px;">';
7718 - echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
7719 - echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
7720 - echo '</p>';
7721 - // Sample instructions button
7722 - echo '<div class="mxchat-instructions-container">';
7723 - echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
7724 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7725 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7726 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7727 - echo '</svg>';
7728 - echo esc_html__('View Sample Instructions', 'mxchat');
7729 - echo '</button>';
7730 - echo '</div>';
7731 -
7732 - // Add modal to WordPress admin footer instead of inline
7733 - add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
7734 -}
7735 -
7736 -// New method to render modal in admin footer
7737 -public function render_sample_instructions_modal() {
7738 - static $modal_rendered = false;
7739 - if ($modal_rendered) return; // Prevent duplicate modals
7740 - $modal_rendered = true;
7741 -
7742 - echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
7743 - echo '<div class="mxchat-instructions-modal-content">';
7744 - echo '<div class="mxchat-instructions-modal-header">';
7745 - echo '<h3 class="mxchat-instructions-modal-title">';
7746 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7747 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7748 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7749 - echo '</svg>';
7750 - echo esc_html__('Sample AI Instructions', 'mxchat');
7751 - echo '</h3>';
7752 - echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
7753 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7754 - echo '<line x1="18" y1="6" x2="6" y2="18"/>';
7755 - echo '<line x1="6" y1="6" x2="18" y2="18"/>';
7756 - echo '</svg>';
7757 - echo '</button>';
7758 - echo '</div>';
7759 - echo '<div class="mxchat-instructions-modal-body">';
7760 - echo '<div class="mxchat-instructions-content">';
7761 - echo esc_html('You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
7762 -
7763 -# Response Style - CRITICALLY IMPORTANT
7764 -- MAXIMUM LENGTH: 1-3 short sentences per response
7765 -- Ultra-concise: Get straight to the answer with no filler
7766 -- No introductions like "Sure!" or "I\'d be happy to help"
7767 -- No phrases like "based on my knowledge" or "according to information"
7768 -- No explanatory text before giving the answer
7769 -- No summaries or repetition
7770 -- Hyperlink all URLs
7771 -- Respond in user\'s language
7772 -- Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
7773 -
7774 -# Knowledge Base Requirements - PREVENT HALLUCINATIONS
7775 -- ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
7776 -- If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
7777 -- NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
7778 -- When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
7779 -- Better to admit insufficient information than provide inaccurate answers');
7780 - echo '</div>';
7781 - echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
7782 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7783 - echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
7784 - echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
7785 - echo '</svg>';
7786 - echo esc_html__('Copy Instructions', 'mxchat');
7787 - echo '</button>';
7788 - echo '</div>';
7789 - echo '<div class="mxchat-instructions-modal-footer">';
7790 - echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
7791 - echo '</div>';
7792 - echo '</div>';
7793 - echo '</div>';
7794 -}
7795 -
7796 -
7797 -public function mxchat_model_callback() {
7798 - // Catalog refactor (plan-d14e89): single source of truth lives in
7799 - // includes/class-mxchat-model-catalog.php. Dropdown groups are the
7800 - // provider labels; each group maps model_id => "Label" strings.
7801 - if (!class_exists('MxChat_Model_Catalog')) {
7802 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
7803 - }
7804 - // Retrieve the currently selected model from saved options
7805 - $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.6-sol';
7806 -
7807 - // Pass the saved model so a provider-retired id keeps rendering as the
7808 - // current selection instead of a blank select (plan e46b8f).
7809 - $models = MxChat_Model_Catalog::settings_dropdown_groups($selected_model);
7810 -
7811 - // Begin the select dropdown
7812 - echo '<select id="model" name="model">';
7813 -
7814 - // Iterate over groups of models
7815 2354 foreach ($models as $group_label => $group_models) {
7816 2355 echo '<optgroup label="' . esc_attr($group_label) . '">';
7817 2356
7818 2357 foreach ($group_models as $model_value => $model_label) {
7819 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
2358 + // Disable if not activated for paid models (Claude or X.AI)
2359 + $disabled = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? 'disabled' : '';
2360 + $label_suffix = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? ' (Pro Only)' : '';
2361 +
2362 + // Output the <option> element
2363 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . ' ' . $disabled . '>' . esc_html($model_label . $label_suffix) . '</option>';
7820 2364 }
7821 2365
7822 2366 echo '</optgroup>';
7823 2367 }
@@ -7822,1027 +2366,690 @@
7822 2366 echo '</optgroup>';
7823 2367 }
7824 2368
7825 2369 echo '</select>';
2370 +}
7826 2371
7827 - // Add a note for OpenRouter
7828 - echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
7829 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
7830 - echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
7831 - echo '</p>';
7832 2372
7833 - // API Key Status Messages (hidden by default, shown by JS based on selected model)
7834 - $has_openai_key = !empty($this->options['api_key']);
7835 - $has_claude_key = !empty($this->options['claude_api_key']);
7836 - $has_xai_key = !empty($this->options['xai_api_key']);
7837 - $has_deepseek_key = !empty($this->options['deepseek_api_key']);
7838 - $has_gemini_key = !empty($this->options['gemini_api_key']);
7839 - $has_openrouter_key = !empty($this->options['openrouter_api_key']);
7840 2373
7841 - // OpenAI/GPT models
7842 - echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
7843 - if ($has_openai_key) {
7844 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
7845 - } else {
7846 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
2374 + public function mxchat_top_bar_title_callback() {
2375 + printf(
2376 + '<input type="text" id="top_bar_title" name="mxchat_options[top_bar_title]" value="%s" />',
2377 + isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : ''
2378 + );
7847 2379 }
7848 - echo '</p>';
7849 2380
7850 - // Claude models
7851 - echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
7852 - if ($has_claude_key) {
7853 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
7854 - } else {
7855 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
2381 + public function mxchat_intro_message_callback() {
2382 + printf(
2383 + '<textarea id="intro_message" name="mxchat_options[intro_message]" rows="5" cols="50">%s</textarea>',
2384 + isset($this->options['intro_message']) ? esc_textarea($this->options['intro_message']) : 'Hello! How can I assist you today?'
2385 + );
7856 2386 }
7857 - echo '</p>';
7858 2387
7859 - // X.AI models
7860 - echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
7861 - if ($has_xai_key) {
7862 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
7863 - } else {
7864 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for X.AI (Grok) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
2388 + public function mxchat_input_copy_callback() {
2389 + printf(
2390 + '<input type="text" id="input_copy" name="mxchat_options[input_copy]" value="%s" placeholder="How can I assist?" />',
2391 + isset($this->options['input_copy']) ? esc_attr($this->options['input_copy']) : 'How can I assist?'
2392 + );
2393 + echo '<p class="description">This is the placeholder text for the chat input field.</p>';
7865 2394 }
7866 - echo '</p>';
7867 2395
7868 - // DeepSeek models
7869 - echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
7870 - if ($has_deepseek_key) {
7871 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
7872 - } else {
7873 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7874 - }
7875 - echo '</p>';
7876 2396
7877 - // Gemini models
7878 - echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
7879 - if ($has_gemini_key) {
7880 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
7881 - } else {
7882 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7883 - }
7884 - echo '</p>';
7885 2397
7886 - // OpenRouter models
7887 - echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
7888 - if ($has_openrouter_key) {
7889 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
7890 - } else {
7891 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7892 - }
7893 - echo '</p>';
7894 2398
7895 - // ADD THESE HIDDEN FIELDS RIGHT HERE:
7896 - $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
7897 - $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
7898 2399
7899 - echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
7900 - echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
7901 -}
7902 2400
7903 -// Update your existing callback method
7904 -public function enable_streaming_toggle_callback() {
7905 - // Get value from options array, default to 'on'
7906 - $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
7907 - $checked = ($enabled === 'on') ? 'checked' : '';
2401 + public function mxchat_close_button_color_callback() {
2402 + $disabled = $this->is_activated ? '' : 'disabled';
7908 2403
7909 - echo '<label class="toggle-switch">';
7910 - echo sprintf(
7911 - '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
7912 - esc_attr($checked)
2404 + echo '<div class="pro-feature-wrapper">';
2405 + printf(
2406 + '<input type="text" id="close_button_color" name="mxchat_options[close_button_color]" value="%s" class="my-color-field" data-default-color="#4a4a4a" %s />',
2407 + isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '',
2408 + esc_attr($disabled)
7913 2409 );
7914 - echo '<span class="slider"></span>';
7915 - echo '</label>';
7916 2410
7917 - // Test button — branded .mxch-btn with inline SVG (IDs preserved for AJAX binding)
7918 - echo '<div class="mxch-streaming-test-row">';
7919 - echo '<button type="button" id="mxchat-test-streaming-btn" class="mxch-btn mxch-btn-secondary">';
7920 - echo '<svg class="mxch-streaming-test-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>';
7921 - echo esc_html__('Test Streaming Compatibility', 'mxchat');
7922 - echo '</button>';
7923 - echo '<p id="mxchat-test-streaming-result" class="mxch-streaming-test-result"></p>';
2411 + if (!$this->is_activated) {
2412 + echo '<div class="pro-feature-overlay">';
2413 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2414 + echo '</div>';
2415 + }
2416 +
7924 2417 echo '</div>';
7925 -}
2418 + }
7926 2419
7927 -// Web Search toggle callback
7928 -public function enable_web_search_toggle_callback() {
7929 - // Get value from options array, default to 'off'
7930 - $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
7931 - $checked = ($enabled === 'on') ? 'checked' : '';
2420 + public function mxchat_chatbot_bg_color_callback() {
2421 + $disabled = $this->is_activated ? '' : 'disabled';
7932 2422
7933 - // Get current model to determine if we should show/enable the toggle
7934 - $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
2423 + echo '<div class="pro-feature-wrapper">';
2424 + printf(
2425 + '<input type="text" id="chatbot_bg_color" name="mxchat_options[chatbot_bg_color]" value="%s" class="my-color-field" data-default-color="#f9f9f9" %s />',
2426 + isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '',
2427 + esc_attr($disabled)
2428 + );
7935 2429
7936 - // Models that DON'T support web search — OpenAI-docs-driven exception list.
7937 - // Keep hardcoded; the catalog can't infer "supports web search" per-model, so any
7938 - // future OpenAI model that lacks Responses-API web_search support is added here.
7939 - $unsupported_models = array('gpt-4.1-nano');
2430 + if (!$this->is_activated) {
2431 + echo '<div class="pro-feature-overlay">';
2432 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2433 + echo '</div>';
2434 + }
7940 2435
7941 - // Web-search-capable chat-model allowlists, derived from the central model catalog
7942 - // (class-mxchat-model-catalog.php). When a new OpenAI/Gemini chat model is added there,
7943 - // the Web Search toggle picks it up automatically — no edit here.
7944 - // OpenAI grounds via the Responses-API web_search tool; Gemini grounds natively via the
7945 - // Google Search tool (plan 46b9ea wired the Gemini dispatch — every shipped Gemini chat
7946 - // model is 2.x/3.x and grounds, matching that path's empty opt-out list, so all catalog
7947 - // Gemini models are supported here).
7948 - if (!class_exists('MxChat_Model_Catalog')) {
7949 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
2436 + echo '</div>';
7950 2437 }
7951 - $chat_catalog = MxChat_Model_Catalog::chat_models();
7952 - $openai_models = (isset($chat_catalog['openai']['models']) && is_array($chat_catalog['openai']['models']))
7953 - ? array_keys($chat_catalog['openai']['models'])
7954 - : array();
7955 - $gemini_models = (isset($chat_catalog['gemini']['models']) && is_array($chat_catalog['gemini']['models']))
7956 - ? array_keys($chat_catalog['gemini']['models'])
7957 - : array();
7958 2438
7959 - $is_capable = in_array($current_model, $openai_models) || in_array($current_model, $gemini_models);
7960 - $is_supported = $is_capable && !in_array($current_model, $unsupported_models);
2439 + public function mxchat_user_message_bg_color_callback() {
2440 + $disabled = $this->is_activated ? '' : 'disabled';
7961 2441
7962 - // Wrapper div with data attributes for JS to show/hide. data-openai-models is kept for
7963 - // back-compat; data-gemini-models is the added second provider the JS now also honors.
7964 - echo '<div id="web-search-toggle-wrapper" data-openai-models="' . esc_attr(implode(',', $openai_models)) . '" data-gemini-models="' . esc_attr(implode(',', $gemini_models)) . '" data-unsupported-models="' . esc_attr(implode(',', $unsupported_models)) . '"' . (!$is_supported ? ' style="display:none;"' : '') . '>';
2442 + echo '<div class="pro-feature-wrapper">';
2443 + printf(
2444 + '<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 />',
2445 + isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '',
2446 + esc_attr($disabled)
2447 + );
7965 2448
7966 - echo '<label class="toggle-switch">';
7967 - echo sprintf(
7968 - '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
7969 - esc_attr($checked)
7970 - );
7971 - echo '<span class="slider"></span>';
7972 - echo '</label>';
2449 + if (!$this->is_activated) {
2450 + echo '<div class="pro-feature-overlay">';
2451 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2452 + echo '</div>';
2453 + }
7973 2454
7974 - echo '</div>';
2455 + echo '</div>';
2456 + }
7975 2457
7976 - // Message shown when a model that can't ground (Claude, Grok, DeepSeek, OpenRouter, etc.) is selected
7977 - echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
7978 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
7979 - echo esc_html__('Web search is only available for OpenAI and Gemini models.', 'mxchat');
7980 - echo '</p>';
7981 -}
2458 + public function mxchat_user_message_font_color_callback() {
2459 + $disabled = $this->is_activated ? '' : 'disabled';
7982 2460
7983 -// AJAX handler to fetch OpenRouter models
7984 -public function fetch_openrouter_models() {
7985 - check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
2461 + echo '<div class="pro-feature-wrapper">';
2462 + printf(
2463 + '<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 />',
2464 + isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '',
2465 + esc_attr($disabled)
2466 + );
7986 2467
7987 - // plan-mxchat-20260731-c63fb6 — nonce is not authorization.
7988 - if (!current_user_can('manage_options')) {
7989 - wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')), 403);
2468 + if (!$this->is_activated) {
2469 + echo '<div class="pro-feature-overlay">';
2470 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2471 + echo '</div>';
2472 + }
2473 +
2474 + echo '</div>';
7990 2475 }
7991 2476
7992 - $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
7993 -
7994 - if (empty($api_key)) {
7995 - wp_send_json_error(array('message' => 'API key is required'));
7996 - }
7997 -
7998 - $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
7999 - 'headers' => array(
8000 - 'Authorization' => 'Bearer ' . $api_key,
8001 - 'Content-Type' => 'application/json',
8002 - ),
8003 - 'timeout' => 15,
8004 - ));
8005 -
8006 - if (is_wp_error($response)) {
8007 - wp_send_json_error(array('message' => $response->get_error_message()));
8008 - }
8009 -
8010 - $body = wp_remote_retrieve_body($response);
8011 - $data = json_decode($body, true);
8012 -
8013 - if (isset($data['data']) && is_array($data['data'])) {
8014 - // Format the models for the frontend
8015 - $models = array_map(function($model) {
8016 - return array(
8017 - 'id' => $model['id'],
8018 - 'name' => $model['name'] ?? $model['id'],
8019 - 'description' => $model['description'] ?? '',
8020 - 'context_length' => $model['context_length'] ?? 0,
8021 - 'pricing' => array(
8022 - 'prompt' => $model['pricing']['prompt'] ?? 0,
8023 - 'completion' => $model['pricing']['completion'] ?? 0,
8024 - ),
8025 - );
8026 - }, $data['data']);
8027 -
8028 - wp_send_json_success(array('models' => $models));
8029 - } else {
8030 - wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
8031 - }
8032 -}
2477 + public function mxchat_bot_message_bg_color_callback() {
2478 + $disabled = $this->is_activated ? '' : 'disabled';
8033 2479
8034 -// Callback function for embedding model selection
8035 -public function embedding_model_callback() {
8036 - $models = array(
8037 - esc_html__('OpenAI Embeddings', 'mxchat') => array(
8038 - 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
8039 - 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
8040 - 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
8041 - ),
8042 - esc_html__('Voyage AI Embeddings', 'mxchat') => array(
8043 - 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
8044 - ),
8045 - esc_html__('Google Gemini Embeddings', 'mxchat') => array(
8046 - 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
8047 - )
8048 - );
8049 - $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
8050 - // With custom-provider embeddings on, this picker is inert — the effective
8051 - // model comes from the Custom Embedding Model field (plan ae02cb). Autosave
8052 - // fires only on user change events, so the disabled attribute cannot cause
8053 - // a missing-key save; JS keeps the state in sync with the toggle live.
8054 - $custom_embeddings_on = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
8055 - echo '<select id="embedding_model" name="embedding_model"' . ($custom_embeddings_on ? ' disabled' : '') . '>';
8056 - foreach ($models as $group_label => $group_models) {
8057 - echo '<optgroup label="' . esc_attr($group_label) . '">';
8058 - foreach ($group_models as $model_value => $model_label) {
8059 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
2480 + echo '<div class="pro-feature-wrapper">';
2481 + printf(
2482 + '<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 />',
2483 + isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '',
2484 + esc_attr($disabled)
2485 + );
2486 +
2487 + if (!$this->is_activated) {
2488 + echo '<div class="pro-feature-overlay">';
2489 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2490 + echo '</div>';
8060 2491 }
8061 - echo '</optgroup>';
2492 +
2493 + echo '</div>';
8062 2494 }
8063 - echo '</select>';
8064 - echo '<p class="mxch-field-description mxchat-embedding-custom-note" id="mxchat_embedding_custom_note"' . ($custom_embeddings_on ? '' : ' style="display:none;"') . '>';
8065 - echo esc_html__('Custom provider embeddings are in use — the model is set in the Custom Embedding Model field under Custom Provider.', 'mxchat');
8066 - echo '</p>';
8067 2495
8068 - // API Key Status Messages for Embedding Models
8069 - $has_openai_key = !empty($this->options['api_key']);
8070 - $has_voyage_key = !empty($this->options['voyage_api_key']);
8071 - $has_gemini_key = !empty($this->options['gemini_api_key']);
2496 + public function mxchat_bot_message_font_color_callback() {
2497 + $disabled = $this->is_activated ? '' : 'disabled';
8072 2498
8073 - // OpenAI Embeddings
8074 - echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
8075 - if ($has_openai_key) {
8076 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
8077 - } else {
8078 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8079 - }
8080 - echo '</p>';
2499 + echo '<div class="pro-feature-wrapper">';
2500 + printf(
2501 + '<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 />',
2502 + isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '',
2503 + esc_attr($disabled)
2504 + );
8081 2505
8082 - // Voyage AI Embeddings
8083 - echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
8084 - if ($has_voyage_key) {
8085 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
8086 - } else {
8087 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
2506 + if (!$this->is_activated) {
2507 + echo '<div class="pro-feature-overlay">';
2508 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2509 + echo '</div>';
2510 + }
2511 +
2512 + echo '</div>';
8088 2513 }
8089 - echo '</p>';
8090 2514
8091 - // Gemini Embeddings
8092 - echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
8093 - if ($has_gemini_key) {
8094 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
8095 - } else {
8096 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
8097 - }
8098 - echo '</p>';
2515 + public function mxchat_live_agent_message_bg_color_callback() {
2516 + $disabled = $this->is_activated ? '' : 'disabled';
8099 2517
8100 -}
2518 + echo '<div class="pro-feature-wrapper">';
2519 + printf(
2520 + '<input type="text" id="live_agent_message_bg_color" name="mxchat_options[live_agent_message_bg_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
2521 + isset($this->options['live_agent_message_bg_color']) ? esc_attr($this->options['live_agent_message_bg_color']) : '',
2522 + esc_attr($disabled)
2523 + );
8101 2524
2525 + if (!$this->is_activated) {
2526 + echo '<div class="pro-feature-overlay">';
2527 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2528 + echo '</div>';
2529 + }
8102 2530
8103 -public function mxchat_top_bar_title_callback() {
8104 - // Retrieve the current value of the top bar title from saved options
8105 - $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
2531 + echo '</div>';
2532 + }
8106 2533
8107 - // Render the input field
8108 - echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
8109 -}
8110 -public function mxchat_ai_agent_text_callback() {
8111 - // Retrieve the current value of the AI agent text from saved options
8112 - $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
8113 - // Render the input field
8114 - echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
8115 -}
2534 + public function mxchat_live_agent_message_font_color_callback() {
2535 + $disabled = $this->is_activated ? '' : 'disabled';
8116 2536
2537 + echo '<div class="pro-feature-wrapper">';
2538 + printf(
2539 + '<input type="text" id="live_agent_message_font_color" name="mxchat_options[live_agent_message_font_color]" value="%s" class="my-color-field" data-default-color="#333333" %s />',
2540 + isset($this->options['live_agent_message_font_color']) ? esc_attr($this->options['live_agent_message_font_color']) : '',
2541 + esc_attr($disabled)
2542 + );
8117 2543
8118 -public function enable_email_block_callback() {
8119 - // Load full plugin options array
8120 - $all_options = get_option('mxchat_options', []);
2544 + if (!$this->is_activated) {
2545 + echo '<div class="pro-feature-overlay">';
2546 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2547 + echo '</div>';
2548 + }
8121 2549
8122 - // Get the value, default to 'off'
8123 - $enable_email_block = isset($all_options['enable_email_block']) ? $all_options['enable_email_block'] : 'off';
2550 + echo '</div>';
2551 + }
8124 2552
8125 - // Check if it's 'on'
8126 - $checked = ($enable_email_block === 'on') ? 'checked' : '';
2553 + // Mode Indicator Background Color Callback
2554 +public function mxchat_mode_indicator_bg_color_callback() {
2555 + $disabled = $this->is_activated ? '' : 'disabled';
8127 2556
8128 - echo '<label class="toggle-switch">';
8129 - echo sprintf(
8130 - '<input type="checkbox" id="enable_email_block" name="enable_email_block" value="on" %s />',
8131 - esc_attr($checked)
2557 + echo '<div class="pro-feature-wrapper">';
2558 + printf(
2559 + '<input type="text" id="mode_indicator_bg_color" name="mxchat_options[mode_indicator_bg_color]" value="%s" class="my-color-field" data-default-color="#767676" %s />',
2560 + isset($this->options['mode_indicator_bg_color']) ? esc_attr($this->options['mode_indicator_bg_color']) : '',
2561 + esc_attr($disabled)
8132 2562 );
8133 - echo '<span class="slider"></span>';
8134 - echo '</label>';
8135 -}
8136 2563
8137 -public function email_blocker_header_content_callback() {
8138 - // Load the entire 'mxchat_options' array
8139 - $all_options = get_option('mxchat_options', []);
2564 + if (!$this->is_activated) {
2565 + echo '<div class="pro-feature-overlay">';
2566 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2567 + echo '</div>';
2568 + }
8140 2569
8141 - // Retrieve the saved content or default to empty
8142 - $content = isset($all_options['email_blocker_header_content'])
8143 - ? $all_options['email_blocker_header_content']
8144 - : '';
8145 -
8146 - // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
8147 - echo '<textarea
8148 - id="email_blocker_header_content"
8149 - name="email_blocker_header_content"
8150 - rows="5"
8151 - cols="70"
8152 - data-setting="email_blocker_header_content"
8153 - >' . esc_textarea($content) . '</textarea>';
2570 + echo '</div>';
8154 2571 }
8155 2572
8156 -public function email_blocker_button_text_callback() {
8157 - // Load the entire 'mxchat_options' array
8158 - $all_options = get_option('mxchat_options', []);
2573 +// Mode Indicator Font Color Callback
2574 +public function mxchat_mode_indicator_font_color_callback() {
2575 + $disabled = $this->is_activated ? '' : 'disabled';
8159 2576
8160 - // Retrieve the saved button text or default to empty
8161 - $button_text = isset($all_options['email_blocker_button_text'])
8162 - ? $all_options['email_blocker_button_text']
8163 - : '';
8164 -
8165 - // Use esc_attr to safely render the existing text
8166 - echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
8167 -}
8168 -
8169 -//Enable name field callback
8170 -public function enable_name_field_callback() {
8171 - // Load full plugin options array
8172 - $all_options = get_option('mxchat_options', []);
8173 - // Get the value, default to 'off'
8174 - $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
8175 - // Check if it's 'on'
8176 - $checked = ($enable_name_field === 'on') ? 'checked' : '';
8177 - echo '<label class="toggle-switch">';
8178 - echo sprintf(
8179 - '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
8180 - esc_attr($checked)
2577 + echo '<div class="pro-feature-wrapper">';
2578 + printf(
2579 + '<input type="text" id="mode_indicator_font_color" name="mxchat_options[mode_indicator_font_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
2580 + isset($this->options['mode_indicator_font_color']) ? esc_attr($this->options['mode_indicator_font_color']) : '',
2581 + esc_attr($disabled)
8181 2582 );
8182 - echo '<span class="slider"></span>';
8183 - echo '</label>';
8184 -}
8185 -//Name field placeholder callback
8186 -public function name_field_placeholder_callback() {
8187 - $all_options = get_option('mxchat_options', []);
8188 - $placeholder = isset($all_options['name_field_placeholder'])
8189 - ? $all_options['name_field_placeholder']
8190 - : esc_html__('Enter your name', 'mxchat');
8191 2583
8192 - echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
8193 -}
2584 + if (!$this->is_activated) {
2585 + echo '<div class="pro-feature-overlay">';
2586 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2587 + echo '</div>';
2588 + }
8194 2589
8195 -
8196 -
8197 -public function mxchat_intro_message_callback() {
8198 - // Load the entire 'mxchat_options' array
8199 - $all_options = get_option('mxchat_options', []);
8200 - // Retrieve the saved intro message or use the default
8201 - $default_message = __('Hello! How can I assist you today?', 'mxchat');
8202 - $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
8203 - // Escape on output (esc_textarea) — neutralizes any payload already stored before the
8204 - // Wordfence Stored-XSS fix (CWE-79, plan-3f8158) and prevents </textarea> context-breakout.
8205 - ?>
8206 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea( $saved_message ); ?></textarea>
8207 - <p class="description" style="margin-top: 8px;">
8208 - <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
8209 - <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
8210 - </p>
8211 - <?php
2590 + echo '</div>';
8212 2591 }
8213 2592
8214 -public function mxchat_input_copy_callback() {
8215 - // Load the entire 'mxchat_options' array
8216 - $all_options = get_option('mxchat_options', []);
2593 +public function mxchat_toolbar_icon_color_callback() {
2594 + $disabled = $this->is_activated ? '' : 'disabled';
8217 2595
8218 - // Retrieve the saved input copy or use the default value
8219 - $default_copy = __('How can I assist?', 'mxchat');
8220 - $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
8221 -
8222 - // Output the input field with the saved value
2596 + echo '<div class="pro-feature-wrapper">';
8223 2597 printf(
8224 - '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
8225 - esc_attr($input_copy),
8226 - esc_attr__('How can I assist?', 'mxchat')
2598 + '<input type="text" id="toolbar_icon_color" name="mxchat_options[toolbar_icon_color]" value="%s" class="my-color-field" data-default-color="#212121" %s />',
2599 + isset($this->options['toolbar_icon_color']) ? esc_attr($this->options['toolbar_icon_color']) : '',
2600 + esc_attr($disabled)
8227 2601 );
8228 -}
8229 2602
2603 + if (!$this->is_activated) {
2604 + echo '<div class="pro-feature-overlay">';
2605 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2606 + echo '</div>';
2607 + }
8230 2608
8231 -public function mxchat_append_to_body_callback() {
8232 - // Fetch fresh options to ensure we have the latest saved values
8233 - $options = get_option('mxchat_options', array());
2609 + echo '</div>';
2610 +}
8234 2611
8235 - // Get value from options array, default to 'off'
8236 - $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
8237 - $checked = ($append_to_body === 'on') ? 'checked' : '';
8238 2612
8239 - // Get post type visibility settings
8240 - $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
8241 - $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
8242 - if (!is_array($visibility_list)) {
8243 - $visibility_list = array();
8244 - }
8245 2613
8246 - echo '<div class="mxchat-autosave-section">';
8247 2614
8248 - // Main toggle
8249 - echo '<label class="toggle-switch">';
8250 - echo sprintf(
8251 - '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
8252 - esc_attr($checked)
8253 - );
8254 - echo '<span class="slider"></span>';
8255 - echo '</label>';
2615 + public function mxchat_top_bar_bg_color_callback() {
2616 + $disabled = $this->is_activated ? '' : 'disabled';
8256 2617
8257 - // Post Type Visibility Options (only visible when auto-display is ON)
8258 - $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
8259 - echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
2618 + echo '<div class="pro-feature-wrapper">';
2619 + printf(
2620 + '<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 />',
2621 + isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '',
2622 + esc_attr($disabled)
2623 + );
8260 2624
8261 - echo '<div class="mxchat-post-type-visibility-header">';
8262 - echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
8263 - echo '</div>';
2625 + if (!$this->is_activated) {
2626 + echo '<div class="pro-feature-overlay">';
2627 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2628 + echo '</div>';
2629 + }
8264 2630
8265 - // Mode selector (radio buttons)
8266 - echo '<div class="mxchat-visibility-mode">';
2631 + echo '</div>';
2632 + }
8267 2633
8268 - echo '<label class="mxchat-radio-label">';
8269 - echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
8270 - echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
8271 - echo '</label>';
2634 + public function mxchat_send_button_font_color_callback() {
2635 + $disabled = $this->is_activated ? '' : 'disabled';
8272 2636
8273 - echo '<label class="mxchat-radio-label">';
8274 - echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
8275 - echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
8276 - echo '</label>';
2637 + echo '<div class="pro-feature-wrapper">';
2638 + printf(
2639 + '<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 />',
2640 + isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '',
2641 + esc_attr($disabled)
2642 + );
8277 2643
8278 - echo '<label class="mxchat-radio-label">';
8279 - echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
8280 - echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
8281 - echo '</label>';
2644 + if (!$this->is_activated) {
2645 + echo '<div class="pro-feature-overlay">';
2646 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2647 + echo '</div>';
2648 + }
8282 2649
8283 - echo '</div>';
2650 + echo '</div>';
2651 + }
8284 2652
8285 - // Post type checkboxes (only visible when mode is include or exclude)
8286 - $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
8287 - echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
2653 + public function mxchat_chatbot_background_color_callback() {
2654 + $disabled = $this->is_activated ? '' : 'disabled';
8288 2655
8289 - // Get all public post types
8290 - $post_types = get_post_types(array('public' => true), 'objects');
2656 + echo '<div class="pro-feature-wrapper">';
2657 + printf(
2658 + '<input type="text" id="chatbot_background_color" name="mxchat_options[chatbot_background_color]" value="%s" class="my-color-field" data-default-color="#000000" %s />',
2659 + isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '',
2660 + esc_attr($disabled)
2661 + );
8291 2662
8292 - foreach ($post_types as $post_type) {
8293 - // Skip attachments
8294 - if ($post_type->name === 'attachment') {
8295 - continue;
2663 + if (!$this->is_activated) {
2664 + echo '<div class="pro-feature-overlay">';
2665 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2666 + echo '</div>';
8296 2667 }
8297 2668
8298 - $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
8299 -
8300 - echo '<label class="mxchat-checkbox-label">';
8301 - echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
8302 - echo '<span>' . esc_html($post_type->label) . '</span>';
8303 - echo '</label>';
2669 + echo '</div>';
8304 2670 }
8305 2671
8306 - echo '</div>'; // End post-type-list
8307 - echo '</div>'; // End post-type-visibility-options
8308 - echo '</div>'; // End mxchat-autosave-section
8309 -}
2672 + public function mxchat_icon_color_callback() {
2673 + $disabled = $this->is_activated ? '' : 'disabled';
8310 2674
8311 -public function mxchat_contextual_awareness_callback() {
8312 - // Get value from options array, default to 'off'
8313 - $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
8314 - $checked = ($contextual_awareness === 'on') ? 'checked' : '';
8315 - echo '<label class="toggle-switch">';
8316 - echo sprintf(
8317 - '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
8318 - esc_attr($checked)
8319 - );
8320 - echo '<span class="slider"></span>';
8321 - echo '</label>';
8322 -}
2675 + echo '<div class="pro-feature-wrapper">';
2676 + printf(
2677 + '<input type="text" id="icon_color" name="mxchat_options[icon_color]" value="%s" class="my-color-field" data-default-color="#ffffff" %s />',
2678 + isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '',
2679 + esc_attr($disabled)
2680 + );
8323 2681
8324 -public function mxchat_citation_links_toggle_callback() {
8325 - // Get value from options array, default to 'on' (enabled by default)
8326 - $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
8327 - $checked = ($citation_links === 'on') ? 'checked' : '';
8328 - echo '<label class="toggle-switch">';
8329 - echo sprintf(
8330 - '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
8331 - esc_attr($checked)
8332 - );
8333 - echo '<span class="slider"></span>';
8334 - echo '</label>';
8335 -}
2682 + if (!$this->is_activated) {
2683 + echo '<div class="pro-feature-overlay">';
2684 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2685 + echo '</div>';
2686 + }
8336 2687
8337 -/**
8338 - * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
8339 - * Default ON. The widget reads this through the localized object; the
8340 - * mxchat_satisfaction_rating_enabled filter still lets developers force
8341 - * the value site-wide.
8342 - *
8343 - * The 5 customization fields (idle/question/thanks/placeholder/saved) are
8344 - * rendered inline here inside a single wrapper div whose initial display
8345 - * is set server-side from the toggle value (plan-29caac). Mirrors the
8346 - * auto-display chatbot pattern at mxchat_append_to_body_callback — no
8347 - * DOMContentLoaded race because rows exist as direct children of this
8348 - * callback's output, and the wrapper's display: none is inline at render
8349 - * time so refresh shows the correct state with no flash.
8350 - */
8351 -public function mxchat_satisfaction_rating_toggle_callback() {
8352 - $options = $this->options;
8353 - $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
8354 - $checked = ($value === 'on') ? 'checked' : '';
2688 + echo '</div>';
2689 + }
8355 2690
8356 - $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
8357 - $idle = max(5, min(600, $idle));
8358 - $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
8359 - $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
8360 - $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
8361 - $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
2691 + public function mxchat_custom_icon_callback() {
2692 + $disabled = $this->is_activated ? '' : 'disabled';
2693 + $custom_icon_url = isset($this->options['custom_icon']) ? esc_url($this->options['custom_icon']) : '';
8362 2694
8363 - echo '<div class="mxchat-autosave-section">';
2695 + echo '<div class="pro-feature-wrapper">';
2696 + printf(
2697 + '<input type="url" id="custom_icon" name="mxchat_options[custom_icon]" value="%s" placeholder="Enter PNG URL" %s />',
2698 + $custom_icon_url,
2699 + esc_attr($disabled)
2700 + );
2701 + echo '<p class="description">Upload your PNG icon and paste the URL here. Recommended size: 48x48 pixels.</p>';
8364 2702
8365 - echo '<label class="toggle-switch">';
8366 - echo sprintf(
8367 - '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
8368 - esc_attr($checked)
8369 - );
8370 - echo '<span class="slider"></span>';
8371 - echo '</label>';
2703 + if (!$this->is_activated) {
2704 + echo '<div class="pro-feature-overlay">';
2705 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2706 + echo '</div>';
2707 + }
8372 2708
8373 - ?>
8374 - <style>
8375 - .mxchat-sub-options-field { margin: 12px 0; }
8376 - .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
8377 - #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
8378 - </style>
8379 - <?php
2709 + echo '</div>';
2710 + }
8380 2711
8381 - $display_style = ($value === 'on') ? '' : 'display: none;';
8382 - echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
8383 2712
8384 - echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
2713 + public function mxchat_chat_input_font_color_callback() {
2714 + $disabled = $this->is_activated ? '' : 'disabled';
8385 2715
8386 - echo '<div class="mxchat-sub-options-field">';
8387 - echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
8388 - printf(
8389 - '<input type="number" id="satisfaction_rating_idle_seconds" name="satisfaction_rating_idle_seconds" value="%d" min="5" max="600" step="1" class="small-text" /> <span class="description">%s</span>',
8390 - (int) $idle,
8391 - esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
8392 - );
8393 - echo '</div>';
2716 + echo '<div class="pro-feature-wrapper">';
2717 + printf(
2718 + '<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 />',
2719 + isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '',
2720 + esc_attr($disabled)
2721 + );
8394 2722
8395 - echo '<div class="mxchat-sub-options-field">';
8396 - echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
8397 - printf(
8398 - '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8399 - esc_attr($question),
8400 - esc_attr__('Was this helpful?', 'mxchat')
8401 - );
8402 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
8403 - echo '</div>';
2723 + if (!$this->is_activated) {
2724 + echo '<div class="pro-feature-overlay">';
2725 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2726 + echo '</div>';
2727 + }
8404 2728
8405 - echo '<div class="mxchat-sub-options-field">';
8406 - echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
8407 - printf(
8408 - '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
8409 - esc_attr($thanks),
8410 - esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
8411 - );
8412 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
8413 - echo '</div>';
2729 + echo '</div>';
2730 + }
8414 2731
8415 - echo '<div class="mxchat-sub-options-field">';
8416 - echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
8417 - printf(
8418 - '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8419 - esc_attr($placeholder),
8420 - esc_attr__('Tell us what could be better…', 'mxchat')
8421 - );
8422 - echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
8423 - echo '</div>';
8424 2732
8425 - echo '<div class="mxchat-sub-options-field">';
8426 - echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
2733 +public function mxchat_append_to_body_callback() {
2734 + $append_to_body_checked = isset($this->options['append_to_body']) && $this->options['append_to_body'] === 'on' ? 'checked' : '';
2735 + echo '<label class="toggle-switch">';
8427 2736 printf(
8428 - '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
8429 - esc_attr($saved),
8430 - esc_attr__('Thanks for the feedback.', 'mxchat')
2737 + '<input type="checkbox" id="append_to_body" name="mxchat_options[append_to_body]" %s />',
2738 + esc_attr($append_to_body_checked)
8431 2739 );
8432 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
8433 - echo '</div>';
2740 + echo '<span class="slider"></span>';
2741 + echo '</label>';
2742 +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>';
2743 +}
8434 2744
8435 - echo '</div>'; // #satisfaction-rating-sub-options
8436 - echo '</div>'; // .mxchat-autosave-section
8437 2745
8438 - ?>
8439 - <script>
8440 - (function() {
8441 - document.addEventListener('DOMContentLoaded', function() {
8442 - var toggle = document.getElementById('satisfaction_rating_enabled');
8443 - var subOptions = document.getElementById('satisfaction-rating-sub-options');
8444 - if (!toggle || !subOptions) return;
8445 - toggle.addEventListener('change', function() {
8446 - subOptions.style.display = toggle.checked ? '' : 'none';
8447 - });
8448 - });
8449 - })();
8450 - </script>
8451 - <?php
8452 -}
8453 -
8454 2746 public function mxchat_privacy_toggle_callback() {
8455 - // Load from mxchat_options array
8456 - $options = get_option('mxchat_options', []);
2747 + // Check if the privacy toggle is enabled
2748 + $privacy_toggle_checked = isset($this->options['privacy_toggle']) && $this->options['privacy_toggle'] === 'on' ? 'checked' : '';
8457 2749
8458 - // Get privacy toggle value with fallback
8459 - $privacy_toggle = isset($options['privacy_toggle']) ? $options['privacy_toggle'] : 'off';
8460 - $checked = ($privacy_toggle === 'on') ? 'checked' : '';
2750 + // Retrieve the stored privacy text if it exists
2751 + $privacy_text = isset($this->options['privacy_text']) ? wp_kses_post($this->options['privacy_text']) : 'By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.';
8461 2752
8462 - // Get privacy text with fallback
8463 - $privacy_text = isset($options['privacy_text'])
8464 - ? $options['privacy_text']
8465 - : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
8466 -
8467 2753 // Output the toggle switch
8468 2754 echo '<label class="toggle-switch">';
8469 - echo sprintf(
8470 - '<input type="checkbox" id="privacy_toggle" name="privacy_toggle" value="on" %s />',
8471 - esc_attr($checked)
2755 + printf(
2756 + '<input type="checkbox" id="privacy_toggle" name="mxchat_options[privacy_toggle]" %s />',
2757 + esc_attr($privacy_toggle_checked)
8472 2758 );
8473 2759 echo '<span class="slider"></span>';
8474 2760 echo '</label>';
2761 + echo '<p class="description">Enable this option to display a privacy notice below the chat widget.</p>';
8475 2762
8476 2763 // Output the custom text input field
8477 - echo sprintf(
8478 - '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
2764 + printf(
2765 + '<textarea id="privacy_text" name="mxchat_options[privacy_text]" rows="5" cols="50" class="regular-text">%s</textarea>',
8479 2766 esc_textarea($privacy_text)
8480 2767 );
2768 + echo '<p class="description">Enter the privacy policy text. You can include HTML links.</p>';
8481 2769 }
8482 2770
8483 2771
8484 2772 public function mxchat_complianz_toggle_callback() {
8485 - // Load from mxchat_options array
8486 - $options = get_option('mxchat_options', []);
2773 + // Check if the Complianz toggle is enabled
2774 + $complianz_toggle_checked = isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on' ? 'checked' : '';
8487 2775
8488 - // Get complianz toggle value with fallback
8489 - $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
8490 - $checked = ($complianz_toggle === 'on') ? 'checked' : '';
2776 + // Check if the plugin is activated (paid feature)
2777 + $disabled = $this->is_activated ? '' : 'disabled';
2778 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8491 2779
2780 + echo '<div class="' . esc_attr($class) . '">';
2781 +
8492 2782 // Output the toggle switch
8493 2783 echo '<label class="toggle-switch">';
8494 - echo sprintf(
8495 - '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
8496 - esc_attr($checked)
2784 + printf(
2785 + '<input type="checkbox" id="complianz_toggle" name="mxchat_options[complianz_toggle]" %s %s />',
2786 + esc_attr($complianz_toggle_checked),
2787 + esc_attr($disabled)
8497 2788 );
8498 2789 echo '<span class="slider"></span>';
8499 2790 echo '</label>';
8500 -}
2791 + echo '<p class="description">Enable this option to apply Complianz consent logic to the chatbot.</p>';
8501 2792
8502 -public function mxchat_link_target_toggle_callback() {
8503 - // Load from mxchat_options array
8504 - $options = get_option('mxchat_options', []);
2793 + // If the feature is not activated, show the Pro feature overlay
2794 + if (!$this->is_activated) {
2795 + echo '<div class="pro-feature-overlay">';
2796 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2797 + echo '</div>';
2798 + }
8505 2799
8506 - // Get link target toggle value with fallback
8507 - $link_target_toggle = isset($options['link_target_toggle']) ? $options['link_target_toggle'] : 'off';
8508 - $checked = ($link_target_toggle === 'on') ? 'checked' : '';
8509 -
8510 - // Output the toggle switch
8511 - echo '<label class="toggle-switch">';
8512 - echo sprintf(
8513 - '<input type="checkbox" id="link_target_toggle" name="link_target_toggle" value="on" %s />',
8514 - esc_attr($checked)
8515 - );
8516 - echo '<span class="slider"></span>';
8517 - echo '</label>';
2800 + echo '</div>';
8518 2801 }
8519 2802
8520 -public function mxchat_chat_persistence_toggle_callback() {
8521 - // Load from mxchat_options array
8522 - $options = get_option('mxchat_options', []);
8523 2803
8524 - // Get chat persistence toggle value with fallback
8525 - $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
8526 - $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
8527 2804
8528 - // Output the toggle switch
8529 - echo '<label class="toggle-switch">';
8530 - echo sprintf(
8531 - '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
8532 - esc_attr($checked)
8533 - );
8534 - echo '<span class="slider"></span>';
8535 - echo '</label>';
8536 -}
8537 2805
8538 -public function mxchat_print_button_toggle_callback() {
8539 - // Load from mxchat_options array
8540 - $options = get_option('mxchat_options', []);
8541 2806
8542 - // Default ON — the option was previously unexposed and the button always showed.
8543 - $print_button_enabled = isset($options['print_button_enabled']) ? $options['print_button_enabled'] : 'on';
8544 - $checked = ($print_button_enabled === 'on') ? 'checked' : '';
2807 +public function mxchat_link_target_toggle_callback() {
2808 + // Check if the toggle is enabled in the options
2809 + $link_target_toggle = isset($this->options['link_target_toggle']) && $this->options['link_target_toggle'] === 'on' ? 'checked' : '';
8545 2810
8546 2811 // Output the toggle switch
8547 2812 echo '<label class="toggle-switch">';
8548 - echo sprintf(
8549 - '<input type="checkbox" id="print_button_enabled" name="print_button_enabled" value="on" %s />',
8550 - esc_attr($checked)
2813 + printf(
2814 + '<input type="checkbox" id="link_target_toggle" name="mxchat_options[link_target_toggle]" %s />',
2815 + esc_attr($link_target_toggle)
8551 2816 );
8552 2817 echo '<span class="slider"></span>';
8553 2818 echo '</label>';
2819 + echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
8554 2820 }
8555 2821
8556 -/**
8557 - * Editor Assistant toggle (plan-8cb0cb). Standalone option, NOT in mxchat_options
8558 - * (bypasses the mxchat_sanitize strip-trap + autosave normalization). Default OFF.
8559 - * Saved by the mxchat_editor_assistant_enabled case in class-ajax-handler.php.
8560 - * Renders on Content → Settings (moved there from Settings → Behavior, plan-f7df40).
8561 - */
8562 -public function mxchat_editor_assistant_toggle_callback() {
8563 - $enabled = get_option('mxchat_editor_assistant_enabled', 'off');
8564 - $checked = ($enabled === 'on') ? 'checked' : '';
2822 +public function mxchat_chat_persistence_toggle_callback() {
2823 + // Check if chat persistence toggle is enabled
2824 + $chat_persistence_toggle_checked = isset($this->options['chat_persistence_toggle']) && $this->options['chat_persistence_toggle'] === 'on' ? 'checked' : '';
8565 2825
8566 - echo '<label class="toggle-switch">';
8567 - echo sprintf(
8568 - '<input type="checkbox" id="mxchat_editor_assistant_enabled" name="mxchat_editor_assistant_enabled" value="on" %s />',
8569 - esc_attr($checked)
8570 - );
8571 - echo '<span class="slider"></span>';
8572 - echo '</label>';
8573 -}
2826 + // Check if the plugin is activated (paid feature)
2827 + $disabled = $this->is_activated ? '' : 'disabled';
2828 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8574 2829
8575 -/**
8576 - * Hybrid keyword boost toggle (plan-38ffa1; rebuilt on the house toggle pattern
8577 - * in plan-64d34f — the hand-rolled .mxch-toggle markup matched neither selector
8578 - * the autosave JS uses to place its save confirmation, so the control looked
8579 - * dead). Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8580 - * mxchat_hybrid_keyword_toggle case in class-ajax-handler.php, which also runs
8581 - * capability detection on enable.
8582 - */
8583 -public function mxchat_hybrid_keyword_toggle_callback() {
8584 - $enabled = get_option('mxchat_hybrid_keyword_toggle', 'off');
8585 - $checked = ($enabled === 'on') ? 'checked' : '';
2830 + echo '<div class="' . esc_attr($class) . '">';
8586 2831
2832 + // Output the toggle switch
8587 2833 echo '<label class="toggle-switch">';
8588 - echo sprintf(
8589 - '<input type="checkbox" id="mxchat_hybrid_keyword_toggle" name="mxchat_hybrid_keyword_toggle" value="on" %s />',
8590 - esc_attr($checked)
2834 + printf(
2835 + '<input type="checkbox" id="chat_persistence_toggle" name="mxchat_options[chat_persistence_toggle]" %s %s />',
2836 + esc_attr($chat_persistence_toggle_checked),
2837 + esc_attr($disabled)
8591 2838 );
8592 2839 echo '<span class="slider"></span>';
8593 2840 echo '</label>';
8594 -}
2841 + echo '<p class="description">Enable to keep chat history when users navigate tabs or return to the site within 24 hours.</p>';
8595 2842
8596 -/**
8597 - * Smart asset loading toggle (plan-915355; rebuilt on the house toggle pattern
8598 - * in plan-64d34f, same dead-save-feedback defect as the hybrid keyword toggle).
8599 - * Standalone option, NOT in mxchat_options. Default OFF. Saved by the
8600 - * mxchat_smart_asset_loading case in class-ajax-handler.php.
8601 - */
8602 -public function mxchat_smart_asset_loading_toggle_callback() {
8603 - $enabled = get_option('mxchat_smart_asset_loading', 'off');
8604 - $checked = ($enabled === 'on') ? 'checked' : '';
2843 + // If not activated, show Pro feature overlay
2844 + if (!$this->is_activated) {
2845 + echo '<div class="pro-feature-overlay">';
2846 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2847 + echo '</div>';
2848 + }
8605 2849
8606 - echo '<label class="toggle-switch">';
8607 - echo sprintf(
8608 - '<input type="checkbox" id="mxchat_smart_asset_loading" name="mxchat_smart_asset_loading" value="on" %s />',
8609 - esc_attr($checked)
8610 - );
8611 - echo '<span class="slider"></span>';
8612 - echo '</label>';
2850 + echo '</div>';
8613 2851 }
8614 2852
8615 -public function mxchat_reset_chat_toggle_callback() {
8616 - // Load from mxchat_options array. plan ac2e81 — default OFF (new, opt-in).
8617 - $options = get_option('mxchat_options', []);
8618 - $reset_chat_enabled = isset($options['reset_chat_enabled']) ? $options['reset_chat_enabled'] : 'off';
8619 - $checked = ($reset_chat_enabled === 'on') ? 'checked' : '';
8620 2853
8621 - echo '<label class="toggle-switch">';
8622 - echo sprintf(
8623 - '<input type="checkbox" id="reset_chat_enabled" name="reset_chat_enabled" value="on" %s />',
8624 - esc_attr($checked)
2854 +public function mxchat_popular_question_1_callback() {
2855 + printf(
2856 + '<input type="text" id="popular_question_1" name="mxchat_options[popular_question_1]" value="%s" placeholder="Enter Popular Question 1" />',
2857 + isset($this->options['popular_question_1']) ? esc_attr($this->options['popular_question_1']) : ''
8625 2858 );
8626 - echo '<span class="slider"></span>';
8627 - echo '</label>';
2859 + echo '<p class="description">This will be the first popular question in the chatbot.</p>';
8628 2860 }
8629 2861
8630 -public function mxchat_reset_chat_label_callback() {
8631 - // Editable label for the "Start new chat" menu item. plan ac2e81.
8632 - $options = get_option('mxchat_options', []);
8633 - $reset_chat_label = isset($options['reset_chat_label']) ? $options['reset_chat_label'] : '';
2862 +public function mxchat_popular_question_2_callback() {
2863 + // Check if the plugin is activated (paid feature)
2864 + $disabled = $this->is_activated ? '' : 'disabled';
2865 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8634 2866
2867 + echo '<div class="' . esc_attr($class) . '">';
2868 +
8635 2869 printf(
8636 - '<input type="text" id="reset_chat_label" name="reset_chat_label" value="%s" placeholder="%s" class="regular-text" />',
8637 - esc_attr($reset_chat_label),
8638 - esc_attr__('Start new chat', 'mxchat')
2870 + '<input type="text" id="popular_question_2" name="mxchat_options[popular_question_2]" value="%s" placeholder="Enter Popular Question 2" %s />',
2871 + isset($this->options['popular_question_2']) ? esc_attr($this->options['popular_question_2']) : '',
2872 + esc_attr($disabled)
8639 2873 );
8640 -}
2874 + echo '<p class="description">This will be the second popular question in the chatbot.</p>';
8641 2875
8642 -public function mxchat_popular_question_1_callback() {
8643 - // Load the full plugin options array
8644 - $all_options = get_option('mxchat_options', []);
2876 + // If not activated, show Pro feature overlay
2877 + if (!$this->is_activated) {
2878 + echo '<div class="pro-feature-overlay">';
2879 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2880 + echo '</div>';
2881 + }
8645 2882
8646 - // Retrieve the specific option for popular_question_1
8647 - $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
8648 -
8649 - // Render the input field
8650 - printf(
8651 - '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
8652 - esc_attr($popular_question_1),
8653 - esc_attr__('Enter Quick Question 1', 'mxchat')
8654 - );
2883 + echo '</div>';
8655 2884 }
8656 2885
2886 +public function mxchat_popular_question_3_callback() {
2887 + // Check if the plugin is activated (paid feature)
2888 + $disabled = $this->is_activated ? '' : 'disabled';
2889 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8657 2890
8658 -public function mxchat_popular_question_2_callback() {
8659 - // Load the full plugin options array
8660 - $all_options = get_option('mxchat_options', []);
2891 + echo '<div class="' . esc_attr($class) . '">';
8661 2892
8662 - // Retrieve the specific option for popular_question_2
8663 - $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
8664 -
8665 - // Render the input field
8666 2893 printf(
8667 - '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
8668 - esc_attr($popular_question_2),
8669 - esc_attr__('Enter Quick Question 2', 'mxchat')
2894 + '<input type="text" id="popular_question_3" name="mxchat_options[popular_question_3]" value="%s" placeholder="Enter Popular Question 3" %s />',
2895 + isset($this->options['popular_question_3']) ? esc_attr($this->options['popular_question_3']) : '',
2896 + esc_attr($disabled)
8670 2897 );
8671 -}
2898 + echo '<p class="description">This will be the third popular question in the chatbot.</p>';
8672 2899
2900 + // If not activated, show Pro feature overlay
2901 + if (!$this->is_activated) {
2902 + echo '<div class="pro-feature-overlay">';
2903 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2904 + echo '</div>';
2905 + }
8673 2906
8674 -public function mxchat_popular_question_3_callback() {
8675 - // Load the full plugin options array
8676 - $all_options = get_option('mxchat_options', []);
8677 -
8678 - // Retrieve the specific option for popular_question_3
8679 - $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
8680 -
8681 - // Render the input field
8682 - printf(
8683 - '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
8684 - esc_attr($popular_question_3),
8685 - esc_attr(__('Enter Quick Question 3', 'mxchat'))
8686 - );
2907 + echo '</div>';
8687 2908 }
8688 2909
8689 2910 public function mxchat_additional_popular_questions_callback() {
8690 - $options = get_option('mxchat_options', []);
8691 - $additional_questions = isset($options['additional_popular_questions'])
8692 - ? $options['additional_popular_questions']
8693 - : get_option('additional_popular_questions', array());
2911 + $disabled = $this->is_activated ? '' : 'disabled';
2912 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
2913 + $additional_questions = isset($this->options['additional_popular_questions']) ? $this->options['additional_popular_questions'] : array();
8694 2914
2915 + echo '<div class="' . esc_attr($class) . '">';
8695 2916 echo '<div id="mxchat-additional-questions-container">';
2917 +
8696 2918 if (!empty($additional_questions)) {
8697 2919 foreach ($additional_questions as $index => $question) {
8698 2920 printf(
8699 2921 '<div class="mxchat-question-row">
8700 - <input type="text" name="additional_popular_questions[]"
8701 - value="%s"
8702 - placeholder="%s"
8703 - class="regular-text mxchat-question-input"
8704 - data-question-index="%d" />
8705 - <button type="button" class="button mxchat-remove-question"
8706 - aria-label="%s">%s</button>
2922 + <input type="text" name="mxchat_options[additional_popular_questions][]" value="%s" placeholder="Enter Additional Popular Question %d" %s />
2923 + <button type="button" class="button mxchat-remove-question" aria-label="Remove question" %s>Remove</button>
8707 2924 </div>',
8708 2925 esc_attr($question),
8709 - esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
8710 - $index,
8711 - esc_attr(__('Remove question', 'mxchat')),
8712 - esc_html__('Remove', 'mxchat')
2926 + $index + 4, // Start numbering from 4
2927 + esc_attr($disabled),
2928 + esc_attr($disabled)
8713 2929 );
8714 2930 }
8715 2931 } else {
8716 2932 printf(
8717 2933 '<div class="mxchat-question-row">
8718 - <input type="text" name="additional_popular_questions[]"
8719 - value=""
8720 - placeholder="%s"
8721 - class="regular-text mxchat-question-input"
8722 - data-question-index="0" />
8723 - <button type="button" class="button mxchat-remove-question"
8724 - aria-label="%s">%s</button>
2934 + <input type="text" name="mxchat_options[additional_popular_questions][]" value="" placeholder="Enter Additional Popular Question 4" %s />
2935 + <button type="button" class="button mxchat-remove-question" aria-label="Remove question" %s>Remove</button>
8725 2936 </div>',
8726 - esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
8727 - esc_attr(__('Remove question', 'mxchat')),
8728 - esc_html__('Remove', 'mxchat')
2937 + esc_attr($disabled),
2938 + esc_attr($disabled)
8729 2939 );
8730 2940 }
2941 +
8731 2942 echo '</div>';
2943 +
8732 2944 printf(
8733 - '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
8734 - esc_attr(__('Add question', 'mxchat')),
8735 - esc_html__('Add Question', 'mxchat')
2945 + '<button type="button" class="button mxchat-add-question" aria-label="Add question" %s>Add Question</button>',
2946 + esc_attr($disabled)
8736 2947 );
2948 +
2949 + echo '<p class="description">You can add more popular questions beyond the default three here.</p>';
2950 +
2951 + if (!$this->is_activated) {
2952 + echo '<div class="pro-feature-overlay">';
2953 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
2954 + echo '</div>';
2955 + }
2956 +
2957 + echo '</div>';
8737 2958 }
8738 2959
2960 +
2961 +/**
2962 + * Callback for Brave API Key field.
2963 + */
8739 2964 public function mxchat_brave_api_key_callback() {
8740 - $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
8741 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2965 + $options = get_option('mxchat_options');
2966 + $brave_api_key = isset($options['brave_api_key']) ? esc_attr($options['brave_api_key']) : '';
8742 2967
8743 2968 echo '<div class="api-key-wrapper">';
8744 - echo sprintf(
8745 - '<input type="text" id="brave_api_key" name="brave_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
8746 - $brave_api_key,
8747 - $nonce
2969 + printf(
2970 + '<input type="password" id="brave_api_key" name="mxchat_options[brave_api_key]" value="%s" class="regular-text" />',
2971 + $brave_api_key
8748 2972 );
8749 - echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
2973 + echo '<button type="button" id="toggleBraveApiKeyVisibility" class="button-secondary">Show</button>';
8750 2974 echo '</div>';
8751 - echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
2975 + echo '<p class="description">' . __('Enter your Brave Search API Key here. (See FAQ for details)', 'mxchat') . '</p>';
2976 +
2977 + ?>
2978 + <?php
8752 2979 }
8753 2980
2981 +/**
2982 + * Callback for Number of Images to Return field.
2983 + */
8754 2984 public function mxchat_brave_image_count_callback() {
8755 - $brave_image_count = isset($this->options['brave_image_count'])
8756 - ? intval($this->options['brave_image_count'])
8757 - : 4;
8758 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2985 + $options = get_option('mxchat_options');
2986 + $brave_image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
8759 2987
8760 - echo '<div class="mxchat-field-wrapper">';
8761 - echo sprintf(
8762 - '<input type="number" id="brave_image_count" name="brave_image_count"
8763 - value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8764 - $brave_image_count,
8765 - $nonce
2988 + printf(
2989 + '<input type="number" id="brave_image_count" name="mxchat_options[brave_image_count]" value="%d" min="1" max="6" />',
2990 + $brave_image_count
8766 2991 );
8767 - echo '</div>';
8768 2992 echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
8769 2993 }
8770 2994
2995 +/**
2996 + * Callback for Safe Search field.
2997 + */
8771 2998 public function mxchat_brave_safe_search_callback() {
8772 - $brave_safe_search = isset($this->options['brave_safe_search'])
8773 - ? esc_attr($this->options['brave_safe_search'])
8774 - : 'strict';
8775 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
2999 + $options = get_option('mxchat_options');
3000 + $brave_safe_search = isset($options['brave_safe_search']) ? esc_attr($options['brave_safe_search']) : 'strict';
8776 3001
8777 - echo '<div class="mxchat-field-wrapper">';
8778 - echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
8779 - echo sprintf(
8780 - '<option value="strict" %s>%s</option>',
8781 - selected($brave_safe_search, 'strict', false),
8782 - __('Strict', 'mxchat')
8783 - );
8784 - echo sprintf(
8785 - '<option value="off" %s>%s</option>',
8786 - selected($brave_safe_search, 'off', false),
8787 - __('Off', 'mxchat')
8788 - );
8789 - echo '</select>';
8790 - echo '</div>';
8791 - echo '<p class="description">' .
8792 - esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
8793 - '</p>';
3002 + ?>
3003 + <select id="brave_safe_search" name="mxchat_options[brave_safe_search]">
3004 + <option value="strict" <?php selected($brave_safe_search, 'strict'); ?>><?php _e('Strict', 'mxchat'); ?></option>
3005 + <option value="off" <?php selected($brave_safe_search, 'off'); ?>><?php _e('Off', 'mxchat'); ?></option>
3006 + </select>
3007 + <p class="description"><?php _e('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat'); ?></p>
3008 + <?php
8794 3009 }
8795 3010
3011 +
3012 +/**
3013 + * Callback for Number of News Articles field.
3014 + */
8796 3015 public function mxchat_brave_news_count_callback() {
8797 - $brave_news_count = isset($this->options['brave_news_count'])
8798 - ? intval($this->options['brave_news_count'])
8799 - : 3;
8800 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3016 + $options = get_option('mxchat_options');
3017 + $brave_news_count = isset($options['brave_news_count']) ? intval($options['brave_news_count']) : 3;
8801 3018
8802 - echo '<div class="mxchat-field-wrapper">';
8803 - echo sprintf(
8804 - '<input type="number" id="brave_news_count" name="brave_news_count"
8805 - value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8806 - $brave_news_count,
8807 - $nonce
3019 + printf(
3020 + '<input type="number" id="brave_news_count" name="mxchat_options[brave_news_count]" value="%d" min="1" max="10" />',
3021 + $brave_news_count
8808 3022 );
8809 - echo '</div>';
8810 - echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
3023 + echo '<p class="description">' . __('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
8811 3024 }
8812 3025
3026 +/**
3027 + * Callback for Country field.
3028 + */
8813 3029 public function mxchat_brave_country_callback() {
8814 - $brave_country = isset($this->options['brave_country'])
8815 - ? esc_attr($this->options['brave_country'])
8816 - : 'us';
8817 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3030 + $options = get_option('mxchat_options');
3031 + $brave_country = isset($options['brave_country']) ? esc_attr($options['brave_country']) : 'us';
8818 3032
8819 - echo '<div class="mxchat-field-wrapper">';
8820 - echo sprintf(
8821 - '<input type="text" id="brave_country" name="brave_country"
8822 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8823 - $brave_country,
8824 - $nonce
3033 + printf(
3034 + '<input type="text" id="brave_country" name="mxchat_options[brave_country]" value="%s" maxlength="2" class="small-text" />',
3035 + $brave_country
8825 3036 );
8826 - echo '</div>';
8827 - echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
3037 + echo '<p class="description">' . __('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
8828 3038 }
8829 3039
3040 +/**
3041 + * Callback for Language field.
3042 + */
8830 3043 public function mxchat_brave_language_callback() {
8831 - $brave_language = isset($this->options['brave_language'])
8832 - ? esc_attr($this->options['brave_language'])
8833 - : 'en';
8834 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3044 + $options = get_option('mxchat_options');
3045 + $brave_language = isset($options['brave_language']) ? esc_attr($options['brave_language']) : 'en';
8835 3046
8836 - echo '<div class="mxchat-field-wrapper">';
8837 - echo sprintf(
8838 - '<input type="text" id="brave_language" name="brave_language"
8839 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8840 - $brave_language,
8841 - $nonce
3047 + printf(
3048 + '<input type="text" id="brave_language" name="mxchat_options[brave_language]" value="%s" maxlength="2" class="small-text" />',
3049 + $brave_language
8842 3050 );
8843 - echo '</div>';
8844 - echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
3051 + echo '<p class="description">' . __('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
8845 3052 }
8846 3053
8847 3054
8848 3055
@@ -8853,1364 +3060,590 @@
8853 3060 echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
8854 3061 }
8855 3062
8856 3063 public function mxchat_chat_toolbar_toggle_callback() {
8857 - // Get chat toolbar toggle value with fallback
8858 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
8859 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
3064 + $checked = isset($this->options['chat_toolbar_toggle']) && $this->options['chat_toolbar_toggle'] === 'on' ? 'checked' : '';
3065 + $disabled = $this->is_activated ? '' : 'disabled';
3066 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8860 3067
8861 - // Output the toggle switch
3068 + echo '<div class="' . esc_attr($class) . '">';
8862 3069 echo '<label class="toggle-switch">';
8863 - echo sprintf(
8864 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
8865 - esc_attr($checked)
3070 + printf(
3071 + '<input type="checkbox" id="chat_toolbar_toggle" name="mxchat_options[chat_toolbar_toggle]" value="on" %s %s>',
3072 + esc_attr($checked),
3073 + esc_attr($disabled)
8866 3074 );
8867 3075 echo '<span class="slider"></span>';
8868 3076 echo '</label>';
8869 3077
8870 - echo '<p class="description">' . esc_html__('Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).', 'mxchat') . '</p>';
8871 -}
3078 + if (!$this->is_activated) {
3079 + echo '<div class="pro-feature-overlay">';
3080 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3081 + echo '</div>';
3082 + }
8872 3083
8873 -/**
8874 - * Callback for PDF upload button toggle setting
8875 - */
8876 -public function mxchat_show_pdf_upload_button_callback() {
8877 - // Get toggle value with fallback
8878 - $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
8879 - $checked = ($show_pdf_button === 'on') ? 'checked' : '';
8880 -
8881 - // Output the toggle switch
8882 - echo '<label class="toggle-switch">';
8883 - echo sprintf(
8884 - '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
8885 - esc_attr($checked)
8886 - );
8887 - echo '<span class="slider"></span>';
8888 - echo '</label>';
8889 -
8890 - echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
3084 + echo '</div>';
3085 + echo '<p class="description">Enable to display the chat toolbar (default is hidden).</p>';
8891 3086 }
8892 3087
8893 -/**
8894 - * Callback for Word upload button toggle setting
8895 - */
8896 -public function mxchat_show_word_upload_button_callback() {
8897 - // Get toggle value with fallback
8898 - $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
8899 - $checked = ($show_word_button === 'on') ? 'checked' : '';
8900 3088
8901 - // Output the toggle switch
8902 - echo '<label class="toggle-switch">';
8903 - echo sprintf(
8904 - '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
8905 - esc_attr($checked)
8906 - );
8907 - echo '<span class="slider"></span>';
8908 - echo '</label>';
8909 3089
8910 - echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
8911 -}
8912 -
3090 +// Intent Trigger Text Callback
8913 3091 public function mxchat_pdf_intent_trigger_text_callback() {
8914 - $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
3092 + $disabled = $this->is_activated ? '' : 'disabled';
3093 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8915 3094
8916 - echo sprintf(
8917 - '<textarea id="pdf_intent_trigger_text"
8918 - name="pdf_intent_trigger_text"
8919 - rows="3"
8920 - cols="50"
8921 - placeholder="%s">%s</textarea>',
8922 - esc_attr__('Enter trigger text', 'mxchat'),
8923 - isset($this->options['pdf_intent_trigger_text'])
8924 - ? esc_textarea($this->options['pdf_intent_trigger_text'])
8925 - : esc_textarea($default_text)
3095 + echo '<div class="' . esc_attr($class) . '">';
3096 + printf(
3097 + '<textarea id="pdf_intent_trigger_text" name="mxchat_options[pdf_intent_trigger_text]" rows="3" cols="50" placeholder="Enter trigger text" %s>%s</textarea>',
3098 + esc_attr($disabled),
3099 + isset($this->options['pdf_intent_trigger_text']) ? esc_textarea($this->options['pdf_intent_trigger_text']) : ''
8926 3100 );
8927 - echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
3101 + echo '<p class="description">Text displayed when the intent is triggered.</p>';
3102 +
3103 + if (!$this->is_activated) {
3104 + echo '<div class="pro-feature-overlay">';
3105 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3106 + echo '</div>';
3107 + }
3108 + echo '</div>';
8928 3109 }
8929 3110
3111 +// Success Text Callback
8930 3112 public function mxchat_pdf_intent_success_text_callback() {
8931 - $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
3113 + $disabled = $this->is_activated ? '' : 'disabled';
3114 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8932 3115
8933 - echo sprintf(
8934 - '<textarea id="pdf_intent_success_text"
8935 - name="pdf_intent_success_text"
8936 - rows="3"
8937 - cols="50"
8938 - placeholder="%s">%s</textarea>',
8939 - esc_attr__('Enter success text', 'mxchat'),
8940 - isset($this->options['pdf_intent_success_text'])
8941 - ? esc_textarea($this->options['pdf_intent_success_text'])
8942 - : esc_textarea($default_text)
3116 + echo '<div class="' . esc_attr($class) . '">';
3117 + printf(
3118 + '<textarea id="pdf_intent_success_text" name="mxchat_options[pdf_intent_success_text]" rows="3" cols="50" placeholder="Enter success text" %s>%s</textarea>',
3119 + esc_attr($disabled),
3120 + isset($this->options['pdf_intent_success_text']) ? esc_textarea($this->options['pdf_intent_success_text']) : ''
8943 3121 );
8944 - echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
3122 + echo '<p class="description">Text displayed when the intent is successful.</p>';
3123 +
3124 + if (!$this->is_activated) {
3125 + echo '<div class="pro-feature-overlay">';
3126 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3127 + echo '</div>';
3128 + }
3129 + echo '</div>';
8945 3130 }
8946 3131
3132 +// Error Text Callback
8947 3133 public function mxchat_pdf_intent_error_text_callback() {
8948 - $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
3134 + $disabled = $this->is_activated ? '' : 'disabled';
3135 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8949 3136
8950 - echo sprintf(
8951 - '<textarea id="pdf_intent_error_text"
8952 - name="pdf_intent_error_text"
8953 - rows="3"
8954 - cols="50"
8955 - placeholder="%s">%s</textarea>',
8956 - esc_attr__('Enter error text', 'mxchat'),
8957 - isset($this->options['pdf_intent_error_text'])
8958 - ? esc_textarea($this->options['pdf_intent_error_text'])
8959 - : esc_textarea($default_text)
3137 + echo '<div class="' . esc_attr($class) . '">';
3138 + printf(
3139 + '<textarea id="pdf_intent_error_text" name="mxchat_options[pdf_intent_error_text]" rows="3" cols="50" placeholder="Enter error text" %s>%s</textarea>',
3140 + esc_attr($disabled),
3141 + isset($this->options['pdf_intent_error_text']) ? esc_textarea($this->options['pdf_intent_error_text']) : ''
8960 3142 );
8961 - echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
3143 + echo '<p class="description">Text displayed when an error occurs during the intent.</p>';
3144 +
3145 + if (!$this->is_activated) {
3146 + echo '<div class="pro-feature-overlay">';
3147 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3148 + echo '</div>';
3149 + }
3150 + echo '</div>';
8962 3151 }
8963 3152
3153 +// Maximum PDF Pages Callback
8964 3154 public function mxchat_pdf_max_pages_callback() {
3155 + $disabled = $this->is_activated ? '' : 'disabled';
3156 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8965 3157 $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
8966 3158
8967 - echo sprintf(
8968 - '<input type="range"
8969 - id="pdf_max_pages"
8970 - name="pdf_max_pages"
8971 - min="1"
8972 - max="69"
8973 - value="%d"
8974 - class="range-slider" />',
8975 - esc_attr($max_pages)
3159 + echo '<div class="' . esc_attr($class) . '">';
3160 + printf(
3161 + '<input type="range" id="pdf_max_pages" name="mxchat_options[pdf_max_pages]" min="1" max="69" value="%d" %s oninput="document.getElementById(\'pdf_max_pages_output\').innerText = this.value;" />',
3162 + esc_attr($max_pages),
3163 + esc_attr($disabled)
8976 3164 );
8977 3165 echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
8978 - echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
3166 + echo '<p class="description">Set the maximum number of PDF pages users can upload for processing. (1-69 pages)</p>';
3167 +
3168 + if (!$this->is_activated) {
3169 + echo '<div class="pro-feature-overlay">';
3170 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3171 + echo '</div>';
3172 + }
3173 + echo '</div>';
8979 3174 }
8980 3175
3176 +
3177 +// Status Toggle Callback
8981 3178 public function mxchat_live_agent_status_callback() {
8982 - // Always get fresh options instead of using cached $this->options
8983 - $fresh_options = get_option('mxchat_options');
8984 - $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
3179 + $disabled = $this->is_activated ? '' : 'disabled';
3180 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
3181 + $status = isset($this->options['live_agent_status']) ? $this->options['live_agent_status'] : 'offline';
8985 3182
8986 - echo '<label class="toggle-switch">';
8987 - echo sprintf(
8988 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
8989 - checked($status, 'on', false)
3183 + echo '<div class="' . esc_attr($class) . '">';
3184 + echo '<label class="mxchat-switch">';
3185 + printf(
3186 + '<input type="checkbox" id="live_agent_status" name="mxchat_options[live_agent_status]" value="online" %s %s />',
3187 + checked($status, 'online', false),
3188 + esc_attr($disabled)
8990 3189 );
8991 - echo '<span class="slider"></span>';
3190 + echo '<span class="mxchat-slider"></span>';
8992 3191 echo '</label>';
8993 3192 echo '<label for="live_agent_status" class="mxchat-status-label">';
8994 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
3193 + echo '<span class="status-text">' . ($status === 'online' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
8995 3194 echo '</label>';
8996 -}
8997 3195
8998 -/**
8999 - * Availability-schedule editor (plans 8ccaa2 + 99d7a4).
9000 - *
9001 - * ONE callback, parameterized by channel ('slack' | 'telegram' via the
9002 - * add_settings_field $args) — the markup and CSS are shared, only the bound
9003 - * option and the helper text differ. Each channel's editor renders under its
9004 - * own Integrations tab and governs ONLY that channel's handoff. While the
9005 - * master toggle is off the day grid is inert and handoff availability stays
9006 - * governed solely by that channel's manual status toggle.
9007 - *
9008 - * The day inputs carry NO name attribute and are marked .mxchat-la-field so the
9009 - * generic autosave skips them; the editor JS folds them into the channel's
9010 - * hidden live_agent_schedule_<channel> input and fires one change, reusing the
9011 - * existing autosave transport rather than growing a second one. All hooks the
9012 - * JS needs are CLASSES scoped inside .mxchat-la-schedule, never ids — the
9013 - * markup exists twice on the page.
9014 - */
9015 -public function mxchat_live_agent_schedule_callback($args = array()) {
9016 - if (!class_exists('MxChat_Live_Agent_Schedule')) {
9017 - return;
3196 + if (!$this->is_activated) {
3197 + echo '<div class="pro-feature-overlay">';
3198 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3199 + echo '</div>';
9018 3200 }
9019 - $channel = (isset($args['channel']) && $args['channel'] === 'telegram') ? 'telegram' : 'slack';
9020 - $field = 'live_agent_schedule_' . $channel;
9021 - $sched = MxChat_Live_Agent_Schedule::get($channel);
9022 - $labels = MxChat_Live_Agent_Schedule::day_labels();
9023 - $tz = MxChat_Live_Agent_Schedule::timezone_label();
9024 - $enabled = !empty($sched['enabled']);
9025 - $channel_label = ($channel === 'telegram') ? __('Telegram', 'mxchat') : __('Slack', 'mxchat');
9026 - ?>
9027 - <div class="mxchat-la-schedule<?php echo $enabled ? ' is-active' : ''; ?>"
9028 - id="mxchat-la-schedule-<?php echo esc_attr($channel); ?>"
9029 - data-channel="<?php echo esc_attr($channel); ?>">
9030 - <label class="toggle-switch">
9031 - <input type="checkbox" id="<?php echo esc_attr($field); ?>_enabled"
9032 - class="mxchat-la-field mxchat-la-enabled" <?php checked($enabled); ?> />
9033 - <span class="slider"></span>
9034 - </label>
9035 - <label for="<?php echo esc_attr($field); ?>_enabled" class="mxchat-status-label">
9036 - <span class="status-text mxchat-la-status-text">
9037 - <?php echo $enabled
9038 - ? esc_html__('Scheduled hours', 'mxchat')
9039 - : esc_html__('Always available', 'mxchat'); ?>
9040 - </span>
9041 - </label>
9042 -
9043 - <div class="mxchat-la-days" aria-hidden="<?php echo $enabled ? 'false' : 'true'; ?>">
9044 - <?php foreach ($labels as $n => $label) :
9045 - $day = $sched['days'][$n];
9046 - $on = !empty($day['enabled']);
9047 - ?>
9048 - <div class="mxchat-la-day<?php echo $on ? ' is-on' : ''; ?>" data-day="<?php echo esc_attr($n); ?>">
9049 - <label class="mxchat-la-day-label">
9050 - <input type="checkbox" class="mxchat-la-field mxchat-la-day-enabled"
9051 - data-day="<?php echo esc_attr($n); ?>" <?php checked($on); ?> />
9052 - <span class="mxchat-la-day-name"><?php echo esc_html($label); ?></span>
9053 - </label>
9054 - <div class="mxchat-la-times">
9055 - <input type="time" class="mxchat-la-field mxchat-la-start"
9056 - data-day="<?php echo esc_attr($n); ?>"
9057 - value="<?php echo esc_attr($day['start']); ?>"
9058 - aria-label="<?php echo esc_attr(sprintf(__('%s start time', 'mxchat'), $label)); ?>" />
9059 - <span class="mxchat-la-dash">&ndash;</span>
9060 - <input type="time" class="mxchat-la-field mxchat-la-end"
9061 - data-day="<?php echo esc_attr($n); ?>"
9062 - value="<?php echo esc_attr($day['end']); ?>"
9063 - aria-label="<?php echo esc_attr(sprintf(__('%s end time', 'mxchat'), $label)); ?>" />
9064 - </div>
9065 - </div>
9066 - <?php endforeach; ?>
9067 - </div>
9068 -
9069 - <input type="hidden" name="<?php echo esc_attr($field); ?>" id="<?php echo esc_attr($field); ?>"
9070 - class="mxchat-la-hidden" value="<?php echo esc_attr(wp_json_encode($sched)); ?>" />
9071 - </div>
9072 - <p class="description">
9073 - <?php printf(
9074 - /* translators: 1: the handoff channel, e.g. Slack or Telegram; 2: the site's timezone, e.g. America/New_York */
9075 - esc_html__('When on, visitors are only offered a %1$s human handoff during these hours — outside them the chatbot keeps answering and never offers to fetch an agent. Applies to %1$s only. Times use the site timezone (%2$s). Set a day\'s end time earlier than its start for an overnight shift; identical start and end means all day.', 'mxchat'),
9076 - '<strong>' . esc_html($channel_label) . '</strong>',
9077 - '<strong>' . esc_html($tz) . '</strong>'
9078 - ); ?>
9079 - </p>
9080 - <?php
3201 + echo '</div>';
9081 3202 }
9082 3203
3204 +// Away Message Callback
9083 3205 public function mxchat_live_agent_away_message_callback() {
3206 + $disabled = $this->is_activated ? '' : 'disabled';
3207 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9084 3208 $message = isset($this->options['live_agent_away_message'])
9085 3209 ? $this->options['live_agent_away_message']
9086 3210 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9087 3211
3212 + echo '<div class="' . esc_attr($class) . '">';
9088 3213 printf(
9089 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
3214 + '<textarea id="live_agent_away_message" name="mxchat_options[live_agent_away_message]" rows="3" cols="50" %s>%s</textarea>',
3215 + esc_attr($disabled),
9090 3216 esc_textarea($message)
9091 3217 );
9092 3218 echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
3219 +
3220 + if (!$this->is_activated) {
3221 + echo '<div class="pro-feature-overlay">';
3222 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3223 + echo '</div>';
3224 + }
3225 + echo '</div>';
9093 3226 }
9094 -
9095 3227 public function mxchat_live_agent_notification_message_callback() {
3228 + $disabled = $this->is_activated ? '' : 'disabled';
3229 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9096 3230 $message = isset($this->options['live_agent_notification_message'])
9097 3231 ? $this->options['live_agent_notification_message']
9098 3232 : __('Live agent has been notified.', 'mxchat');
9099 3233
3234 + echo '<div class="' . esc_attr($class) . '">';
9100 3235 printf(
9101 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
3236 + '<textarea id="live_agent_notification_message" name="mxchat_options[live_agent_notification_message]" rows="3" cols="50" %s>%s</textarea>',
3237 + esc_attr($disabled),
9102 3238 esc_textarea($message)
9103 3239 );
9104 3240 echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
3241 +
3242 + if (!$this->is_activated) {
3243 + echo '<div class="pro-feature-overlay">';
3244 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3245 + echo '</div>';
3246 + }
3247 + echo '</div>';
9105 3248 }
9106 3249
9107 3250 public function mxchat_live_agent_webhook_url_callback() {
3251 + $disabled = $this->is_activated ? '' : 'disabled';
3252 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9108 3253 $webhook_url = isset($this->options['live_agent_webhook_url'])
9109 3254 ? esc_url($this->options['live_agent_webhook_url'])
9110 3255 : esc_url(get_option('live_agent_webhook_url', ''));
9111 3256
3257 + echo '<div class="' . esc_attr($class) . '">';
9112 3258 printf(
9113 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
9114 - $webhook_url
3259 + '<input type="password" id="live_agent_webhook_url" name="mxchat_options[live_agent_webhook_url]" value="%s" class="regular-text" %s />',
3260 + $webhook_url,
3261 + esc_attr($disabled)
9115 3262 );
9116 - echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9117 - echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
9118 -}
9119 -
9120 -public function mxchat_live_agent_secret_key_callback() {
9121 - printf(
9122 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
9123 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
9124 - );
9125 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9126 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
9127 -}
9128 -
9129 -public function mxchat_live_agent_bot_token_callback() {
9130 - printf(
9131 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
9132 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
9133 - );
9134 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
9135 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
9136 -}
9137 -
9138 -public function mxchat_live_agent_user_ids_callback() {
9139 - $user_ids = isset($this->options['live_agent_user_ids'])
9140 - ? esc_textarea($this->options['live_agent_user_ids'])
9141 - : '';
9142 -
9143 - printf(
9144 - '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
9145 - $user_ids
9146 - );
9147 - echo '<p class="description">' . esc_html__('Enter Slack User IDs of agents who should be automatically invited to chat channels (one per line). Find user IDs in Slack profiles under "More" → "Copy member ID". Example: U1234567890', 'mxchat') . '</p>';
9148 -}
9149 -
9150 -public function mxchat_live_agent_shared_channel_callback() {
9151 - $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : '';
9152 - printf(
9153 - '<input type="text" id="live_agent_shared_channel" name="live_agent_shared_channel" value="%s" class="regular-text" placeholder="#support or C0123456789" />',
9154 - esc_attr($value)
9155 - );
9156 - echo '<p class="description">' . esc_html__('Optional. Route ALL live agent handoffs into this one existing Slack channel — each conversation becomes its own thread there. Enter a channel ID (starts with C) or a #channel-name, and invite your bot to the channel first (/invite @YourBot). Agents reply inside a conversation\'s thread; !endchat inside the thread ends that chat. Leave blank to keep creating a separate chat- channel per conversation.', 'mxchat') . '</p>';
9157 -
9158 - // Surface the last failed handoff so a wrong name / missing invite is
9159 - // visible right where it gets fixed. A successful handoff clears this.
9160 - $shared_error = get_option('mxchat_slack_shared_channel_error');
9161 - if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) {
9162 - echo '<p class="description"><strong>' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . '</strong> — '
9163 - . esc_html(sprintf(
9164 - /* translators: %s: Slack API error code */
9165 - __('Slack said "%s". Handoffs are falling back to per-conversation channels until this is fixed. Check the channel name or ID and make sure the bot has been invited to it.', 'mxchat'),
9166 - $shared_error['error']
9167 - )) . '</p>';
3263 + echo '<button type="button" id="toggleWebhookUrlVisibility">Show</button>';
3264 + echo '<p class="description">Enter your Slack webhook URL for live agent notifications.</p>';
3265 + if (!$this->is_activated) {
3266 + echo '<div class="pro-feature-overlay">';
3267 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3268 + echo '</div>';
9168 3269 }
3270 + echo '</div>';
9169 3271 }
9170 3272
9171 -public function mxchat_live_agent_archive_on_end_callback() {
9172 - $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off';
9173 - printf(
9174 - '<input type="checkbox" id="live_agent_archive_on_end_toggle" name="live_agent_archive_on_end_toggle" value="on" %s />',
9175 - checked('on', $value, false)
9176 - );
9177 - echo '<label for="live_agent_archive_on_end_toggle" class="mxchat-status-label">' . esc_html__('Archive the conversation\'s chat- channel when an agent ends the chat with !endchat', 'mxchat') . '</label>';
9178 - echo '<p class="description">' . esc_html__('Keeps your Slack sidebar tidy on busy sites — each ended conversation\'s channel is archived instead of living forever. Archived channels stay searchable in Slack, so the record is never lost. Only applies to per-conversation chat- channels; a Shared Handoff Channel is never archived. If a returning visitor requests an agent again, a fresh channel is created automatically.', 'mxchat') . '</p>';
9179 -}
9180 3273
9181 -/**
9182 - * Telegram Integration Callbacks
9183 - */
9184 -public function mxchat_telegram_section_callback() {
9185 - echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
3274 +public function mxchat_similarity_threshold_callback() {
3275 + $threshold = get_option('mxchat_similarity_threshold', 80); // Default to 80
3276 + ?>
3277 + <input type="range" id="mxchat_similarity_threshold" name="mxchat_similarity_threshold"
3278 + min="70" max="85" step="1"
3279 + value="<?php echo esc_attr($threshold); ?>"
3280 + oninput="document.getElementById('mxchat_threshold_value').textContent = this.value;">
3281 + <span id="mxchat_threshold_value"><?php echo esc_html($threshold); ?></span>
3282 + <p class="description">
3283 + Lower values match less relevant content, higher values match more strictly.
3284 + </p>
3285 + <?php
9186 3286 }
9187 3287
9188 -public function mxchat_telegram_status_callback() {
9189 - $fresh_options = get_option('mxchat_options');
9190 - $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
9191 3288
9192 - echo '<label class="toggle-switch">';
9193 - echo sprintf(
9194 - '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
9195 - checked($status, 'on', false)
9196 - );
9197 - echo '<span class="slider"></span>';
9198 - echo '</label>';
9199 - echo '<label for="telegram_status" class="mxchat-status-label">';
9200 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
9201 - echo '</label>';
9202 -}
9203 3289
9204 -public function mxchat_telegram_notification_message_callback() {
9205 - $message = isset($this->options['telegram_notification_message'])
9206 - ? $this->options['telegram_notification_message']
9207 - : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
3290 +public function mxchat_live_agent_secret_key_callback() {
3291 + $disabled = $this->is_activated ? '' : 'disabled';
3292 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9208 3293
3294 + echo '<div class="' . esc_attr($class) . '">';
9209 3295 printf(
9210 - '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
9211 - esc_textarea($message)
3296 + '<input type="password" id="live_agent_secret_key" name="mxchat_options[live_agent_secret_key]" value="%s" class="regular-text" %s />',
3297 + isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : '',
3298 + esc_attr($disabled)
9212 3299 );
9213 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
9214 -}
3300 + echo '<button type="button" id="toggleSecretKeyVisibility">Show</button>';
3301 + echo '<p class="description">Secret key for validating Slack requests. Keep this secure.</p>';
9215 3302
9216 -public function mxchat_telegram_away_message_callback() {
9217 - $message = isset($this->options['telegram_away_message'])
9218 - ? $this->options['telegram_away_message']
9219 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
9220 -
9221 - printf(
9222 - '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
9223 - esc_textarea($message)
9224 - );
9225 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
3303 + if (!$this->is_activated) {
3304 + echo '<div class="pro-feature-overlay">';
3305 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3306 + echo '</div>';
3307 + }
3308 + echo '</div>';
9226 3309 }
9227 3310
9228 -public function mxchat_telegram_bot_token_callback() {
9229 - printf(
9230 - '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
9231 - isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
9232 - );
9233 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_bot_token\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9234 - echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
9235 -}
3311 +public function mxchat_live_agent_bot_token_callback() {
3312 + $disabled = $this->is_activated ? '' : 'disabled';
3313 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
9236 3314
9237 -public function mxchat_telegram_group_id_callback() {
3315 + echo '<div class="' . esc_attr($class) . '">';
9238 3316 printf(
9239 - '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
9240 - isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
3317 + '<input type="password" id="live_agent_bot_token" name="mxchat_options[live_agent_bot_token]" value="%s" class="regular-text" %s />',
3318 + isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : '',
3319 + esc_attr($disabled)
9241 3320 );
9242 - echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
9243 -}
3321 + echo '<button type="button" id="toggleBotTokenVisibility">Show</button>';
3322 + echo '<p class="description">Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.</p>';
9244 3323
9245 -public function mxchat_telegram_webhook_secret_callback() {
9246 - $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
9247 -
9248 - // Auto-generate secret if empty
9249 - if (empty($secret)) {
9250 - $secret = wp_generate_password(64, false, false);
9251 - $options = get_option('mxchat_options', []);
9252 - $options['telegram_webhook_secret'] = $secret;
9253 - update_option('mxchat_options', $options);
9254 - $this->options['telegram_webhook_secret'] = $secret;
3324 + if (!$this->is_activated) {
3325 + echo '<div class="pro-feature-overlay">';
3326 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3327 + echo '</div>';
9255 3328 }
9256 -
9257 - printf(
9258 - '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
9259 - esc_attr($secret)
9260 - );
9261 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_webhook_secret\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
9262 - echo '<p class="description">' . esc_html__('Secret token for webhook verification. Use this when setting up your Telegram webhook with the secret_token parameter.', 'mxchat') . '</p>';
9263 -}
9264 -
9265 -public function mxchat_similarity_threshold_callback() {
9266 - // Load from mxchat_options array
9267 - $options = get_option('mxchat_options', []);
9268 -
9269 - // Get value from options array with default of 35
9270 - $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
9271 -
9272 - echo '<div class="slider-container">';
9273 - echo sprintf(
9274 - '<input type="range"
9275 - id="similarity_threshold"
9276 - name="similarity_threshold"
9277 - min="20"
9278 - max="85"
9279 - step="1"
9280 - value="%s"
9281 - class="range-slider" />',
9282 - esc_attr($threshold)
9283 - );
9284 - echo sprintf(
9285 - '<span id="threshold_value" class="range-value">%s</span>',
9286 - esc_html($threshold)
9287 - );
9288 3329 echo '</div>';
9289 3330 }
9290 3331
9291 -public function mxchat_max_input_length_callback() {
9292 - // Load from mxchat_options array (plan a3fae2 part C).
9293 - $options = get_option('mxchat_options', []);
3332 + public function mxchat_enqueue_admin_assets() {
3333 + wp_enqueue_style('wp-color-picker');
9294 3334
9295 - // 0 = unlimited (default — preserves current behavior, no cap).
9296 - $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0;
3335 + // Get the plugin version or file modification time for cache busting
3336 + $plugin_version = '1.5.3'; // Replace this with your plugin's version
9297 3337
9298 - echo sprintf(
9299 - '<input type="number"
9300 - id="max_input_length"
9301 - name="max_input_length"
9302 - min="0"
9303 - max="100000"
9304 - step="1"
9305 - value="%s"
9306 - placeholder="0"
9307 - class="mxch-input mxch-input-sm" />',
9308 - esc_attr($max_input_length)
9309 - );
9310 -}
3338 + // File paths
3339 + $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
3340 + $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
3341 + $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
3342 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
9311 3343
9312 -public function mxchat_rag_sources_limit_callback() {
9313 - // Load from mxchat_options array
9314 - $options = get_option('mxchat_options', []);
3344 + // Check if files exist and get modification times
3345 + $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
3346 + $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
3347 + $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
3348 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
9315 3349
9316 - // Get value from options array with default of 3
9317 - $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
3350 + // Enqueue scripts and styles with corrected paths
3351 + wp_enqueue_script(
3352 + 'mxchat-color-picker',
3353 + plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
3354 + array('wp-color-picker'),
3355 + $color_picker_version,
3356 + true
3357 + );
9318 3358
9319 - echo '<div class="slider-container">';
9320 - echo sprintf(
9321 - '<input type="range"
9322 - id="rag_sources_limit"
9323 - name="rag_sources_limit"
9324 - min="3"
9325 - max="10"
9326 - step="1"
9327 - value="%s"
9328 - class="range-slider" />',
9329 - esc_attr($rag_sources_limit)
9330 - );
9331 - echo sprintf(
9332 - '<span id="rag_sources_limit_value" class="range-value">%s</span>',
9333 - esc_html($rag_sources_limit)
9334 - );
9335 - echo '</div>';
9336 -}
3359 + wp_enqueue_script(
3360 + 'mxchat-embedding-check',
3361 + plugin_dir_url(__FILE__) . '../js/embedding-check.js',
3362 + array(),
3363 + $embedding_check_version,
3364 + true
3365 + );
9337 3366
9338 -public function mxchat_rag_chunks_limit_callback() {
9339 - // Load from mxchat_options array
9340 - $options = get_option('mxchat_options', []);
3367 + wp_enqueue_script(
3368 + 'mxchat-transcripts-js',
3369 + plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
3370 + array('jquery'),
3371 + $transcripts_js_version,
3372 + true
3373 + );
9341 3374
9342 - // Get value from options array with default of 15
9343 - $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
3375 + wp_enqueue_script(
3376 + 'mxchat-admin-js',
3377 + plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
3378 + array('jquery'),
3379 + $plugin_version,
3380 + true
3381 + );
9344 3382
9345 - echo '<div class="slider-container">';
9346 - echo sprintf(
9347 - '<input type="range"
9348 - id="rag_chunks_limit"
9349 - name="rag_chunks_limit"
9350 - min="8"
9351 - max="20"
9352 - step="1"
9353 - value="%s"
9354 - class="range-slider" />',
9355 - esc_attr($rag_chunks_limit)
9356 - );
9357 - echo sprintf(
9358 - '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
9359 - esc_html($rag_chunks_limit)
9360 - );
9361 - echo '</div>';
9362 -}
9363 3383
9364 -/**
9365 - * Add body class on the Onboarding wizard page so CSS-only chrome surgery
9366 - * (collapsing the WP admin sidebar) only applies on this page.
9367 - * Plan: plan-mxchat-20260527-905439.
9368 - */
9369 -public function mxchat_add_onboarding_body_class($classes) {
9370 - if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') {
9371 - $classes .= ' mxchat-onboarding-focused';
9372 - }
9373 - return $classes;
9374 -}
9375 3384
9376 -public function mxchat_enqueue_admin_assets($hook_suffix = '') {
9377 - // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY
9378 - // guard here was the strpos() on $_GET['page'] below — which is
9379 - // attacker-controlled — so ANY logged-in user (Subscriber included) could
9380 - // load a page they are legitimately allowed to see, e.g.
9381 - // /wp-admin/profile.php?page=mxchat, and receive every nonce this method
9382 - // localizes. Three of the handlers behind those nonces verified the nonce
9383 - // but checked no capability. Every MxChat menu page is registered
9384 - // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for
9385 - // legitimate users.
9386 - if (!current_user_can('manage_options')) {
9387 - return;
9388 - }
3385 + // Localize the script with data for the activation process
3386 + wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
3387 + 'ajax_url' => admin_url('admin-ajax.php'),
3388 + 'nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
3389 + ));
9389 3390
9390 - // Get plugin version
9391 - $version = MXCHAT_VERSION;
3391 + wp_enqueue_style(
3392 + 'mxchat-admin-css',
3393 + plugin_dir_url(__FILE__) . '../css/admin-style.css',
3394 + array(),
3395 + $admin_css_version
3396 + );
9392 3397
9393 - // Use file modification time for development (remove in production)
9394 - if (defined('WP_DEBUG') && WP_DEBUG) {
9395 - $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
9396 - }
3398 + wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
3399 + 'ajax_url' => admin_url('admin-ajax.php'),
3400 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
3401 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
3402 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
3403 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
3404 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
3405 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
3406 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
3407 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
3408 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
3409 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
3410 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
3411 + 'pre_chat_message' => $this->options['pre_chat_message'] ?? 'Hey there! Ask me anything!',
3412 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9397 3413
9398 - $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
9399 - $plugin_url = plugin_dir_url(__FILE__) . '../';
3414 + // New fields for Loops Integration
3415 + 'loops_api_key' => $this->options['loops_api_key'] ?? '',
3416 + 'loops_mailing_list' => $this->options['loops_mailing_list'] ?? '',
3417 + 'triggered_phrase_response' => $this->options['triggered_phrase_response'] ?? 'Would you like to join our mailing list? Please provide your email below.',
3418 + 'email_capture_response' => $this->options['email_capture_response'] ?? 'Thank you for providing your email! You\'ve been added to our list.',
3419 + 'pdf_intent_trigger_text' => $this->options['pdf_intent_trigger_text'] ?? "Please provide the URL to the PDF you'd like to discuss.",
3420 + 'pdf_intent_success_text' => $this->options['pdf_intent_success_text'] ?? "I've processed the PDF. What questions do you have about it?",
3421 + 'pdf_intent_error_text' => $this->options['pdf_intent_error_text'] ?? "Sorry, I couldn't process the PDF. Please ensure it's a valid file.",
3422 + 'pdf_max_pages' => $this->options['pdf_max_pages'] ?? 69,
9400 3423
9401 - // Only load on MxChat pages. Prefer the server-derived $hook_suffix that
9402 - // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be
9403 - // forged onto a screen MxChat does not own. Falls back to the legacy
9404 - // $_GET check only when the hook is unavailable (direct/legacy callers).
9405 - if ($hook_suffix !== '') {
9406 - if (strpos($hook_suffix, 'mxchat') === false) {
9407 - return;
9408 - }
9409 - } elseif (strpos($current_page, 'mxchat') === false) {
9410 - return;
9411 - }
3424 + // Live Agent Integration
3425 + 'live_agent_webhook_url' => $this->options['live_agent_webhook_url'] ?? '',
3426 + 'live_agent_secret_key' => $this->options['live_agent_secret_key'] ?? '',
3427 + 'live_agent_bot_token' => $this->options['live_agent_bot_token'] ?? '',
9412 3428
9413 - // Always load these on all MxChat pages
9414 - $this->enqueue_core_admin_assets($plugin_url, $version);
9415 - $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
9416 - $this->localize_admin_scripts($current_page);
9417 -}
9418 -private function enqueue_core_admin_assets($plugin_url, $version) {
9419 - // Core admin styles
9420 - wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
9421 - wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
3429 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
3430 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
3431 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
3432 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
3433 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
3434 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
9422 3435
9423 - // New sidebar navigation styles (for main settings page)
9424 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9425 -
9426 - // Core admin scripts
9427 - wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
9428 -}
9429 -private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
9430 - switch ($current_page) {
9431 - case 'mxchat-prompts':
9432 - // Shared shell JS: tab switching, deep-linking and the mobile menu
9433 - // for this page's flat nav (inline copies removed by plan c192a4).
9434 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9435 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9436 - 'copied' => __('Copied', 'mxchat'),
9437 3436 ));
9438 - // Knowledge processing page assets
9439 - wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
9440 - wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
9441 - // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
9442 - wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
9443 - // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the
9444 - // Testing tab's match-card / chunk-detail components, which are scoped
9445 - // under .mxch-testing-results. Load that stylesheet here so the inspector
9446 - // modal renders identically to the Testing tab.
9447 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version);
9448 - break;
9449 3437
9450 - case 'mxchat-transcripts':
9451 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9452 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9453 - // Load transcripts-specific styles
9454 - wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
9455 - wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
9456 - break;
9457 -
9458 - case 'mxchat-actions':
9459 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9460 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9461 - // Load actions-specific styles
9462 - wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
9463 - wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
9464 -
9465 - // Localize script data for actions page
9466 - $is_activated = get_option('mxchat_pro_license_status') === 'active';
9467 - wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
9468 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9469 - 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
9470 - 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9471 - 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
9472 - 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
9473 - 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
9474 - 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9475 - 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9476 - 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9477 - 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9478 - 'isActivated' => $is_activated,
9479 - 'i18n' => array(
9480 - 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'),
9481 - 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'),
9482 - 'saving' => __('Saving...', 'mxchat'),
9483 - 'saved' => __('Saved successfully!', 'mxchat'),
9484 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9485 - 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
9486 - 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
9487 - )
9488 - ));
9489 - break;
9490 -
9491 - case 'mxchat-activation':
9492 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
9493 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9494 - // Load pro page-specific styles
9495 - wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
9496 - // Load pro page JavaScript
9497 - wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
9498 - // Load activation script for license activation/deactivation
9499 - wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
9500 - break;
9501 -
9502 - case 'mxchat-content':
9503 - // Load admin sidebar CSS (shared styles for sidebar navigation)
9504 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9505 - // Load content page-specific styles
9506 - wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
9507 - // Load content page JavaScript
9508 - wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
9509 - break;
9510 -
9511 - case 'mxchat-api-access':
9512 - // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
9513 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9514 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9515 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9516 - 'copied' => __('Copied', 'mxchat'),
9517 - ));
9518 - break;
9519 -
9520 - case 'mxchat-max':
9521 - case 'mxchat-onboarding':
9522 - // Onboarding page — uses the shared admin shell PLUS the wizard
9523 - // overlay (plan-905439). admin-onboarding-wizard.css scopes the
9524 - // WP-chrome surgery to body.mxchat-onboarding-focused so it only
9525 - // applies on THIS page. The body class is added below via the
9526 - // admin_body_class filter.
9527 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
9528 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9529 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9530 - 'copied' => __('Copied', 'mxchat'),
9531 - ));
9532 - // admin-style.css provides the .mxchat-instructions-modal-* classes
9533 - // the new Behavior step's "View Sample Instructions" modal needs.
9534 - // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay
9535 - // so the wizard's own rules win where they collide. plan-a2e4d6.
9536 - wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version);
9537 - wp_enqueue_style('mxchat-admin-onboarding-wizard-css', $plugin_url . 'css/admin-onboarding-wizard.css', array('mxchat-admin-sidebar-css', 'mxchat-admin-style-css'), $version);
9538 - wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true);
9539 - break;
9540 - default:
9541 - // Settings page: load the shared shell JS for #hash deep-linking
9542 - // to tabs (plan 4ede16). The page's own inline nav script owns
9543 - // clicks/accordion behaviour; the shell script adds load +
9544 - // hashchange activation and replaceState so plain href="#tab"
9545 - // anchors and shared URLs land on the right tab. Kept inside the
9546 - // default case because the settings page also needs everything
9547 - // below (Testing tab chatbot + streaming assets).
9548 - if ($current_page === 'mxchat-settings') {
9549 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
9550 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
9551 - 'copied' => __('Copied', 'mxchat'),
9552 - ));
9553 - }
9554 -
9555 - wp_enqueue_script(
9556 - 'mxchat-test-streaming-js',
9557 - $plugin_url . 'js/mxchat-test-streaming.js',
9558 - ['jquery'],
9559 - $version,
9560 - true
9561 - );
9562 -
9563 - wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
9564 - 'ajax_url' => admin_url('admin-ajax.php'),
9565 - 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
9566 - 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
9567 - ]);
9568 -
9569 - // Testing Tab: Load chatbot assets for the embedded testing chatbot
9570 - wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
9571 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
9572 -
9573 - wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
9574 - wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
9575 -
9576 - // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
9577 - do_action('mxchat_enqueue_testing_tab_assets');
9578 -
9579 - // Localize mxchatChat for the chatbot JS (same settings as frontend)
9580 - $options = get_option('mxchat_options', array());
9581 - $prompts_options = get_option('mxchat_prompts_options', array());
9582 - $theme_options = get_option('mxchat_theme_options', array());
9583 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
9584 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
9585 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
9586 -
9587 - wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
9588 - 'ajax_url' => admin_url('admin-ajax.php'),
9589 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
9590 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
9591 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
9592 - 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
9593 - 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
9594 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
9595 - 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
9596 - 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
9597 - 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
9598 - 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
9599 - 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
9600 - 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
9601 - 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
9602 - 'close_button_color' => $options['close_button_color'] ?? '#fff',
9603 - 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
9604 - 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
9605 - 'icon_color' => $options['icon_color'] ?? '#fff',
9606 - 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
9607 - 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
9608 - 'appendWidgetToBody' => 'off',
9609 - 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
9610 - 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
9611 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
9612 - 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
9613 - 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
9614 - 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
9615 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
9616 - 'email_collection_enabled' => 'off', // No email collection in testing
9617 - 'initial_email_state' => null,
9618 - 'skip_email_check' => true,
9619 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
9620 - 'skip_inline_colors' => $skip_inline_colors,
9621 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
9622 - ));
9623 -
9624 - // Localize testing tab script data
9625 - wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
9626 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9627 - 'nonce' => wp_create_nonce('mxchat_test_nonce'),
9628 - 'isAdmin' => true,
9629 - 'testingEnabled' => true
9630 - ));
9631 -
9632 - // Add testing enabled flag for the chatbot to return debug data
9633 - add_action('admin_footer', function() {
9634 - echo '<script>window.mxchatTestingEnabled = true;</script>';
9635 - });
9636 -
9637 - break;
9638 - }
9639 -}
9640 -/**
9641 - * The base mxchatAdmin payload shared by every MxChat admin page.
9642 - *
9643 - * Extracted (plan c192a4) so page-specific re-localizations of the SAME
9644 - * global — the knowledge page prints a second `var mxchatAdmin` via the
9645 - * mxchat-knowledge-processing handle, and last-printed wins — can merge
9646 - * their extra keys on top of this instead of silently narrowing the object
9647 - * that mxchat-admin.js also reads on that page.
9648 - */
9649 -private function mxchat_get_admin_base_localization() {
9650 - return array(
9651 - 'ajax_url' => admin_url('admin-ajax.php'),
9652 - 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
9653 - 'admin_url' => admin_url(),
9654 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
9655 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
9656 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9657 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9658 - 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9659 - 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
9660 - 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
9661 - 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
9662 - 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
9663 - 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
9664 - 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
9665 - 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
9666 - 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
9667 - 'is_activated' => $this->is_activated ? '1' : '0',
9668 - 'status_refresh_interval' => 5000,
9669 - 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'),
9670 - 'unsaved_label' => __('Unsaved', 'mxchat'),
9671 - // Live-agent schedule status text (plan 8ccaa2).
9672 - 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'),
9673 - 'i18n_always_available' => __('Always available', 'mxchat'),
9674 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9675 - 'ajaxurl' => admin_url('admin-ajax.php')
9676 - );
9677 -}
9678 -private function localize_admin_scripts($current_page) {
9679 - // Base localization data for main admin script
9680 - $base_data = $this->mxchat_get_admin_base_localization();
9681 -
9682 - // Localize main admin script with base data
9683 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
9684 -
9685 - // Canonical chat-model catalog for the modal picker grid
9686 - // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php
9687 - // automatically appears here.
9688 - if (!class_exists('MxChat_Model_Catalog')) {
9689 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
9690 - }
9691 - wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape());
9692 -
9693 - // Page-specific localizations
9694 - $this->localize_page_specific_scripts($current_page);
9695 -}
9696 -private function localize_page_specific_scripts($current_page) {
9697 - switch ($current_page) {
9698 - case 'mxchat-prompts':
9699 - // Status updater localization
9700 - wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
9701 - 'ajax_url' => admin_url('admin-ajax.php'),
9702 - 'nonce' => wp_create_nonce('mxchat_status_nonce')
9703 - ));
9704 -
9705 - // Content selector localization
9706 - wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
9707 - 'ajaxurl' => admin_url('admin-ajax.php'),
9708 - 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
9709 - 'i18n' => array(
9710 - 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
9711 - 'selectAll' => __('Select All', 'mxchat'),
9712 - 'process' => __('Process Selected', 'mxchat'),
9713 - 'cancel' => __('Cancel', 'mxchat'),
9714 - 'noResults' => __('No content found.', 'mxchat'),
9715 - 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
9716 - 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
9717 - )
9718 - ));
9719 -
9720 - // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's
9721 - // base one) and last-printed wins — so it must carry the FULL base
9722 - // payload plus the knowledge-page extras, or every mxchatAdmin.*
9723 - // key mxchat-admin.js reads on this page comes up undefined
9724 - // (plan c192a4). Extras merge last: status_refresh_interval stays
9725 - // at this page's faster 2000ms cadence.
9726 - wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge(
9727 - $this->mxchat_get_admin_base_localization(),
9728 - array(
9729 - 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
9730 - 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
9731 - 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
9732 - 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
9733 - 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
9734 - 'status_refresh_interval' => 2000,
9735 - 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
9736 - )
9737 - ));
9738 - break;
9739 -
9740 - case 'mxchat-activation':
9741 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9742 - // fixed here by a5b297): this second `var mxchatAdmin` must carry
9743 - // the full base payload plus the page extras.
9744 - wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge(
9745 - $this->mxchat_get_admin_base_localization(),
9746 - array(
9747 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
9748 - )
9749 - ));
9750 - break;
9751 -
9752 - case 'mxchat-content':
9753 - wp_localize_script('mxchat-content-js', 'mxchatContent', array(
9754 - 'ajaxUrl' => admin_url('admin-ajax.php'),
9755 - 'nonce' => wp_create_nonce('mxchat_content_nonce'),
9756 - 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9757 - 'previewUrl' => home_url('/?p='),
9758 - 'isActivated' => $this->is_activated(),
9759 - 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
9760 - 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
9761 - // Whether Search Console is actually LINKED — distinct from hasGSC
9762 - // (add-on active). Reads the same option the add-on's settings
9763 - // card keys off; harmless false when the add-on is absent.
9764 - 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false),
9765 - 'seoOptimize' => array(
9766 - 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
9767 - 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
9768 - 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
9769 - 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
9770 - 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
9771 - 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
9772 - 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
9773 - ),
9774 - 'i18n' => array(
9775 - 'generating' => __('Generating...', 'mxchat'),
9776 - 'planning' => __('Planning content structure...', 'mxchat'),
9777 - 'images' => __('Generating images...', 'mxchat'),
9778 - 'writing' => __('Writing full content...', 'mxchat'),
9779 - 'creating' => __('Creating WordPress post...', 'mxchat'),
9780 - 'done' => __('Content generated successfully!', 'mxchat'),
9781 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
9782 - 'editSuccess' => __('Content updated successfully.', 'mxchat'),
9783 - 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
9784 - )
9785 - ));
9786 - break;
9787 -
9788 - case 'mxchat-transcripts':
9789 - // Get chart data for localization
9790 - $chart_data = $this->get_transcripts_chart_data();
9791 -
9792 - // Same last-printed-wins clobber as the knowledge page (plan c192a4,
9793 - // fixed here by a5b297): merge the base payload under the page keys.
9794 - // export_nonce/setting_nonce/ajax_url duplicate base values identically;
9795 - // delete_nonce and translate_nonce are the page-specific adds.
9796 - wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge(
9797 - $this->mxchat_get_admin_base_localization(),
9798 - array(
9799 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
9800 - 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
9801 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
9802 - 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
9803 - )
9804 - ));
9805 -
9806 - // Localize chart data separately - use array_values to ensure proper JSON array encoding
9807 - wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
9808 - 'labels' => array_values($chart_data['labels']),
9809 - 'chats' => array_values($chart_data['chats']),
9810 - 'messages' => array_values($chart_data['messages'])
9811 - ));
9812 - break;
9813 -
9814 - case 'mxchat-settings':
9815 - default:
9816 - // The 'mxchatStyleSettings' localize that used to live here was
9817 - // REMOVED by plan-mxchat-20260731-c63fb6.
9818 - //
9819 - // It targeted the script handle 'mxchat-color-picker', which is
9820 - // registered/enqueued NOWHERE in the plugin — so wp_localize_script()
9821 - // returned false and printed nothing. That accident was the only
9822 - // thing keeping it from being a live secret disclosure: the payload
9823 - // carried loops_api_key, live_agent_secret_key and
9824 - // live_agent_bot_token in full, and this whole method ran for any
9825 - // logged-in user (see the capability gate added to
9826 - // mxchat_enqueue_admin_assets). One future
9827 - // wp_enqueue_script('mxchat-color-picker', ...) would have printed
9828 - // three secrets into page HTML for Subscribers.
9829 - //
9830 - // Nothing consumed the object: a tree-wide grep for
9831 - // 'mxchatStyleSettings' returns only this call site, and js/ names
9832 - // loops_api_key only at mxchat-admin.js:572, as a field-NAME string
9833 - // in an autosave allowlist — not a value read. Removed entirely
9834 - // rather than deleting just the three secret keys, so there is no
9835 - // dead payload left for someone to re-arm.
9836 - break;
9837 - }
9838 -
9839 - // Additional localization that was in the original code
9840 - wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
9841 - 'ajax_url' => admin_url('admin-ajax.php'),
9842 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
3438 + // Localize the script to pass the nonce and other data to JavaScript
3439 + wp_localize_script('mxchat-admin-js', 'mxchatInlineEdit', array(
3440 + 'nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
3441 + 'ajax_url' => admin_url('admin-ajax.php')
9843 3442 ));
9844 -}
9845 3443
9846 -public function mxchat_sanitize($input) {
9847 - $new_input = array();
9848 3444
9849 - if (isset($input['api_key'])) {
9850 - $new_input['api_key'] = sanitize_text_field($input['api_key']);
9851 3445 }
9852 3446
9853 - if (isset($input['similarity_threshold'])) {
9854 - $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
9855 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
9856 - }
3447 + public function mxchat_sanitize($input) {
3448 + $new_input = array();
9857 3449
9858 - if (isset($input['rag_sources_limit'])) {
9859 - $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
9860 - $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
9861 - }
3450 + if (isset($input['api_key'])) {
3451 + $new_input['api_key'] = sanitize_text_field($input['api_key']);
3452 + }
9862 3453
9863 - if (isset($input['rag_chunks_limit'])) {
9864 - $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
9865 - $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
9866 - }
3454 + if (isset($input['similarity_threshold'])) {
3455 + $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
3456 + $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 70), 85); // Enforce range
3457 + }
9867 3458
9868 - if (isset($input['xai_api_key'])) {
9869 - $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
9870 - }
3459 + if (isset($input['xai_api_key'])) {
3460 + $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
3461 + }
9871 3462
9872 - if (isset($input['claude_api_key'])) {
9873 - $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
9874 - }
3463 + if (isset($input['claude_api_key'])) {
3464 + $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
3465 + }
9875 3466
9876 - if (isset($input['enable_streaming_toggle'])) {
9877 - $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
9878 - } else {
9879 - // If checkbox not checked, it won't be in $input, so set to 'off'
9880 - $new_input['enable_streaming_toggle'] = 'off';
9881 - }
3467 + if (isset($input['enable_woocommerce_integration'])) {
3468 + $new_input['enable_woocommerce_integration'] = isset($input['enable_woocommerce_integration']) && $input['enable_woocommerce_integration'] === '1' ? '1' : '0';
9882 3469
9883 - if (isset($input['enable_web_search'])) {
9884 - $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
9885 - } else {
9886 - // If checkbox not checked, it won't be in $input, so set to 'off'
9887 - $new_input['enable_web_search'] = 'off';
9888 - }
3470 + }
9889 3471
9890 - if (isset($input['deepseek_api_key'])) {
9891 - $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
9892 - }
3472 + if (isset($input['privacy_toggle'])) {
3473 + $new_input['privacy_toggle'] = $input['privacy_toggle'];
3474 + }
9893 3475
9894 - if (isset($input['gemini_api_key'])) {
9895 - $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
9896 - }
3476 + if (isset($input['complianz_toggle'])) {
3477 + $new_input['complianz_toggle'] = $input['complianz_toggle'];
3478 + }
9897 3479
9898 - if (isset($input['enable_woocommerce_integration'])) {
9899 - $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
9900 - }
3480 + // Handle custom privacy text input
3481 + if (isset($input['privacy_text'])) {
3482 + // Allow basic HTML for links
3483 + $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
3484 + }
9901 3485
9902 - if (isset($input['privacy_toggle'])) {
9903 - $new_input['privacy_toggle'] = $input['privacy_toggle'];
9904 - }
3486 + if (isset($input['system_prompt_instructions'])) {
3487 + $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
3488 + }
9905 3489
9906 - if (isset($input['complianz_toggle'])) {
9907 - $new_input['complianz_toggle'] = $input['complianz_toggle'];
9908 - }
3490 + if (isset($input['mxchat_pro_email'])) {
3491 + $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
3492 + }
9909 3493
9910 - // Handle custom privacy text input
9911 - if (isset($input['privacy_text'])) {
9912 - // Allow basic HTML for links
9913 - $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
9914 - }
3494 + if (isset($input['mxchat_activation_key'])) {
3495 + $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
3496 + }
9915 3497
9916 - if (isset($input['system_prompt_instructions'])) {
9917 - $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
9918 - }
3498 + if (isset($input['append_to_body'])) {
3499 + $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
3500 + }
9919 3501
9920 - if (isset($input['mxchat_pro_email'])) {
9921 - $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
9922 - }
3502 + if (isset($input['top_bar_title'])) {
3503 + $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
3504 + }
9923 3505
9924 - if (isset($input['mxchat_activation_key'])) {
9925 - $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
9926 - }
3506 + if (isset($input['intro_message'])) {
3507 + $new_input['intro_message'] = sanitize_text_field($input['intro_message']);
3508 + }
9927 3509
9928 - if (isset($input['append_to_body'])) {
9929 - $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
9930 - }
3510 + if (isset($input['input_copy'])) {
3511 + $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
3512 + }
9931 3513
9932 - // Post type visibility settings
9933 - if (isset($input['post_type_visibility_mode'])) {
9934 - $allowed_modes = array('all', 'include', 'exclude');
9935 - $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
9936 - ? $input['post_type_visibility_mode']
9937 - : 'all';
9938 - }
9939 3514
9940 - if (isset($input['post_type_visibility_list'])) {
9941 - if (is_array($input['post_type_visibility_list'])) {
9942 - $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
9943 - } else {
9944 - $new_input['post_type_visibility_list'] = array();
3515 + if (isset($input['rate_limit_message'])) {
3516 + $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
9945 3517 }
9946 - }
9947 3518
9948 - if (isset($input['contextual_awareness_toggle'])) {
9949 - $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
9950 -}
3519 + if (isset($input['rate_limit_logged_in'])) {
3520 + $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
3521 + $rate_limit = sanitize_text_field($input['rate_limit_logged_in']);
9951 3522
9952 - if (isset($input['citation_links_toggle'])) {
9953 - $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
9954 -}
9955 -
9956 - // Satisfaction rating prompt — defaults ON when unchecked (so first save
9957 - // doesn't accidentally disable it). The form posts 'on' when checked;
9958 - // unchecked checkboxes don't post a value at all, so we infer 'off' only
9959 - // when the autosave/PHP request explicitly clears it via empty string.
9960 - if (array_key_exists('satisfaction_rating_enabled', $input)) {
9961 - $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
9962 - }
9963 -
9964 - // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
9965 - // the 4 text strings are sanitized + capped server-side. Blank values are
9966 - // preserved so the integrator falls back to translated defaults.
9967 - if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
9968 - $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
9969 - }
9970 -
9971 - // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default,
9972 - // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out
9973 - // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist,
9974 - // so without this isset-handler the key is stripped on the next save of ANY field
9975 - // (the 2c02ea global-rate-limit footgun).
9976 - if (array_key_exists('max_input_length', $input)) {
9977 - $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length'])));
9978 - }
9979 - if (array_key_exists('satisfaction_rating_question', $input)) {
9980 - $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
9981 - }
9982 - if (array_key_exists('satisfaction_rating_thanks', $input)) {
9983 - $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
9984 - }
9985 - if (array_key_exists('satisfaction_rating_placeholder', $input)) {
9986 - $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
9987 - }
9988 - if (array_key_exists('satisfaction_rating_saved', $input)) {
9989 - $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
9990 - }
9991 -
9992 - if (isset($input['top_bar_title'])) {
9993 - $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
9994 - }
9995 -
9996 - if (isset($input['ai_agent_text'])) {
9997 - $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
3523 + if (in_array($rate_limit, $allowed_limits, true)) {
3524 + $new_input['rate_limit_logged_in'] = $rate_limit;
3525 + } else {
3526 + $new_input['rate_limit_logged_in'] = '100'; // Default for logged-in users
3527 + }
9998 3528 }
9999 3529
10000 - if (isset($input['enable_email_block'])) {
10001 - $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
10002 - }
3530 + if (isset($input['rate_limit_logged_out'])) {
3531 + $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
3532 + $rate_limit = sanitize_text_field($input['rate_limit_logged_out']);
10003 3533
10004 - if (isset($input['email_blocker_header_content'])) {
10005 - // wp_kses_post() allows standard HTML tags permitted by WordPress
10006 - $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
10007 - }
10008 - if (isset($input['email_blocker_button_text'])) {
10009 - $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
10010 - }
10011 - // Sanitize name field toggle
10012 - if (isset($input['enable_name_field'])) {
10013 - $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
10014 - } else {
10015 - $new_input['enable_name_field'] = 'off';
10016 - }
10017 - // Sanitize name field placeholder
10018 - if (isset($input['name_field_placeholder'])) {
10019 - $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
10020 - }
10021 - if (isset($input['intro_message'])) {
10022 - $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
10023 - }
10024 -
10025 - if (isset($input['input_copy'])) {
10026 - $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
10027 - }
10028 -
10029 - if (isset($input['rate_limit_message'])) {
10030 - $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
10031 - }
10032 -
10033 -// Handle the new rate limits format
10034 -if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
10035 - $new_input['rate_limits'] = array();
10036 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10037 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10038 -
10039 - foreach ($input['rate_limits'] as $role_id => $settings) {
10040 - $new_input['rate_limits'][$role_id] = array();
10041 -
10042 - // Sanitize limit
10043 - if (isset($settings['limit'])) {
10044 - $limit = sanitize_text_field($settings['limit']);
10045 - // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive
10046 - // integer (custom value) — mirrors the global branch (plan-2c02ea). Without
10047 - // the custom path the per-role custom input was dropped and reset to the role
10048 - // default on every save (plan-7e23e7).
10049 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10050 - $new_input['rate_limits'][$role_id]['limit'] = $limit;
3534 + if (in_array($rate_limit, $allowed_limits, true)) {
3535 + $new_input['rate_limit_logged_out'] = $rate_limit;
10051 3536 } else {
10052 - $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
3537 + $new_input['rate_limit_logged_out'] = '10'; // Default for logged-out users
10053 3538 }
10054 3539 }
10055 3540
10056 - // Preserve the per-role custom value (mirrors the global branch's limit_custom).
10057 - if (isset($settings['limit_custom'])) {
10058 - $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']);
3541 + if (isset($input['pre_chat_message'])) {
3542 + $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10059 3543 }
10060 3544
10061 - // Sanitize timeframe
10062 - if (isset($settings['timeframe'])) {
10063 - $timeframe = sanitize_text_field($settings['timeframe']);
10064 - if (in_array($timeframe, $allowed_timeframes, true)) {
10065 - $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
10066 - } else {
10067 - $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
3545 + if (isset($input['model'])) {
3546 + $allowed_models = array(
3547 + 'grok-beta',
3548 + 'claude-3-5-sonnet-20241022',
3549 + 'claude-3-opus-20240229',
3550 + 'claude-3-sonnet-20240229',
3551 + 'claude-3-haiku-20240307',
3552 + 'gpt-4o',
3553 + 'gpt-4o-mini',
3554 + 'gpt-4-turbo',
3555 + 'gpt-4',
3556 + 'gpt-3.5-turbo',
3557 + );
3558 + if (in_array($input['model'], $allowed_models)) {
3559 + $new_input['model'] = sanitize_text_field($input['model']);
10068 3560 }
10069 3561 }
10070 3562
10071 - // Sanitize message
10072 - if (isset($settings['message'])) {
10073 - $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
3563 + // Sanitize new pro features
3564 + if (isset($input['close_button_color'])) {
3565 + $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
10074 3566 }
10075 - }
10076 -}
10077 3567
10078 -// Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea).
10079 -// Mirrors the per-role block above, adapted to the single global shape. Without
10080 -// this branch the whitelist-rebuild dropped rate_limits_global entirely on every
10081 -// save, so the global cap silently fell back to its 'unlimited' default.
10082 -// MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed.
10083 -if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) {
10084 - $g = $input['rate_limits_global'];
10085 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
10086 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
10087 - $global_out = array();
3568 + if (isset($input['chatbot_bg_color'])) {
3569 + $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
3570 + }
10088 3571
10089 - if (isset($g['limit'])) {
10090 - $limit = sanitize_text_field($g['limit']);
10091 - // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the
10092 - // autosave handler / renderer), OR any positive integer (custom value).
10093 - if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) {
10094 - $global_out['limit'] = $limit;
10095 - } else {
10096 - $global_out['limit'] = 'unlimited';
3572 + if (isset($input['woocommerce_consumer_key'])) {
3573 + $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10097 3574 }
10098 - }
10099 3575
10100 - if (isset($g['limit_custom'])) {
10101 - $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']);
10102 - }
3576 + if (isset($input['woocommerce_consumer_secret'])) {
3577 + $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
3578 + }
10103 3579
10104 - if (isset($g['timeframe'])) {
10105 - $timeframe = sanitize_text_field($g['timeframe']);
10106 - $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily';
10107 - }
3580 + if (isset($input['user_message_bg_color'])) {
3581 + $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
3582 + }
10108 3583
10109 - if (isset($g['message'])) {
10110 - $global_out['message'] = sanitize_textarea_field($g['message']);
10111 - }
3584 + if (isset($input['user_message_font_color'])) {
3585 + $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
3586 + }
10112 3587
10113 - $new_input['rate_limits_global'] = $global_out;
10114 -}
3588 + if (isset($input['bot_message_bg_color'])) {
3589 + $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
3590 + }
10115 3591
10116 - if (isset($input['pre_chat_message'])) {
10117 - $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
10118 - }
3592 + if (isset($input['bot_message_font_color'])) {
3593 + $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
3594 + }
10119 3595
10120 - if (isset($input['voyage_api_key'])) {
10121 - $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
10122 - }
3596 + if (isset($input['live_agent_message_bg_color'])) {
3597 + $new_input['live_agent_message_bg_color'] = sanitize_hex_color($input['live_agent_message_bg_color']);
3598 + }
10123 3599
10124 - // Add to your sanitize function
10125 - if (isset($input['embedding_model'])) {
10126 - // Catalog refactor (plan-d14e89): allowlist derived from the canonical
10127 - // catalog in includes/class-mxchat-model-catalog.php.
10128 - if (!class_exists('MxChat_Model_Catalog')) {
10129 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
3600 + if (isset($input['live_agent_message_font_color'])) {
3601 + $new_input['live_agent_message_font_color'] = sanitize_hex_color($input['live_agent_message_font_color']);
10130 3602 }
10131 - $allowed_models = MxChat_Model_Catalog::embedding_model_ids();
10132 - if (in_array($input['embedding_model'], $allowed_models)) {
10133 - $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
3603 +
3604 + if (isset($input['mode_indicator_bg_color'])) {
3605 + $new_input['mode_indicator_bg_color'] = sanitize_hex_color($input['mode_indicator_bg_color']);
10134 3606 }
10135 - }
10136 3607
10137 -if (isset($input['model'])) {
10138 - if ($input['model'] === 'openrouter') {
10139 - $new_input['model'] = 'openrouter';
10140 - } else {
10141 - if (!class_exists('MxChat_Model_Catalog')) {
10142 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php';
3608 + if (isset($input['mode_indicator_font_color'])) {
3609 + $new_input['mode_indicator_font_color'] = sanitize_hex_color($input['mode_indicator_font_color']);
10143 3610 }
10144 - $allowed_models = MxChat_Model_Catalog::chat_model_ids();
10145 3611
10146 - if (in_array($input['model'], $allowed_models)) {
10147 - $new_input['model'] = sanitize_text_field($input['model']);
10148 - } else {
10149 - // Fallback for any deprecated model
10150 - $new_input['model'] = 'gpt-5.6-sol';
3612 + if (isset($input['toolbar_icon_color'])) {
3613 + $new_input['toolbar_icon_color'] = sanitize_hex_color($input['toolbar_icon_color']);
10151 3614 }
10152 - }
10153 -}
10154 -
10155 -if (isset($input['openrouter_selected_model'])) {
10156 - // Just sanitize it, don't validate against a whitelist
10157 - $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
10158 -}
10159 3615
10160 -// ADD THIS:
10161 -if (isset($input['openrouter_selected_model_name'])) {
10162 - $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
10163 -}
10164 -
10165 - if (isset($input['openrouter_api_key'])) {
10166 - $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
10167 - }
3616 + if (isset($input['top_bar_bg_color'])) {
3617 + $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
3618 + }
10168 3619
10169 - // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
10170 - if (isset($input['custom_provider_base_url'])) {
10171 - $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
10172 - }
10173 - if (isset($input['custom_provider_api_key'])) {
10174 - $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
10175 - }
10176 - if (isset($input['custom_provider_model'])) {
10177 - $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
10178 - }
10179 - if (isset($input['custom_provider_auth_scheme'])) {
10180 - $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
10181 - $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
10182 - }
10183 - if (isset($input['custom_provider_for_embeddings'])) {
10184 - $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
10185 - }
10186 - if (isset($input['custom_provider_for_images'])) {
10187 - $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
10188 - }
10189 - if (isset($input['custom_provider_embedding_model'])) {
10190 - $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
10191 - }
10192 - if (isset($input['custom_provider_api_version'])) {
10193 - $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
10194 - }
3620 + if (isset($input['send_button_font_color'])) {
3621 + $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
3622 + }
10195 3623
3624 + if (isset($input['chatbot_background_color'])) {
3625 + $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
3626 + }
10196 3627
3628 + if (isset($input['icon_color'])) {
3629 + $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
3630 + }
10197 3631
10198 - if (isset($input['woocommerce_consumer_key'])) {
10199 - $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
10200 - }
3632 + if (isset($input['custom_icon'])) {
3633 + $new_input['custom_icon'] = esc_url_raw($input['custom_icon']);
3634 + }
10201 3635
10202 - if (isset($input['woocommerce_consumer_secret'])) {
10203 - $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
10204 - }
3636 + if (isset($input['chat_input_font_color'])) {
3637 + $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
3638 + }
10205 3639
3640 + // Sanitize link_target_toggle
3641 + if (isset($input['link_target_toggle'])) {
3642 + $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
3643 + }
10206 3644
10207 - // Sanitize link_target_toggle
10208 - if (isset($input['link_target_toggle'])) {
10209 - $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
10210 - }
10211 -
10212 - // Sanitize Loops API Key
3645 + // Sanitize Loops API Key
10213 3646 if (isset($input['loops_api_key'])) {
10214 3647 $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
10215 3648 }
10216 3649
@@ -10217,25 +3650,10 @@
10217 3650 if (isset($input['chat_persistence_toggle'])) {
10218 3651 $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
10219 3652 }
10220 3653
10221 - // No else clause: an absent key stays absent, so the front-end default ('on') applies
10222 - // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here).
10223 - if (isset($input['print_button_enabled'])) {
10224 - $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off';
10225 - }
10226 3654
10227 - // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label.
10228 - // No else on the toggle: an absent key stays absent so the front-end '?? off'
10229 - // default applies, and the full-array autosave rebuild preserves a saved value.
10230 - if (isset($input['reset_chat_enabled'])) {
10231 - $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off';
10232 - }
10233 3655
10234 - if (isset($input['reset_chat_label'])) {
10235 - $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']);
10236 - }
10237 -
10238 3656 if (isset($input['popular_question_1'])) {
10239 3657 $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
10240 3658 }
10241 3659
@@ -10255,17 +3673,19 @@
10255 3673 if (isset($input['loops_mailing_list'])) {
10256 3674 $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
10257 3675 }
10258 3676
10259 -// Sanitize Triggered Phrase Response
3677 + // Sanitize Triggered Phrase Response
10260 3678 if (isset($input['triggered_phrase_response'])) {
10261 3679 $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
10262 3680 }
3681 +
10263 3682 if (isset($input['email_capture_response'])) {
10264 - $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
3683 + $new_input['email_capture_response'] = sanitize_textarea_field($input['email_capture_response']);
10265 3684 }
10266 3685
10267 - // Sanitize Brave Search Settings
3686 +
3687 + // Sanitize Brave Search Settings
10268 3688 if (isset($input['brave_api_key'])) {
10269 3689 $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
10270 3690 }
10271 3691
@@ -10280,9 +3700,9 @@
10280 3700 }
10281 3701
10282 3702 if (isset($input['brave_news_count'])) {
10283 3703 $news_count = intval($input['brave_news_count']);
10284 - $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
3704 + $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
10285 3705 }
10286 3706
10287 3707 if (isset($input['brave_country'])) {
10288 3708 $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
@@ -10291,26 +3711,14 @@
10291 3711 if (isset($input['brave_language'])) {
10292 3712 $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
10293 3713 }
10294 3714
3715 +
10295 3716 if (isset($input['chat_toolbar_toggle'])) {
10296 3717 $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
10297 3718 }
10298 3719
10299 - // Sanitize PDF upload button toggle
10300 - if (isset($input['show_pdf_upload_button'])) {
10301 - $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
10302 - } else {
10303 - $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
10304 - }
10305 3720
10306 - // Sanitize Word upload button toggle
10307 - if (isset($input['show_word_upload_button'])) {
10308 - $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
10309 - } else {
10310 - $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
10311 - }
10312 -
10313 3721 if (isset($input['pdf_intent_trigger_text'])) {
10314 3722 $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
10315 3723 }
10316 3724
@@ -10328,751 +3736,651 @@
10328 3736 $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
10329 3737 }
10330 3738 }
10331 3739
10332 - if (isset($input['live_agent_webhook_url'])) {
10333 - $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
10334 - }
10335 - if (isset($input['live_agent_secret_key'])) {
10336 - $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
10337 - }
10338 3740
10339 - // Live Agent Integration
10340 - if (isset($input['live_agent_bot_token'])) {
10341 - $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
10342 - }
3741 + if (isset($input['live_agent_webhook_url'])) {
3742 + $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
3743 + }
3744 + if (isset($input['live_agent_secret_key'])) {
3745 + $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
3746 + }
10343 3747
10344 - if (isset($input['live_agent_shared_channel'])) {
10345 - $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']);
10346 - }
3748 + // Live Agent Integration
3749 + if (isset($input['live_agent_bot_token'])) {
3750 + $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
3751 + }
10347 3752
10348 - // Default-OFF toggle: absent key stays absent (unchecked box = off).
10349 - if (isset($input['live_agent_archive_on_end_toggle'])) {
10350 - $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off';
10351 - }
10352 -
10353 - if (isset($input['live_agent_user_ids'])) {
10354 - $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
10355 - }
10356 -
10357 3753 if (isset($input['live_agent_status'])) {
10358 - $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
3754 + $new_input['live_agent_status'] = ($input['live_agent_status'] === 'online') ? 'online' : 'offline';
10359 3755 }
10360 3756 if (isset($input['live_agent_away_message'])) {
10361 3757 $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
10362 3758 }
10363 - if (isset($input['live_agent_notification_message'])) {
3759 + if (isset($input['live_agent_notification_message'])) {
10364 3760 $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
10365 3761 }
10366 3762
10367 - // Telegram Integration
10368 - if (isset($input['telegram_status'])) {
10369 - $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
10370 - }
10371 - if (isset($input['telegram_bot_token'])) {
10372 - $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
10373 - }
10374 - if (isset($input['telegram_group_id'])) {
10375 - $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
10376 - }
10377 - if (isset($input['telegram_webhook_secret'])) {
10378 - $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
10379 - }
10380 - if (isset($input['telegram_notification_message'])) {
10381 - $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
10382 - }
10383 - if (isset($input['telegram_away_message'])) {
10384 - $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
10385 - }
10386 3763
10387 - // Sanitize script loading strategy
10388 - if (isset($input['script_loading_strategy'])) {
10389 - $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
10390 - $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
10391 - ? $input['script_loading_strategy']
10392 - : 'default';
3764 + return $new_input;
10393 3765 }
10394 3766
10395 - // Sanitize debug mode
10396 - if (isset($input['debug_mode'])) {
10397 - $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
10398 - }
10399 3767
10400 - // Content Generator Settings
10401 - if (isset($input['content_model'])) {
10402 - $new_input['content_model'] = sanitize_text_field($input['content_model']);
3768 + // Method to append the chatbot to the body
3769 + public function mxchat_append_chatbot_to_body() {
3770 + $options = get_option('mxchat_options');
3771 + if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
3772 + echo do_shortcode('[mxchat_chatbot floating="yes"]');
3773 + }
10403 3774 }
10404 - if (isset($input['content_image_model'])) {
10405 - $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
10406 - }
10407 - if (isset($input['content_image_quality'])) {
10408 - $q = sanitize_text_field($input['content_image_quality']);
10409 - $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
10410 - }
10411 - if (isset($input['content_enable_images'])) {
10412 - $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
10413 - }
10414 - if (isset($input['content_use_placeholders'])) {
10415 - $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
10416 - }
10417 - if (isset($input['content_internal_linking'])) {
10418 - $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
10419 - }
10420 - if (isset($input['content_tool_use'])) {
10421 - $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
10422 - }
10423 - if (isset($input['content_image_count'])) {
10424 - $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count']));
10425 - }
10426 3775
10427 - // SEO Optimize toggle fields
10428 - foreach (array('seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $seo_key) {
10429 - if (isset($input[$seo_key])) {
10430 - $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
10431 - }
10432 - }
10433 3776
10434 - // Preserve content generator settings when saving from main settings page
10435 - // (where content fields are not in the form submission)
10436 - $existing = get_option('mxchat_options', array());
10437 - foreach (array('content_model', 'content_image_model', 'content_image_quality', 'content_image_count', 'content_enable_images', 'content_use_placeholders', 'content_internal_linking', 'content_tool_use', 'seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $key) {
10438 - if (!isset($new_input[$key]) && isset($existing[$key])) {
10439 - $new_input[$key] = $existing[$key];
10440 - }
10441 - }
10442 3777
10443 - return $new_input;
10444 -}
3778 +private static function mxchat_extract_main_content($html) {
3779 + $dom = new DOMDocument;
3780 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
3781 + @$dom->loadHTML($html);
3782 + libxml_clear_errors();
10445 3783
10446 -/**
10447 - * Log a debug message if debug mode is enabled
10448 - *
10449 - * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
10450 - * @param string $message The log message
10451 - * @param array $data Optional additional data to log
10452 - * @return bool Whether the message was logged
10453 - */
10454 -public static function mxchat_log_debug( $type, $message, $data = array() ) {
10455 - $options = get_option( 'mxchat_options', array() );
3784 + $xpath = new DOMXPath($dom);
10456 3785
10457 - // Check if debug mode is enabled
10458 - if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
10459 - return false;
10460 - }
3786 + // Simplified selectors focusing on common content areas
3787 + $selectors = [
3788 + '//article',
3789 + '//*[@id="content"]',
3790 + '//*[@class="entry-content"]',
3791 + '//main',
3792 + ];
10461 3793
10462 - // Get current log
10463 - $log = get_option( 'mxchat_debug_log', array() );
10464 - if ( ! is_array( $log ) ) {
10465 - $log = array();
3794 + foreach ($selectors as $selector) {
3795 + $nodes = $xpath->query($selector);
3796 + if ($nodes->length > 0) {
3797 + $content = '';
3798 + foreach ($nodes as $node) {
3799 + $content .= $dom->saveHTML($node);
3800 + }
3801 + return $content;
3802 + }
10466 3803 }
10467 3804
10468 - // Add new entry
10469 - $entry = array(
10470 - 'time' => current_time( 'Y-m-d H:i:s' ),
10471 - 'type' => sanitize_key( $type ),
10472 - 'message' => sanitize_text_field( $message ),
10473 - );
3805 + // Fallback: Return the entire body content if no specific selector matches
3806 + $body = $dom->getElementsByTagName('body');
3807 + return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
3808 +}
10474 3809
10475 - if ( ! empty( $data ) ) {
10476 - $entry['data'] = $data;
3810 +public function mxchat_handle_sitemap_submission() {
3811 + // Check if the form was submitted and verify permissions
3812 + if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
3813 + wp_die(esc_html__('Unauthorized access', 'mxchat'));
10477 3814 }
10478 3815
10479 - // Add to beginning of array (newest first)
10480 - array_unshift( $log, $entry );
3816 + // Verify nonce
3817 + check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
10481 3818
10482 - // Keep only last 100 entries
10483 - if ( count( $log ) > 100 ) {
10484 - $log = array_slice( $log, 0, 100 );
3819 + // Validate URL
3820 + if (!isset($_POST['sitemap_url']) || empty($_POST['sitemap_url'])) {
3821 + set_transient('mxchat_admin_notice_error',
3822 + esc_html__('Please provide a valid URL.', 'mxchat'),
3823 + 30
3824 + );
3825 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3826 + exit;
10485 3827 }
10486 3828
10487 - // Save log
10488 - update_option( 'mxchat_debug_log', $log, false );
3829 + $submitted_url = esc_url_raw($_POST['sitemap_url']);
3830 + $response = wp_remote_get($submitted_url, array('timeout' => 30));
10489 3831
10490 - return true;
10491 -}
3832 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
3833 + $error_message = is_wp_error($response) ? $response->get_error_message() : 'Failed to fetch URL';
3834 + set_transient('mxchat_admin_notice_error',
3835 + sprintf(
3836 + esc_html__('Failed to fetch the URL: %s', 'mxchat'),
3837 + esc_html($error_message)
3838 + ),
3839 + 30
3840 + );
3841 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3842 + exit;
3843 + }
10492 3844
10493 -/**
10494 - * Get the debug log entries
10495 - *
10496 - * @return array The debug log entries
10497 - */
10498 -public static function mxchat_get_debug_log() {
10499 - $log = get_option( 'mxchat_debug_log', array() );
10500 - return is_array( $log ) ? $log : array();
10501 -}
3845 + $content_type = wp_remote_retrieve_header($response, 'content-type');
3846 + $body_content = wp_remote_retrieve_body($response);
10502 3847
10503 -/**
10504 - * Clear the debug log
10505 - *
10506 - * @return bool Whether the log was cleared
10507 - */
10508 -public static function mxchat_clear_debug_log() {
10509 - return delete_option( 'mxchat_debug_log' );
10510 -}
10511 -
10512 -/**
10513 - * Export settings as JSON with masked API keys
10514 - *
10515 - * @return array The sanitized settings array
10516 - */
10517 -public static function mxchat_export_settings() {
10518 - $options = get_option( 'mxchat_options', array() );
10519 -
10520 - if ( ! is_array( $options ) ) {
10521 - return array();
3848 + if (empty($body_content)) {
3849 + set_transient('mxchat_admin_notice_error',
3850 + esc_html__('Empty response received from URL.', 'mxchat'),
3851 + 30
3852 + );
3853 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3854 + exit;
10522 3855 }
10523 3856
10524 - // List of API key fields to mask
10525 - $api_key_fields = array(
10526 - 'api_key',
10527 - 'xai_api_key',
10528 - 'claude_api_key',
10529 - 'deepseek_api_key',
10530 - 'voyage_api_key',
10531 - 'gemini_api_key',
10532 - 'openrouter_api_key',
10533 - 'loops_api_key',
10534 - 'brave_api_key',
10535 - 'live_agent_secret_key',
10536 - 'live_agent_bot_token',
10537 - 'telegram_bot_token',
10538 - 'telegram_webhook_secret',
10539 - 'woocommerce_consumer_key',
10540 - 'woocommerce_consumer_secret',
10541 - );
3857 + // Handle PDF URL
3858 + if ($this->is_pdf_url($submitted_url, $response)) {
3859 + $result = $this->handle_pdf_for_knowledge_base($submitted_url, $response);
10542 3860
10543 - // Mask API keys (show only last 4 characters)
10544 - foreach ( $api_key_fields as $field ) {
10545 - if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
10546 - $value = $options[ $field ];
10547 - if ( strlen( $value ) > 4 ) {
10548 - $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
10549 - } else {
10550 - $options[ $field ] = '****';
10551 - }
3861 + if ($result === 'scheduled') {
3862 + set_transient(
3863 + 'mxchat_last_pdf_url',
3864 + sanitize_text_field($submitted_url),
3865 + DAY_IN_SECONDS
3866 + );
3867 + set_transient('mxchat_admin_notice_info',
3868 + esc_html__('PDF processing has started in the background. You can check the progress in the Knowledge Base section.', 'mxchat'),
3869 + 30
3870 + );
3871 + } else {
3872 + set_transient('mxchat_admin_notice_error',
3873 + esc_html__('Failed to start PDF processing. Please try again.', 'mxchat'),
3874 + 30
3875 + );
10552 3876 }
3877 +
3878 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3879 + exit;
10553 3880 }
10554 3881
10555 - // Add metadata
10556 - $export = array(
10557 - 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
10558 - 'export_date' => current_time( 'Y-m-d H:i:s' ),
10559 - 'wordpress_version' => get_bloginfo( 'version' ),
10560 - 'php_version' => phpversion(),
10561 - 'settings' => $options,
10562 - );
3882 + // Handle Sitemap XML
3883 + if (strpos($content_type, 'xml') !== false || strpos($body_content, '<urlset') !== false) {
3884 + libxml_use_internal_errors(true);
3885 + $xml = simplexml_load_string($body_content);
3886 + $xml_errors = libxml_get_errors();
3887 + libxml_clear_errors();
10563 3888
10564 - return $export;
10565 -}
3889 + if ($xml === false || !empty($xml_errors)) {
3890 + set_transient('mxchat_admin_notice_error',
3891 + esc_html__('Invalid sitemap XML. Please provide a valid sitemap.', 'mxchat'),
3892 + 30
3893 + );
3894 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3895 + exit;
3896 + }
10566 3897
10567 -/**
10568 - * Reset all settings to defaults
10569 - *
10570 - * @return bool Whether the reset was successful
10571 - */
10572 -public static function mxchat_reset_all_settings() {
10573 - // Delete main options
10574 - $deleted = delete_option( 'mxchat_options' );
3898 + $result = $this->handle_sitemap_for_knowledge_base($xml, $submitted_url);
10575 3899
10576 - // Also clear the debug log
10577 - delete_option( 'mxchat_debug_log' );
3900 + if ($result === 'scheduled') {
3901 + set_transient(
3902 + 'mxchat_last_sitemap_url',
3903 + sanitize_text_field($submitted_url),
3904 + DAY_IN_SECONDS
3905 + );
3906 + set_transient('mxchat_admin_notice_info',
3907 + esc_html__('Sitemap processing has started in the background. You can check the progress in the Knowledge Base section.', 'mxchat'),
3908 + 30
3909 + );
3910 + } else {
3911 + set_transient('mxchat_admin_notice_error',
3912 + esc_html__('Failed to start sitemap processing. Please try again.', 'mxchat'),
3913 + 30
3914 + );
3915 + }
10578 3916
10579 - // Log the reset (will create new log since we just cleared it)
10580 - // We need to temporarily enable debug mode to log this
10581 - $temp_options = array( 'debug_mode' => 'on' );
10582 - update_option( 'mxchat_options', $temp_options );
3917 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3918 + exit;
3919 + }
10583 3920
10584 - self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
3921 + // Handle Regular URL
3922 + $page_content = $this->mxchat_extract_main_content($body_content);
3923 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
10585 3924
10586 - // Now delete again to trigger re-initialization
10587 - delete_option( 'mxchat_options' );
10588 -
10589 - return $deleted;
10590 -}
10591 -
10592 - // Method to append the chatbot to the body
10593 - public function mxchat_append_chatbot_to_body() {
10594 - $options = get_option('mxchat_options');
10595 - if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
10596 - echo do_shortcode('[mxchat_chatbot floating="yes"]');
10597 - }
3925 + if (empty($sanitized_content)) {
3926 + set_transient('mxchat_admin_notice_error',
3927 + esc_html__('No valid content found on the provided URL.', 'mxchat'),
3928 + 30
3929 + );
3930 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3931 + exit;
10598 3932 }
10599 3933
10600 -
10601 -
10602 -
10603 -
10604 -private function mxchat_fetch_loops_mailing_lists($api_key) {
10605 - $url = 'https://app.loops.so/api/v1/lists';
10606 - $response = wp_remote_get($url, array(
10607 - 'headers' => array(
10608 - 'Authorization' => 'Bearer ' . $api_key,
10609 - 'Content-Type' => 'application/json'
10610 - )
10611 - ));
10612 -
10613 - if (is_wp_error($response)) {
10614 - return array();
3934 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
3935 + if (is_array($embedding_vector)) {
3936 + MxChat_Utils::submit_content_to_db(
3937 + $sanitized_content,
3938 + $submitted_url,
3939 + $this->options['api_key']
3940 + );
3941 + set_transient('mxchat_admin_notice_success',
3942 + esc_html__('URL content successfully submitted!', 'mxchat'),
3943 + 30
3944 + );
3945 + } else {
3946 + set_transient('mxchat_admin_notice_error',
3947 + esc_html__('Failed to generate embedding for the URL content. Please check your API key and try again.', 'mxchat'),
3948 + 30
3949 + );
10615 3950 }
10616 3951
10617 - $body = wp_remote_retrieve_body($response);
10618 - $lists = json_decode($body, true);
3952 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
3953 + exit;
3954 +}
3955 +private function is_pdf_url($url, $response) {
3956 + $content_type = wp_remote_retrieve_header($response, 'content-type');
3957 + $file_extension = strtolower(pathinfo($url, PATHINFO_EXTENSION));
10619 3958
10620 - return isset($lists) && is_array($lists) ? $lists : array();
3959 + return strpos($content_type, 'pdf') !== false || $file_extension === 'pdf';
10621 3960 }
10622 3961
10623 -function mxchat_calculate_cosine_similarity($vec1, $vec2) {
10624 - if (empty($vec1) || empty($vec2)) {
10625 - return 0.0;
3962 +private function handle_pdf_for_knowledge_base($pdf_url, $response) {
3963 + if (!current_user_can('manage_options')) {
3964 + //error_log('Unauthorized PDF processing attempt');
3965 + return false;
10626 3966 }
10627 3967
10628 - $dot_product = 0.0;
10629 - $norm_a = 0.0;
10630 - $norm_b = 0.0;
3968 + $pdf_url = esc_url_raw($pdf_url);
3969 + $upload_dir = wp_upload_dir();
10631 3970
10632 - for ($i = 0; $i < count($vec1); $i++) {
10633 - $dot_product += $vec1[$i] * $vec2[$i];
10634 - $norm_a += pow($vec1[$i], 2);
10635 - $norm_b += pow($vec2[$i], 2);
3971 + if (isset($upload_dir['error']) && $upload_dir['error'] !== false) {
3972 + //error_log(sprintf('Upload directory error: %s', esc_html($upload_dir['error'])));
3973 + return false;
10636 3974 }
10637 3975
10638 - if ($norm_a == 0.0 || $norm_b == 0.0) {
10639 - return 0.0;
10640 - } else {
10641 - return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
3976 + $pdf_filename = sanitize_file_name('mxchat_kb_' . time() . '.pdf');
3977 + $pdf_path = trailingslashit($upload_dir['path']) . $pdf_filename;
3978 +
3979 + $response_body = wp_remote_retrieve_body($response);
3980 + if (empty($response_body)) {
3981 + //error_log('Empty PDF response body');
3982 + return false;
10642 3983 }
10643 -}
10644 3984
10645 -/**
10646 - * Validates nonce and deletes all chat prompts
10647 - */
10648 -public function mxchat_handle_delete_all_prompts() {
10649 - //error_log('=== DELETE ALL DEBUG START ===');
10650 -
10651 - // Verify nonce
10652 - if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
10653 - //error_log('DEBUG: Nonce verification failed');
10654 - wp_die(__('Nonce verification failed.', 'mxchat'));
3985 + if (!wp_mkdir_p(dirname($pdf_path))) {
3986 + //error_log(sprintf('Failed to create directory for PDF: %s', esc_html($pdf_path)));
3987 + return false;
10655 3988 }
10656 -
10657 - // Check permissions
10658 - if (!current_user_can('manage_options')) {
10659 - //error_log('DEBUG: Permission check failed');
10660 - wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
10661 - }
10662 -
10663 - // Get bot_id and content type filter from POST data
10664 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
10665 - $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
10666 3989
10667 - $success = true;
10668 - $error_messages = array();
3990 + try {
3991 + file_put_contents($pdf_path, $response_body);
10669 3992
10670 - // Get bot-specific Pinecone configuration
10671 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10672 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
3993 + if (!file_exists($pdf_path)) {
3994 + throw new Exception('Failed to save PDF file');
3995 + }
10673 3996
10674 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3997 + $parser = new \Smalot\PdfParser\Parser();
3998 + $pdf = $parser->parseFile($pdf_path);
3999 + $total_pages = absint(count($pdf->getPages()));
10675 4000
10676 - if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
10677 - // Delete from Pinecone (with optional content type filter)
10678 - $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
4001 + if ($total_pages < 1) {
4002 + throw new Exception('Invalid PDF: no pages found');
4003 + }
10679 4004
10680 - if (!$result['success']) {
10681 - $success = false;
10682 - $error_messages[] = $result['message'];
10683 - }
4005 + wp_schedule_single_event(time(), 'mxchat_process_pdf_pages', array(
4006 + 'pdf_path' => $pdf_path,
4007 + 'pdf_url' => $pdf_url,
4008 + 'total_pages' => $total_pages,
4009 + 'batch_size' => absint(15),
4010 + 'batch_pause' => absint(10)
4011 + ));
10684 4012
10685 - } else {
10686 - // Delete from WordPress database
10687 - global $wpdb;
10688 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
4013 + $status_data = array(
4014 + 'total_pages' => $total_pages,
4015 + 'processed_pages' => 0,
4016 + 'status' => 'processing',
4017 + 'last_update' => time()
4018 + );
10689 4019
10690 - // Build WHERE conditions
10691 - $where_clauses = array();
10692 - $where_values = array();
4020 + set_transient(
4021 + sanitize_key('mxchat_pdf_status_' . md5($pdf_url)),
4022 + array_map('sanitize_text_field', $status_data),
4023 + DAY_IN_SECONDS
4024 + );
10693 4025
10694 - // Bot filter
10695 - if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
10696 - $where_clauses[] = 'bot_id = %s';
10697 - $where_values[] = $bot_id;
10698 - }
4026 + return 'scheduled';
10699 4027
10700 - // Content type filter
10701 - if (!empty($content_type_filter)) {
10702 - $where_clauses[] = 'content_type = %s';
10703 - $where_values[] = $content_type_filter;
4028 + } catch (Exception $e) {
4029 + //error_log(sprintf('Error preparing PDF for processing: %s', esc_html($e->getMessage())));
4030 + if (file_exists($pdf_path)) {
4031 + wp_delete_file($pdf_path);
10704 4032 }
4033 + return false;
4034 + }
4035 +}
4036 +public static function process_pdf_pages_cron($pdf_path, $pdf_url, $total_pages, $batch_size, $batch_pause) {
4037 + // Validate inputs
4038 + $pdf_path = sanitize_text_field($pdf_path);
4039 + $pdf_url = esc_url_raw($pdf_url);
4040 + $total_pages = absint($total_pages);
4041 + $batch_size = absint($batch_size);
4042 + $batch_pause = absint($batch_pause);
10705 4043
10706 - if (!empty($where_clauses)) {
10707 - $where_sql = implode(' AND ', $where_clauses);
10708 - $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
10709 - } else {
10710 - // No filters — delete all
10711 - $result = $wpdb->query("DELETE FROM {$table_name}");
4044 + try {
4045 + if (!file_exists($pdf_path)) {
4046 + throw new Exception(sprintf('PDF file not found at path: %s', esc_html($pdf_path)));
10712 4047 }
10713 4048
10714 - if ($result === false) {
10715 - $success = false;
10716 - $error_messages[] = 'Failed to delete from WordPress database';
10717 - }
10718 - }
4049 + $parser = new \Smalot\PdfParser\Parser();
4050 + $pdf = $parser->parseFile($pdf_path);
4051 + $pages = $pdf->getPages();
10719 4052
10720 - // Redirect back with a success message and bot_id
10721 - $redirect_url = add_query_arg(array(
10722 - 'page' => 'mxchat-prompts',
10723 - 'bot_id' => $bot_id,
10724 - 'all_deleted' => $success ? 'true' : 'false'
10725 - ), admin_url('admin.php'));
10726 -
10727 - wp_safe_redirect($redirect_url);
10728 - exit;
10729 -}
4053 + // Get current progress
4054 + $status_key = sanitize_key('mxchat_pdf_status_' . md5($pdf_url));
4055 + $status = get_transient($status_key);
10730 4056
4057 + if (!$status || !is_array($status)) {
4058 + throw new Exception('Invalid status data retrieved from transient');
4059 + }
10731 4060
4061 + $start_page = absint($status['processed_pages']);
4062 + $end_page = min($start_page + $batch_size, $total_pages);
10732 4063
10733 - /**
10734 - * Handles deletion prompt with nonce validation
10735 - */
10736 - public function mxchat_handle_delete_prompt() {
10737 - // Sanitize and validate nonce
10738 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
10739 - if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
10740 - wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
10741 - }
4064 + $instance = new self(); // Create an instance of the class
10742 4065
10743 - // Check permissions
10744 - if (!current_user_can('manage_options')) {
10745 - wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
10746 - }
4066 + for ($i = $start_page; $i < $end_page; $i++) {
4067 + $text = $pages[$i]->getText();
4068 + $sanitized_content = $instance->mxchat_sanitize_content_for_api($text); // Call via instance
10747 4069
10748 - // Get ID and source parameters
10749 - $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
10750 - $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
4070 + if (!empty($sanitized_content)) {
4071 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
4072 + if (is_array($embedding_vector)) {
4073 + $metadata = array(
4074 + 'document_type' => 'pdf',
4075 + 'total_pages' => $total_pages,
4076 + 'current_page' => $i + 1,
4077 + 'prev_page' => $i > 0 ? $i : null,
4078 + 'next_page' => $i < ($total_pages - 1) ? $i + 2 : null,
4079 + 'source_url' => $pdf_url
4080 + );
10751 4081
10752 - if (empty($id)) {
10753 - wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
10754 - }
4082 + $content_with_metadata = wp_json_encode($metadata) . "\n---\n" . $sanitized_content;
4083 + $page_url = esc_url($pdf_url . "#page=" . ($i + 1));
10755 4084
10756 - $success = false;
10757 - $error_message = '';
4085 + $options = get_option('mxchat_options');
4086 + MxChat_Utils::submit_content_to_db($content_with_metadata, $page_url, $options['api_key']);
4087 + }
4088 + }
10758 4089
10759 - // Resolve per-bot Pinecone settings — the global option is the wrong
10760 - // index entirely when the row belongs to a bot with its own host
10761 - $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default';
10762 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
10763 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
10764 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
4090 + // Update progress with sanitized data
4091 + $status['processed_pages'] = absint($i + 1);
4092 + $status['last_update'] = time();
4093 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4094 + }
10765 4095
10766 - // If source is not specified, determine based on Pinecone configuration
10767 - if (empty($source)) {
10768 - $source = $use_pinecone ? 'pinecone' : 'wordpress';
10769 - }
4096 + // Schedule next batch if needed
4097 + if ($end_page < $total_pages) {
4098 + wp_schedule_single_event(time() + $batch_pause, 'mxchat_process_pdf_pages', array(
4099 + 'pdf_path' => $pdf_path,
4100 + 'pdf_url' => $pdf_url,
4101 + 'total_pages' => $total_pages,
4102 + 'batch_size' => $batch_size,
4103 + 'batch_pause' => $batch_pause
4104 + ));
4105 + } else {
4106 + // Processing complete
4107 + $status['status'] = 'complete';
4108 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4109 + if (file_exists($pdf_path)) {
4110 + wp_delete_file($pdf_path);
4111 + }
4112 + }
10770 4113
10771 - if ($source === 'pinecone' || $use_pinecone) {
10772 - //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
4114 + } catch (\Exception $e) {
4115 + $status['status'] = 'error';
4116 + $status['error'] = sanitize_text_field($e->getMessage());
4117 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4118 + if (file_exists($pdf_path)) {
4119 + wp_delete_file($pdf_path);
4120 + }
4121 + }
4122 +}
10773 4123
10774 - // Handle Pinecone deletion
10775 - if (empty($pinecone_options['mxchat_pinecone_host']) ||
10776 - empty($pinecone_options['mxchat_pinecone_api_key'])) {
10777 - wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
10778 - }
4124 +public function get_pdf_processing_status($pdf_url) {
4125 + $pdf_url = esc_url_raw($pdf_url);
4126 + $status = get_transient(sanitize_key('mxchat_pdf_status_' . md5($pdf_url)));
10779 4127
10780 - // Delete from Pinecone using the vector ID directly
10781 - $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
10782 - $id,
10783 - $pinecone_options['mxchat_pinecone_api_key'],
10784 - $pinecone_options['mxchat_pinecone_host'],
10785 - $pinecone_options['mxchat_pinecone_namespace'] ?? ''
10786 - );
10787 - if ($result['success']) {
10788 - $success = true;
4128 + if (!$status || !is_array($status)) {
4129 + return false;
4130 + }
10789 4131
10790 - // Remove from vector cache
10791 - $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
10792 - $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
4132 + return array(
4133 + 'total_pages' => absint($status['total_pages']),
4134 + 'processed_pages' => absint($status['processed_pages']),
4135 + 'percentage' => round((absint($status['processed_pages']) / absint($status['total_pages'])) * 100),
4136 + 'status' => sanitize_text_field($status['status']),
4137 + 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ago'
4138 + );
4139 +}
10793 4140
10794 - set_transient('mxchat_admin_notice_success',
10795 - esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
10796 - } else {
10797 - $error_message = $result['message'];
10798 - set_transient('mxchat_admin_notice_error',
10799 - esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
10800 - }
10801 - } else {
10802 - //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
4141 +private function handle_sitemap_for_knowledge_base($xml, $sitemap_url) {
4142 + if (!current_user_can('manage_options')) {
4143 + //error_log('Unauthorized sitemap processing attempt');
4144 + return false;
4145 + }
10803 4146
10804 - // Handle WordPress database deletion
10805 - global $wpdb;
10806 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
4147 + try {
4148 + $sitemap_url = esc_url_raw($sitemap_url);
10807 4149
10808 - // Clear cache and delete prompt
10809 - wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
4150 + if (!$xml || !is_object($xml)) {
4151 + throw new Exception('Invalid XML object provided');
4152 + }
10810 4153
10811 - $result = $wpdb->delete(
10812 - $table_name,
10813 - array('id' => intval($id)),
10814 - array('%d')
10815 - );
4154 + $urls = [];
4155 + foreach ($xml->url as $url_element) {
4156 + $url = esc_url_raw((string)$url_element->loc);
4157 + if ($url) {
4158 + $urls[] = $url;
4159 + }
4160 + }
10816 4161
10817 - if ($result !== false) {
10818 - $success = true;
10819 - set_transient('mxchat_admin_notice_success',
10820 - esc_html__('Entry deleted successfully.', 'mxchat'), 30);
10821 - } else {
10822 - set_transient('mxchat_admin_notice_error',
10823 - esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
10824 - }
10825 - }
4162 + $total_urls = absint(count($urls));
10826 4163
10827 - // Redirect back to the prompts page
10828 - wp_safe_redirect(add_query_arg(
10829 - array(
10830 - 'page' => 'mxchat-prompts',
10831 - 'deleted' => $success ? 'true' : 'false'
10832 - ),
10833 - admin_url('admin.php')
10834 - ));
10835 - exit;
10836 - }
4164 + if ($total_urls < 1) {
4165 + throw new Exception('No valid URLs found in sitemap');
4166 + }
10837 4167
4168 + wp_schedule_single_event(time(), 'mxchat_process_sitemap_urls', array(
4169 + 'urls' => $urls,
4170 + 'sitemap_url' => $sitemap_url,
4171 + 'total_urls' => $total_urls,
4172 + 'batch_size' => absint(10),
4173 + 'batch_pause' => absint(5)
4174 + ));
10838 4175
4176 + $status_data = array(
4177 + 'total_urls' => $total_urls,
4178 + 'processed_urls' => 0,
4179 + 'status' => 'processing',
4180 + 'last_update' => time()
4181 + );
10839 4182
4183 + set_transient(
4184 + sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)),
4185 + array_map('sanitize_text_field', $status_data),
4186 + DAY_IN_SECONDS
4187 + );
10840 4188
10841 - /**
10842 - * Averages multiple vectors into a single vector
10843 - */
10844 - private function mxchat_average_vectors($vectors) {
10845 - $vector_length = count($vectors[0]);
10846 - $sum_vector = array_fill(0, $vector_length, 0);
4189 + return 'scheduled';
10847 4190
10848 - foreach ($vectors as $vector) {
10849 - for ($i = 0; $i < $vector_length; $i++) {
10850 - $sum_vector[$i] += $vector[$i];
10851 - }
10852 - }
4191 + } catch (\Exception $e) {
4192 + //error_log(sprintf('Error preparing sitemap for processing: %s', esc_html($e->getMessage())));
4193 + return false;
4194 + }
4195 +}
4196 +public static function process_sitemap_urls_cron($urls, $sitemap_url, $total_urls, $batch_size, $batch_pause) {
4197 + // Validate inputs
4198 + $sitemap_url = esc_url_raw($sitemap_url);
4199 + $total_urls = absint($total_urls);
4200 + $batch_size = absint($batch_size);
4201 + $batch_pause = absint($batch_pause);
10853 4202
10854 - // Divide each component by the number of vectors to get the average
10855 - $num_vectors = count($vectors);
10856 - for ($i = 0; $i < $vector_length; $i++) {
10857 - $sum_vector[$i] /= $num_vectors;
10858 - }
4203 + if (!is_array($urls) || empty($urls)) {
4204 + return;
4205 + }
10859 4206
10860 - return $sum_vector;
10861 - }
4207 + try {
4208 + $status_key = sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url));
4209 + $status = get_transient($status_key);
10862 4210
4211 + if (!$status || !is_array($status)) {
4212 + throw new Exception('Invalid status data retrieved from transient');
4213 + }
10863 4214
4215 + $start_url = absint($status['processed_urls']);
4216 + $end_url = min($start_url + $batch_size, $total_urls);
10864 4217
4218 + $instance = new self(); // Create an instance of the class
4219 + $embedding_success = true;
10865 4220
10866 - /**
10867 - * Generates embeddings from input text for MXChat
10868 - */
10869 - public function mxchat_generate_embedding($text) {
10870 - // Enable detailed logging for debugging
10871 - //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
10872 - //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
4221 + for ($i = $start_url; $i < $end_url; $i++) {
4222 + $page_url = esc_url_raw($urls[$i]);
4223 + $page_response = wp_remote_get($page_url);
10873 4224
10874 - $options = get_option('mxchat_options');
10875 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
10876 - //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
4225 + if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
4226 + continue;
4227 + }
10877 4228
10878 - // Determine provider and endpoint
10879 - if (strpos($selected_model, 'voyage') === 0) {
10880 - $api_key = $options['voyage_api_key'] ?? '';
10881 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
10882 - $provider_name = 'Voyage AI';
10883 - //error_log('[MXCHAT-EMBED] Using Voyage AI API');
10884 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
10885 - $api_key = $options['gemini_api_key'] ?? '';
10886 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
10887 - $provider_name = 'Google Gemini';
10888 - //error_log('[MXCHAT-EMBED] Using Google Gemini API');
10889 - } else {
10890 - $api_key = $options['api_key'] ?? '';
10891 - $endpoint = 'https://api.openai.com/v1/embeddings';
10892 - $provider_name = 'OpenAI';
10893 - //error_log('[MXCHAT-EMBED] Using OpenAI API');
10894 - }
4229 + $page_html = wp_remote_retrieve_body($page_response);
4230 + $page_content = $instance->mxchat_extract_main_content($page_html); // Call via instance
4231 + $sanitized_content = $instance->mxchat_sanitize_content_for_api($page_content); // Call via instance
10895 4232
10896 - //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
4233 + if (!empty($sanitized_content)) {
4234 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
4235 + if (is_array($embedding_vector)) {
4236 + $options = get_option('mxchat_options');
4237 + MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $options['api_key']);
4238 + } else {
4239 + $embedding_success = false;
4240 + }
4241 + }
10897 4242
10898 - if (empty($api_key)) {
10899 - $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
10900 - //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
10901 - return $error_message;
10902 - }
4243 + $status['processed_urls'] = absint($i + 1);
4244 + $status['last_update'] = time();
4245 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4246 + }
10903 4247
10904 - // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
10905 - $estimated_tokens = ceil(str_word_count($text) / 0.75);
10906 - //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
4248 + if ($end_url < $total_urls) {
4249 + wp_schedule_single_event(time() + $batch_pause, 'mxchat_process_sitemap_urls', array(
4250 + 'urls' => array_map('esc_url_raw', $urls),
4251 + 'sitemap_url' => $sitemap_url,
4252 + 'total_urls' => $total_urls,
4253 + 'batch_size' => $batch_size,
4254 + 'batch_pause' => $batch_pause,
4255 + ));
4256 + } else {
4257 + $status['status'] = 'complete';
4258 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4259 + }
4260 + } catch (\Exception $e) {
4261 + $status['status'] = 'error';
4262 + $status['error'] = sanitize_text_field($e->getMessage());
4263 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
4264 + }
4265 +}
10907 4266
10908 - if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
10909 - //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
10910 - // Consider truncating text here
10911 - }
4267 +public function get_sitemap_processing_status($sitemap_url) {
4268 + $sitemap_url = esc_url_raw($sitemap_url);
4269 + $status = get_transient(sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)));
10912 4270
10913 - // Prepare request body based on provider
10914 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10915 - // Gemini API format
10916 - $request_body = array(
10917 - 'model' => 'models/' . $selected_model,
10918 - 'content' => array(
10919 - 'parts' => array(
10920 - array('text' => $text)
10921 - )
10922 - )
10923 - );
4271 + if (!$status || !is_array($status)) {
4272 + return false;
4273 + }
10924 4274
10925 - // Set output dimensionality to 1536 for consistency with other models
10926 - $request_body['outputDimensionality'] = 1536;
10927 - } else {
10928 - // OpenAI/Voyage API format
10929 - $request_body = array(
10930 - 'model' => $selected_model,
10931 - 'input' => $text
10932 - );
4275 + return array(
4276 + 'total_urls' => absint($status['total_urls']),
4277 + 'processed_urls' => absint($status['processed_urls']),
4278 + 'percentage' => round((absint($status['processed_urls']) / absint($status['total_urls'])) * 100),
4279 + 'status' => sanitize_text_field($status['status']),
4280 + 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ago'
4281 + );
4282 +}
4283 +public function mxchat_stop_processing() {
4284 + // Verify permissions
4285 + if (!current_user_can('manage_options')) {
4286 + wp_die(esc_html__('Unauthorized access', 'mxchat'));
4287 + }
10933 4288
10934 - // Add output_dimension for voyage-3-large model
10935 - if ($selected_model === 'voyage-3-large') {
10936 - $request_body['output_dimension'] = 2048;
10937 - }
10938 - }
4289 + // Verify nonce
4290 + check_admin_referer('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce');
10939 4291
10940 - //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
4292 + // Get the last sitemap URL and clear its transient
4293 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
4294 + if ($sitemap_url) {
4295 + delete_transient('mxchat_sitemap_status_' . md5($sitemap_url));
4296 + delete_transient('mxchat_last_sitemap_url');
4297 + }
10941 4298
10942 - // Prepare headers based on provider
10943 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10944 - // Gemini uses API key as query parameter
10945 - $endpoint .= '?key=' . $api_key;
10946 - $headers = array(
10947 - 'Content-Type' => 'application/json'
10948 - );
10949 - } else {
10950 - // OpenAI/Voyage use Bearer token
10951 - $headers = array(
10952 - 'Authorization' => 'Bearer ' . $api_key,
10953 - 'Content-Type' => 'application/json'
10954 - );
10955 - }
4299 + // Get the last PDF URL and clear its transient
4300 + $pdf_url = get_transient('mxchat_last_pdf_url');
4301 + if ($pdf_url) {
4302 + delete_transient('mxchat_pdf_status_' . md5($pdf_url));
4303 + delete_transient('mxchat_last_pdf_url');
4304 + }
10956 4305
10957 - // Make API request
10958 - //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
10959 - $response = wp_remote_post($endpoint, array(
10960 - 'body' => wp_json_encode($request_body),
10961 - 'headers' => $headers,
10962 - 'timeout' => 60 // Increased timeout for large inputs
10963 - ));
4306 + // Unschedule any pending sitemap events
4307 + $timestamp = wp_next_scheduled('mxchat_process_sitemap_urls');
4308 + if ($timestamp) {
4309 + wp_unschedule_event($timestamp, 'mxchat_process_sitemap_urls');
4310 + }
10964 4311
10965 - // Handle wp_remote_post errors
10966 - if (is_wp_error($response)) {
10967 - $error_message = $response->get_error_message();
10968 - //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
10969 - return 'Connection error: ' . $error_message;
10970 - }
4312 + // Redirect back with a success message
4313 + set_transient('mxchat_admin_notice_success',
4314 + esc_html__('Processing has been stopped successfully.', 'mxchat'),
4315 + 30
4316 + );
4317 + wp_safe_redirect(admin_url('admin.php?page=mxchat-prompts'));
4318 + exit;
4319 +}
4320 +private function mxchat_sanitize_content_for_api($content) {
4321 + // Remove script, style tags, and HTML comments
4322 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
4323 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
4324 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
10971 4325
10972 - // Get and check HTTP response code
10973 - $http_code = wp_remote_retrieve_response_code($response);
10974 - //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
4326 + // Remove all HTML tags and decode HTML entities
4327 + $content = wp_strip_all_tags($content);
4328 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
10975 4329
10976 - if ($http_code !== 200) {
10977 - $error_body = wp_remote_retrieve_body($response);
10978 - //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
4330 + // Trim and normalize whitespace
4331 + $content = trim(preg_replace('/\s+/', ' ', $content));
10979 4332
10980 - // Try to parse error for more details
10981 - $error_json = json_decode($error_body, true);
10982 - if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
10983 - $error_type = $error_json['error']['type'] ?? 'unknown';
10984 - $error_message = $error_json['error']['message'] ?? 'No message';
10985 - //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
10986 - //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
4333 + return $content;
4334 +}
10987 4335
10988 - // Customize error message for common API errors
10989 - if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
10990 - $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
10991 - } elseif ($error_type === 'authentication_error') {
10992 - $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
10993 - }
10994 4336
10995 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
10996 - return $error_message;
10997 - }
10998 4337
10999 - $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
11000 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
11001 - return $error_message;
11002 - }
4338 +private function mxchat_fetch_loops_mailing_lists($api_key) {
4339 + $url = 'https://app.loops.so/api/v1/lists';
4340 + $response = wp_remote_get($url, array(
4341 + 'headers' => array(
4342 + 'Authorization' => 'Bearer ' . $api_key,
4343 + 'Content-Type' => 'application/json'
4344 + )
4345 + ));
11003 4346
11004 - // Parse response body
11005 - $response_body = wp_remote_retrieve_body($response);
11006 - //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
4347 + if (is_wp_error($response)) {
4348 + return array();
4349 + }
11007 4350
11008 - $response_data = json_decode($response_body, true);
4351 + $body = wp_remote_retrieve_body($response);
4352 + $lists = json_decode($body, true);
11009 4353
11010 - if (json_last_error() !== JSON_ERROR_NONE) {
11011 - $error = json_last_error_msg();
11012 - //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
11013 - //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
11014 - return "Failed to parse API response: $error";
11015 - }
4354 + return isset($lists) && is_array($lists) ? $lists : array();
4355 +}
11016 4356
11017 - // Handle different response formats based on provider
11018 - if (strpos($selected_model, 'gemini-embedding') === 0) {
11019 - // Gemini API response format
11020 - if (isset($response_data['embedding']['values'])) {
11021 - $embedding_dimensions = count($response_data['embedding']['values']);
11022 - //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
11023 4357
11024 - // Check if embedding dimensions are as expected (should be 1536)
11025 - if ($embedding_dimensions !== 1536) {
11026 - //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
11027 - }
11028 4358
11029 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11030 - return $response_data['embedding']['values'];
11031 - } else {
11032 - //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
11033 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
11034 4359
11035 - if (isset($response_data['error'])) {
11036 - $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
11037 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11038 - return $error_message;
11039 - }
11040 4360
11041 - $error_message = "Invalid Gemini API response format: No embedding found";
11042 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11043 - return $error_message;
11044 - }
11045 - } else {
11046 - // OpenAI/Voyage API response format
11047 - if (isset($response_data['data'][0]['embedding'])) {
11048 - $embedding_dimensions = count($response_data['data'][0]['embedding']);
11049 - //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
4361 +function mxchat_calculate_cosine_similarity($vec1, $vec2) {
4362 + if (empty($vec1) || empty($vec2)) {
4363 + return 0.0;
4364 + }
11050 4365
11051 - // Check if embedding dimensions are as expected
11052 - if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
11053 - ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
11054 - //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
11055 - }
4366 + $dot_product = 0.0;
4367 + $norm_a = 0.0;
4368 + $norm_b = 0.0;
11056 4369
11057 - MxChat_Utils::stamp_active_embedding_model($selected_model);
11058 - return $response_data['data'][0]['embedding'];
11059 - } else {
11060 - //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
11061 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
4370 + for ($i = 0; $i < count($vec1); $i++) {
4371 + $dot_product += $vec1[$i] * $vec2[$i];
4372 + $norm_a += pow($vec1[$i], 2);
4373 + $norm_b += pow($vec2[$i], 2);
4374 + }
11062 4375
11063 - if (isset($response_data['error'])) {
11064 - $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
11065 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11066 - return $error_message;
11067 - }
4376 + if ($norm_a == 0.0 || $norm_b == 0.0) {
4377 + return 0.0;
4378 + } else {
4379 + return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
4380 + }
4381 +}
11068 4382
11069 - $error_message = "Invalid API response format: No embedding found";
11070 - //error_log('[MXCHAT-EMBED] ' . $error_message);
11071 - return $error_message;
11072 - }
11073 - }
11074 - }
11075 4383
11076 4384
11077 4385
11078 4386 }