PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.1.7
MxChat – AI Chatbot & Content Generation for WordPress v2.1.7
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-admin.php +3355 -1415 2.0.52.1.7 View file →
@@ -37,11 +37,12 @@
37 37 add_action('wp_ajax_mxchat_save_inline_prompt', array($this, 'mxchat_save_inline_prompt'));
38 38 add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
39 39 add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
40 40 add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
41 - add_action('admin_post_mxchat_update_intent_threshold', array($this, 'mxchat_handle_update_intent_threshold'));
41 + add_action('wp_ajax_mxchat_toggle_action', array($this, 'mxchat_toggle_action'));
42 + add_action('wp_ajax_mxchat_update_intent_threshold', array($this, 'mxchat_update_intent_threshold'));
42 43 add_action('admin_post_mxchat_stop_processing', array($this, 'mxchat_stop_processing'));
43 - add_action('admin_post_mxchat_edit_intent', array($this, 'handle_edit_intent'));
44 + add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
44 45 add_action('save_post', array($this, 'handle_post_update'), 10, 3);
45 46 add_action('post_updated', array($this, 'handle_post_update'), 10, 3);
46 47 add_action('wp_ajax_mxchat_save_setting', array($this, 'mxchat_save_setting_callback'));
47 48 add_action('wp_trash_post', array($this, 'mxchat_handle_post_delete'));
@@ -56,16 +57,23 @@
56 57 add_action('wp_insert_post', array($this, 'mxchat_handle_product_change'), 10, 3);
57 58 add_action('wp_trash_post', array($this, 'mxchat_handle_product_delete'));
58 59 add_action('before_delete_post', array($this, 'mxchat_handle_product_delete'));
59 60 }
61 +
62 + add_action('wp_ajax_mxchat_get_status_updates', array($this, 'ajax_get_status_updates'));
63 + add_action('admin_notices', array($this, 'display_admin_notices'));
64 +
60 65 }
61 66
62 - // Method to check if the license is active
63 67 private function is_license_active() {
64 - $license_status = get_option('mxchat_license_status', esc_html__('inactive', 'mxchat'));
65 - return $license_status === esc_html__('active', 'mxchat');
66 - }
68 + // Get the raw value without translation
69 + $license_status = get_option('mxchat_license_status', 'inactive');
70 +
71 + // Check against multiple possible values, bypassing translation issues
72 + return ($license_status === 'active' || $license_status === esc_html__('active', 'mxchat'));
73 +}
67 74
75 +
68 76 // Initialize default options
69 77 private function initialize_default_options() {
70 78 $default_options = array(
71 79 'api_key' => '',
@@ -71,8 +79,11 @@
71 79 'api_key' => '',
72 80 'xai_api_key' => '',
73 81 'claude_api_key' => '',
74 82 'deepseek_api_key' => '',
83 + 'voyage_api_key' => '',
84 + 'gemini_api_key' => '',
85 + 'embedding_model' => 'text-embedding-ada-002',
75 86 'system_prompt_instructions' => esc_html__('[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:
76 87 - Your name is [Chatbot Name].
77 88 - 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.
78 89 - Do not make up links to pages. Only use specific links you see in your knowledgebase from [insert your domain]. Do not make assumptions or make up URLs.
@@ -82,12 +93,13 @@
82 93 'rate_limit_logged_out' => esc_html__('100', 'mxchat'),
83 94 'role_rate_limits' => array(),
84 95 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
85 96 'enable_email_block' => '',
86 - 'email_blocker_header_content' => esc_html__("<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>", 'mxchat'),
97 + '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'),
87 98 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
88 99 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
89 - 'intro_message' => esc_html__('Hello! How can I assist you today?', 'mxchat'),
100 + 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
101 + 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
90 102 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
91 103 'append_to_body' => esc_html__('off', 'mxchat'),
92 104 'close_button_color' => esc_html__('#fff', 'mxchat'),
93 105 'chatbot_bg_color' => esc_html__('#fff', 'mxchat'),
@@ -106,17 +118,19 @@
106 118
107 119 // New fields for Loops Integration
108 120 'loops_api_key' => '',
109 121 'loops_mailing_list' => '',
110 - 'triggered_phrase_response' => esc_html__('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
111 - 'email_capture_response' => esc_html__('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
122 + 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
123 + 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
112 124 'popular_question_1' => '',
113 125 'popular_question_2' => '',
114 126 'popular_question_3' => '',
115 - 'pdf_intent_trigger_text' => esc_html__("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
116 - 'pdf_intent_success_text' => esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat'),
117 - 'pdf_intent_error_text' => esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
127 + 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
128 + 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
129 + 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
118 130 'pdf_max_pages' => 69,
131 + 'show_pdf_upload_button' => 'on',
132 + 'show_word_upload_button' => 'on',
119 133
120 134 // Live Agent Integration
121 135 'live_agent_webhook_url' => '',
122 136 'live_agent_secret_key' => '',
@@ -185,13 +199,13 @@
185 199 );
186 200
187 201 add_submenu_page(
188 202 'mxchat-max',
189 - esc_html__('MxChat Intents', 'mxchat'),
190 - esc_html__('Intents', 'mxchat'),
203 + esc_html__('MxChat Actions', 'mxchat'),
204 + esc_html__('Actions', 'mxchat'),
191 205 'manage_options',
192 - 'mxchat-intents',
193 - array($this, 'mxchat_intents_page_html')
206 + 'mxchat-actions',
207 + array($this, 'mxchat_actions_page_html')
194 208 );
195 209
196 210 add_submenu_page(
197 211 'mxchat-max',
@@ -221,28 +235,52 @@
221 235
222 236 public function mxchat_save_setting_callback() {
223 237 check_ajax_referer('mxchat_save_setting_nonce');
224 238 if (!current_user_can('manage_options')) {
239 + ('MXChat Save: Unauthorized access attempt');
225 240 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')]);
226 241 }
242 +
227 243 $name = isset($_POST['name']) ? $_POST['name'] : '';
228 244 // Strip slashes from the value before saving
229 245 $value = isset($_POST['value']) ? stripslashes($_POST['value']) : '';
246 +
247 + //error_log('MXChat Save: Processing field name: ' . $name);
248 + //error_log('MXChat Save: Field value: ' . $value);
249 +
230 250 if (empty($name)) {
251 + //error_log('MXChat Save: Empty field name detected');
231 252 wp_send_json_error(['message' => esc_html__('Invalid field name', 'mxchat')]);
232 253 }
254 +
233 255 // Load the full options array
234 256 $options = get_option('mxchat_options', []);
257 + //error_log('MXChat Save: Current options array: ' . print_r($options, true));
258 +
235 259 // Handle special cases
236 260 switch ($name) {
237 261 case 'additional_popular_questions':
262 + //error_log('MXChat Save: Processing additional_popular_questions');
238 263 $questions = json_decode($value, true); // No need for stripslashes here
239 264 if (is_array($questions)) {
240 265 $options[$name] = $questions;
241 266 // Also update old option for backwards compatibility
242 267 update_option('additional_popular_questions', $questions);
268 + //error_log('MXChat Save: Saved ' . count($questions) . ' additional questions');
269 + } else {
270 + //error_log('MXChat Save: Failed to decode questions JSON');
243 271 }
244 272 break;
273 + case 'email_blocker_header_content':
274 + //error_log('MXChat Save: Processing email_blocker_header_content');
275 + // Allow HTML content but sanitize it safely
276 + $options[$name] = wp_kses_post($value);
277 + break;
278 + case 'similarity_threshold':
279 + //error_log('MXChat Save: Processing similarity_threshold');
280 + // Save to the options array
281 + $options[$name] = $value;
282 + break;
245 283 case 'user_message_bg_color':
246 284 case 'user_message_font_color':
247 285 case 'bot_message_bg_color':
248 286 case 'bot_message_font_color':
@@ -255,63 +293,136 @@
255 293 case 'live_agent_message_font_color':
256 294 case 'mode_indicator_bg_color':
257 295 case 'mode_indicator_font_color':
258 296 case 'toolbar_icon_color':
297 + //error_log('MXChat Save: Processing color value: ' . $name);
259 298 // Store color values directly
260 299 $options[$name] = $value;
261 300 break;
262 301 case 'live_agent_status':
302 + //error_log('MXChat Save: Processing live_agent_status');
263 303 // Set the new value
264 304 $options[$name] = ($value === 'on') ? 'on' : 'off';
265 305 break;
266 306 case 'enable_woocommerce_integration':
307 + //error_log('MXChat Save: Processing enable_woocommerce_integration');
267 308 // Handle values that used to be 1/0
268 309 $options[$name] = ($value === 'on' || $value === '1') ? 'on' : 'off';
269 310 break;
270 311 default:
271 - // Handle role rate limits
272 - if (strpos($name, 'mxchat_options[role_rate_limits]') !== false) {
312 + // First check for rate limits settings
313 + if (strpos($name, 'mxchat_options[rate_limits]') !== false) {
314 + //error_log('MXChat Save: Detected rate_limits field: ' . $name);
315 +
316 + // Extract role ID and setting from the name
317 + preg_match('/\[rate_limits\]\[(.*?)\]\[(.*?)\]/', $name, $matches);
318 + //error_log('MXChat Save: Regex matches: ' . print_r($matches, true));
319 +
320 + if (isset($matches[1]) && isset($matches[2])) {
321 + $role_id = $matches[1];
322 + $setting_key = $matches[2]; // limit, timeframe, or message
323 +
324 + //error_log('MXChat Save: Role ID = ' . $role_id . ', Setting Key = ' . $setting_key);
325 +
326 + // Initialize rate_limits if it doesn't exist
327 + if (!isset($options['rate_limits'])) {
328 + // //error_log('MXChat Save: Initializing rate_limits array');
329 + $options['rate_limits'] = [];
330 + }
331 +
332 + // Initialize role settings if it doesn't exist
333 + if (!isset($options['rate_limits'][$role_id])) {
334 + //error_log('MXChat Save: Initializing rate_limits for role: ' . $role_id);
335 + $options['rate_limits'][$role_id] = [
336 + 'limit' => ($role_id === 'logged_out') ? '10' : '100',
337 + 'timeframe' => 'daily',
338 + 'message' => 'Rate limit exceeded. Please try again later.'
339 + ];
340 + }
341 +
342 + // Update the specific setting
343 + $options['rate_limits'][$role_id][$setting_key] = $value;
344 + //error_log('MXChat Save: Updated rate_limits[' . $role_id . '][' . $setting_key . '] = ' . $value);
345 + } else {
346 + //error_log('MXChat Save: Failed to parse rate_limits pattern: ' . $name);
347 + }
348 + }
349 + // Then check for role rate limits (old format)
350 + else if (strpos($name, 'mxchat_options[role_rate_limits]') !== false) {
351 + //error_log('MXChat Save: Processing role_rate_limits field: ' . $name);
273 352 // Extract role ID from the name
274 353 preg_match('/\[role_rate_limits\]\[(.*?)\]/', $name, $matches);
354 + //error_log('MXChat Save: Regex matches: ' . print_r($matches, true));
355 +
275 356 if (isset($matches[1])) {
276 357 $role_id = $matches[1];
277 358 // Initialize role_rate_limits if it doesn't exist
278 359 if (!isset($options['role_rate_limits'])) {
360 + //error_log('MXChat Save: Initializing role_rate_limits array');
279 361 $options['role_rate_limits'] = [];
280 362 }
281 363 // Update the specific role's rate limit
282 364 $options['role_rate_limits'][$role_id] = sanitize_text_field($value);
283 - break;
365 + //error_log('MXChat Save: Updated role_rate_limits[' . $role_id . '] = ' . $value);
366 + } else {
367 + //error_log('MXChat Save: Failed to parse role_rate_limits pattern: ' . $name);
284 368 }
285 369 }
286 370 // Handle toggles
287 - if (strpos($name, 'toggle') !== false || in_array($name, [
371 + else if (strpos($name, 'toggle') !== false || in_array($name, [
288 372 'chat_persistence_toggle',
289 373 'privacy_toggle',
290 374 'complianz_toggle',
291 - 'chat_toolbar_toggle' // Removed live_agent_status from here
375 + 'chat_toolbar_toggle',
376 + 'show_pdf_upload_button',
377 + 'show_word_upload_button'
292 378 ])) {
379 + //error_log('MXChat Save: Processing toggle: ' . $name);
293 380 $options[$name] = ($value === 'on') ? 'on' : 'off';
294 381 } else {
382 + //error_log('MXChat Save: Processing standard field: ' . $name);
295 383 // Store all other values directly
296 384 $options[$name] = $value;
297 385 }
298 386 break;
299 387 }
300 - // Save all updates
388 +
389 + // Save all updates to the options array
301 390 $updated = update_option('mxchat_options', $options);
302 - // Handle backwards compatibility for certain fields
303 - $legacy_fields = ['brave_api_key', 'brave_image_count', 'brave_safe_search', 'brave_news_count',
304 - 'brave_country', 'brave_language', 'similarity_threshold'];
305 - if (in_array($name, $legacy_fields)) {
306 - // Also update the individual option for backwards compatibility
307 - update_option($name, $value);
391 + //error_log('MXChat Save: Update result: ' . ($updated ? 'success' : 'unchanged') . ' for field: ' . $name);
392 + //error_log('MXChat Save: Updated options array: ' . print_r($options, true));
393 +
394 + // Always return success even if WordPress says nothing changed
395 + // (which happens when the value is the same as before)
396 + wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
397 +}
398 +
399 +/**
400 + * Helper function to compare if a value has changed
401 + * Handles various data types appropriately
402 + */
403 +private function has_value_changed($old_value, $new_value) {
404 + // Handle null values
405 + if ($old_value === null && $new_value === '') {
406 + return false;
308 407 }
309 - if ($updated) {
310 - wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
311 - } else {
312 - wp_send_json_error(['message' => esc_html__('Update failed or no changes', 'mxchat')]);
408 +
409 + // Handle array values (like additional_popular_questions)
410 + if (is_array($old_value) && is_array($new_value)) {
411 + // Convert both to JSON for comparison to handle ordering differences
412 + return json_encode($old_value) !== json_encode($new_value);
313 413 }
414 +
415 + // Handle toggle/checkbox values consistently
416 + if (in_array($old_value, ['on', '1', 1, true]) && in_array($new_value, ['on', '1', 1, true])) {
417 + return false;
418 + }
419 + if (in_array($old_value, ['off', '0', 0, false, '']) && in_array($new_value, ['off', '0', 0, false, ''])) {
420 + return false;
421 + }
422 +
423 + // Default direct comparison
424 + return $old_value !== $new_value;
314 425 }
315 426
316 427 /**
317 428 * Handles AJAX auto-save for prompts and auto-sync settings.
@@ -316,30 +427,41 @@
316 427 /**
317 428 * Handles AJAX auto-save for prompts and auto-sync settings.
318 429 */
319 430 public function mxchat_save_prompts_setting_callback() {
320 - // Check the correct nonce for this action.
321 - check_ajax_referer( 'mxchat_prompts_setting_nonce', '_ajax_nonce' );
322 -
323 - if ( ! current_user_can( 'manage_options' ) ) {
324 - wp_send_json_error( [ 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ] );
431 + check_ajax_referer('mxchat_prompts_setting_nonce', '_ajax_nonce');
432 +
433 + if (!current_user_can('manage_options')) {
434 + wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')]);
325 435 }
326 -
327 - $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
328 - $value = isset( $_POST['value'] ) ? sanitize_text_field( wp_unslash( $_POST['value'] ) ) : '';
329 -
330 - if ( empty( $name ) ) {
331 - wp_send_json_error( [ 'message' => esc_html__( 'Invalid field name', 'mxchat' ) ] );
436 +
437 + $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
438 + $value = isset($_POST['value']) ? sanitize_text_field($_POST['value']) : '';
439 +
440 + if (empty($name)) {
441 + wp_send_json_error(['message' => esc_html__('Invalid field name', 'mxchat')]);
332 442 }
333 -
334 - // Handle standalone auto-sync settings.
335 - if ( in_array( $name, [ 'mxchat_auto_sync_posts', 'mxchat_auto_sync_pages' ], true ) ) {
336 - // Convert checkbox value to "1" if checked, "0" if not.
337 - $value = ( $value === 'on' ) ? '1' : '0';
338 - update_option( $name, $value );
339 - wp_send_json_success( [ 'message' => esc_html__( 'Setting saved', 'mxchat' ) ] );
443 +
444 + // Log the values we're trying to save (for debugging)
445 + //error_log('Attempting to save setting: ' . $name . ' = ' . $value);
446 +
447 + // For all auto-sync options
448 + if (strpos($name, 'mxchat_auto_sync_') === 0) {
449 + // Convert 'on'/'off' to '1'/'0' for consistency (if needed)
450 + $option_value = ($value === 'on') ? '1' : '0';
451 +
452 + $result = update_option($name, $option_value);
453 +
454 + if ($result) {
455 + //error_log('Successfully saved setting: ' . $name . ' = ' . $option_value);
456 + wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
457 + } else {
458 + //error_log('Failed to save setting: ' . $name . ' (no changes or error)');
459 + wp_send_json_error(['message' => esc_html__('Update failed or no changes', 'mxchat')]);
460 + }
461 + return;
340 462 }
341 -
463 +
342 464 // Handle fields stored in the 'mxchat_prompts_options' array.
343 465 // Handle fields stored in the 'mxchat_prompts_options' array.
344 466 if ( false !== strpos( $name, 'mxchat_prompts_options[' ) ) {
345 467 // Extract the key name using regex.
@@ -365,9 +487,8 @@
365 487
366 488
367 489 wp_send_json_error( [ 'message' => esc_html__( 'Field not recognized', 'mxchat' ) ] );
368 490 }
369 -
370 491 public function mxchat_display_admin_notice() {
371 492 // Success notice
372 493 if ($message = get_transient('mxchat_admin_notice_success')) {
373 494 ?>
@@ -397,181 +518,215 @@
397 518
398 519 public function mxchat_create_admin_page() {
399 520
400 521 ?>
401 - <div class="wrap mxchat-admin">
402 - <?php if (!$this->is_activated): ?>
403 - <div class="mxchat-pro-banner">
404 - <p>
405 - <?php echo esc_html__('For a limited time, get lifetime access and save $20 on MxChat Pro!', 'mxchat'); ?>
406 - <a href="https://mxchat.ai/" target="_blank"><?php echo esc_html__('Upgrade to Pro today', 'mxchat'); ?></a>
407 - </p>
522 + <div class="wrap mxchat-wrapper">
523 + <!-- Hero Section -->
524 + <div class="mxchat-hero">
525 + <h1 class="mxchat-main-title">
526 + <span class="mxchat-gradient-text">MxChat</span> Settings
527 + </h1>
528 + <p class="mxchat-hero-subtitle">
529 + <?php esc_html_e('Configure your AI chatbot, manage integrations and explore tutorials to get the most out of MxChat.', 'mxchat'); ?>
530 + </p>
408 531 </div>
409 - <?php endif; ?>
410 532
411 - <div class="mxchat-agents-banner">
412 - <p>
413 - <strong><?php echo esc_html__('The MxChat Add-Ons Platform', 'mxchat'); ?></strong><?php echo esc_html__(' is here! Pro users get unlimited access to our growing collection of powerful add-ons. ', 'mxchat'); ?><a href="<?php echo admin_url('admin.php?page=mxchat-addons'); ?>"><?php echo esc_html__('Explore all add-ons', 'mxchat'); ?></a><?php echo esc_html__(' including Forms Builder, Theme Customizer, Content Moderation, and more – all included with your lifetime Pro license!', 'mxchat'); ?>
414 - </p>
415 - </div>
533 + <div class="mxchat-content">
534 + <?php if (!$this->is_activated): ?>
535 + <div class="mxchat-pro-card">
536 + <div class="mxchat-pro-notification">
537 + <div class="mxchat-pro-content">
538 + <h3>🚀 Limited Time Offer: Save $20 on MxChat Pro Lifetime Access!</h3>
539 + <p>Unlock <strong>unlimited access</strong> to our growing collection of powerful add-ons including Forms Builder, Theme Customizer, WooCommerce, Perplexity, and more – all included with your lifetime license!</p>
540 + </div>
541 + <div class="mxchat-pro-cta">
542 + <a href="https://mxchat.ai/" target="_blank" class="mxchat-button"><?php echo esc_html__('Upgrade to Pro Today', 'mxchat'); ?></a>
543 + <a href="<?php echo admin_url('admin.php?page=mxchat-addons'); ?>" class="mxchat-link"><?php echo esc_html__('Preview Add-ons', 'mxchat'); ?></a>
544 + </div>
545 + </div>
546 + </div>
547 + <?php endif; ?>
416 548
417 - <h2 class="mxchat-nav-tab-wrapper">
418 - <a href="#chatbot" class="mxchat-nav-tab mxchat-nav-tab-active" data-tab="chatbot"><?php echo esc_html__('Chatbot', 'mxchat'); ?></a>
419 - <a href="#embed" class="mxchat-nav-tab" data-tab="embed"><?php echo esc_html__('Integrations', 'mxchat'); ?></a>
420 - <a href="#general" class="mxchat-nav-tab" data-tab="general"><?php echo esc_html__('FAQ', 'mxchat'); ?></a>
421 - </h2>
549 + <!-- Tabs Navigation -->
550 + <div class="mxchat-tabs">
551 + <button class="mxchat-tab-button active" data-tab="chatbot"><?php echo esc_html__('Chatbot', 'mxchat'); ?></button>
552 + <button class="mxchat-tab-button" data-tab="embed"><?php echo esc_html__('Integrations', 'mxchat'); ?></button>
553 + <button class="mxchat-tab-button" data-tab="general"><?php echo esc_html__('YouTube Tutorials', 'mxchat'); ?></button>
554 + </div>
422 555
423 - <div id="chatbot" class="mxchat-tab-content active">
424 - <div class="mxchat-autosave-section">
425 - <?php do_settings_sections('mxchat-chatbot'); ?>
556 + <!-- Tab Contents -->
557 + <div id="chatbot" class="mxchat-tab-content active">
558 + <div class="mxchat-card">
559 + <div class="mxchat-autosave-section">
560 + <?php do_settings_sections('mxchat-chatbot'); ?>
561 + </div>
562 + </div>
426 563 </div>
427 - </div>
428 564
429 - <div id="embed" class="mxchat-tab-content">
430 - <div class="mxchat-autosave-section">
431 -
432 - <div class="mxchat-settings-section">
433 - <h2><?php echo esc_html__('Loops Settings', 'mxchat'); ?></h2>
434 - <table class="form-table">
435 - <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
436 - </table>
565 + <div id="embed" class="mxchat-tab-content">
566 + <div class="mxchat-card">
567 + <h2><?php esc_html_e('Loops Settings', 'mxchat'); ?></h2>
568 + <div class="mxchat-autosave-section">
569 + <table class="form-table">
570 + <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
571 + </table>
572 + </div>
437 573 </div>
438 574
439 - <div class="section-divider"></div>
440 -
441 - <div class="mxchat-settings-section">
442 - <h2><?php echo esc_html__('Brave Search Settings', 'mxchat'); ?></h2>
443 - <table class="form-table">
444 - <?php do_settings_fields('mxchat-embed', 'mxchat_brave_section'); ?>
445 - </table>
575 + <div class="mxchat-card">
576 + <h2><?php esc_html_e('Brave Search Settings', 'mxchat'); ?></h2>
577 + <div class="mxchat-autosave-section">
578 + <table class="form-table">
579 + <?php do_settings_fields('mxchat-embed', 'mxchat_brave_section'); ?>
580 + </table>
581 + </div>
446 582 </div>
447 583
448 - <div class="section-divider"></div>
449 -
450 - <div class="mxchat-settings-section">
451 - <h2><?php echo esc_html__('Toolbar Settings & Intents', 'mxchat'); ?></h2>
452 - <table class="form-table">
453 - <?php do_settings_fields('mxchat-embed', 'mxchat_pdf_intent_section'); ?>
454 - </table>
584 + <div class="mxchat-card">
585 + <h2><?php esc_html_e('Toolbar Settings & Intents', 'mxchat'); ?></h2>
586 + <div class="mxchat-autosave-section">
587 + <table class="form-table">
588 + <?php do_settings_fields('mxchat-embed', 'mxchat_pdf_intent_section'); ?>
589 + </table>
590 + </div>
455 591 </div>
456 592
457 - <div class="section-divider"></div>
458 -
459 - <!-- Live Agent Settings Section -->
460 - <div class="mxchat-settings-section">
461 - <h2><?php echo esc_html__('Live Agent Settings', 'mxchat'); ?></h2>
462 - <p><?php echo esc_html__('Visit our', 'mxchat'); ?> <a href="https://mxchat.ai/documentation/#slack_integration" target="_blank"><?php echo esc_html__('documentation page', 'mxchat'); ?></a> <?php echo esc_html__('to set up live agent transfer via Slack.', 'mxchat'); ?></p>
463 - <table class="form-table">
464 - <?php do_settings_fields('mxchat-embed', 'mxchat_live_agent_section'); ?>
465 - </table>
593 + <div class="mxchat-card">
594 + <h2><?php esc_html_e('Live Agent Settings', 'mxchat'); ?></h2>
595 + <div class="mxchat-autosave-section">
596 + <p><?php echo esc_html__('Visit our', 'mxchat'); ?> <a href="https://mxchat.ai/documentation/#slack_integration" target="_blank"><?php echo esc_html__('documentation page', 'mxchat'); ?></a> <?php echo esc_html__('to set up live agent transfer via Slack.', 'mxchat'); ?></p>
597 + <table class="form-table">
598 + <?php do_settings_fields('mxchat-embed', 'mxchat_live_agent_section'); ?>
599 + </table>
600 + </div>
466 601 </div>
467 602 </div>
468 - </div>
469 603
604 + <div id="general" class="mxchat-tab-content">
605 + <div class="mxchat-card">
606 + <?php do_settings_sections('mxchat-general'); ?>
607 + <div class="video-tutorials-section">
470 608
471 - <div id="general" class="mxchat-tab-content">
472 - <?php do_settings_sections('mxchat-general'); ?>
473 - <p>
474 - <?php echo esc_html__('If you’re having trouble with setup or getting the responses you need, we encourage you to review our', 'mxchat'); ?>
475 - <a href="https://mxchat.ai/documentation/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('documentation', 'mxchat'); ?></a> <?php echo esc_html__('or', 'mxchat'); ?>
476 - <a href="https://wordpress.org/support/plugin/mxchat-basic/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('create a support ticket', 'mxchat'); ?></a>.
477 - </p>
478 - <p>
479 - <?php echo esc_html__('If you like our plugin, please consider', 'mxchat'); ?> <a href="https://wordpress.org/plugins/mxchat-basic/#reviews" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('leaving us a review', 'mxchat'); ?></a>.
480 - </p>
481 -
482 - <div class="faq-item">
483 - <h3><?php echo esc_html__('How does the Claude API integration work?', 'mxchat'); ?></h3>
484 - <p>
485 - <?php echo esc_html__('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.', 'mxchat'); ?>
486 - </p>
487 - <p>
488 - <?php echo esc_html__('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.', 'mxchat'); ?>
489 - </p>
490 - <p>
491 - <?php echo esc_html__('You can obtain your Claude API key by signing up on the', 'mxchat'); ?> <a href="https://www.anthropic.com/api" target="_blank" rel="noopener"><?php echo esc_html__('Anthropic API page', 'mxchat'); ?></a>.
492 - </p>
609 + <div class="tutorial-grid">
610 + <div class="tutorial-item">
611 + <h3><?php echo esc_html__('MxChat Forms Tutorial', 'mxchat'); ?></h3>
612 + <div class="video-description">
613 + <p><?php echo esc_html__('Learn how to create and manage smart forms that automatically trigger during chat conversations.', 'mxchat'); ?></p>
614 + <a href="https://www.youtube.com/watch?v=3MrWy5dRalA" target="_blank" rel="noopener" class="video-link">
615 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
616 + <?php echo esc_html__('Watch MxChat Forms Tutorial', 'mxchat'); ?>
617 + </a>
493 618 </div>
619 + </div>
494 620
495 - <div class="faq-item">
496 - <h3><?php echo esc_html__('How does the X.AI API integration work?', 'mxchat'); ?></h3>
497 - <p>
498 - <?php echo esc_html__('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.', 'mxchat'); ?>
499 - </p>
500 - <p>
501 - <?php echo esc_html__('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', 'mxchat'); ?> <a href="https://docs.x.ai/docs" target="_blank" rel="noopener"><?php echo esc_html__('X.AI API documentation', 'mxchat'); ?></a>.
502 - </p>
621 + <div class="tutorial-item">
622 + <h3><?php echo esc_html__('Intent Tester Guide', 'mxchat'); ?></h3>
623 + <div class="video-description">
624 + <p><?php echo esc_html__('Discover how to use the Intent Tester to fine-tune your chatbot\'s responses and ensure it accurately understands user queries.', 'mxchat'); ?></p>
625 + <a href="https://www.youtube.com/watch?v=uTr14tn59Hc" target="_blank" rel="noopener" class="video-link">
626 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
627 + <?php echo esc_html__('Watch Intent Tester Tutorial', 'mxchat'); ?>
628 + </a>
503 629 </div>
630 + </div>
504 631
505 - <div class="faq-item">
506 - <h3><?php echo esc_html__('Do I need an OpenAI API key to use the chatbot?', 'mxchat'); ?></h3>
507 - <p>
508 - <?php echo esc_html__('Yes, you will need an OpenAI API key to power the chatbot. You can obtain an API key by signing up on the', 'mxchat'); ?> <a href="https://platform.openai.com/signup" target="_blank" rel="noopener"><?php echo esc_html__('OpenAI platform', 'mxchat'); ?></a>. <?php echo esc_html__('After signing up, you must add credits to your account—typically, $5 in credits is sufficient to get started.', 'mxchat'); ?>
509 - </p>
510 - <p>
511 - <?php echo esc_html__('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.', 'mxchat'); ?>
512 - </p>
632 + <div class="tutorial-item">
633 + <h3><?php echo esc_html__('WooCommerce Integration', 'mxchat'); ?></h3>
634 + <div class="video-description">
635 + <p><?php echo esc_html__('See how to integrate MxChat with your WooCommerce store to provide product recommendations and shopping assistance to your customers.', 'mxchat'); ?></p>
636 + <a href="https://www.youtube.com/watch?v=WsqAppHRGdA" target="_blank" rel="noopener" class="video-link">
637 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
638 + <?php echo esc_html__('Watch WooCommerce Integration Tutorial', 'mxchat'); ?>
639 + </a>
513 640 </div>
641 + </div>
514 642
515 - <div class="faq-item">
516 - <h3><?php echo esc_html__('How do I add the chatbot to my site?', 'mxchat'); ?></h3>
517 - <p>
518 - <?php echo esc_html__('You can add the chatbot using the shortcode', 'mxchat'); ?> <code>[mxchat_chatbot floating="yes"]</code> <?php echo esc_html__('or', 'mxchat'); ?> <code>[mxchat_chatbot floating="no"]</code>. <?php echo esc_html__('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.', 'mxchat'); ?>
519 - </p>
643 + <div class="tutorial-item">
644 + <h3><?php echo esc_html__('Knowledge Base Setup', 'mxchat'); ?></h3>
645 + <div class="video-description">
646 + <p><?php echo esc_html__('Learn how to set up your knowledge base using PDFs, sitemaps, and manual entries to enhance your chatbot\'s responses with site-specific information.', 'mxchat'); ?></p>
647 + <p><small><?php echo esc_html__('Note: This tutorial uses an older UI, but the process remains the same.', 'mxchat'); ?></small></p>
648 + <a href="https://www.youtube.com/watch?v=8Ztjs66-VTo" target="_blank" rel="noopener" class="video-link">
649 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
650 + <?php echo esc_html__('Watch Knowledge Base Setup Tutorial', 'mxchat'); ?>
651 + </a>
520 652 </div>
653 + </div>
521 654
522 - <div class="faq-item">
523 - <h3><?php echo esc_html__('How does the chatbot use my content to generate responses?', 'mxchat'); ?></h3>
524 - <p>
525 - <?php echo esc_html__('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.', 'mxchat'); ?>
526 - </p>
655 + <div class="tutorial-item">
656 + <h3><?php echo esc_html__('Toolbar Chat with Documents', 'mxchat'); ?></h3>
657 + <div class="video-description">
658 + <p><?php echo esc_html__('See how to use the MxChat toolbar to chat with PDF and Word documents for enhanced document analysis and information retrieval.', 'mxchat'); ?></p>
659 + <a href="https://www.youtube.com/watch?v=j_c45WWCTG0" target="_blank" rel="noopener" class="video-link">
660 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
661 + <?php echo esc_html__('Watch Document Chat Tutorial', 'mxchat'); ?>
662 + </a>
527 663 </div>
528 -
529 - <div class="faq-item">
530 - <h3><?php echo esc_html__('Why does the chatbot sometimes make up links or information?', 'mxchat'); ?></h3>
531 - <p>
532 - <?php echo esc_html__('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.', 'mxchat'); ?>
533 - </p>
664 + </div>
665 +
666 + <div class="tutorial-item">
667 + <h3><?php echo esc_html__('Perplexity Integration', 'mxchat'); ?></h3>
668 + <div class="video-description">
669 + <p><?php echo esc_html__('Learn how to integrate Perplexity with your chatbot for real-time web search capabilities. This tutorial covers intent recognition, the toolbar toggle button, and how to enable your chatbot to search the web and provide up-to-date information to your visitors.', 'mxchat'); ?></p>
670 + <a href="https://youtu.be/wpKkbt24-bo" target="_blank" rel="noopener" class="video-link">
671 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
672 + <?php echo esc_html__('Watch Perplexity Integration Tutorial', 'mxchat'); ?>
673 + </a>
534 674 </div>
675 + </div>
535 676
536 - <div class="faq-item">
537 - <h3><?php echo esc_html__('How do intents work in MxChat?', 'mxchat'); ?></h3>
538 - <p>
539 - <?php echo esc_html__('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', 'mxchat'); ?> <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Intents Documentation', 'mxchat'); ?></a>.
540 - </p>
677 + <div class="tutorial-item">
678 + <h3><?php echo esc_html__('Brave Search Intent', 'mxchat'); ?></h3>
679 + <div class="video-description">
680 + <p><?php echo esc_html__('Learn how to leverage Brave Search intent capabilities to improve your chatbot\'s understanding of user queries and provide more accurate responses.', 'mxchat'); ?></p>
681 + <a href="https://www.youtube.com/watch?v=7vDL5H7vToc" target="_blank" rel="noopener" class="video-link">
682 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
683 + <?php echo esc_html__('Watch Brave Search Intent Tutorial', 'mxchat'); ?>
684 + </a>
541 685 </div>
686 + </div>
542 687
543 - <div class="faq-item">
544 - <h3><?php echo esc_html__('How does the Complianz integration work?', 'mxchat'); ?></h3>
545 - <p>
546 - <?php echo esc_html__('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.', 'mxchat'); ?>
547 - </p>
688 + <div class="tutorial-item">
689 + <h3><?php echo esc_html__('Loops Email Capture', 'mxchat'); ?></h3>
690 + <div class="video-description">
691 + <p><?php echo esc_html__('Discover how to set up email capture with MxChat using Loops to grow your mailing list while providing value through your chatbot.', 'mxchat'); ?></p>
692 + <p><small><?php echo esc_html__('Note: This tutorial uses an older UI, but the process remains the same.', 'mxchat'); ?></small></p>
693 + <a href="https://www.youtube.com/watch?v=CNgm5TYDyTc" target="_blank" rel="noopener" class="video-link">
694 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
695 + <?php echo esc_html__('Watch Loops Email Capture Tutorial', 'mxchat'); ?>
696 + </a>
548 697 </div>
698 + </div>
549 699
550 - <div class="faq-item">
551 - <h3><?php echo esc_html__('How does the WooCommerce integration work?', 'mxchat'); ?></h3>
552 - <p>
553 - <?php echo esc_html__('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.', 'mxchat'); ?>
554 - </p>
700 + <div class="tutorial-item">
701 + <h3><?php echo esc_html__('MxChat AI Agent Testing Service', 'mxchat'); ?></h3>
702 + <div class="video-description">
703 + <p><?php echo esc_html__('Learn how to use the MxChat AI Agent Testing Service to evaluate and improve your chatbot\'s performance and accuracy.', 'mxchat'); ?></p>
704 + <p><small><?php echo esc_html__('Note: This tutorial uses an older UI, but the process remains the same.', 'mxchat'); ?></small></p>
705 + <a href="https://www.youtube.com/watch?v=A0jowbpyX54" target="_blank" rel="noopener" class="video-link">
706 + <span class="video-icon"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6z"></path><polygon points="10 15 15 12 10 9 10 15"></polygon></svg></span>
707 + <?php echo esc_html__('Watch AI Agent Testing Tutorial', 'mxchat'); ?>
708 + </a>
555 709 </div>
710 + </div>
711 + </div>
556 712
557 - <div class="faq-item">
558 - <h3><?php echo esc_html__('Why isn\'t my chatbot responding as expected?', 'mxchat'); ?></h3>
559 - <p>
560 - <?php echo esc_html__('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', 'mxchat'); ?> <a href="https://mxchat.ai/contact/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('contact us', 'mxchat'); ?></a> <?php echo esc_html__('for personalized support.', 'mxchat'); ?>
561 - </p>
562 - <p>
563 - <?php echo esc_html__('We’re dedicated to your success and ready to guide you in aligning the AI\'s behavior to meet your goals.', 'mxchat'); ?>
564 - </p>
713 + <div class="support-section">
714 + <h3><?php echo esc_html__('Need Help?', 'mxchat'); ?></h3>
715 + <div class="support-content">
716 + <p>
717 + <?php echo esc_html__('If you\'re having trouble with setup or getting the responses you need, we encourage you to review our', 'mxchat'); ?>
718 + <a href="https://mxchat.ai/documentation/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('documentation', 'mxchat'); ?></a> <?php echo esc_html__('or', 'mxchat'); ?>
719 + <a href="https://wordpress.org/support/plugin/mxchat-basic/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('create a support ticket', 'mxchat'); ?></a>.
720 + </p>
721 + <p>
722 + <?php echo esc_html__('If you like our plugin, please consider', 'mxchat'); ?> <a href="https://wordpress.org/plugins/mxchat-basic/#reviews" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('leaving us a review', 'mxchat'); ?></a>.
723 + </p>
724 + </div>
725 + </div>
726 + </div>
727 + </div>
565 728 </div>
566 -
567 - <div class="faq-item">
568 - <h3><?php echo esc_html__('What is Loops, and how do I get an API key?', 'mxchat'); ?></h3>
569 - <p>
570 - <?php echo esc_html__('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', 'mxchat'); ?> <a href="https://loops.so" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Loops website', 'mxchat'); ?></a> <?php echo esc_html__('to get started or to sign up for an account.', 'mxchat'); ?>
571 - </p>
572 - </div>
573 -
574 729 </div>
575 730 </div>
576 731 <?php
577 732 }
@@ -998,10 +1153,39 @@
998 1153 <div class="mxchat-content">
999 1154 <!-- Import Settings Card -->
1000 1155 <div class="mxchat-card">
1001 1156 <h2><?php esc_html_e('Knowledge Import Settings', 'mxchat'); ?></h2>
1002 - <p><?php esc_html_e('Using the free Pinecone DB Manager add-on is recommended for high performance and a knowledge database of more than 500.', 'mxchat'); ?></p>
1157 +<?php
1158 +// Check if the appropriate embedding API key exists
1159 +$embedding_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
1160 +$has_openai_key = !empty($this->options['api_key']);
1161 +$has_voyage_key = !empty($this->options['voyage_api_key']);
1003 1162
1163 +// Determine if they have the needed API key for their selected embedding model
1164 +$has_required_key = false;
1165 +$required_key_type = '';
1166 +
1167 +if (strpos($embedding_model, 'text-embedding-') !== false && $has_openai_key) {
1168 + $has_required_key = true;
1169 + $required_key_type = 'OpenAI';
1170 +} elseif (strpos($embedding_model, 'voyage-') !== false && $has_voyage_key) {
1171 + $has_required_key = true;
1172 + $required_key_type = 'Voyage AI';
1173 +} elseif (strpos($embedding_model, 'text-embedding-') !== false) {
1174 + $required_key_type = 'OpenAI';
1175 +} elseif (strpos($embedding_model, 'voyage-') !== false) {
1176 + $required_key_type = 'Voyage AI';
1177 +}
1178 +?>
1179 +
1180 +<div class="mxchat-knowledge-warning <?php echo $has_required_key ? 'success' : 'warning'; ?>">
1181 + <?php if ($has_required_key): ?>
1182 + <p><span class="dashicons dashicons-yes-alt"></span> <?php echo wp_kses_post(sprintf(__('We detected your %s API key. <strong>You must have added credits to your %s account</strong> before using the knowledgebase.', 'mxchat'), $required_key_type, $required_key_type)); ?></p>
1183 + <?php else: ?>
1184 + <p><span class="dashicons dashicons-warning"></span> <strong><?php esc_html_e('Important:', 'mxchat'); ?></strong> <?php echo sprintf(esc_html__('Before importing knowledge, you must add a %s API key with sufficient credits in the Chatbot settings.', 'mxchat'), $required_key_type); ?> <a href="<?php echo admin_url('admin.php?page=mxchat-max'); ?>"><?php esc_html_e('Go to API Key Settings', 'mxchat'); ?></a></p>
1185 + <?php endif; ?>
1186 +</div>
1187 +
1004 1188 <!-- Tab Contents -->
1005 1189 <div class="mxchat-tab-contents">
1006 1190 <!-- Default Database Tab -->
1007 1191 <div id="default-db" class="mxchat-tab-content active">
@@ -1026,8 +1210,9 @@
1026 1210 <span class="mxchat-toggle-label">
1027 1211 <?php esc_html_e('Auto-sync Posts', 'mxchat'); ?>
1028 1212 </span>
1029 1213 </div>
1214 +
1030 1215 <div class="mxchat-toggle-container">
1031 1216 <label class="mxchat-toggle-switch">
1032 1217 <input type="checkbox"
1033 1218 name="mxchat_auto_sync_pages"
@@ -1040,8 +1225,64 @@
1040 1225 <span class="mxchat-toggle-label">
1041 1226 <?php esc_html_e('Auto-sync Pages', 'mxchat'); ?>
1042 1227 </span>
1043 1228 </div>
1229 +
1230 +
1231 +
1232 +
1233 + <!-- Replace the existing custom post types section with this code -->
1234 +<div class="mxchat-section-content">
1235 + <div class="mxchat-custom-post-types-header">
1236 + <button id="mxchat-custom-post-types-toggle" class="mxchat-button-secondary">
1237 + <?php esc_html_e('Advanced Custom Post Sync Settings', 'mxchat'); ?>
1238 + <span class="mxchat-toggle-icon">▼</span>
1239 + </button>
1240 + </div>
1241 +
1242 + <div id="mxchat-custom-post-types-container" class="mxchat-custom-post-types-container" style="display: none;">
1243 + <h3><?php esc_html_e('Sync Custom Post Types', 'mxchat'); ?></h3>
1244 + <p><?php esc_html_e('Select additional custom post types to automatically sync with the chatbot.', 'mxchat'); ?></p>
1245 +
1246 + <div class="mxchat-custom-post-types">
1247 + <?php
1248 + $post_types = $this->get_public_post_types();
1249 +
1250 + // Skip post and page as they're handled separately
1251 + unset($post_types['post']);
1252 + unset($post_types['page']);
1253 +
1254 + if (!empty($post_types)) {
1255 + foreach ($post_types as $post_type => $label) {
1256 + $option_name = 'mxchat_auto_sync_' . $post_type;
1257 + $is_enabled = get_option($option_name, '0');
1258 + ?>
1259 + <div class="mxchat-toggle-container">
1260 + <label class="mxchat-toggle-switch">
1261 + <input type="checkbox"
1262 + name="<?php echo esc_attr($option_name); ?>"
1263 + class="mxchat-autosave-field"
1264 + value="1"
1265 + data-nonce="<?php echo wp_create_nonce('mxchat_prompts_setting_nonce'); ?>"
1266 + <?php checked($is_enabled, '1'); ?>>
1267 + <span class="mxchat-toggle-slider"></span>
1268 + </label>
1269 + <span class="mxchat-toggle-label">
1270 + <?php echo esc_html($label); ?> (<?php echo esc_html($post_type); ?>)
1271 + </span>
1272 + </div>
1273 + <?php
1274 + }
1275 + } else {
1276 + echo '<p>' . esc_html__('No custom post types found.', 'mxchat') . '</p>';
1277 + }
1278 + ?>
1279 + </div>
1280 + </div>
1281 +</div>
1282 +
1283 +
1284 +
1044 1285 </div>
1045 1286 </div>
1046 1287 </div>
1047 1288
@@ -1048,10 +1289,9 @@
1048 1289 <!-- Import Methods -->
1049 1290 <div class="mxchat-import-methods">
1050 1291 <div class="mxchat-method-card">
1051 1292 <h4><?php esc_html_e('Sitemap Import', 'mxchat'); ?></h4>
1052 - <p><?php esc_html_e('Import all content from your sitemap automatically. Use a content-specific sub-sitemap, not the sitemap index.', 'mxchat'); ?></p>
1053 - </div>
1293 + <p><span class="red-warning">IMPORTANT:</span> <?php esc_html_e('Use a content-specific sub-sitemap, not the sitemap index.', 'mxchat'); ?></p> </div>
1054 1294 <div class="mxchat-method-card">
1055 1295 <h4><?php esc_html_e('PDF Import', 'mxchat'); ?></h4>
1056 1296 <p><?php esc_html_e('Import knowledge directly from PDF documents.', 'mxchat'); ?></p>
1057 1297 </div>
@@ -1087,85 +1327,177 @@
1087 1327 </div>
1088 1328 <?php endif; ?>
1089 1329
1090 1330 <!-- Processing Status -->
1091 - <?php if ($pdf_status && $pdf_status['status'] !== 'complete') : ?>
1092 - <div class="mxchat-status-card">
1093 - <div class="mxchat-status-header">
1094 - <h4><?php esc_html_e('PDF Processing Status', 'mxchat'); ?></h4>
1095 - <?php if ($is_processing) : ?>
1096 - <form method="post" class="mxchat-stop-form"
1097 - action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
1098 - <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
1099 - <button type="submit" name="stop_processing" class="mxchat-button-secondary">
1100 - <?php esc_html_e('Stop Processing', 'mxchat'); ?>
1101 - </button>
1102 - </form>
1103 - <?php endif; ?>
1104 - </div>
1105 - <div class="mxchat-progress-bar">
1106 - <div class="mxchat-progress-fill" style="width: <?php echo esc_attr($pdf_status['percentage']); ?>%"></div>
1107 - </div>
1108 - <div class="mxchat-status-details">
1109 - <p><?php printf(
1110 - esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'),
1111 - absint($pdf_status['processed_pages']),
1112 - absint($pdf_status['total_pages']),
1113 - absint($pdf_status['percentage'])
1114 - ); ?></p>
1115 - <p><?php printf(
1116 - esc_html__('Status: %s', 'mxchat'),
1117 - esc_html(ucfirst($pdf_status['status']))
1118 - ); ?></p>
1119 - <p><?php printf(
1120 - esc_html__('Last update: %s', 'mxchat'),
1121 - esc_html($pdf_status['last_update'])
1122 - ); ?></p>
1123 - </div>
1124 - </div>
1125 - <?php endif; ?>
1331 +<?php if ($pdf_status && $pdf_status['status'] !== 'complete') : ?>
1332 + <div class="mxchat-status-card">
1333 + <div class="mxchat-status-header">
1334 + <h4><?php esc_html_e('PDF Processing Status', 'mxchat'); ?></h4>
1335 + <?php if ($is_processing) : ?>
1336 + <form method="post" class="mxchat-stop-form"
1337 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
1338 + <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
1339 + <button type="submit" name="stop_processing" class="mxchat-button-secondary">
1340 + <?php esc_html_e('Stop Processing', 'mxchat'); ?>
1341 + </button>
1342 + </form>
1343 + <?php endif; ?>
1344 +
1345 + <?php if ($pdf_status['status'] === 'error') : ?>
1346 + <span class="mxchat-status-badge mxchat-status-failed"><?php esc_html_e('Error', 'mxchat'); ?></span>
1347 + <?php endif; ?>
1348 + </div>
1349 + <div class="mxchat-progress-bar">
1350 + <div class="mxchat-progress-fill" style="width: <?php echo esc_attr($pdf_status['percentage']); ?>%"></div>
1351 + </div>
1352 + <div class="mxchat-status-details">
1353 + <p><?php printf(
1354 + esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'),
1355 + absint($pdf_status['processed_pages']),
1356 + absint($pdf_status['total_pages']),
1357 + absint($pdf_status['percentage'])
1358 + ); ?></p>
1359 + <p><?php printf(
1360 + esc_html__('Status: %s', 'mxchat'),
1361 + esc_html(ucfirst($pdf_status['status']))
1362 + ); ?></p>
1363 + <p><?php printf(
1364 + esc_html__('Last update: %s', 'mxchat'),
1365 + esc_html($pdf_status['last_update'])
1366 + ); ?></p>
1367 +
1368 + <?php if (!empty($pdf_status['error'])) : ?>
1369 + <div class="mxchat-error-notice">
1370 + <p class="error"><?php echo esc_html($pdf_status['error']); ?></p>
1371 + </div>
1372 + <?php endif; ?>
1373 + </div>
1374 + </div>
1375 +<?php endif; ?>
1126 1376
1127 - <?php if ($sitemap_status && $sitemap_status['status'] !== 'complete') : ?>
1128 - <div class="mxchat-status-card">
1129 - <div class="mxchat-status-header">
1130 - <h4><?php esc_html_e('Sitemap Processing Status (Refresh for update)', 'mxchat'); ?></h4>
1131 - <?php if ($is_processing) : ?>
1132 - <form method="post" class="mxchat-stop-form"
1133 - action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
1134 - <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
1135 - <button type="submit" name="stop_processing" class="mxchat-button-secondary">
1136 - <?php esc_html_e('Stop Processing', 'mxchat'); ?>
1137 - </button>
1138 - </form>
1139 - <?php endif; ?>
1140 - </div>
1141 - <div class="mxchat-progress-bar">
1142 - <div class="mxchat-progress-fill" style="width: <?php echo esc_attr($sitemap_status['percentage']); ?>%"></div>
1143 - </div>
1144 - <div class="mxchat-status-details">
1145 - <p><?php printf(
1146 - esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'),
1147 - absint($sitemap_status['processed_urls']),
1148 - absint($sitemap_status['total_urls']),
1149 - absint($sitemap_status['percentage'])
1150 - ); ?></p>
1151 - <?php if (!empty($sitemap_status['error']) || !empty($sitemap_status['last_error'])) : ?>
1152 - <div class="mxchat-error-notice">
1153 - <?php if (!empty($sitemap_status['error'])) : ?>
1154 - <p class="error"><?php echo esc_html($sitemap_status['error']); ?></p>
1155 - <?php endif; ?>
1156 - <?php if (!empty($sitemap_status['last_error'])) : ?>
1157 - <p class="last-error"><?php echo esc_html__('Last error:', 'mxchat') . ' ' . esc_html($sitemap_status['last_error']); ?></p>
1158 - <?php endif; ?>
1159 - </div>
1160 - <?php endif; ?>
1161 - </div>
1162 - </div>
1163 - <?php endif; ?>
1377 +
1378 +<!-- Single URL Submission Status -->
1379 +<?php
1380 +// Get single URL status
1381 +$single_url_status = $this->get_single_url_status();
1382 +$is_active_processing =
1383 + ($sitemap_status && $sitemap_status['status'] === 'processing') ||
1384 + ($pdf_status && $pdf_status['status'] === 'processing');
1385 +?>
1386 +
1387 +<div id="mxchat-single-url-status-container" <?php echo $is_active_processing ? 'style="display:none;"' : ''; ?>>
1388 + <?php if ($single_url_status && !$is_active_processing) : ?>
1389 + <div class="mxchat-status-card">
1390 + <div class="mxchat-status-header">
1391 + <h4><?php esc_html_e('Last URL Submission', 'mxchat'); ?></h4>
1392 + <?php if ($single_url_status['status'] === 'failed') : ?>
1393 + <span class="mxchat-status-badge mxchat-status-failed"><?php esc_html_e('Failed', 'mxchat'); ?></span>
1394 + <?php else : ?>
1395 + <span class="mxchat-status-badge mxchat-status-success"><?php esc_html_e('Success', 'mxchat'); ?></span>
1396 + <?php endif; ?>
1397 + </div>
1398 + <div class="mxchat-status-details">
1399 + <p><strong><?php esc_html_e('URL:', 'mxchat'); ?></strong>
1400 + <a href="<?php echo esc_url($single_url_status['url']); ?>" target="_blank">
1401 + <?php echo esc_html(strlen($single_url_status['url']) > 60 ? substr($single_url_status['url'], 0, 57) . '...' : $single_url_status['url']); ?>
1402 + </a>
1403 + </p>
1404 + <p><strong><?php esc_html_e('Submitted:', 'mxchat'); ?></strong> <?php echo esc_html($single_url_status['human_time']); ?></p>
1405 +
1406 + <?php if ($single_url_status['status'] === 'failed' && !empty($single_url_status['error'])) : ?>
1407 + <div class="mxchat-error-notice">
1408 + <p class="error"><?php echo esc_html($single_url_status['error']); ?></p>
1164 1409 </div>
1410 + <?php endif; ?>
1165 1411
1412 + <?php if ($single_url_status['status'] === 'complete') : ?>
1413 + <p><strong><?php esc_html_e('Content Length:', 'mxchat'); ?></strong> <?php echo esc_html($single_url_status['content_length']); ?> <?php esc_html_e('characters', 'mxchat'); ?></p>
1414 + <p><strong><?php esc_html_e('Embedding Dimensions:', 'mxchat'); ?></strong> <?php echo esc_html($single_url_status['embedding_dimensions']); ?></p>
1415 + <?php endif; ?>
1416 + </div>
1417 + </div>
1418 + <?php endif; ?>
1419 +</div>
1166 1420
1421 +
1422 +<?php if ($sitemap_status && $sitemap_status['status'] !== 'complete') : ?>
1423 + <div class="mxchat-status-card">
1424 + <div class="mxchat-status-header">
1425 + <h4><?php esc_html_e('Sitemap Processing Status', 'mxchat'); ?></h4>
1426 + <?php if ($is_processing) : ?>
1427 + <form method="post" class="mxchat-stop-form"
1428 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
1429 + <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
1430 + <button type="submit" name="stop_processing" class="mxchat-button-secondary">
1431 + <?php esc_html_e('Stop Processing', 'mxchat'); ?>
1432 + </button>
1433 + </form>
1434 + <?php endif; ?>
1435 + </div>
1436 + <div class="mxchat-progress-bar">
1437 + <div class="mxchat-progress-fill" style="width: <?php echo esc_attr($sitemap_status['percentage']); ?>%"></div>
1438 + </div>
1439 + <div class="mxchat-status-details">
1440 + <p><?php printf(
1441 + esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'),
1442 + absint($sitemap_status['processed_urls']),
1443 + absint($sitemap_status['total_urls']),
1444 + absint($sitemap_status['percentage'])
1445 + ); ?></p>
1446 + <?php if (!empty($sitemap_status['error']) || !empty($sitemap_status['last_error'])) : ?>
1447 + <div class="mxchat-error-notice">
1448 + <?php if (!empty($sitemap_status['error'])) : ?>
1449 + <p class="error"><?php echo esc_html($sitemap_status['error']); ?></p>
1450 + <?php endif; ?>
1451 + <?php if (!empty($sitemap_status['last_error'])) : ?>
1452 + <p class="last-error"><?php echo esc_html__('Last error:', 'mxchat') . ' ' . esc_html($sitemap_status['last_error']); ?></p>
1453 + <?php endif; ?>
1167 1454 </div>
1455 + <?php endif; ?>
1456 +
1457 + <?php if (!empty($sitemap_status['failed_urls']) && $sitemap_status['failed_urls'] > 0) : ?>
1458 + <div class="mxchat-failed-urls">
1459 + <h5><?php echo sprintf(esc_html__('Failed URLs (%d)', 'mxchat'), absint($sitemap_status['failed_urls'])); ?></h5>
1460 + <?php if (!empty($sitemap_status['failed_urls_list'])) : ?>
1461 + <div class="mxchat-failed-urls-list" style="max-height: 200px; overflow-y: auto; margin-top: 10px;">
1462 + <table class="widefat striped">
1463 + <thead>
1464 + <tr>
1465 + <th><?php esc_html_e('URL', 'mxchat'); ?></th>
1466 + <th><?php esc_html_e('Error', 'mxchat'); ?></th>
1467 + <th><?php esc_html_e('Time', 'mxchat'); ?></th>
1468 + </tr>
1469 + </thead>
1470 + <tbody>
1471 + <?php foreach ($sitemap_status['failed_urls_list'] as $failed_url) : ?>
1472 + <tr>
1473 + <td style="word-break: break-all;">
1474 + <a href="<?php echo esc_url($failed_url['url']); ?>" target="_blank" rel="noopener noreferrer">
1475 + <?php echo esc_html(strlen($failed_url['url']) > 60 ? substr($failed_url['url'], 0, 57) . '...' : $failed_url['url']); ?>
1476 + </a>
1477 + </td>
1478 + <td><?php echo esc_html($failed_url['error']); ?></td>
1479 + <td><?php echo esc_html(human_time_diff($failed_url['time'], time()) . ' ' . __('ago', 'mxchat')); ?></td>
1480 + </tr>
1481 + <?php endforeach; ?>
1482 + </tbody>
1483 + </table>
1484 + </div>
1485 + <?php endif; ?>
1486 + </div>
1487 + <?php endif; ?>
1488 + </div>
1489 + </div>
1490 +<?php endif; ?>
1491 +
1492 +
1493 + </div>
1494 +
1495 +
1496 + </div>
1497 +
1498 +
1499 +
1168 1500 </div>
1169 1501
1170 1502 <!-- Direct Content Submission Card -->
1171 1503 <div class="mxchat-card">
@@ -1247,16 +1579,19 @@
1247 1579 <?php echo esc_textarea($prompt->article_content); ?>
1248 1580 </textarea>
1249 1581 </td>
1250 1582 <td class="mxchat-url-cell">
1251 - <?php if (!empty($prompt->source_url)) : ?>
1252 - <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank">
1253 - <span class="dashicons dashicons-external"></span>
1254 - <?php esc_html_e('View Source', 'mxchat'); ?>
1255 - </a>
1256 - <?php else : ?>
1257 - <span class="mxchat-na"><?php esc_html_e('N/A', 'mxchat'); ?></span>
1258 - <?php endif; ?>
1583 + <div class="url-view">
1584 + <?php if (!empty($prompt->source_url)) : ?>
1585 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank">
1586 + <span class="dashicons dashicons-external"></span>
1587 + <?php esc_html_e('View Source', 'mxchat'); ?>
1588 + </a>
1589 + <?php else : ?>
1590 + <span class="mxchat-na"><?php esc_html_e('N/A', 'mxchat'); ?></span>
1591 + <?php endif; ?>
1592 + </div>
1593 + <input type="text" class="url-edit" style="display:none;" value="<?php echo esc_attr($prompt->source_url); ?>" />
1259 1594 </td>
1260 1595 <td class="mxchat-actions-cell">
1261 1596 <button class="mxchat-button-icon edit-button"
1262 1597 data-id="<?php echo esc_attr($prompt->id); ?>">
@@ -1358,30 +1693,154 @@
1358 1693
1359 1694 wp_safe_redirect(add_query_arg(array('page' => 'mxchat-prompts', 'deleted' => 'true'), admin_url('admin.php')));
1360 1695 exit;
1361 1696 }
1362 -public function mxchat_generate_embedding($text) {
1363 - $options = get_option('mxchat_options');
1364 - $api_key = $options['api_key'] ?? esc_html__('default_api_key', 'mxchat');
1365 1697
1366 - $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
1367 - 'body' => wp_json_encode(array(
1368 - 'model' => esc_html__('text-embedding-ada-002', 'mxchat'),
1369 - 'input' => $text
1370 - )),
1371 - 'headers' => array(
1372 - 'Authorization' => 'Bearer ' . $api_key,
1373 - 'Content-Type' => esc_html__('application/json', 'mxchat')
1374 - ),
1375 - ));
1376 1698
1377 - if (is_wp_error($response)) {
1378 - return null;
1699 +public function mxchat_generate_embedding($text) {
1700 + // Enable detailed logging for debugging
1701 + //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
1702 + //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
1703 +
1704 + $options = get_option('mxchat_options');
1705 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
1706 + //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
1707 +
1708 + // Determine provider and endpoint
1709 + if (strpos($selected_model, 'voyage') === 0) {
1710 + $api_key = $options['voyage_api_key'] ?? '';
1711 + $endpoint = 'https://api.voyageai.com/v1/embeddings';
1712 + $provider_name = 'Voyage AI';
1713 + //error_log('[MXCHAT-EMBED] Using Voyage AI API');
1714 + } else {
1715 + $api_key = $options['api_key'] ?? '';
1716 + $endpoint = 'https://api.openai.com/v1/embeddings';
1717 + $provider_name = 'OpenAI';
1718 + //error_log('[MXCHAT-EMBED] Using OpenAI API');
1719 + }
1720 +
1721 + //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
1722 +
1723 + if (empty($api_key)) {
1724 + $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
1725 + //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
1726 + return $error_message;
1727 + }
1728 +
1729 + // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
1730 + $estimated_tokens = ceil(str_word_count($text) / 0.75);
1731 + //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
1732 +
1733 + if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false) {
1734 + //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
1735 + // Consider truncating text here
1736 + }
1737 +
1738 + // Prepare request body
1739 + $request_body = array(
1740 + 'model' => $selected_model,
1741 + 'input' => $text
1742 + );
1743 +
1744 + // Add output_dimension for voyage-3-large model
1745 + if ($selected_model === 'voyage-3-large') {
1746 + $request_body['output_dimension'] = 2048;
1747 + }
1748 +
1749 + //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
1750 +
1751 + // Make API request
1752 + //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
1753 + $response = wp_remote_post($endpoint, array(
1754 + 'body' => wp_json_encode($request_body),
1755 + 'headers' => array(
1756 + 'Authorization' => 'Bearer ' . $api_key,
1757 + 'Content-Type' => 'application/json'
1758 + ),
1759 + 'timeout' => 60 // Increased timeout for large inputs
1760 + ));
1761 +
1762 + // Handle wp_remote_post errors
1763 + if (is_wp_error($response)) {
1764 + $error_message = $response->get_error_message();
1765 + //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
1766 + return 'Connection error: ' . $error_message;
1767 + }
1768 +
1769 + // Get and check HTTP response code
1770 + $http_code = wp_remote_retrieve_response_code($response);
1771 + //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
1772 +
1773 + if ($http_code !== 200) {
1774 + $error_body = wp_remote_retrieve_body($response);
1775 + //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
1776 +
1777 + // Try to parse error for more details
1778 + $error_json = json_decode($error_body, true);
1779 + if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
1780 + $error_type = $error_json['error']['type'] ?? 'unknown';
1781 + $error_message = $error_json['error']['message'] ?? 'No message';
1782 + //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
1783 + //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
1784 +
1785 + // Customize error message for common API errors
1786 + if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
1787 + $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
1788 + } elseif ($error_type === 'authentication_error') {
1789 + $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
1790 + }
1791 +
1792 + //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
1793 + return $error_message;
1379 1794 }
1795 +
1796 + $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
1797 + //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
1798 + return $error_message;
1799 + }
1800 +
1801 + // Parse response body
1802 + $response_body = wp_remote_retrieve_body($response);
1803 + //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
1804 +
1805 + $response_data = json_decode($response_body, true);
1806 +
1807 + if (json_last_error() !== JSON_ERROR_NONE) {
1808 + $error = json_last_error_msg();
1809 + //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
1810 + //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
1811 + return "Failed to parse API response: $error";
1812 + }
1813 +
1814 + // Both APIs use the same structure, so we can extract the embedding the same way
1815 + if (isset($response_data['data'][0]['embedding'])) {
1816 + $embedding_dimensions = count($response_data['data'][0]['embedding']);
1817 + //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
1818 +
1819 + // Check if embedding dimensions are as expected
1820 + if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
1821 + ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
1822 + //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
1823 + }
1824 +
1825 + return $response_data['data'][0]['embedding'];
1826 + } else {
1827 + //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
1828 + //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
1829 +
1830 + if (isset($response_data['error'])) {
1831 + $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
1832 + //error_log('[MXCHAT-EMBED] ' . $error_message);
1833 + return $error_message;
1834 + }
1835 +
1836 + $error_message = "Invalid API response format: No embedding found";
1837 + //error_log('[MXCHAT-EMBED] ' . $error_message);
1838 + return $error_message;
1839 + }
1840 +}
1380 1841
1381 - $response_data = json_decode(wp_remote_retrieve_body($response), true);
1382 - return $response_data['data'][0]['embedding'] ?? null;
1383 - }
1842 +
1384 1843 public function mxchat_delete_chat_history() {
1385 1844 if (!current_user_can('manage_options')) {
1386 1845 echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
1387 1846 wp_die();
@@ -1469,45 +1928,106 @@
1469 1928 }
1470 1929
1471 1930
1472 1931
1473 -// Add this method to handle post updates
1932 +/**
1933 + * Get all public post types
1934 + *
1935 + * @return array Associative array of post type names and labels
1936 + */
1937 +private function get_public_post_types() {
1938 + $post_types = get_post_types(array('public' => true), 'objects');
1939 + $post_type_options = array();
1940 +
1941 + foreach ($post_types as $post_type) {
1942 + $post_type_options[$post_type->name] = $post_type->label;
1943 + }
1944 +
1945 + return $post_type_options;
1946 +}
1947 +
1948 +/**
1949 + * Handle post updates and process content for the chatbot
1950 + *
1951 + * @param int $post_id The ID of the post being saved
1952 + * @param WP_Post $post The post object
1953 + * @param bool $update Whether this is an existing post being updated
1954 + */
1474 1955 public function handle_post_update($post_id, $post, $update) {
1475 1956 // Basic validation checks
1476 1957 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || wp_is_post_revision($post_id)) {
1477 1958 return;
1478 1959 }
1479 -
1960 +
1480 1961 // Only process published content
1481 - if (!in_array($post->post_status, array('publish'))) {
1962 + if ($post->post_status !== 'publish') {
1482 1963 return;
1483 1964 }
1484 -
1965 +
1966 + $post_type = $post->post_type;
1967 +
1485 1968 // Check if sync is enabled for this post type
1486 - $post_type = $post->post_type;
1487 - if (!in_array($post_type, array('post', 'page'))) {
1488 - return;
1969 + $should_sync = false;
1970 +
1971 + // Check built-in post types first
1972 + if ($post_type === 'post' && get_option('mxchat_auto_sync_posts') === '1') {
1973 + $should_sync = true;
1974 + } else if ($post_type === 'page' && get_option('mxchat_auto_sync_pages') === '1') {
1975 + $should_sync = true;
1976 + } else {
1977 + // Check custom post types
1978 + $option_name = 'mxchat_auto_sync_' . $post_type;
1979 + if (get_option($option_name) === '1') {
1980 + $should_sync = true;
1981 + }
1489 1982 }
1490 -
1491 - $sync_option = ($post_type === 'post') ? 'mxchat_auto_sync_posts' : 'mxchat_auto_sync_pages';
1492 - if (get_option($sync_option) != '1') {
1983 +
1984 + if (!$should_sync) {
1493 1985 return;
1494 1986 }
1495 -
1987 +
1496 1988 // Prepare content and URL
1497 1989 $content = wp_strip_all_tags($post->post_content);
1990 +
1991 + // For custom post types like job_listing, include additional fields
1992 + if ($post_type === 'job_listing') {
1993 + // Add title as it's important for job listings
1994 + $content = $post->post_title . "\n\n" . $content;
1995 +
1996 + // Add job-specific meta if available
1997 + $job_location = get_post_meta($post_id, '_job_location', true);
1998 + if (!empty($job_location)) {
1999 + $content .= "\n\nLocation: " . $job_location;
2000 + }
2001 +
2002 + // Get job type terms
2003 + $job_types = get_the_terms($post_id, 'job_listing_type');
2004 + if (!empty($job_types) && !is_wp_error($job_types)) {
2005 + $types = array();
2006 + foreach ($job_types as $type) {
2007 + $types[] = $type->name;
2008 + }
2009 + $content .= "\n\nJob Type: " . implode(', ', $types);
2010 + }
2011 +
2012 + // Get company name if available
2013 + $company_name = get_post_meta($post_id, '_company_name', true);
2014 + if (!empty($company_name)) {
2015 + $content .= "\n\nCompany: " . $company_name;
2016 + }
2017 + }
2018 +
1498 2019 $url = get_permalink($post_id);
1499 -
2020 +
1500 2021 // Generate embedding vector
1501 2022 $embedding_vector = $this->mxchat_generate_embedding($content);
1502 2023 if (!$embedding_vector) {
1503 2024 return;
1504 2025 }
1505 -
2026 +
1506 2027 // Check for Pinecone addon and its settings
1507 2028 $pinecone_settings = get_option('mxchat_pinecone_addon_options');
1508 2029 $use_pinecone = false;
1509 -
1510 2030 if ($pinecone_settings && is_array($pinecone_settings)) {
1511 2031 // Check if Pinecone is enabled and all required settings are present
1512 2032 $use_pinecone = (
1513 2033 isset($pinecone_settings['mxchat_use_pinecone']) &&
@@ -1517,9 +2037,9 @@
1517 2037 !empty($pinecone_settings['mxchat_pinecone_index']) &&
1518 2038 !empty($pinecone_settings['mxchat_pinecone_environment'])
1519 2039 );
1520 2040 }
1521 -
2041 +
1522 2042 if ($use_pinecone) {
1523 2043 // Use Pinecone
1524 2044 $pinecone_result = $this->store_in_pinecone_main(
1525 2045 $embedding_vector,
@@ -1528,11 +2048,10 @@
1528 2048 $pinecone_settings['mxchat_pinecone_api_key'],
1529 2049 $pinecone_settings['mxchat_pinecone_environment'],
1530 2050 $pinecone_settings['mxchat_pinecone_index']
1531 2051 );
1532 -
1533 2052 if (!$pinecone_result['success']) {
1534 - //error_log('MXChat: Pinecone sync failed - falling back to WordPress DB');
2053 + // Fallback to WordPress DB
1535 2054 $this->store_in_wordpress_db($content, $url, $embedding_vector);
1536 2055 }
1537 2056 } else {
1538 2057 // Fallback to WordPress DB storage
@@ -1537,9 +2056,122 @@
1537 2056 } else {
1538 2057 // Fallback to WordPress DB storage
1539 2058 $this->store_in_wordpress_db($content, $url, $embedding_vector);
1540 2059 }
2060 +
1541 2061 }
2062 +/**
2063 + * Handle deletion of posts from both Pinecone and WordPress DB
2064 + *
2065 + * @param int $post_id The ID of the post being deleted
2066 + * @return void
2067 + */
2068 +public function mxchat_handle_post_delete($post_id) {
2069 + // Get post data before it's deleted
2070 + $post = get_post($post_id);
2071 +
2072 + // Basic validation
2073 + if (!$post || wp_is_post_revision($post_id)) {
2074 + return;
2075 + }
2076 +
2077 + $post_type = $post->post_type;
2078 +
2079 + // Check if sync is enabled for this post type
2080 + $should_sync = false;
2081 +
2082 + // Check built-in post types first
2083 + if ($post_type === 'post' && get_option('mxchat_auto_sync_posts') === '1') {
2084 + $should_sync = true;
2085 + } else if ($post_type === 'page' && get_option('mxchat_auto_sync_pages') === '1') {
2086 + $should_sync = true;
2087 + } else {
2088 + // Check custom post types
2089 + $option_name = 'mxchat_auto_sync_' . $post_type;
2090 + if (get_option($option_name) === '1') {
2091 + $should_sync = true;
2092 + }
2093 + }
2094 +
2095 + if (!$should_sync) {
2096 + return;
2097 + }
2098 +
2099 + // Get the URL before post is deleted
2100 + $source_url = get_permalink($post_id);
2101 + if (!$source_url) {
2102 + //error_log('MXChat: Failed to get permalink for post ' . $post_id);
2103 + return;
2104 + }
2105 +
2106 + // Check for Pinecone addon and its settings
2107 + $pinecone_settings = get_option('mxchat_pinecone_addon_options');
2108 + $use_pinecone = false;
2109 + if ($pinecone_settings && is_array($pinecone_settings)) {
2110 + $use_pinecone = (
2111 + isset($pinecone_settings['mxchat_use_pinecone']) &&
2112 + $pinecone_settings['mxchat_use_pinecone'] === '1' &&
2113 + !empty($pinecone_settings['mxchat_pinecone_api_key']) &&
2114 + !empty($pinecone_settings['mxchat_pinecone_host']) &&
2115 + !empty($pinecone_settings['mxchat_pinecone_index']) &&
2116 + !empty($pinecone_settings['mxchat_pinecone_environment'])
2117 + );
2118 + }
2119 +
2120 + $deletion_successful = false;
2121 +
2122 + if ($use_pinecone) {
2123 + try {
2124 + $pinecone_result = $this->delete_from_pinecone(
2125 + array($source_url),
2126 + $pinecone_settings['mxchat_pinecone_api_key'],
2127 + $pinecone_settings['mxchat_pinecone_environment'],
2128 + $pinecone_settings['mxchat_pinecone_index']
2129 + );
2130 +
2131 + if (!$pinecone_result['success']) {
2132 + //error_log('MXChat: Pinecone deletion failed for URL: ' . $source_url . ' - ' . $pinecone_result['message']);
2133 + } else {
2134 + $deletion_successful = true;
2135 + }
2136 + } catch (Exception $e) {
2137 + //error_log('MXChat: Exception during Pinecone deletion - ' . $e->getMessage());
2138 + }
2139 + }
2140 +
2141 + // Always attempt WordPress DB deletion, regardless of Pinecone status
2142 + try {
2143 + global $wpdb;
2144 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2145 +
2146 + $result = $wpdb->delete(
2147 + $table_name,
2148 + array('source_url' => $source_url),
2149 + array('%s')
2150 + );
2151 +
2152 + if ($result === false) {
2153 + //error_log('MXChat: WordPress DB deletion failed for URL: ' . $source_url);
2154 + } else {
2155 + $deletion_successful = true;
2156 + }
2157 + } catch (Exception $e) {
2158 + //error_log('MXChat: Exception during WordPress DB deletion - ' . $e->getMessage());
2159 + }
2160 +
2161 + if (!$deletion_successful) {
2162 + //error_log('MXChat: Complete deletion failure for post ID: ' . $post_id . ' URL: ' . $source_url);
2163 + } else {
2164 +
2165 + }
2166 +}
2167 +
2168 +
2169 +
2170 +
2171 +
2172 +
2173 +
1542 2174 // Modified storage function to add type field
1543 2175 private function store_in_pinecone_main($embedding_vector, $content, $url, $api_key, $environment, $index_name, $vector_id = null) {
1544 2176 $vector_id = $vector_id ?: md5($url);
1545 2177 $options = get_option('mxchat_pinecone_addon_options');
@@ -1606,8 +2238,10 @@
1606 2238 'success' => true,
1607 2239 'message' => 'Successfully stored in Pinecone'
1608 2240 );
1609 2241 }
2242 +
2243 +
1610 2244 // Helper method for WordPress DB storage
1611 2245 private function store_in_wordpress_db($content, $url, $embedding_vector) {
1612 2246 global $wpdb;
1613 2247 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
@@ -1639,103 +2273,10 @@
1639 2273 array('%s', '%s', '%s', '%s')
1640 2274 );
1641 2275 }
1642 2276 }
1643 -/**
1644 - * Handle deletion of posts and pages from both Pinecone and WordPress DB
1645 - *
1646 - * @param int $post_id The ID of the post being deleted
1647 - * @return void
1648 - */
1649 -public function mxchat_handle_post_delete($post_id) {
1650 - // Get post data before it's deleted
1651 - $post = get_post($post_id);
1652 2277
1653 - // Basic validation
1654 - if (!$post || wp_is_post_revision($post_id)) {
1655 - return;
1656 - }
1657 2278
1658 - // Check post type
1659 - $post_type = $post->post_type;
1660 - if (!in_array($post_type, array('post', 'page'))) {
1661 - return;
1662 - }
1663 -
1664 - // Check if sync is enabled for this post type
1665 - $sync_option = ($post_type === 'post') ? 'mxchat_auto_sync_posts' : 'mxchat_auto_sync_pages';
1666 - if (get_option($sync_option) != '1') {
1667 - return;
1668 - }
1669 -
1670 - // Get the URL before post is deleted
1671 - $source_url = get_permalink($post_id);
1672 - if (!$source_url) {
1673 - //error_log('MXChat: Failed to get permalink for post ' . $post_id);
1674 - return;
1675 - }
1676 -
1677 - // Check for Pinecone addon and its settings
1678 - $pinecone_settings = get_option('mxchat_pinecone_addon_options');
1679 - $use_pinecone = false;
1680 - if ($pinecone_settings && is_array($pinecone_settings)) {
1681 - $use_pinecone = (
1682 - isset($pinecone_settings['mxchat_use_pinecone']) &&
1683 - $pinecone_settings['mxchat_use_pinecone'] === '1' &&
1684 - !empty($pinecone_settings['mxchat_pinecone_api_key']) &&
1685 - !empty($pinecone_settings['mxchat_pinecone_host']) &&
1686 - !empty($pinecone_settings['mxchat_pinecone_index']) &&
1687 - !empty($pinecone_settings['mxchat_pinecone_environment'])
1688 - );
1689 - }
1690 -
1691 - $deletion_successful = false;
1692 -
1693 - if ($use_pinecone) {
1694 - try {
1695 - $pinecone_result = $this->delete_from_pinecone(
1696 - array($source_url),
1697 - $pinecone_settings['mxchat_pinecone_api_key'],
1698 - $pinecone_settings['mxchat_pinecone_environment'],
1699 - $pinecone_settings['mxchat_pinecone_index']
1700 - );
1701 -
1702 - if (!$pinecone_result['success']) {
1703 - //error_log('MXChat: Pinecone deletion failed for URL: ' . $source_url . ' - ' . $pinecone_result['message']);
1704 - } else {
1705 - $deletion_successful = true;
1706 - }
1707 - } catch (Exception $e) {
1708 - //error_log('MXChat: Exception during Pinecone deletion - ' . $e->getMessage());
1709 - }
1710 - }
1711 -
1712 - // Always attempt WordPress DB deletion, regardless of Pinecone status
1713 - try {
1714 - global $wpdb;
1715 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1716 -
1717 - $result = $wpdb->delete(
1718 - $table_name,
1719 - array('source_url' => $source_url),
1720 - array('%s')
1721 - );
1722 -
1723 - if ($result === false) {
1724 - //error_log('MXChat: WordPress DB deletion failed for URL: ' . $source_url);
1725 - } else {
1726 - $deletion_successful = true;
1727 - }
1728 - } catch (Exception $e) {
1729 - //error_log('MXChat: Exception during WordPress DB deletion - ' . $e->getMessage());
1730 - }
1731 -
1732 - if (!$deletion_successful) {
1733 - //error_log('MXChat: Complete deletion failure for post ID: ' . $post_id . ' URL: ' . $source_url);
1734 - }
1735 -}
1736 -
1737 -
1738 2279 public function mxchat_handle_content_submission() {
1739 2280 // Check if the form was submitted and the user has permission.
1740 2281 if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
1741 2282 return;
@@ -1907,31 +2448,57 @@
1907 2448 $start_page = absint($status['processed_pages']);
1908 2449 $end_page = min($start_page + $batch_size, $total_pages);
1909 2450
1910 2451 $instance = new self(); // Create an instance of the class
2452 + $options = get_option('mxchat_options');
2453 +
2454 + if (empty($options['api_key'])) {
2455 + throw new Exception('API key is missing or invalid');
2456 + }
1911 2457
1912 2458 for ($i = $start_page; $i < $end_page; $i++) {
1913 2459 $text = $pages[$i]->getText();
2460 +
2461 + if (empty($text)) {
2462 + // Log empty page but continue processing
2463 + //error_log(sprintf('[MXCHAT-PDF] Warning: Empty text on page %d of %s', $i + 1, $pdf_url));
2464 + continue;
2465 + }
2466 +
1914 2467 $sanitized_content = $instance->mxchat_sanitize_content_for_api($text); // Call via instance
1915 2468
1916 - if (!empty($sanitized_content)) {
1917 - $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
1918 - if (is_array($embedding_vector)) {
1919 - $metadata = array(
1920 - 'document_type' => 'pdf',
1921 - 'total_pages' => $total_pages,
1922 - 'current_page' => $i + 1,
1923 - 'prev_page' => $i > 0 ? $i : null,
1924 - 'next_page' => $i < ($total_pages - 1) ? $i + 2 : null,
1925 - 'source_url' => $pdf_url
1926 - );
2469 + if (empty($sanitized_content)) {
2470 + // Log empty sanitized content but continue processing
2471 + //error_log(sprintf('[MXCHAT-PDF] Warning: No valid content after sanitization on page %d of %s', $i + 1, $pdf_url));
2472 + continue;
2473 + }
1927 2474
1928 - $content_with_metadata = wp_json_encode($metadata) . "\n---\n" . $sanitized_content;
1929 - $page_url = esc_url($pdf_url . "#page=" . ($i + 1));
2475 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
2476 +
2477 + if (!is_array($embedding_vector)) {
2478 + // If embedding generation fails, log error and throw exception
2479 + $error_msg = is_string($embedding_vector) ? $embedding_vector : 'Unknown embedding generation error';
2480 + //error_log(sprintf('[MXCHAT-PDF] Error generating embedding for page %d: %s', $i + 1, $error_msg));
2481 + throw new Exception(sprintf('Failed to generate embedding for page %d: %s', $i + 1, $error_msg));
2482 + }
2483 +
2484 + $metadata = array(
2485 + 'document_type' => 'pdf',
2486 + 'total_pages' => $total_pages,
2487 + 'current_page' => $i + 1,
2488 + 'prev_page' => $i > 0 ? $i : null,
2489 + 'next_page' => $i < ($total_pages - 1) ? $i + 2 : null,
2490 + 'source_url' => $pdf_url
2491 + );
1930 2492
1931 - $options = get_option('mxchat_options');
1932 - MxChat_Utils::submit_content_to_db($content_with_metadata, $page_url, $options['api_key']);
1933 - }
2493 + $content_with_metadata = wp_json_encode($metadata) . "\n---\n" . $sanitized_content;
2494 + $page_url = esc_url($pdf_url . "#page=" . ($i + 1));
2495 +
2496 + $db_result = MxChat_Utils::submit_content_to_db($content_with_metadata, $page_url, $options['api_key']);
2497 +
2498 + if (is_wp_error($db_result)) {
2499 + throw new Exception(sprintf('Failed to store content in database for page %d: %s',
2500 + $i + 1, $db_result->get_error_message()));
1934 2501 }
1935 2502
1936 2503 // Update progress with sanitized data
1937 2504 $status['processed_pages'] = absint($i + 1);
@@ -1957,16 +2524,36 @@
1957 2524 }
1958 2525 }
1959 2526
1960 2527 } catch (\Exception $e) {
1961 - $status['status'] = 'error';
1962 - $status['error'] = sanitize_text_field($e->getMessage());
2528 + //error_log(sprintf('[MXCHAT-PDF] Error processing PDF: %s', $e->getMessage()));
2529 +
2530 + // Get current status to update it
2531 + $status_key = sanitize_key('mxchat_pdf_status_' . md5($pdf_url));
2532 + $status = get_transient($status_key);
2533 +
2534 + if (!$status || !is_array($status)) {
2535 + $status = array(
2536 + 'total_pages' => $total_pages,
2537 + 'processed_pages' => 0,
2538 + 'status' => 'error',
2539 + 'error' => sanitize_text_field($e->getMessage()),
2540 + 'last_update' => time()
2541 + );
2542 + } else {
2543 + $status['status'] = 'error';
2544 + $status['error'] = sanitize_text_field($e->getMessage());
2545 + $status['last_update'] = time();
2546 + }
2547 +
1963 2548 set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
2549 +
1964 2550 if (file_exists($pdf_path)) {
1965 2551 wp_delete_file($pdf_path);
1966 2552 }
1967 2553 }
1968 2554 }
2555 +
1969 2556 public function get_pdf_processing_status($pdf_url) {
1970 2557 $pdf_url = esc_url_raw($pdf_url);
1971 2558 $status = get_transient(sanitize_key('mxchat_pdf_status_' . md5($pdf_url)));
1972 2559
@@ -1973,29 +2560,57 @@
1973 2560 if (!$status || !is_array($status)) {
1974 2561 return false;
1975 2562 }
1976 2563
1977 - return array(
2564 + // Check for stalled processing (no updates for 5 minutes)
2565 + if ($status['status'] === 'processing' && (time() - absint($status['last_update'])) > 300) {
2566 + $status['status'] = 'error';
2567 + $status['error'] = __('PDF processing appears to be stalled. No updates for over 5 minutes.', 'mxchat');
2568 +
2569 + // Save the updated status
2570 + set_transient(
2571 + sanitize_key('mxchat_pdf_status_' . md5($pdf_url)),
2572 + array_map('sanitize_text_field', $status),
2573 + DAY_IN_SECONDS
2574 + );
2575 + }
2576 +
2577 + $result = array(
1978 2578 'total_pages' => absint($status['total_pages']),
1979 2579 'processed_pages' => absint($status['processed_pages']),
1980 2580 'percentage' => ($status['total_pages'] > 0)
1981 - ? round((absint($status['processed_pages']) / absint($status['total_pages'])) * 100)
1982 - : 0,
2581 + ? round((absint($status['processed_pages']) / absint($status['total_pages'])) * 100)
2582 + : 0,
1983 2583 'status' => sanitize_text_field($status['status']),
1984 2584 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ' . esc_html__('ago', 'mxchat')
1985 2585 );
2586 +
2587 + // Add error message if present
2588 + if (isset($status['error']) && !empty($status['error'])) {
2589 + $result['error'] = sanitize_text_field($status['error']);
2590 + }
2591 +
2592 + return $result;
1986 2593 }
2594 +
2595 +
1987 2596 public function mxchat_handle_sitemap_submission() {
2597 + // Start logging the submission process
2598 + //error_log('[MXCHAT-URL] ===== Starting URL submission process =====');
2599 +
1988 2600 // Check if the form was submitted and verify permissions
1989 2601 if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
2602 + //error_log('[MXCHAT-URL] Error: Unauthorized access or form not submitted properly');
1990 2603 wp_die(esc_html__('Unauthorized access', 'mxchat'));
1991 2604 }
1992 2605
1993 2606 // Verify nonce
2607 + //error_log('[MXCHAT-URL] Verifying nonce');
1994 2608 check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
1995 2609
1996 2610 // Validate URL
1997 2611 if (!isset($_POST['sitemap_url']) || empty($_POST['sitemap_url'])) {
2612 + //error_log('[MXCHAT-URL] Error: Empty or missing URL');
1998 2613 set_transient('mxchat_admin_notice_error',
1999 2614 esc_html__('Please provide a valid URL.', 'mxchat'),
2000 2615 30
2001 2616 );
@@ -2003,12 +2618,40 @@
2003 2618 exit;
2004 2619 }
2005 2620
2006 2621 $submitted_url = esc_url_raw($_POST['sitemap_url']);
2622 + //error_log('[MXCHAT-URL] Processing URL: ' . $submitted_url);
2623 +
2624 + // Validate API key first
2625 + $options = get_option('mxchat_options');
2626 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
2627 +
2628 + if (strpos($selected_model, 'voyage') === 0) {
2629 + $api_key = $options['voyage_api_key'] ?? '';
2630 + $provider_name = 'Voyage AI';
2631 + } else {
2632 + $api_key = $options['api_key'] ?? '';
2633 + $provider_name = 'OpenAI';
2634 + }
2635 +
2636 + if (empty($api_key)) {
2637 + $error_message = sprintf(
2638 + esc_html__('%s API key is not configured. Please add your API key in the settings before submitting content.', 'mxchat'),
2639 + $provider_name
2640 + );
2641 + //error_log('[MXCHAT-URL] Error: ' . $error_message);
2642 + set_transient('mxchat_admin_notice_error', $error_message, 30);
2643 + //error_log('[MXCHAT-URL] Set error transient: ' . $error_message);
2644 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2645 + exit;
2646 + }
2647 +
2648 + //error_log('[MXCHAT-URL] Fetching URL content');
2007 2649 $response = wp_remote_get($submitted_url, array('timeout' => 30));
2008 2650
2009 2651 if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2010 - $error_message = is_wp_error($response) ? $response->get_error_message() : __('Failed to fetch URL', 'mxchat');
2652 + $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP Status: ' . wp_remote_retrieve_response_code($response);
2653 + //error_log('[MXCHAT-URL] Error fetching URL: ' . $error_message);
2011 2654 set_transient('mxchat_admin_notice_error',
2012 2655 sprintf(
2013 2656 esc_html__('Failed to fetch the URL: %s', 'mxchat'),
2014 2657 esc_html($error_message)
@@ -2019,11 +2662,13 @@
2019 2662 exit;
2020 2663 }
2021 2664
2022 2665 $content_type = wp_remote_retrieve_header($response, 'content-type');
2666 + //error_log('[MXCHAT-URL] Content type: ' . $content_type);
2023 2667 $body_content = wp_remote_retrieve_body($response);
2024 2668
2025 2669 if (empty($body_content)) {
2670 + //error_log('[MXCHAT-URL] Error: Empty response body');
2026 2671 set_transient('mxchat_admin_notice_error',
2027 2672 esc_html__('Empty response received from URL.', 'mxchat'),
2028 2673 30
2029 2674 );
@@ -2029,12 +2674,15 @@
2029 2674 );
2030 2675 wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2031 2676 exit;
2032 2677 }
2678 + //error_log('[MXCHAT-URL] Retrieved body content length: ' . strlen($body_content) . ' bytes');
2033 2679
2034 2680 // Handle PDF URL
2035 2681 if ($this->is_pdf_url($submitted_url, $response)) {
2682 + //error_log('[MXCHAT-URL] Detected PDF URL, handling PDF for knowledge base');
2036 2683 $result = $this->handle_pdf_for_knowledge_base($submitted_url, $response);
2684 + //error_log('[MXCHAT-URL] PDF handling result: ' . $result);
2037 2685
2038 2686 if ($result === 'scheduled') {
2039 2687 set_transient(
2040 2688 'mxchat_last_pdf_url',
@@ -2046,9 +2694,9 @@
2046 2694 30
2047 2695 );
2048 2696 } else {
2049 2697 set_transient('mxchat_admin_notice_error',
2050 - esc_html__('Failed to start PDF processing. Please try again.', 'mxchat'),
2698 + esc_html__('Failed to start PDF processing: ', 'mxchat') . esc_html($result),
2051 2699 30
2052 2700 );
2053 2701 }
2054 2702
@@ -2057,8 +2705,9 @@
2057 2705 }
2058 2706
2059 2707 // Handle Sitemap XML
2060 2708 if (strpos($content_type, 'xml') !== false || strpos($body_content, '<urlset') !== false) {
2709 + //error_log('[MXCHAT-URL] Detected XML content, processing as sitemap');
2061 2710 libxml_use_internal_errors(true);
2062 2711 $xml = simplexml_load_string($body_content);
2063 2712 $xml_errors = libxml_get_errors();
2064 2713 libxml_clear_errors();
@@ -2063,8 +2712,15 @@
2063 2712 $xml_errors = libxml_get_errors();
2064 2713 libxml_clear_errors();
2065 2714
2066 2715 if ($xml === false || !empty($xml_errors)) {
2716 + //error_log('[MXCHAT-URL] Error: Invalid XML format');
2717 + if (!empty($xml_errors)) {
2718 + foreach ($xml_errors as $error) {
2719 + //error_log('[MXCHAT-URL] XML Error: ' . $error->message);
2720 + }
2721 + }
2722 +
2067 2723 set_transient('mxchat_admin_notice_error',
2068 2724 esc_html__('Invalid sitemap XML. Please provide a valid sitemap.', 'mxchat'),
2069 2725 30
2070 2726 );
@@ -2071,9 +2727,11 @@
2071 2727 wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2072 2728 exit;
2073 2729 }
2074 2730
2731 + //error_log('[MXCHAT-URL] Valid XML found, handling sitemap for knowledge base');
2075 2732 $result = $this->handle_sitemap_for_knowledge_base($xml, $submitted_url);
2733 + //error_log('[MXCHAT-URL] Sitemap handling result: ' . $result);
2076 2734
2077 2735 if ($result === 'scheduled') {
2078 2736 set_transient(
2079 2737 'mxchat_last_sitemap_url',
@@ -2084,10 +2742,12 @@
2084 2742 esc_html__('Sitemap processing has started in the background. You can check the progress in the Knowledge Base section.', 'mxchat'),
2085 2743 30
2086 2744 );
2087 2745 } else {
2746 + // Return to the admin page without a redirect for better error display
2747 + // The error is already stored in the sitemap status transient
2088 2748 set_transient('mxchat_admin_notice_error',
2089 - esc_html__('Failed to start sitemap processing. Please try again.', 'mxchat'),
2749 + esc_html__('Failed to start sitemap processing. Please check the status below for details.', 'mxchat'),
2090 2750 30
2091 2751 );
2092 2752 }
2093 2753
@@ -2095,42 +2755,147 @@
2095 2755 exit;
2096 2756 }
2097 2757
2098 2758 // Handle Regular URL
2099 - $page_content = $this->mxchat_extract_main_content($body_content);
2100 - $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
2759 + // Handle Regular URL
2760 +//error_log('[MXCHAT-URL] Processing as regular webpage');
2761 +$page_content = $this->mxchat_extract_main_content($body_content);
2762 +//error_log('[MXCHAT-URL] Extracted content length: ' . strlen($page_content) . ' bytes');
2101 2763
2102 - if (empty($sanitized_content)) {
2103 - set_transient('mxchat_admin_notice_error',
2104 - esc_html__('No valid content found on the provided URL.', 'mxchat'),
2105 - 30
2106 - );
2764 +$sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
2765 +//error_log('[MXCHAT-URL] Sanitized content length: ' . strlen($sanitized_content) . ' bytes');
2766 +
2767 +if (empty($sanitized_content)) {
2768 + //error_log('[MXCHAT-URL] Error: No valid content after sanitization');
2769 +
2770 + // Set both transients - the error notice and the URL status
2771 + set_transient('mxchat_admin_notice_error',
2772 + esc_html__('No valid content found on the provided URL.', 'mxchat'),
2773 + 30
2774 + );
2775 +
2776 + // Set URL status transient
2777 + set_transient('mxchat_single_url_status', [
2778 + 'url' => $submitted_url,
2779 + 'timestamp' => current_time('mysql'),
2780 + 'status' => 'failed',
2781 + 'error' => esc_html__('No valid content found on the provided URL.', 'mxchat')
2782 + ], DAY_IN_SECONDS);
2783 +
2784 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2785 + exit;
2786 +}
2787 +
2788 +//error_log('[MXCHAT-URL] Generating embedding for content');
2789 +$embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2790 +
2791 +// Check if embedding_vector is a string (error message)
2792 +if (is_string($embedding_vector)) {
2793 + //error_log('[MXCHAT-URL] Error generating embedding: ' . $embedding_vector);
2794 + $error_message = esc_html__('Failed to generate embedding: ', 'mxchat') . esc_html($embedding_vector);
2795 + //error_log('[MXCHAT-URL] Setting error transient: ' . $error_message);
2796 +
2797 + // Set both transients
2798 + set_transient('mxchat_admin_notice_error', $error_message, 30);
2799 +
2800 + // Set URL status transient
2801 + set_transient('mxchat_single_url_status', [
2802 + 'url' => $submitted_url,
2803 + 'timestamp' => current_time('mysql'),
2804 + 'status' => 'failed',
2805 + 'error' => $error_message
2806 + ], DAY_IN_SECONDS);
2807 +
2808 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2809 + exit;
2810 +}
2811 +
2812 +if (is_array($embedding_vector)) {
2813 + //error_log('[MXCHAT-URL] Successfully generated embedding with ' . count($embedding_vector) . ' dimensions');
2814 +
2815 + $db_result = MxChat_Utils::submit_content_to_db(
2816 + $sanitized_content,
2817 + $submitted_url,
2818 + $this->options['api_key']
2819 + );
2820 +
2821 + if (is_wp_error($db_result)) {
2822 + //error_log('[MXCHAT-URL] Error: Failed to store content in database: ' . $db_result->get_error_message());
2823 + $error_message = esc_html__('Failed to store content in database: ', 'mxchat') . esc_html($db_result->get_error_message());
2824 + //error_log('[MXCHAT-URL] Setting error transient: ' . $error_message);
2825 +
2826 + // Set both transients
2827 + set_transient('mxchat_admin_notice_error', $error_message, 30);
2828 +
2829 + // Set URL status transient
2830 + set_transient('mxchat_single_url_status', [
2831 + 'url' => $submitted_url,
2832 + 'timestamp' => current_time('mysql'),
2833 + 'status' => 'failed',
2834 + 'error' => $error_message
2835 + ], DAY_IN_SECONDS);
2836 +
2107 2837 wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2108 2838 exit;
2109 2839 }
2110 2840
2111 - $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
2112 - if (is_array($embedding_vector)) {
2113 - MxChat_Utils::submit_content_to_db(
2114 - $sanitized_content,
2115 - $submitted_url,
2116 - $this->options['api_key']
2117 - );
2118 - set_transient('mxchat_admin_notice_success',
2119 - esc_html__('URL content successfully submitted!', 'mxchat'),
2120 - 30
2121 - );
2122 - } else {
2123 - set_transient('mxchat_admin_notice_error',
2124 - esc_html__('Failed to generate embedding for the URL content. Please check your API key and try again.', 'mxchat'),
2125 - 30
2126 - );
2841 + //error_log('[MXCHAT-URL] Successfully stored content in database');
2842 + $success_message = esc_html__('URL content successfully submitted!', 'mxchat');
2843 + //error_log('[MXCHAT-URL] Setting success transient: ' . $success_message);
2844 +
2845 + // Set both transients
2846 + set_transient('mxchat_admin_notice_success', $success_message, 30);
2847 +
2848 + // Set URL status transient with success
2849 + set_transient('mxchat_single_url_status', [
2850 + 'url' => $submitted_url,
2851 + 'timestamp' => current_time('mysql'),
2852 + 'status' => 'complete',
2853 + 'content_length' => strlen($sanitized_content),
2854 + 'embedding_dimensions' => count($embedding_vector)
2855 + ], DAY_IN_SECONDS);
2856 +
2857 +} else {
2858 + //error_log('[MXCHAT-URL] Error: Failed to generate embedding. Unexpected result type: ' . gettype($embedding_vector));
2859 + $error_message = esc_html__('Failed to generate embedding: Unexpected result type. Please check your API key and try again.', 'mxchat');
2860 + //error_log('[MXCHAT-URL] Setting error transient: ' . $error_message);
2861 +
2862 + // Set both transients
2863 + set_transient('mxchat_admin_notice_error', $error_message, 30);
2864 +
2865 + // Set URL status transient
2866 + set_transient('mxchat_single_url_status', [
2867 + 'url' => $submitted_url,
2868 + 'timestamp' => current_time('mysql'),
2869 + 'status' => 'failed',
2870 + 'error' => $error_message
2871 + ], DAY_IN_SECONDS);
2872 +}
2873 +
2874 +//error_log('[MXCHAT-URL] ===== Completed URL submission process =====');
2875 +wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2876 +exit;
2877 +}
2878 +/**
2879 + * Get the status of the last single URL submission
2880 + */
2881 +private function get_single_url_status() {
2882 + $status = get_transient('mxchat_single_url_status');
2883 + if (!$status) {
2884 + return null;
2127 2885 }
2886 +
2887 + // Add human-readable time
2888 + if (isset($status['timestamp'])) {
2889 + $status['human_time'] = human_time_diff(strtotime($status['timestamp']), current_time('timestamp')) . ' ' . __('ago', 'mxchat');
2890 + }
2891 +
2892 + return $status;
2893 +}
2128 2894
2129 - wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
2130 - exit;
2131 -}
2132 2895 private function handle_sitemap_for_knowledge_base($xml, $sitemap_url) {
2896 + // Clear any single URL status when starting sitemap processing
2897 + delete_transient('mxchat_single_url_status');
2133 2898 if (!current_user_can('manage_options')) {
2134 2899 //error_log(esc_html__('Unauthorized sitemap processing attempt', 'mxchat'));
2135 2900 return false;
2136 2901 }
@@ -2141,8 +2906,40 @@
2141 2906 if (!$xml || !is_object($xml)) {
2142 2907 throw new Exception(__('Invalid XML object provided', 'mxchat'));
2143 2908 }
2144 2909
2910 + // Add embedding validation before processing
2911 + // Test embedding with a small sample text to verify API key is working
2912 + $test_result = $this->mxchat_generate_embedding("This is a test to verify the embedding API key is working.");
2913 +
2914 + // Check if test_result is a string (error message) rather than an array (valid embedding)
2915 + if (is_string($test_result)) {
2916 + //error_log('[MXCHAT-URL] Embedding API validation failed: ' . $test_result);
2917 +
2918 + // Store the error in the status transient so it can be displayed later
2919 + $status_data = array(
2920 + 'total_urls' => 0,
2921 + 'processed_urls' => 0,
2922 + 'status' => 'error',
2923 + 'error' => __('Embedding API validation failed: ', 'mxchat') . $test_result,
2924 + 'last_update' => time()
2925 + );
2926 +
2927 + set_transient(
2928 + sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)),
2929 + array_map('sanitize_text_field', $status_data),
2930 + DAY_IN_SECONDS
2931 + );
2932 +
2933 + throw new Exception(__('Embedding API validation failed: ', 'mxchat') . $test_result);
2934 + }
2935 +
2936 + // Make sure it's an array (valid embedding)
2937 + if (!is_array($test_result)) {
2938 + //error_log('[MXCHAT-URL] Embedding API returned unexpected result type: ' . gettype($test_result));
2939 + throw new Exception(__('Embedding API returned unexpected result type. Please check your configuration.', 'mxchat'));
2940 + }
2941 +
2145 2942 $urls = [];
2146 2943 foreach ($xml->url as $url_element) {
2147 2944 $url = esc_url_raw((string)$url_element->loc);
2148 2945 if ($url) {
@@ -2179,12 +2976,36 @@
2179 2976
2180 2977 return __('scheduled', 'mxchat');
2181 2978
2182 2979 } catch (\Exception $e) {
2183 - //error_log(sprintf(esc_html__('Error preparing sitemap for processing: %s', 'mxchat'), esc_html($e->getMessage())));
2184 - return false;
2980 + $error_message = $e->getMessage();
2981 + //error_log(sprintf(esc_html__('Error preparing sitemap for processing: %s', 'mxchat'), esc_html($error_message)));
2982 +
2983 + // Store the sitemap URL and error in transients so they can be displayed
2984 + set_transient(
2985 + 'mxchat_last_sitemap_url',
2986 + sanitize_text_field($sitemap_url),
2987 + DAY_IN_SECONDS
2988 + );
2989 +
2990 + $status_data = array(
2991 + 'total_urls' => 0,
2992 + 'processed_urls' => 0,
2993 + 'status' => 'error',
2994 + 'error' => $error_message,
2995 + 'last_update' => time()
2996 + );
2997 +
2998 + set_transient(
2999 + sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)),
3000 + array_map('sanitize_text_field', $status_data),
3001 + DAY_IN_SECONDS
3002 + );
3003 +
3004 + return $error_message;
2185 3005 }
2186 3006 }
3007 +
2187 3008 public static function process_sitemap_urls_cron($urls, $sitemap_url, $total_urls, $batch_size, $batch_pause) {
2188 3009 // Validate inputs
2189 3010 $sitemap_url = esc_url_raw($sitemap_url);
2190 3011 $total_urls = absint($total_urls);
@@ -2202,8 +3023,13 @@
2202 3023 if (!$status || !is_array($status)) {
2203 3024 throw new Exception('Invalid status data retrieved from transient');
2204 3025 }
2205 3026
3027 + // Initialize failed_urls array if it doesn't exist
3028 + if (!isset($status['failed_urls_list']) || !is_array($status['failed_urls_list'])) {
3029 + $status['failed_urls_list'] = [];
3030 + }
3031 +
2206 3032 $start_url = absint($status['processed_urls']);
2207 3033 $end_url = min($start_url + $batch_size, $total_urls);
2208 3034 $instance = new self();
2209 3035
@@ -2210,11 +3036,38 @@
2210 3036 // Track failures in batch
2211 3037 $batch_stats = [
2212 3038 'processed' => 0,
2213 3039 'failed' => 0,
2214 - 'last_error' => ''
3040 + 'last_error' => '',
3041 + 'embedding_errors' => 0 // Track specifically embedding errors
2215 3042 ];
2216 3043
3044 + // Check embedding configuration with first URL
3045 + if ($start_url === 0) {
3046 + $page_url = esc_url_raw($urls[0]);
3047 + $page_response = wp_remote_get($page_url);
3048 +
3049 + if (!is_wp_error($page_response) && wp_remote_retrieve_response_code($page_response) === 200) {
3050 + $page_html = wp_remote_retrieve_body($page_response);
3051 + $page_content = $instance->mxchat_extract_main_content($page_html);
3052 + $sanitized_content = $instance->mxchat_sanitize_content_for_api($page_content);
3053 +
3054 + if (!empty($sanitized_content)) {
3055 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content);
3056 +
3057 + // Check if embedding_vector is a string (error message)
3058 + if (is_string($embedding_vector)) {
3059 + throw new Exception('Embedding generation failed: ' . $embedding_vector);
3060 + }
3061 +
3062 + // Make sure it's an array (valid embedding)
3063 + if (!is_array($embedding_vector)) {
3064 + throw new Exception('Embedding generation returned unexpected result type: ' . gettype($embedding_vector));
3065 + }
3066 + }
3067 + }
3068 + }
3069 +
2217 3070 for ($i = $start_url; $i < $end_url; $i++) {
2218 3071 $page_url = esc_url_raw($urls[$i]);
2219 3072 $page_response = wp_remote_get($page_url);
2220 3073
@@ -2219,8 +3072,18 @@
2219 3072 $page_response = wp_remote_get($page_url);
2220 3073
2221 3074 if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
2222 3075 $batch_stats['failed']++;
3076 + $error_message = is_wp_error($page_response) ? $page_response->get_error_message() : 'HTTP Status: ' . wp_remote_retrieve_response_code($page_response);
3077 + $batch_stats['last_error'] = 'Failed to fetch URL: ' . $error_message;
3078 +
3079 + // Add to failed URLs list with error message
3080 + $status['failed_urls_list'][] = [
3081 + 'url' => $page_url,
3082 + 'error' => $error_message,
3083 + 'time' => time()
3084 + ];
3085 +
2223 3086 continue;
2224 3087 }
2225 3088
2226 3089 $page_html = wp_remote_retrieve_body($page_response);
@@ -2229,8 +3092,29 @@
2229 3092
2230 3093 if (!empty($sanitized_content)) {
2231 3094 $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content);
2232 3095
3096 + // Check if embedding_vector is a string (error message)
3097 + if (is_string($embedding_vector)) {
3098 + $batch_stats['failed']++;
3099 + $batch_stats['embedding_errors']++;
3100 + $batch_stats['last_error'] = 'Failed to generate embedding: ' . $embedding_vector;
3101 +
3102 + // Add to failed URLs list with error message
3103 + $status['failed_urls_list'][] = [
3104 + 'url' => $page_url,
3105 + 'error' => 'Embedding error: ' . $embedding_vector,
3106 + 'time' => time()
3107 + ];
3108 +
3109 + // If we have multiple embedding errors, stop processing
3110 + if ($batch_stats['embedding_errors'] >= 10) {
3111 + throw new Exception('Multiple embedding failures detected: ' . $embedding_vector);
3112 + }
3113 + continue;
3114 + }
3115 +
3116 + // Check if it's an array (valid embedding)
2233 3117 if (is_array($embedding_vector)) {
2234 3118 $options = get_option('mxchat_options');
2235 3119 $submission_result = MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $options['api_key']);
2236 3120
@@ -2236,8 +3120,16 @@
2236 3120
2237 3121 if (is_wp_error($submission_result)) {
2238 3122 $batch_stats['failed']++;
2239 3123 $batch_stats['last_error'] = $submission_result->get_error_message();
3124 +
3125 + // Add to failed URLs list with error message
3126 + $status['failed_urls_list'][] = [
3127 + 'url' => $page_url,
3128 + 'error' => 'Database submission error: ' . $submission_result->get_error_message(),
3129 + 'time' => time()
3130 + ];
3131 +
2240 3132 continue;
2241 3133 }
2242 3134
2243 3135 $batch_stats['processed']++;
@@ -2242,9 +3134,22 @@
2242 3134
2243 3135 $batch_stats['processed']++;
2244 3136 } else {
2245 3137 $batch_stats['failed']++;
2246 - $batch_stats['last_error'] = 'Failed to generate embedding. Please check OpenAI API key.';
3138 + $batch_stats['embedding_errors']++;
3139 + $batch_stats['last_error'] = 'Failed to generate embedding: Unexpected result type: ' . gettype($embedding_vector);
3140 +
3141 + // Add to failed URLs list with error message
3142 + $status['failed_urls_list'][] = [
3143 + 'url' => $page_url,
3144 + 'error' => 'Embedding error: Unexpected result type: ' . gettype($embedding_vector),
3145 + 'time' => time()
3146 + ];
3147 +
3148 + // If we have multiple embedding errors, stop processing
3149 + if ($batch_stats['embedding_errors'] >= 10) {
3150 + throw new Exception('Multiple embedding failures detected. Please check your embedding API configuration.');
3151 + }
2247 3152 }
2248 3153 }
2249 3154
2250 3155 $status['processed_urls'] = absint($i + 1);
@@ -2251,9 +3156,14 @@
2251 3156 $status['last_update'] = time();
2252 3157 $status['failed_urls'] = absint($status['failed_urls'] ?? 0) + $batch_stats['failed'];
2253 3158 $status['last_error'] = $batch_stats['last_error'];
2254 3159
2255 - set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3160 + // Limit the number of failed URLs we store to prevent transient size issues
3161 + if (count($status['failed_urls_list']) > 100) {
3162 + $status['failed_urls_list'] = array_slice($status['failed_urls_list'], -100);
3163 + }
3164 +
3165 + set_transient($status_key, $status, DAY_IN_SECONDS);
2256 3166 }
2257 3167
2258 3168 // If all URLs in this batch failed, stop processing
2259 3169 if ($batch_stats['processed'] === 0 && $batch_stats['failed'] > 0) {
@@ -2262,15 +3172,15 @@
2262 3172 'Processing stopped: %d consecutive failures. Last error: %s',
2263 3173 $batch_stats['failed'],
2264 3174 $batch_stats['last_error']
2265 3175 );
2266 - set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3176 + set_transient($status_key, $status, DAY_IN_SECONDS);
2267 3177 return;
2268 3178 }
2269 3179
2270 3180 if ($end_url < $total_urls) {
2271 3181 wp_schedule_single_event(time() + $batch_pause, 'mxchat_process_sitemap_urls', array(
2272 - 'urls' => array_map('esc_url_raw', $urls),
3182 + 'urls' => $urls,
2273 3183 'sitemap_url' => $sitemap_url,
2274 3184 'total_urls' => $total_urls,
2275 3185 'batch_size' => $batch_size,
2276 3186 'batch_pause' => $batch_pause,
@@ -2276,17 +3186,249 @@
2276 3186 'batch_pause' => $batch_pause,
2277 3187 ));
2278 3188 } else {
2279 3189 $status['status'] = 'complete';
2280 - set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3190 + set_transient($status_key, $status, DAY_IN_SECONDS);
2281 3191 }
2282 3192 } catch (\Exception $e) {
2283 3193 $status['status'] = 'error';
2284 - $status['error'] = sanitize_text_field($e->getMessage());
2285 - set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3194 + $status['error'] = $e->getMessage();
3195 + set_transient($status_key, $status, DAY_IN_SECONDS);
2286 3196 }
2287 3197 }
2288 3198
3199 +private function mxchat_sanitize_content_for_api($content) {
3200 + //error_log('[MXCHAT-SANITIZE] Original content preview: ' . substr($content, 0, 500) . '...');
3201 +
3202 + // Remove script, style tags, and HTML comments
3203 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
3204 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
3205 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
3206 +
3207 + // Remove all HTML tags and decode HTML entities
3208 + $content = wp_strip_all_tags($content);
3209 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
3210 +
3211 + // Trim and normalize whitespace
3212 + $content = trim(preg_replace('/\s+/', ' ', $content));
3213 +
3214 + // Remove control characters (which can cause database issues)
3215 + $content = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $content);
3216 +
3217 + // Remove NULL bytes which can cause database errors
3218 + $content = str_replace("\0", "", $content);
3219 +
3220 + // Ensure valid UTF-8 encoding
3221 + $content = wp_check_invalid_utf8($content);
3222 +
3223 + // Remove any extremely long strings without spaces (often garbage)
3224 + $content = preg_replace('/\S{300,}/', ' ', $content);
3225 +
3226 + // Replace problematic characters that often cause database issues
3227 + $content = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $content); // Remove emoji and other high Unicode characters
3228 +
3229 + // Replace any remaining potentially problematic characters with spaces
3230 + $content = preg_replace('/[^\p{L}\p{N}\p{P}\p{Z}\p{Sm}]/u', ' ', $content);
3231 +
3232 + // Limit to reasonable length if needed
3233 + $max_length = 65000; // Just under MySQL TEXT field limit
3234 + if (strlen($content) > $max_length) {
3235 + $content = substr($content, 0, $max_length);
3236 + }
3237 +
3238 + //error_log('[MXCHAT-SANITIZE] Sanitized content preview: ' . substr($content, 0, 500) . '...');
3239 + return $content;
3240 +}
3241 +private static function mxchat_extract_main_content($html) {
3242 + if (empty($html)) {
3243 + return '';
3244 + }
3245 + try {
3246 + $dom = new DOMDocument;
3247 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
3248 + @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
3249 + $xpath = new DOMXPath($dom);
3250 +
3251 + // For debugging purposes
3252 + $debugEnabled = false; // Set to true to enable debugging output
3253 + $debug = function($message) use ($debugEnabled) {
3254 + if ($debugEnabled) {
3255 + //error_log('[MXCHAT-DEBUG] ' . $message);
3256 + }
3257 + };
3258 +
3259 + // Direct targeting for Gerow theme posts
3260 + $post_text = $xpath->query('//div[contains(@class, "post-text")]');
3261 + if ($post_text && $post_text->length > 0) {
3262 + $debug("Found post-text directly");
3263 + $content = '';
3264 + foreach ($post_text as $node) {
3265 + $content .= $dom->saveHTML($node);
3266 + }
3267 + if (!empty($content)) {
3268 + $debug("Returning post-text content");
3269 + return $content;
3270 + }
3271 + }
3272 +
3273 + // Try to get the blog details content which contains the post-text
3274 + $blog_details = $xpath->query('//div[contains(@class, "blog-details-content")]');
3275 + if ($blog_details && $blog_details->length > 0) {
3276 + $debug("Found blog-details-content");
3277 + $content = '';
3278 + foreach ($blog_details as $node) {
3279 + $content .= $dom->saveHTML($node);
3280 + }
3281 + if (!empty($content)) {
3282 + $debug("Returning blog-details-content");
3283 + return $content;
3284 + }
3285 + }
3286 +
3287 + // Try to get the article which contains the blog details
3288 + $article = $xpath->query('//article[contains(@class, "blog-details-wrap")]');
3289 + if ($article && $article->length > 0) {
3290 + $debug("Found article with blog-details-wrap");
3291 + $content = '';
3292 + foreach ($article as $node) {
3293 + $content .= $dom->saveHTML($node);
3294 + }
3295 + if (!empty($content)) {
3296 + $debug("Returning article content");
3297 + return $content;
3298 + }
3299 + }
3300 +
3301 + // Try even broader with the blog-item-wrap
3302 + $blog_item = $xpath->query('//div[contains(@class, "blog-item-wrap")]');
3303 + if ($blog_item && $blog_item->length > 0) {
3304 + $debug("Found blog-item-wrap");
3305 + $content = '';
3306 + foreach ($blog_item as $node) {
3307 + $content .= $dom->saveHTML($node);
3308 + }
3309 + if (!empty($content)) {
3310 + $debug("Returning blog-item-wrap content");
3311 + return $content;
3312 + }
3313 + }
3314 +
3315 + // Specific Gerow theme path
3316 + $gerow_path = $xpath->query('//section[contains(@class, "blog-area")]//div[contains(@class, "post-text")]');
3317 + if ($gerow_path && $gerow_path->length > 0) {
3318 + $debug("Found Gerow theme path to post-text");
3319 + $content = '';
3320 + foreach ($gerow_path as $node) {
3321 + $content .= $dom->saveHTML($node);
3322 + }
3323 + if (!empty($content)) {
3324 + $debug("Returning Gerow post-text content");
3325 + return $content;
3326 + }
3327 + }
3328 +
3329 + // Generic blog post selectors
3330 + $selectors = [
3331 + // Blog post specific selectors
3332 + '//div[contains(@class, "post-text")]',
3333 + '//article[contains(@class, "blog-post-item")]//div[contains(@class, "post-text")]',
3334 + '//div[contains(@class, "blog-details-content")]',
3335 + '//article[contains(@class, "blog-details-wrap")]',
3336 + '//div[contains(@class, "entry-content")]',
3337 + '//div[contains(@class, "blog-content")]',
3338 + '//div[contains(@class, "blog-item-wrap")]',
3339 +
3340 + // More general content selectors
3341 + '//div[contains(@class, "page__content")]',
3342 + '//div[contains(@class, "elementor-widget-container")]',
3343 + '//div[contains(@class, "elementor-text-editor")]',
3344 + '//div[contains(@class, "elementor-widget-text-editor")]',
3345 + '//*[contains(@class, "entry-content")]',
3346 + '//*[contains(@class, "post-content")]',
3347 + '//*[contains(@class, "article-content")]',
3348 + '//*[@id="content"]',
3349 + '//*[@id="main-content"]',
3350 + '//section[contains(@class, "blog-area")]',
3351 + '//article',
3352 + '//main',
3353 + '//div[contains(@class, "content")]'
3354 + ];
3355 +
3356 + // First handle Elementor content
3357 + $debug("Checking for Elementor content");
3358 + $elementor_widgets = $xpath->query('//div[contains(@class, "elementor-element")]//div[contains(@class, "elementor-widget-container")]');
3359 + if ($elementor_widgets && $elementor_widgets->length > 0) {
3360 + $debug("Found Elementor widgets");
3361 + $combined_content = '';
3362 + foreach ($elementor_widgets as $widget) {
3363 + $widget_content = $dom->saveHTML($widget);
3364 + if (!empty($widget_content)) {
3365 + $combined_content .= $widget_content;
3366 + }
3367 + }
3368 + if (!empty($combined_content)) {
3369 + $debug("Returning Elementor content");
3370 + return $combined_content;
3371 + }
3372 + }
3373 +
3374 + // Try standard selectors one by one
3375 + foreach ($selectors as $selector) {
3376 + $debug("Trying selector: " . $selector);
3377 + $nodes = $xpath->query($selector);
3378 + if ($nodes && $nodes->length > 0) {
3379 + $debug("Found matches for selector: " . $selector);
3380 + $content = '';
3381 + foreach ($nodes as $node) {
3382 + $content .= $dom->saveHTML($node);
3383 + }
3384 + if (!empty($content)) {
3385 + $debug("Returning content from selector: " . $selector);
3386 + return $content;
3387 + }
3388 + }
3389 + }
3390 +
3391 + // Manual regex fallback for post-text if DOM methods fail
3392 + $debug("Trying regex fallback");
3393 + if (preg_match('/<div class="post-text">(.*?)<\/div>\s*<\/div>\s*<\/div>/s', $html, $matches)) {
3394 + $debug("Found post-text via regex");
3395 + return '<div class="post-text">' . $matches[1] . '</div>';
3396 + }
3397 +
3398 + // Try to extract the blog section as a whole
3399 + $blog_section = $xpath->query('//section[contains(@class, "blog-area")]');
3400 + if ($blog_section && $blog_section->length > 0) {
3401 + $debug("Found blog-area section");
3402 + $content = '';
3403 + foreach ($blog_section as $node) {
3404 + $content .= $dom->saveHTML($node);
3405 + }
3406 + if (!empty($content)) {
3407 + $debug("Returning blog-area section content");
3408 + return $content;
3409 + }
3410 + }
3411 +
3412 + // Fallback: Return the body content if no specific selector matches
3413 + $debug("Using body fallback");
3414 + $body = $dom->getElementsByTagName('body');
3415 + if ($body->length > 0) {
3416 + return $dom->saveHTML($body->item(0));
3417 + }
3418 +
3419 + // Last resort: return the original HTML
3420 + $debug("Returning original HTML");
3421 + return $html;
3422 + } catch (Exception $e) {
3423 + //error_log('[MXCHAT-ERROR] Content extraction failed: ' . $e->getMessage());
3424 + return $html; // Return original HTML if parsing fails
3425 + } finally {
3426 + libxml_clear_errors();
3427 + }
3428 +}
3429 +
3430 +
2289 3431 public function get_sitemap_processing_status($sitemap_url) {
2290 3432 $sitemap_url = esc_url_raw($sitemap_url);
2291 3433 $status = get_transient(sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)));
2292 3434
@@ -2298,17 +3440,53 @@
2298 3440 'total_urls' => absint($status['total_urls']),
2299 3441 'processed_urls' => absint($status['processed_urls']),
2300 3442 'failed_urls' => absint($status['failed_urls'] ?? 0),
2301 3443 'percentage' => ($status['total_urls'] > 0)
2302 - ? round((absint($status['processed_urls']) / absint($status['total_urls'])) * 100)
2303 - : 0,
3444 + ? round((absint($status['processed_urls']) / absint($status['total_urls'])) * 100)
3445 + : 0,
2304 3446 'status' => sanitize_text_field($status['status']),
2305 3447 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ' . esc_html__('ago', 'mxchat'),
2306 3448 'error' => isset($status['error']) ? sanitize_text_field($status['error']) : '',
2307 - 'last_error' => isset($status['last_error']) ? sanitize_text_field($status['last_error']) : ''
3449 + 'last_error' => isset($status['last_error']) ? sanitize_text_field($status['last_error']) : '',
3450 + 'failed_urls_list' => isset($status['failed_urls_list']) ? $status['failed_urls_list'] : array()
2308 3451 );
2309 3452 }
3453 +public function ajax_get_status_updates() {
3454 + // Verify the request
3455 + check_ajax_referer('mxchat_status_nonce', 'nonce');
2310 3456
3457 + // Get the status just like in your admin page
3458 + $pdf_url = get_transient('mxchat_last_pdf_url');
3459 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
3460 + $pdf_status = $pdf_url ? $this->get_pdf_processing_status($pdf_url) : false;
3461 + $sitemap_status = $sitemap_url ? $this->get_sitemap_processing_status($sitemap_url) : false;
3462 +
3463 + // Check for true processing status, not just presence of status
3464 + $is_active_processing =
3465 + ($sitemap_status && $sitemap_status['status'] === 'processing') ||
3466 + ($pdf_status && $pdf_status['status'] === 'processing');
3467 +
3468 + // Get single URL status, but only if no sitemap/PDF is processing
3469 + $single_url_status = !$is_active_processing ? $this->get_single_url_status() : false;
3470 +
3471 + // Only clear transients for completed processes, not error states
3472 + if ($pdf_status && $pdf_status['status'] === 'complete') {
3473 + delete_transient('mxchat_last_pdf_url');
3474 + $pdf_status = false;
3475 + }
3476 + if ($sitemap_status && $sitemap_status['status'] === 'complete') {
3477 + delete_transient('mxchat_last_sitemap_url');
3478 + $sitemap_status = false;
3479 + }
3480 +
3481 + // Return JSON response with the status data
3482 + wp_send_json(array(
3483 + 'pdf_status' => $pdf_status,
3484 + 'sitemap_status' => $sitemap_status,
3485 + 'single_url_status' => $single_url_status,
3486 + 'is_processing' => $is_active_processing
3487 + ));
3488 +}
2311 3489 public function mxchat_stop_processing() {
2312 3490 // Verify permissions
2313 3491 if (!current_user_can('manage_options')) {
2314 3492 wp_die(esc_html__('Unauthorized access', 'mxchat'));
@@ -2344,27 +3522,10 @@
2344 3522 );
2345 3523 wp_safe_redirect(admin_url('admin.php?page=mxchat-prompts'));
2346 3524 exit;
2347 3525 }
2348 -private function mxchat_sanitize_content_for_api($content) {
2349 - // Remove script, style tags, and HTML comments
2350 - $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
2351 - $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
2352 - $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
2353 3526
2354 - // Remove all HTML tags and decode HTML entities
2355 - $content = wp_strip_all_tags($content);
2356 - $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
2357 3527
2358 - // Trim and normalize whitespace
2359 - $content = trim(preg_replace('/\s+/', ' ', $content));
2360 -
2361 - return $content;
2362 -}
2363 -
2364 -
2365 -
2366 -
2367 3528 public function mxchat_handle_product_change($post_id, $post, $update) {
2368 3529 if ($post->post_type !== 'product') {
2369 3530 return;
2370 3531 }
@@ -2377,9 +3538,8 @@
2377 3538 }
2378 3539 });
2379 3540 }
2380 3541 }
2381 -
2382 3542 private function mxchat_store_product_embedding($product) {
2383 3543 if (!isset($this->options['enable_woocommerce_integration']) ||
2384 3544 !in_array($this->options['enable_woocommerce_integration'], ['1', 'on'])) {
2385 3545 return;
@@ -2435,9 +3595,8 @@
2435 3595 // Use WordPress DB storage
2436 3596 $this->store_in_wordpress_db($description, $source_url, $embedding_vector);
2437 3597 }
2438 3598 }
2439 -
2440 3599 public function mxchat_handle_product_delete($post_id) {
2441 3600 if (get_post_type($post_id) !== 'product') {
2442 3601 return;
2443 3602 }
@@ -2624,9 +3783,9 @@
2624 3783 </div>
2625 3784 <?php
2626 3785 }
2627 3786
2628 -public function mxchat_intents_page_html() {
3787 +public function mxchat_actions_page_html() {
2629 3788 if (!current_user_can('manage_options')) {
2630 3789 return;
2631 3790 }
2632 3791
@@ -2639,9 +3798,9 @@
2639 3798
2640 3799 // Success message
2641 3800 if (isset($_GET['updated']) && $_GET['updated'] === 'true') {
2642 3801 echo '<div class="notice notice-success is-dismissible"><p>' .
2643 - esc_html__('Intent updated successfully.', 'mxchat') .
3802 + esc_html__('Action updated successfully.', 'mxchat') .
2644 3803 '</p></div>';
2645 3804 }
2646 3805
2647 3806 // Filtering logic
@@ -2662,10 +3821,10 @@
2662 3821 // Pagination
2663 3822 $total_intents = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE $where");
2664 3823 $total_pages = ceil($total_intents / $per_page);
2665 3824
2666 - // Get intents
2667 - $intents = $wpdb->get_results($wpdb->prepare(
3825 + // Get intents (now called actions)
3826 + $actions = $wpdb->get_results($wpdb->prepare(
2668 3827 "SELECT * FROM $table_name WHERE $where LIMIT %d OFFSET %d",
2669 3828 $per_page, $offset
2670 3829 ));
2671 3830
@@ -2670,441 +3829,619 @@
2670 3829 ));
2671 3830
2672 3831 // Get callbacks
2673 3832 $available_callbacks = $this->mxchat_get_available_callbacks();
2674 -
3833 +
2675 3834 ?>
2676 3835 <div class="wrap mxchat-wrapper">
2677 3836 <!-- Hero Section -->
2678 3837 <div class="mxchat-hero">
2679 3838 <h1 class="mxchat-main-title">
2680 - <span class="mxchat-gradient-text">Intent</span> Manager
3839 + <span class="mxchat-gradient-text">Actions</span> Manager
2681 3840 </h1>
2682 3841 <p class="mxchat-hero-subtitle">
2683 - <?php esc_html_e('Create and manage custom intents to enhance your chatbots understanding and response capabilities.', 'mxchat'); ?>
3842 + <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
2684 3843 </p>
2685 3844 </div>
2686 3845
2687 - <div class="mxchat-content">
2688 - <!-- Add Intent Card -->
2689 - <div class="mxchat-card">
2690 - <div class="mxchat-card-header">
2691 - <h2><?php esc_html_e('Add New Intent', 'mxchat'); ?></h2>
2692 - </div>
2693 -
2694 - <div class="mxchat-intent-documentation">
2695 - <p>
2696 - <?php esc_html_e('We highly encourage users to quickly read our ', 'mxchat'); ?>
2697 - <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">
2698 - <?php esc_html_e('documentation', 'mxchat'); ?>
2699 - </a>
2700 - <?php esc_html_e(' to better understand intents. Some intents require setup in the Integration tab. If your intent is not triggering lower similarity threshold test.', 'mxchat'); ?>
2701 - </p>
2702 - </div>
2703 -
2704 - <form id="mxchat-add-intent-form" method="post"
2705 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
2706 - <input type="hidden" name="action" value="mxchat_add_intent">
2707 - <?php wp_nonce_field('mxchat_add_intent_nonce'); ?>
2708 -
2709 - <div class="mxchat-form-group">
2710 - <label for="intent_label">
2711 - <?php esc_html_e('Intent Label (For your reference only)', 'mxchat'); ?>
2712 - </label>
2713 - <input name="intent_label" type="text" id="intent_label" required
2714 - class="mxchat-intent-input"
2715 - placeholder="<?php esc_attr_e('Example Email Capture: Newsletter Signup', 'mxchat'); ?>">
3846 + <!-- Actions Header with Search and Filter -->
3847 + <div class="mxchat-actions-header">
3848 + <div class="mxchat-actions-filters">
3849 + <form method="get" class="mxchat-search-form">
3850 + <input type="hidden" name="page" value="mxchat-actions">
3851 + <div class="mxchat-search-group">
3852 + <span class="dashicons dashicons-search"></span>
3853 + <input type="text" name="s" class="mxchat-search-input"
3854 + placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
3855 + value="<?php echo esc_attr($search_term); ?>">
2716 3856 </div>
2717 -
2718 - <div class="mxchat-form-group">
2719 - <label for="phrases">
2720 - <?php esc_html_e('Phrases (comma-separated)', 'mxchat'); ?>
2721 - </label>
2722 - <textarea name="phrases" id="phrases" rows="5" required
2723 - class="mxchat-intent-textarea"
2724 - placeholder="<?php esc_attr_e('Example Email Capture: sign me up, subscribe me, I want to join, add me to the newsletter, send me updates, keep me informed', 'mxchat'); ?>"></textarea>
2725 - </div>
2726 -
2727 - <div class="mxchat-form-group">
2728 - <label for="callback_function">
2729 - <?php esc_html_e('Callback Function', 'mxchat'); ?>
2730 - </label>
2731 - <select name="callback_function" id="callback_function"
2732 - class="mxchat-intent-select" required>
2733 - <option value="">
2734 - <?php esc_html_e('Select a Callback', 'mxchat'); ?>
3857 + <select name="callback_filter" class="mxchat-action-filter">
3858 + <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
3859 + <?php foreach ($available_callbacks as $function => $callback_data) :
3860 + $label = $callback_data['label']; ?>
3861 + <option value="<?php echo esc_attr($function); ?>"
3862 + <?php selected($callback_filter, $function); ?>>
3863 + <?php echo esc_html($label); ?>
2735 3864 </option>
2736 - <?php
2737 - $groups = $this->mxchat_get_available_callbacks(true);
2738 - foreach ($groups as $group_label => $group_callbacks) :
2739 - echo '<optgroup label="' . esc_attr($group_label) . '">';
2740 - foreach ($group_callbacks as $function => $data) :
2741 - $label = $data['label'];
2742 - $pro_only = $data['pro_only'];
2743 - $disabled = (!$this->is_activated && $pro_only) ? 'disabled' : '';
2744 - $label_suffix = (!$this->is_activated && $pro_only) ? ' (Pro Only)' : '';
2745 - ?>
2746 - <option value="<?php echo esc_attr($function); ?>"
2747 - <?php echo $disabled; ?>>
2748 - <?php echo esc_html($label . $label_suffix); ?>
2749 - </option>
2750 - <?php
2751 - endforeach;
2752 - echo '</optgroup>';
2753 - endforeach;
2754 - ?>
2755 - </select>
2756 - </div>
2757 -
2758 - <button type="submit" class="mxchat-button-primary">
2759 - <?php esc_html_e('Add Intent', 'mxchat'); ?>
3865 + <?php endforeach; ?>
3866 + </select>
3867 + <button type="submit" class="mxchat-button-secondary">
3868 + <?php esc_html_e('Filter', 'mxchat'); ?>
2760 3869 </button>
2761 3870 </form>
2762 3871 </div>
3872 + <div class="mxchat-actions-controls">
3873 + <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
3874 + <span class="dashicons dashicons-plus-alt"></span>
3875 + <?php esc_html_e('Add New Action', 'mxchat'); ?>
3876 + </button>
3877 + </div>
3878 + </div>
2763 3879
2764 - <!-- Manage Intents Card -->
2765 - <div class="mxchat-card">
2766 - <div class="mxchat-card-header">
2767 - <h2><?php esc_html_e('Manage Intents', 'mxchat'); ?></h2>
2768 - <div class="mxchat-header-actions">
2769 - <form method="get" class="mxchat-search-form">
2770 - <input type="hidden" name="page" value="mxchat-intents">
2771 - <div class="mxchat-search-group">
2772 - <span class="dashicons dashicons-search"></span>
2773 - <input type="text" name="s"
2774 - placeholder="<?php esc_attr_e('Search Intents', 'mxchat'); ?>"
2775 - value="<?php echo esc_attr($search_term); ?>">
2776 - <select name="callback_filter" class="mxchat-intent-filter">
2777 - <option value="">
2778 - <?php esc_html_e('All Callbacks', 'mxchat'); ?>
2779 - </option>
2780 - <?php foreach ($available_callbacks as $function => $callback_data) :
2781 - $label = $callback_data['label']; ?>
2782 - <option value="<?php echo esc_attr($function); ?>"
2783 - <?php selected($callback_filter, $function); ?>>
2784 - <?php echo esc_html($label); ?>
2785 - </option>
2786 - <?php endforeach; ?>
2787 - </select>
2788 - <button type="submit" class="mxchat-button-secondary">
2789 - <?php esc_html_e('Filter', 'mxchat'); ?>
2790 - </button>
3880 + <!-- Actions Grid Layout - All actions in a single grid -->
3881 + <div class="mxchat-actions-grid">
3882 + <div class="mxchat-cards-container">
3883 + <?php if (!empty($actions)) : ?>
3884 + <?php foreach ($actions as $action) :
3885 + $callback_function = $action->callback_function;
3886 + $callback_label = isset($available_callbacks[$callback_function]['label'])
3887 + ? $available_callbacks[$callback_function]['label']
3888 + : $callback_function;
3889 + $threshold_value = isset($action->similarity_threshold)
3890 + ? round($action->similarity_threshold * 100)
3891 + : 85;
3892 +
3893 + // Check if this is a form action
3894 + $is_form_action = strpos($action->intent_label, 'Form ') === 0;
3895 +
3896 + // Get action status (enabled/disabled) - default to true if column doesn't exist
3897 + $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
3898 + ?>
3899 + <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
3900 + <div class="mxchat-card-header">
3901 + <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
3902 + <div class="mxchat-card-toggle">
3903 + <label class="mxchat-switch">
3904 + <input type="checkbox" class="mxchat-action-toggle"
3905 + data-action-id="<?php echo esc_attr($action->id); ?>"
3906 + <?php checked($is_enabled); ?>>
3907 + <span class="mxchat-slider round"></span>
3908 + </label>
3909 + </div>
2791 3910 </div>
2792 - </form>
2793 - </div>
2794 - </div>
2795 -
2796 - <div class="mxchat-table-wrapper">
2797 - <table class="mxchat-records-table">
2798 - <thead>
2799 - <tr>
2800 - <th><?php esc_html_e('Intent Label', 'mxchat'); ?></th>
2801 - <th><?php esc_html_e('Phrases', 'mxchat'); ?></th>
2802 - <th><?php esc_html_e('Callback Function', 'mxchat'); ?></th>
2803 - <th><?php esc_html_e('Similarity Threshold', 'mxchat'); ?></th>
2804 - <th><?php esc_html_e('Actions', 'mxchat'); ?></th>
2805 - </tr>
2806 - </thead>
2807 - <tbody>
2808 - <?php if ($intents) :
2809 - foreach ($intents as $intent) :
2810 - $callback_function = $intent->callback_function;
2811 - $callback_label = isset($available_callbacks[$callback_function]['label'])
2812 - ? $available_callbacks[$callback_function]['label']
2813 - : $callback_function;
2814 - $threshold_value = isset($intent->similarity_threshold)
2815 - ? round($intent->similarity_threshold * 100)
2816 - : 85;
2817 -
2818 - // Check if this is a form intent (its intent_label starts with "Form ")
2819 - $is_form_intent = strpos($intent->intent_label, 'Form ') === 0;
3911 +
3912 + <div class="mxchat-card-body">
3913 + <div class="mxchat-card-description">
3914 + <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
3915 + <?php echo esc_html($callback_label); ?>
3916 + </div>
3917 +
3918 + <div class="mxchat-card-phrases">
3919 + <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
3920 + <div class="mxchat-phrases-preview">
3921 + <?php
3922 + // Check if the helper function exists, otherwise use a simple substring
3923 + if (method_exists($this, 'get_trimmed_phrases')) {
3924 + echo esc_html($this->get_trimmed_phrases($action->phrases));
3925 + } else {
3926 + echo esc_html(strlen($action->phrases) > 100 ?
3927 + substr($action->phrases, 0, 97) . '...' :
3928 + $action->phrases);
3929 + }
2820 3930 ?>
2821 - <tr<?php echo $is_form_intent ? ' class="mxchat-form-intent"' : ''; ?>>
2822 - <td>
2823 - <?php
2824 - if ($is_form_intent) {
2825 - // Attempt to extract the form ID from the intent_label.
2826 - preg_match('/Form (\d+)/', $intent->intent_label, $matches);
2827 - $form_id = isset($matches[1]) ? intval($matches[1]) : 0;
2828 - if ($form_id) {
2829 - global $wpdb;
2830 - $forms_table = $wpdb->prefix . 'mxchat_forms';
2831 - $form = $wpdb->get_row($wpdb->prepare("SELECT title FROM $forms_table WHERE id = %d", $form_id));
2832 - if ($form && !empty($form->title)) {
2833 - echo esc_html($form->title);
2834 - } else {
2835 - echo esc_html($intent->intent_label);
2836 - }
2837 - } else {
2838 - echo esc_html($intent->intent_label);
2839 - }
2840 - echo ' <span class="mxchat-badge">Form Intent</span>';
2841 - } else {
2842 - echo esc_html($intent->intent_label);
2843 - }
2844 - ?>
2845 - </td>
2846 - <td class="mxchat-content-cell">
2847 - <?php echo esc_html($intent->phrases); ?>
2848 - </td>
2849 - <td><?php echo esc_html($callback_label); ?></td>
2850 - <td>
2851 - <!-- Similarity threshold adjustment (shown for all intents) -->
2852 - <form method="post"
2853 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
2854 - class="mxchat-threshold-form">
2855 - <?php wp_nonce_field('mxchat_update_intent_threshold_nonce'); ?>
2856 - <input type="hidden" name="action"
2857 - value="mxchat_update_intent_threshold">
2858 - <input type="hidden" name="intent_id"
2859 - value="<?php echo esc_attr($intent->id); ?>">
2860 - <div class="mxchat-slider-group">
2861 - <input type="range"
2862 - name="intent_threshold"
2863 - id="intent_threshold_<?php echo esc_attr($intent->id); ?>"
2864 - min="70"
2865 - max="95"
2866 - value="<?php echo esc_attr($threshold_value); ?>"
2867 - class="mxchat-intent-slider"
2868 - oninput="document.getElementById('threshold_output_<?php echo esc_attr($intent->id); ?>').value = this.value + '%'">
2869 - <output id="threshold_output_<?php echo esc_attr($intent->id); ?>"
2870 - class="mxchat-intent-output">
2871 - <?php echo esc_html($threshold_value); ?>%
2872 - </output>
2873 - </div>
2874 - <button type="submit" class="mxchat-button-icon">
2875 - <span class="dashicons dashicons-saved"></span>
2876 - </button>
2877 - </form>
2878 - </td>
2879 - <td class="mxchat-actions-cell">
2880 - <?php if (!$is_form_intent) : ?>
2881 - <!-- Standard intents: allow edit and delete -->
2882 - <button type="button"
2883 - class="mxchat-button-icon mxchat-edit-button"
2884 - data-intent-id="<?php echo esc_attr($intent->id); ?>"
2885 - data-phrases="<?php echo esc_attr($intent->phrases); ?>">
2886 - <span class="dashicons dashicons-edit"></span>
2887 - </button>
2888 - <form method="post"
2889 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
2890 - class="mxchat-delete-form"
2891 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this intent?', 'mxchat'); ?>');">
2892 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
2893 - <input type="hidden" name="action" value="mxchat_delete_intent">
2894 - <input type="hidden" name="intent_id"
2895 - value="<?php echo esc_attr($intent->id); ?>">
2896 - <button type="submit" class="mxchat-button-icon">
2897 - <span class="dashicons dashicons-trash"></span>
2898 - </button>
2899 - </form>
2900 - <?php else : ?>
2901 - <!-- Form intents: show manage in forms button -->
2902 - <?php
2903 - preg_match('/Form (\d+)/', $intent->intent_label, $matches);
2904 - $form_id = isset($matches[1]) ? $matches[1] : '';
2905 - ?>
2906 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
2907 - class="mxchat-button-secondary">
2908 - <?php esc_html_e('Manage in Forms', 'mxchat'); ?>
2909 - </a>
2910 - <?php endif; ?>
2911 - </td>
2912 - </tr>
2913 - <?php endforeach;
2914 - else : ?>
2915 - <tr>
2916 - <td colspan="5" class="mxchat-no-records">
2917 - <?php esc_html_e('No intents found.', 'mxchat'); ?>
2918 - </td>
2919 - </tr>
2920 - <?php endif; ?>
2921 - </tbody>
2922 - </table>
2923 - </div>
2924 -
2925 - <?php if ($total_pages > 1) : ?>
2926 - <div class="mxchat-pagination">
2927 - <?php
2928 - echo paginate_links(array(
2929 - 'base' => add_query_arg('paged', '%#%'),
2930 - 'format' => '',
2931 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
2932 - 'next_text' => __('Next &raquo;', 'mxchat'),
2933 - 'total' => $total_pages,
2934 - 'current' => $page
2935 - ));
2936 - ?>
3931 + </div>
3932 + </div>
3933 +
3934 + <div class="mxchat-threshold-control">
3935 + <div class="mxchat-threshold-label">
3936 + <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
3937 + <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
3938 + </div>
3939 + </div>
3940 + </div>
3941 +
3942 + <div class="mxchat-card-footer">
3943 + <?php
3944 + // Check if it's a form action
3945 + $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
3946 +
3947 + // Check if it's a recommendation flow action
3948 + $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
3949 +
3950 + if ($is_form_action) {
3951 + $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
3952 + ?>
3953 + <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
3954 + class="mxchat-button-primary">
3955 + <span class="dashicons dashicons-feedback"></span>
3956 + <?php esc_html_e('Edit Form', 'mxchat'); ?>
3957 + </a>
3958 + <?php } elseif ($is_flow_action) {
3959 + ?>
3960 + <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
3961 + class="mxchat-button-primary">
3962 + <span class="dashicons dashicons-list-view"></span>
3963 + <?php esc_html_e('Manage Flows', 'mxchat'); ?>
3964 + </a>
3965 + <?php } else { ?>
3966 + <button type="button"
3967 + class="mxchat-button-secondary mxchat-edit-button"
3968 + data-action-id="<?php echo esc_attr($action->id); ?>"
3969 + data-phrases="<?php echo esc_attr($action->phrases); ?>"
3970 + data-label="<?php echo esc_attr($action->intent_label); ?>"
3971 + data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
3972 + data-callback-function="<?php echo esc_attr($action->callback_function); ?>">
3973 + <span class="dashicons dashicons-edit"></span>
3974 + <?php esc_html_e('Edit', 'mxchat'); ?>
3975 + </button>
3976 + <form method="post"
3977 + action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
3978 + class="mxchat-delete-form"
3979 + onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
3980 + <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
3981 + <input type="hidden" name="action" value="mxchat_delete_intent">
3982 + <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
3983 + <button type="submit" class="mxchat-button-text mxchat-delete-button">
3984 + <span class="dashicons dashicons-trash"></span>
3985 + <?php esc_html_e('Delete', 'mxchat'); ?>
3986 + </button>
3987 + </form>
3988 + <?php } ?>
3989 + </div>
3990 +
3991 +
3992 + </div>
3993 + <?php endforeach; ?>
3994 + <?php else : ?>
3995 + <!-- If no actions found -->
3996 + <div class="mxchat-no-actions">
3997 + <div class="mxchat-empty-state">
3998 + <span class="dashicons dashicons-format-chat"></span>
3999 + <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4000 + <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4001 + <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4002 + <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4003 + </button>
4004 + </div>
2937 4005 </div>
2938 4006 <?php endif; ?>
2939 4007 </div>
2940 4008 </div>
2941 -
2942 - <!-- Edit Modal -->
2943 -<div id="mxchat-edit-modal" class="mxchat-modal" style="display: none;">
4009 +
4010 + <?php if ($total_pages > 1) : ?>
4011 + <div class="mxchat-pagination">
4012 + <?php
4013 + echo paginate_links(array(
4014 + 'base' => add_query_arg('paged', '%#%'),
4015 + 'format' => '',
4016 + 'prev_text' => __('&laquo; Previous', 'mxchat'),
4017 + 'next_text' => __('Next &raquo;', 'mxchat'),
4018 + 'total' => $total_pages,
4019 + 'current' => $page
4020 + ));
4021 + ?>
4022 + </div>
4023 + <?php endif; ?>
4024 +
4025 +<!-- Add/Edit Action Modal with Step-Based Approach -->
4026 +<!-- Complete Modal HTML with Defined Groups Variable -->
4027 +<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
2944 4028 <div class="mxchat-modal-content">
2945 4029 <span class="mxchat-modal-close">&times;</span>
2946 - <div class="mxchat-card-header">
2947 - <h2><?php esc_html_e('Edit Intent Phrases', 'mxchat'); ?></h2>
2948 - </div>
2949 4030
2950 - <form id="mxchat-edit-intent-form" method="post"
2951 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
2952 - <?php wp_nonce_field('mxchat_edit_intent_nonce'); ?>
2953 - <input type="hidden" name="action" value="mxchat_edit_intent">
2954 - <input type="hidden" name="intent_id" id="edit_intent_id">
4031 + <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4032 + <!-- Dynamic nonce field -->
4033 + <div id="action-nonce-container">
4034 + <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
4035 + </div>
4036 + <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4037 + <input type="hidden" name="intent_id" id="edit_action_id" value="">
4038 + <input type="hidden" name="callback_function" id="callback_function" value="">
2955 4039
2956 - <div class="mxchat-form-group">
2957 - <label for="edit_phrases">
2958 - <?php esc_html_e('Phrases (comma-separated)', 'mxchat'); ?>
2959 - </label>
2960 - <textarea name="phrases"
2961 - id="edit_phrases"
2962 - rows="5"
2963 - class="mxchat-intent-textarea"
2964 - required></textarea>
4040 + <!-- Step 1: Action Type Selection -->
4041 + <div id="mxchat-action-step-1" class="mxchat-action-step active">
4042 + <div class="mxchat-step-indicator">
4043 + <div class="mxchat-step-number">1</div>
4044 + <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4045 + </div>
4046 +
4047 + <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4048 + <div class="mxchat-action-type-search">
4049 + <span class="dashicons dashicons-search"></span>
4050 + <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4051 + </div>
4052 +
4053 + <?php
4054 + // Get the callbacks - IMPORTANT: Define the $groups variable here
4055 + $groups = $this->mxchat_get_available_callbacks(true, true);
4056 + ?>
4057 +
4058 + <div class="mxchat-action-type-categories">
4059 + <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
4060 + <?php
4061 + // Get unique categories from the defined groups
4062 + foreach ($groups as $group_label => $group_callbacks) :
4063 + $category_slug = sanitize_title($group_label);
4064 + ?>
4065 + <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4066 + <?php endforeach; ?>
4067 + </div>
4068 +
4069 + <div class="mxchat-action-types-grid">
4070 + <?php
4071 + // Generate action cards from available callbacks
4072 + foreach ($groups as $group_label => $group_callbacks) :
4073 + $category_slug = sanitize_title($group_label);
4074 +
4075 + foreach ($group_callbacks as $function => $data) :
4076 + $label = $data['label'];
4077 + $pro_only = $data['pro_only'];
4078 + $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4079 + $description = isset($data['description']) ? $data['description'] : '';
4080 + $is_addon = isset($data['addon']) && $data['addon'] !== false;
4081 + $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4082 + $is_installed = isset($data['installed']) ? $data['installed'] : true;
4083 +
4084 + // Determine card status and styling
4085 + $card_class = 'mxchat-action-type-card';
4086 + $icon_class = 'mxchat-action-type-icon';
4087 + $status_badge = '';
4088 +
4089 + if ($pro_only && !$this->is_activated) {
4090 + // Pro feature but no Pro license
4091 + $icon_class .= ' pro-feature';
4092 + $status_badge = '<span class="mxchat-pro-badge">' . esc_html__('Pro', 'mxchat') . '</span>';
4093 + }
4094 +
4095 + if ($is_addon && !$is_installed) {
4096 + // Add-on not installed
4097 + $card_class .= ' not-installed';
4098 + $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4099 + }
4100 +
4101 + // Default description if none provided
4102 + if (empty($description)) {
4103 + $description = sprintf(
4104 + esc_html__('Use the %s action in your chatbot', 'mxchat'),
4105 + $label
4106 + );
4107 + }
4108 + ?>
4109 + <div class="<?php echo esc_attr($card_class); ?>"
4110 + data-category="<?php echo esc_attr($category_slug); ?>"
4111 + data-value="<?php echo esc_attr($function); ?>"
4112 + data-label="<?php echo esc_attr($label); ?>"
4113 + data-pro="<?php echo $pro_only ? 'true' : 'false'; ?>"
4114 + data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4115 + data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>">
4116 + <div class="<?php echo esc_attr($icon_class); ?>">
4117 + <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4118 + </div>
4119 + <div class="mxchat-action-type-info">
4120 + <h4><?php echo esc_html($label); ?></h4>
4121 + <p><?php echo esc_html($description); ?></p>
4122 + <?php if (!empty($status_badge)) : ?>
4123 + <?php echo $status_badge; ?>
4124 + <?php endif; ?>
4125 +
4126 + <?php if ($is_addon && !$is_installed) : ?>
4127 + <div class="mxchat-addon-info">
4128 + <?php echo esc_html(sprintf(
4129 + __('Requires %s', 'mxchat'),
4130 + $addon_name
4131 + )); ?>
4132 + </div>
4133 + <?php endif; ?>
4134 + </div>
4135 + </div>
4136 + <?php endforeach;
4137 + endforeach; ?>
4138 + </div>
4139 + </div>
4140 +
4141 + <div class="mxchat-modal-actions">
4142 + <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4143 + <?php esc_html_e('Cancel', 'mxchat'); ?>
4144 + </button>
4145 + </div>
2965 4146 </div>
2966 4147
2967 - <div class="mxchat-modal-actions">
2968 - <button type="submit" class="mxchat-button-primary">
2969 - <?php esc_html_e('Update Phrases', 'mxchat'); ?>
2970 - </button>
2971 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
2972 - <?php esc_html_e('Cancel', 'mxchat'); ?>
2973 - </button>
4148 + <!-- Step 2: Action Configuration -->
4149 + <div id="mxchat-action-step-2" class="mxchat-action-step">
4150 + <div class="mxchat-step-indicator">
4151 + <div class="mxchat-step-number">2</div>
4152 + <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4153 + </div>
4154 +
4155 + <div class="mxchat-selected-action">
4156 + <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
4157 + <span class="dashicons dashicons-arrow-left-alt"></span>
4158 + <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
4159 + </button>
4160 + <div class="mxchat-selected-action-info">
4161 + <div id="selected-action-icon" class="mxchat-action-type-icon">
4162 + <span class="dashicons dashicons-admin-generic"></span>
4163 + </div>
4164 + <div class="mxchat-selected-action-details">
4165 + <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
4166 + <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
4167 + </div>
4168 + </div>
4169 + </div>
4170 +
4171 + <div class="mxchat-form-group">
4172 + <label for="intent_label">
4173 + <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
4174 + </label>
4175 + <input name="intent_label" type="text" id="intent_label" required
4176 + class="mxchat-intent-input"
4177 + placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
4178 + </div>
4179 +
4180 + <div class="mxchat-form-group">
4181 + <label for="phrases">
4182 + <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
4183 + </label>
4184 + <textarea name="phrases" id="action_phrases" rows="5" required
4185 + class="mxchat-intent-textarea"
4186 + placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
4187 + </div>
4188 +
4189 + <div class="mxchat-form-group">
4190 + <label for="similarity_threshold">
4191 + <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
4192 + <span class="mxchat-threshold-value-display">85%</span>
4193 + </label>
4194 + <div class="mxchat-slider-group modal-slider">
4195 + <input type="range"
4196 + name="similarity_threshold"
4197 + id="similarity_threshold"
4198 + min="70"
4199 + max="95"
4200 + value="85"
4201 + class="mxchat-intent-slider"
4202 + oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
4203 + </div>
4204 + <div class="mxchat-threshold-hint">
4205 + <?php esc_html_e('Lower values make the action trigger more easily. Higher values require more exact matches.', 'mxchat'); ?>
4206 + </div>
4207 + </div>
4208 +
4209 + <div class="mxchat-modal-actions">
4210 + <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4211 + <?php esc_html_e('Cancel', 'mxchat'); ?>
4212 + </button>
4213 + <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
4214 + <?php esc_html_e('Save Action', 'mxchat'); ?>
4215 + </button>
4216 + </div>
2974 4217 </div>
2975 4218 </form>
2976 4219 </div>
2977 4220 </div>
2978 4221
2979 - </div><!-- .mxchat-content -->
4222 +<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
4223 + <div class="mxchat-action-loading-spinner"></div>
4224 + <div class="mxchat-action-loading-text">
4225 + <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
4226 + </div>
4227 +</div>
2980 4228 </div><!-- .mxchat-wrapper -->
4229 + <?php
4230 +}
2981 4231
2982 - <div id="mxchat-intent-loading" class="mxchat-intent-loading" style="display: none;">
2983 - <div class="mxchat-intent-loading-spinner"></div>
2984 - <div class="mxchat-intent-loading-text">
2985 - <?php esc_html_e('Saving intent, please wait...', 'mxchat'); ?>
2986 - </div>
2987 - </div>
2988 -<?php
4232 +/**
4233 + * Helper method to trim phrases for display
4234 + * Adding this in case it doesn't exist in your class
4235 + */
4236 +private function get_trimmed_phrases($phrases, $max_length = 100) {
4237 + if (strlen($phrases) <= $max_length) {
4238 + return $phrases;
4239 + }
4240 +
4241 + $trimmed = substr($phrases, 0, $max_length);
4242 + $last_comma = strrpos($trimmed, ',');
4243 +
4244 + if ($last_comma !== false) {
4245 + $trimmed = substr($trimmed, 0, $last_comma);
4246 + }
4247 +
4248 + return $trimmed . '...';
2989 4249 }
2990 4250
4251 +/**
4252 + * AJAX handler for toggling an action on/off
4253 + */
4254 +public function mxchat_toggle_action() {
4255 + // Check nonce
4256 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_actions_nonce')) {
4257 + wp_send_json_error(array('message' => 'Security check failed'));
4258 + return;
4259 + }
4260 +
4261 + // Check permissions
4262 + if (!current_user_can('manage_options')) {
4263 + wp_send_json_error(array('message' => 'Permission denied'));
4264 + return;
4265 + }
4266 +
4267 + // Validate params
4268 + $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
4269 + $enabled = isset($_POST['enabled']) ? (bool)$_POST['enabled'] : false;
4270 +
4271 + if (!$intent_id) {
4272 + wp_send_json_error(array('message' => 'Invalid action ID'));
4273 + return;
4274 + }
4275 +
4276 + // Update the intent/action status in the database
4277 + global $wpdb;
4278 + $table_name = $wpdb->prefix . 'mxchat_intents';
4279 +
4280 + // Using the 'enabled' field - add this field if it doesn't exist
4281 + $result = $wpdb->update(
4282 + $table_name,
4283 + array('enabled' => $enabled ? 1 : 0),
4284 + array('id' => $intent_id),
4285 + array('%d'),
4286 + array('%d')
4287 + );
4288 +
4289 + if ($result === false) {
4290 + wp_send_json_error(array('message' => 'Database error'));
4291 + return;
4292 + }
4293 +
4294 + wp_send_json_success();
4295 +}
2991 4296
4297 +/**
4298 + * Add the 'enabled' column to the intents table if it doesn't exist
4299 + * Call this during plugin activation or update
4300 + */
4301 +public function mxchat_add_enabled_column_to_intents() {
4302 + global $wpdb;
4303 + $table_name = $wpdb->prefix . 'mxchat_intents';
4304 +
4305 + // Check if the column already exists
4306 + $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
4307 +
4308 + if (empty($columns)) {
4309 + // Add the column with default value of 1 (enabled)
4310 + $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
4311 + }
4312 +}
2992 4313
2993 4314 /**
2994 - * Handle editing of intent phrases
4315 + * Handle embedding generation errors using existing admin notice system
4316 + *
4317 + * @param string $message Error message to display
4318 + * @param bool $redirect Whether to redirect back to the actions page
4319 + * @return void
4320 + */
4321 +private function handle_embedding_error($message, $redirect = true) {
4322 + // Store the error message in the existing transient
4323 + set_transient('mxchat_admin_notice_error', $message, 60);
4324 +
4325 + if ($redirect) {
4326 + // Redirect back to the actions page
4327 + $redirect_url = add_query_arg(
4328 + array(
4329 + 'page' => 'mxchat-actions'
4330 + ),
4331 + admin_url('admin.php')
4332 + );
4333 + wp_safe_redirect($redirect_url);
4334 + exit;
4335 + }
4336 +}
4337 +
4338 +/**
4339 + * Handle editing of intent phrases - with improved error handling
2995 4340 *
2996 4341 * @since 1.0.0
2997 4342 * @return void
2998 4343 */
2999 -public function handle_edit_intent() {
3000 - // Verify nonce and user capabilities
3001 - if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'mxchat_edit_intent_nonce')) {
3002 - wp_die(esc_html__('Security check failed.', 'mxchat'));
3003 - }
3004 -
4344 +public function mxchat_handle_edit_intent() {
4345 + // Security checks (nonce and permissions)
3005 4346 if (!current_user_can('manage_options')) {
3006 - wp_die(esc_html__('You do not have permission to perform this action.', 'mxchat'));
4347 + wp_die(esc_html__('Unauthorized user', 'mxchat'));
3007 4348 }
4349 + check_admin_referer('mxchat_edit_intent');
3008 4350
3009 - // Validate and sanitize input
4351 + // Get POST data
3010 4352 $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
3011 - if (!$intent_id) {
3012 - wp_die(esc_html__('Invalid intent ID.', 'mxchat'));
3013 - }
4353 + $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
4354 + $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
4355 + $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
4356 + $similarity_threshold = min(95, max(70, $threshold_percentage)) / 100; // Convert to 0.70–0.95
3014 4357
3015 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
3016 - if (empty($phrases_input)) {
3017 - wp_die(esc_html__('Phrases cannot be empty.', 'mxchat'));
4358 + // Validate inputs
4359 + if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
4360 + $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
4361 + return;
3018 4362 }
3019 4363
3020 - // Process phrases the same way as in intent creation
3021 4364 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
3022 -
3023 4365 if (empty($phrases_array)) {
3024 - wp_die(esc_html__('Please enter at least one valid phrase.', 'mxchat'));
4366 + $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
4367 + return;
3025 4368 }
3026 4369
3027 - // Generate embeddings and combine them
4370 + // Generate embeddings with improved error handling
3028 4371 $vectors = [];
4372 + $failed_phrases = [];
4373 +
3029 4374 foreach ($phrases_array as $phrase) {
3030 4375 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
3031 4376 if (is_array($embedding_vector)) {
3032 4377 $vectors[] = $embedding_vector;
3033 4378 } else {
3034 - wp_die(esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase));
4379 + $failed_phrases[] = $phrase;
3035 4380 }
3036 4381 }
3037 -
4382 +
4383 + if (!empty($failed_phrases)) {
4384 + $this->handle_embedding_error(
4385 + sprintf(
4386 + __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
4387 + implode(', ', $failed_phrases)
4388 + )
4389 + );
4390 + return;
4391 + }
4392 +
3038 4393 if (empty($vectors)) {
3039 - wp_die(esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4394 + $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4395 + return;
3040 4396 }
3041 4397
3042 - // Create combined vector just like in intent creation
3043 4398 $combined_vector = $this->mxchat_average_vectors($vectors);
3044 4399 $serialized_vector = maybe_serialize($combined_vector);
3045 4400
4401 + // Update the database
3046 4402 global $wpdb;
3047 4403 $table_name = $wpdb->prefix . 'mxchat_intents';
3048 4404
3049 - // Update the intent with both new phrases and the combined vector
3050 4405 $result = $wpdb->update(
3051 4406 $table_name,
3052 4407 array(
4408 + 'intent_label' => $intent_label,
3053 4409 'phrases' => implode(', ', $phrases_array),
3054 - 'embedding_vector' => $serialized_vector
4410 + 'embedding_vector' => $serialized_vector,
4411 + 'similarity_threshold' => $similarity_threshold
3055 4412 ),
3056 4413 array('id' => $intent_id),
3057 - array('%s', '%s'),
3058 - array('%d')
4414 + array('%s', '%s', '%s', '%f'), // Format: string, string, string, float
4415 + array('%d') // Where format: integer
3059 4416 );
3060 4417
3061 4418 if (false === $result) {
3062 - wp_die(esc_html__('Failed to update intent.', 'mxchat'));
4419 + $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
4420 + return;
3063 4421 }
3064 4422
3065 - // Redirect back to the intents page with a success message
4423 + // Set success message and redirect
4424 + set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
4425 +
3066 4426 $redirect_url = add_query_arg(
3067 4427 array(
3068 - 'page' => 'mxchat-intents',
3069 - 'updated' => 'true'
4428 + 'page' => 'mxchat-actions'
3070 4429 ),
3071 4430 admin_url('admin.php')
3072 4431 );
3073 -
3074 4432 wp_safe_redirect($redirect_url);
3075 4433 exit;
3076 4434 }
3077 -public function mxchat_handle_update_intent_threshold() {
3078 - if ( ! current_user_can( 'manage_options' ) ) {
3079 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
3080 - }
3081 4435
3082 - check_admin_referer('mxchat_update_intent_threshold_nonce');
3083 -
3084 - if (isset($_POST['intent_id'], $_POST['intent_threshold'])) {
3085 - global $wpdb;
3086 - $table_name = $wpdb->prefix . 'mxchat_intents';
3087 - $intent_id = intval($_POST['intent_id']);
3088 - $threshold_percentage = max(70, min(95, intval($_POST['intent_threshold'])));
3089 - $similarity_threshold = $threshold_percentage / 100;
3090 -
3091 - $wpdb->update(
3092 - $table_name,
3093 - ['similarity_threshold' => $similarity_threshold],
3094 - ['id' => $intent_id],
3095 - ['%f'],
3096 - ['%d']
3097 - );
3098 - }
3099 -
3100 - wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
3101 - exit;
3102 -}
3103 -
4436 +/**
4437 + * Handle adding new intent - with improved error handling
4438 + *
4439 + * @return void
4440 + */
3104 4441 public function mxchat_handle_add_intent() {
3105 - if ( ! current_user_can( 'manage_options' ) ) {
3106 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
4442 + if (!current_user_can('manage_options')) {
4443 + wp_die(esc_html__('Unauthorized user', 'mxchat'));
3107 4444 }
3108 4445
3109 4446 check_admin_referer('mxchat_add_intent_nonce');
3110 4447
@@ -3116,120 +4453,484 @@
3116 4453 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
3117 4454 $default_threshold = 0.85;
3118 4455
3119 4456 if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
3120 - wp_die( esc_html__('Invalid input. Please ensure all fields are filled out.', 'mxchat') );
4457 + $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
4458 + return;
3121 4459 }
3122 4460
3123 4461 $available_callbacks = $this->mxchat_get_available_callbacks();
3124 4462
3125 4463 if (!array_key_exists($callback_function, $available_callbacks)) {
3126 - wp_die( esc_html__('Invalid callback function selected.', 'mxchat') );
4464 + $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
4465 + return;
3127 4466 }
3128 4467
3129 4468 $is_pro_only = $available_callbacks[$callback_function]['pro_only'];
3130 4469 if ($is_pro_only && !$this->is_activated) {
3131 - wp_die( esc_html__('This callback function is available in the Pro version only.', 'mxchat') );
4470 + $this->handle_embedding_error(__('This callback function is available in the Pro version only.', 'mxchat'));
4471 + return;
3132 4472 }
3133 4473
3134 4474 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
3135 4475
3136 4476 if (empty($phrases_array)) {
3137 - wp_die( esc_html__('Please enter at least one valid phrase.', 'mxchat') );
4477 + $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
4478 + return;
3138 4479 }
3139 4480
4481 + // Generate embeddings with improved error handling
3140 4482 $vectors = [];
4483 + $failed_phrases = [];
4484 +
3141 4485 foreach ($phrases_array as $phrase) {
3142 4486 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
3143 4487 if (is_array($embedding_vector)) {
3144 4488 $vectors[] = $embedding_vector;
3145 4489 } else {
3146 - wp_die( esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase) );
4490 + $failed_phrases[] = $phrase;
3147 4491 }
3148 4492 }
4493 +
4494 + if (!empty($failed_phrases)) {
4495 + $this->handle_embedding_error(
4496 + sprintf(
4497 + __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
4498 + implode(', ', $failed_phrases)
4499 + )
4500 + );
4501 + return;
4502 + }
3149 4503
3150 - if (!empty($vectors)) {
3151 - $combined_vector = $this->mxchat_average_vectors($vectors);
3152 - $serialized_vector = maybe_serialize($combined_vector);
4504 + if (empty($vectors)) {
4505 + $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4506 + return;
4507 + }
3153 4508
3154 - $result = $wpdb->insert($table_name, [
3155 - 'intent_label' => $intent_label,
3156 - 'phrases' => implode(', ', $phrases_array),
3157 - 'embedding_vector' => $serialized_vector,
3158 - 'callback_function' => $callback_function,
3159 - 'similarity_threshold' => $default_threshold,
3160 - ]);
4509 + $combined_vector = $this->mxchat_average_vectors($vectors);
4510 + $serialized_vector = maybe_serialize($combined_vector);
3161 4511
3162 - if ($result === false) {
3163 - wp_die( esc_html__('Database error: ', 'mxchat') . esc_html($wpdb->last_error) );
3164 - }
3165 - } else {
3166 - wp_die( esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat') );
4512 + $result = $wpdb->insert($table_name, [
4513 + 'intent_label' => $intent_label,
4514 + 'phrases' => implode(', ', $phrases_array),
4515 + 'embedding_vector' => $serialized_vector,
4516 + 'callback_function' => $callback_function,
4517 + 'similarity_threshold' => $default_threshold,
4518 + ]);
4519 +
4520 + if ($result === false) {
4521 + $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
4522 + return;
3167 4523 }
3168 4524
3169 - wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
4525 + // Set success message
4526 + set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
4527 +
4528 + wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
3170 4529 exit;
3171 4530 }
3172 4531
3173 4532
4533 +/**
4534 + * Update intent threshold with AJAX support
4535 + */
4536 +public function mxchat_update_intent_threshold() {
4537 + // Check permissions
4538 + if (!current_user_can('manage_options')) {
4539 + if (wp_doing_ajax()) {
4540 + wp_send_json_error(array('message' => 'Unauthorized user'));
4541 + return;
4542 + }
4543 + wp_die(esc_html__('Unauthorized user', 'mxchat'));
4544 + }
4545 +
4546 + // Verify nonce
4547 + check_admin_referer('mxchat_update_intent_threshold_nonce');
4548 +
4549 + // Process the update if we have valid data
4550 + if (isset($_POST['intent_id'], $_POST['intent_threshold'])) {
4551 + global $wpdb;
4552 + $table_name = $wpdb->prefix . 'mxchat_intents';
4553 + $intent_id = intval($_POST['intent_id']);
4554 + $threshold_percentage = max(70, min(95, intval($_POST['intent_threshold'])));
4555 + $similarity_threshold = $threshold_percentage / 100;
4556 +
4557 + $result = $wpdb->update(
4558 + $table_name,
4559 + ['similarity_threshold' => $similarity_threshold],
4560 + ['id' => $intent_id],
4561 + ['%f'],
4562 + ['%d']
4563 + );
4564 +
4565 + // Handle AJAX requests
4566 + if (wp_doing_ajax()) {
4567 + if ($result === false) {
4568 + wp_send_json_error(array('message' => 'Failed to update threshold'));
4569 + } else {
4570 + wp_send_json_success(array('threshold' => $threshold_percentage));
4571 + }
4572 + return;
4573 + }
4574 + }
4575 +
4576 + // Redirect for regular form submissions
4577 + wp_safe_redirect(admin_url('admin.php?page=mxchat-actions&updated=true'));
4578 + exit;
4579 +}
3174 4580
3175 4581
3176 4582
3177 -
3178 -private function mxchat_get_available_callbacks($grouped = false) {
3179 - $callbacks = [
3180 - 'mxchat_handle_email_capture' => [
3181 - 'label' => __('Email Capture', 'mxchat'),
3182 - 'pro_only' => false,
3183 - 'group' => __('Customer Engagement', 'mxchat'),
3184 - ],
3185 - 'mxchat_generate_image' => [
3186 - 'label' => __('Generate Image', 'mxchat'),
3187 - 'pro_only' => true,
3188 - 'group' => __('Other Features', 'mxchat'),
3189 - ],
3190 - 'mxchat_handle_search_request' => [
3191 - 'label' => __('Brave Web Search', 'mxchat'),
3192 - 'pro_only' => false,
3193 - 'group' => __('Search Features', 'mxchat'),
3194 - ],
3195 - 'mxchat_handle_image_search_request' => [
3196 - 'label' => __('Brave Image Search', 'mxchat'),
3197 - 'pro_only' => false,
3198 - 'group' => __('Search Features', 'mxchat'),
3199 - ],
3200 - 'mxchat_handle_pdf_discussion' => [
3201 - 'label' => __('Chat with PDF', 'mxchat'),
3202 - 'pro_only' => true,
3203 - 'group' => __('Other Features', 'mxchat'),
3204 - ],
3205 - 'mxchat_live_agent_handover' => [
3206 - 'label' => __('Live Agent', 'mxchat'),
3207 - 'pro_only' => true,
3208 - 'group' => __('Customer Engagement', 'mxchat'),
3209 - ],
3210 - 'mxchat_handle_switch_to_chatbot_intent' => [
3211 - 'label' => __('Back to Chatbot', 'mxchat'),
3212 - 'pro_only' => true,
3213 - 'group' => __('Customer Engagement', 'mxchat'),
3214 - ],
3215 - ];
3216 -
3217 - // Allow other plugins to add their callbacks
3218 - $callbacks = apply_filters('mxchat_available_callbacks', $callbacks);
3219 -
4583 +/**
4584 + * Enhanced get_available_callbacks function with form action exclusion
4585 + *
4586 + * @param bool $grouped Whether to return callbacks grouped by category
4587 + * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
4588 + * @return array Callbacks data with icons, descriptions and availability status
4589 + */
4590 +private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
4591 + // Load WordPress plugin functions if needed
4592 + if (!function_exists('get_plugins')) {
4593 + require_once ABSPATH . 'wp-admin/includes/plugin.php';
4594 + }
4595 +
4596 + // Get active plugins
4597 + $active_plugins = get_option('active_plugins', array());
4598 +
4599 + // Functions to exclude from the action selector only if Pro is activated
4600 + // If user doesn't have Pro, show these so they can see what they're missing
4601 + $excluded_when_pro_active_functions = array(
4602 + 'mxchat_handle_form_collection', // Forms add-on action
4603 + 'mxchat_sr_recommendation_flow' // Smart Recommender flow actions
4604 + );
4605 +
4606 + // Always excluded functions (regardless of Pro status)
4607 + $always_excluded_functions = array();
4608 +
4609 + // Combine exclusion lists based on Pro activation status
4610 + $excluded_functions = $always_excluded_functions;
4611 + if ($this->is_activated) {
4612 + // Only exclude add-on managed functions if Pro is active
4613 + $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
4614 + }
4615 +
4616 + // Define add-on plugin files and their corresponding action functions
4617 + $addon_plugins = array(
4618 + 'mxchat-woo/mxchat-woo.php' => array(
4619 + 'functions' => array(
4620 + 'mxchat_handle_product_recommendations',
4621 + 'mxchat_handle_order_history',
4622 + 'mxchat_show_product_card',
4623 + 'mxchat_add_to_cart',
4624 + 'mxchat_checkout_redirect'
4625 + ),
4626 + 'name' => __('WooCommerce Add-on', 'mxchat'),
4627 + 'pro_required' => true
4628 + ),
4629 + 'mxchat-perplexity/mxchat-perplexity.php' => array(
4630 + 'functions' => array('mxchat_perplexity_research'),
4631 + 'name' => __('Perplexity Add-on', 'mxchat'),
4632 + 'pro_required' => true
4633 + ),
4634 + 'mxchat-forms/mxchat-forms.php' => array(
4635 + 'functions' => array('mxchat_handle_form_collection'),
4636 + 'name' => __('Forms Add-on', 'mxchat'),
4637 + 'pro_required' => true
4638 + ),
4639 + 'mxchat-smart-recommender/mxchat-smart-recommender.php' => array(
4640 + 'functions' => array('mxchat_sr_recommendation_flow'),
4641 + 'name' => __('Smart Recommender Add-on', 'mxchat'),
4642 + 'pro_required' => true
4643 + ),
4644 + // Add other add-ons and their functions here
4645 + );
4646 +
4647 + // Get the functions that are provided by active add-ons
4648 + $addon_provided_functions = array();
4649 + $addon_function_mapping = array(); // Maps functions to their add-on info
4650 +
4651 + // Check which add-ons are active
4652 + foreach ($addon_plugins as $plugin_file => $addon_info) {
4653 + $is_active = in_array($plugin_file, $active_plugins);
4654 +
4655 + // For each function in this addon
4656 + foreach ($addon_info['functions'] as $function) {
4657 + // Consider a function installed only if:
4658 + // 1. The add-on is active AND
4659 + // 2. Either it doesn't require Pro OR Pro is activated
4660 + $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
4661 +
4662 + // If the add-on is installed, mark this function as provided by an add-on
4663 + if ($is_installed) {
4664 + $addon_provided_functions[] = $function;
4665 + }
4666 +
4667 + // Store addon info for this function regardless of installation status
4668 + $addon_function_mapping[$function] = array(
4669 + 'addon' => basename(dirname($plugin_file)),
4670 + 'addon_name' => $addon_info['name'],
4671 + 'pro_required' => $addon_info['pro_required'],
4672 + 'is_active' => $is_active,
4673 + 'is_installed' => $is_installed
4674 + );
4675 + }
4676 + }
4677 +
4678 + // Core callbacks - always available in the base plugin
4679 + $core_callbacks = array(
4680 + 'mxchat_handle_email_capture' => array(
4681 + 'label' => __('Loops Email Capture', 'mxchat'),
4682 + 'pro_only' => false,
4683 + 'group' => __('Customer Engagement', 'mxchat'),
4684 + 'icon' => 'email-alt',
4685 + 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
4686 + 'addon' => false, // Not from an add-on
4687 + 'installed' => true // Always installed with base plugin
4688 + ),
4689 + 'mxchat_handle_search_request' => array(
4690 + 'label' => __('Brave Web Search', 'mxchat'),
4691 + 'pro_only' => false,
4692 + 'group' => __('Search Features', 'mxchat'),
4693 + 'icon' => 'search',
4694 + 'description' => __('Let users search the web directly from the chat', 'mxchat'),
4695 + 'addon' => false,
4696 + 'installed' => true
4697 + ),
4698 + 'mxchat_handle_image_search_request' => array(
4699 + 'label' => __('Brave Image Search', 'mxchat'),
4700 + 'pro_only' => false,
4701 + 'group' => __('Search Features', 'mxchat'),
4702 + 'icon' => 'format-image',
4703 + 'description' => __('Search and display images in the chat conversation', 'mxchat'),
4704 + 'addon' => false,
4705 + 'installed' => true
4706 + ),
4707 + // Pro core features - check is_activated property
4708 + 'mxchat_generate_image' => array(
4709 + 'label' => __('Generate Image', 'mxchat'),
4710 + 'pro_only' => false,
4711 + 'group' => __('Other Features', 'mxchat'),
4712 + 'icon' => 'art',
4713 + 'description' => __('Create images with DALL-E 3 from OpenAI (requires OpenAI API key)', 'mxchat'),
4714 + 'addon' => false,
4715 + 'installed' => true
4716 + ),
4717 + 'mxchat_handle_pdf_discussion' => array(
4718 + 'label' => __('Chat with PDF', 'mxchat'),
4719 + 'pro_only' => false,
4720 + 'group' => __('Other Features', 'mxchat'),
4721 + 'icon' => 'media-document',
4722 + 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
4723 + 'addon' => false,
4724 + 'installed' => true
4725 + ),
4726 + 'mxchat_live_agent_handover' => array(
4727 + 'label' => __('Slack Live Agent', 'mxchat'),
4728 + 'pro_only' => false,
4729 + 'group' => __('Customer Engagement', 'mxchat'),
4730 + 'icon' => 'admin-users',
4731 + 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
4732 + 'addon' => false,
4733 + 'installed' => true
4734 + ),
4735 + 'mxchat_handle_switch_to_chatbot_intent' => array(
4736 + 'label' => __('Back to Chatbot', 'mxchat'),
4737 + 'pro_only' => false,
4738 + 'group' => __('Customer Engagement', 'mxchat'),
4739 + 'icon' => 'backup',
4740 + 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
4741 + 'addon' => false,
4742 + 'installed' => true
4743 + ),
4744 + );
4745 +
4746 + // Add-on callbacks with placeholders - only include if the add-on is NOT active
4747 + $addon_callbacks = array(
4748 + // WooCommerce Add-on
4749 + 'mxchat_handle_product_recommendations' => array(
4750 + 'label' => __('Product Recommendations', 'mxchat'),
4751 + 'pro_only' => true,
4752 + 'group' => __('WooCommerce Features', 'mxchat'),
4753 + 'icon' => 'cart',
4754 + 'description' => __('Suggest products based on customer preferences', 'mxchat'),
4755 + ),
4756 + 'mxchat_handle_order_history' => array(
4757 + 'label' => __('Order History', 'mxchat'),
4758 + 'pro_only' => true,
4759 + 'group' => __('WooCommerce Features', 'mxchat'),
4760 + 'icon' => 'clipboard',
4761 + 'description' => __('Allow customers to check their order status', 'mxchat'),
4762 + ),
4763 + 'mxchat_show_product_card' => array(
4764 + 'label' => __('Show Product Card', 'mxchat'),
4765 + 'pro_only' => true,
4766 + 'group' => __('WooCommerce Features', 'mxchat'),
4767 + 'icon' => 'products',
4768 + 'description' => __('Display product information in the chat', 'mxchat'),
4769 + ),
4770 + 'mxchat_add_to_cart' => array(
4771 + 'label' => __('Add to Cart', 'mxchat'),
4772 + 'pro_only' => true,
4773 + 'group' => __('WooCommerce Features', 'mxchat'),
4774 + 'icon' => 'plus-alt',
4775 + 'description' => __('Add products to cart directly from chat', 'mxchat'),
4776 + ),
4777 + 'mxchat_checkout_redirect' => array(
4778 + 'label' => __('Proceed to Checkout', 'mxchat'),
4779 + 'pro_only' => true,
4780 + 'group' => __('WooCommerce Features', 'mxchat'),
4781 + 'icon' => 'arrow-right-alt',
4782 + 'description' => __('Redirect customer to checkout page', 'mxchat'),
4783 + ),
4784 +
4785 + // Perplexity Add-on
4786 + 'mxchat_perplexity_research' => array(
4787 + 'label' => __('Perplexity Research', 'mxchat'),
4788 + 'pro_only' => true,
4789 + 'group' => __('Search Features', 'mxchat'),
4790 + 'icon' => 'book-alt',
4791 + 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
4792 + ),
4793 +
4794 + // Forms Add-on (only shown when Pro is not activated)
4795 + 'mxchat_handle_form_collection' => array(
4796 + 'label' => __('Form Collection', 'mxchat'),
4797 + 'pro_only' => true,
4798 + 'group' => __('Form Features', 'mxchat'),
4799 + 'icon' => 'feedback',
4800 + 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
4801 + ),
4802 +
4803 + // Smart Recommender Add-on (only shown when Pro is not activated)
4804 + 'mxchat_sr_recommendation_flow' => array(
4805 + 'label' => __('Smart Recommender Flow', 'mxchat'),
4806 + 'pro_only' => true,
4807 + 'group' => __('Recommendation Features', 'mxchat'),
4808 + 'icon' => 'cart',
4809 + 'description' => __('Create interactive conversation flows that collect user preferences and deliver personalized product or service recommendations', 'mxchat'),
4810 + ),
4811 + );
4812 +
4813 + // Enhance add-on callbacks with installation status and addon info
4814 + foreach ($addon_callbacks as $function => $data) {
4815 + if (isset($addon_function_mapping[$function])) {
4816 + $addon_info = $addon_function_mapping[$function];
4817 +
4818 + $addon_callbacks[$function]['addon'] = $addon_info['addon'];
4819 + $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
4820 + $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
4821 +
4822 + // Set pro_only based on add-on configuration
4823 + $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
4824 + } else {
4825 + $addon_callbacks[$function]['addon'] = 'unknown';
4826 + $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
4827 + $addon_callbacks[$function]['installed'] = false;
4828 + }
4829 + }
4830 +
4831 + // Initialize callbacks with core features
4832 + $callbacks = $core_callbacks;
4833 +
4834 + // Get callbacks from active add-ons
4835 + $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
4836 +
4837 + // Add placeholder callbacks only for add-ons that aren't active
4838 + if ($include_all) {
4839 + foreach ($addon_callbacks as $function => $data) {
4840 + // Skip placeholders for functions provided by active add-ons
4841 + if (in_array($function, $addon_provided_functions)) {
4842 + continue;
4843 + }
4844 +
4845 + // Skip excluded functions
4846 + if (in_array($function, $excluded_functions)) {
4847 + continue;
4848 + }
4849 +
4850 + // Add the placeholder
4851 + $callbacks[$function] = $data;
4852 + }
4853 + }
4854 +
4855 + // Add callbacks from active add-ons (will override placeholders)
4856 + foreach ($active_addon_callbacks as $function => $data) {
4857 + // Skip excluded functions
4858 + if (in_array($function, $excluded_functions)) {
4859 + continue;
4860 + }
4861 +
4862 + // Always include callbacks from add-ons
4863 + $callbacks[$function] = $data;
4864 +
4865 + // Ensure they have the proper add-on info
4866 + if (isset($addon_function_mapping[$function])) {
4867 + $addon_info = $addon_function_mapping[$function];
4868 + $callbacks[$function]['addon'] = $addon_info['addon'];
4869 + $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
4870 + $callbacks[$function]['installed'] = $addon_info['is_installed'];
4871 + $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
4872 + }
4873 + }
4874 +
4875 + // Just before returning callbacks, sort them to prioritize free features
4876 + if (!$grouped) {
4877 + // Create temporary arrays for sorting
4878 + $free_callbacks = array();
4879 + $pro_callbacks = array();
4880 +
4881 + // Split callbacks into free and pro
4882 + foreach ($callbacks as $key => $data) {
4883 + if (isset($data['pro_only']) && $data['pro_only']) {
4884 + $pro_callbacks[$key] = $data;
4885 + } else {
4886 + $free_callbacks[$key] = $data;
4887 + }
4888 + }
4889 +
4890 + // Merge with free callbacks first
4891 + $callbacks = array_merge($free_callbacks, $pro_callbacks);
4892 + }
4893 +
3220 4894 // Return grouped structure if requested
3221 4895 if ($grouped) {
3222 - $grouped_callbacks = [];
4896 + $grouped_callbacks = array();
3223 4897 foreach ($callbacks as $key => $data) {
3224 - $group_label = $data['group'] ?? __('Other Features', 'mxchat');
3225 - $grouped_callbacks[$group_label][$key] = [
3226 - 'label' => $data['label'],
3227 - 'pro_only' => $data['pro_only'],
3228 - ];
4898 + $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
4899 +
4900 + // Ensure we carry forward all the new fields in grouped mode
4901 + $callback_data = array(
4902 + 'label' => $data['label'],
4903 + 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
4904 + 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
4905 + 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
4906 + 'addon' => isset($data['addon']) ? $data['addon'] : false,
4907 + 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
4908 + 'installed' => isset($data['installed']) ? $data['installed'] : true
4909 + );
4910 +
4911 + $grouped_callbacks[$group_label][$key] = $callback_data;
3229 4912 }
4913 +
4914 + // Sort within each group to prioritize free features
4915 + foreach ($grouped_callbacks as $group => $items) {
4916 + $free_items = array();
4917 + $pro_items = array();
4918 +
4919 + foreach ($items as $key => $data) {
4920 + if (isset($data['pro_only']) && $data['pro_only']) {
4921 + $pro_items[$key] = $data;
4922 + } else {
4923 + $free_items[$key] = $data;
4924 + }
4925 + }
4926 +
4927 + $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
4928 + }
4929 +
3230 4930 return $grouped_callbacks;
3231 4931 }
4932 +
3232 4933 return $callbacks;
3233 4934 }
3234 4935
3235 4936
@@ -3266,9 +4967,9 @@
3266 4967
3267 4968 $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
3268 4969 }
3269 4970
3270 - wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
4971 + wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
3271 4972 exit;
3272 4973 }
3273 4974
3274 4975
@@ -3319,41 +5020,98 @@
3319 5020 );
3320 5021
3321 5022
3322 5023 // Existing fields...
3323 - add_settings_field(
3324 - 'api_key',
3325 - esc_html__('OpenAI API Key', 'mxchat'),
3326 - array($this, 'api_key_callback'),
3327 - 'mxchat-chatbot',
3328 - 'mxchat_chatbot_section'
3329 - );
5024 + add_settings_field(
5025 + 'api_key',
5026 + esc_html__('OpenAI API Key', 'mxchat'),
5027 + array($this, 'api_key_callback'),
5028 + 'mxchat-chatbot',
5029 + 'mxchat_chatbot_section',
5030 + array(
5031 + 'class' => 'mxchat-setting-row',
5032 + 'data-provider' => 'openai'
5033 + )
5034 + );
5035 +
5036 + add_settings_field(
5037 + 'xai_api_key',
5038 + esc_html__('X.AI API Key', 'mxchat'),
5039 + array($this, 'xai_api_key_callback'),
5040 + 'mxchat-chatbot',
5041 + 'mxchat_chatbot_section',
5042 + array(
5043 + 'class' => 'mxchat-setting-row',
5044 + 'data-provider' => 'xai'
5045 + )
5046 + );
5047 +
5048 + add_settings_field(
5049 + 'claude_api_key',
5050 + esc_html__('Claude API Key', 'mxchat'),
5051 + array($this, 'claude_api_key_callback'),
5052 + 'mxchat-chatbot',
5053 + 'mxchat_chatbot_section',
5054 + array(
5055 + 'class' => 'mxchat-setting-row',
5056 + 'data-provider' => 'claude'
5057 + )
5058 + );
5059 +
5060 + add_settings_field(
5061 + 'deepseek_api_key',
5062 + esc_html__('DeepSeek API Key', 'mxchat'),
5063 + array($this, 'deepseek_api_key_callback'),
5064 + 'mxchat-chatbot',
5065 + 'mxchat_chatbot_section',
5066 + array(
5067 + 'class' => 'mxchat-setting-row',
5068 + 'data-provider' => 'deepseek'
5069 + )
5070 + );
5071 +
5072 + add_settings_field(
5073 + 'gemini_api_key',
5074 + esc_html__('Google Gemini API Key', 'mxchat'),
5075 + array($this, 'gemini_api_key_callback'),
5076 + 'mxchat-chatbot',
5077 + 'mxchat_chatbot_section',
5078 + array(
5079 + 'class' => 'mxchat-setting-row',
5080 + 'data-provider' => 'gemini'
5081 + )
5082 + );
5083 +
5084 + add_settings_field(
5085 + 'voyage_api_key',
5086 + esc_html__('Voyage AI API Key', 'mxchat'),
5087 + array($this, 'voyage_api_key_callback'),
5088 + 'mxchat-chatbot',
5089 + 'mxchat_chatbot_section',
5090 + array(
5091 + 'class' => 'mxchat-setting-row',
5092 + 'data-provider' => 'voyage'
5093 + )
5094 + );
3330 5095
3331 5096 add_settings_field(
3332 - 'xai_api_key',
3333 - esc_html__('X.AI API Key', 'mxchat'),
3334 - array($this, 'xai_api_key_callback'),
5097 + 'model',
5098 + esc_html__('Chat Model', 'mxchat'),
5099 + array($this, 'mxchat_model_callback'),
3335 5100 'mxchat-chatbot',
3336 5101 'mxchat_chatbot_section'
3337 5102 );
3338 -
5103 +
5104 + // Add the settings field
3339 5105 add_settings_field(
3340 - 'claude_api_key',
3341 - esc_html__('Claude API Key', 'mxchat'),
3342 - array($this, 'claude_api_key_callback'),
5106 + 'embedding_model',
5107 + esc_html__('Embedding Model', 'mxchat'),
5108 + array($this, 'embedding_model_callback'),
3343 5109 'mxchat-chatbot',
3344 5110 'mxchat_chatbot_section'
3345 5111 );
3346 -
5112 +
3347 5113 add_settings_field(
3348 - 'deepseek_api_key',
3349 - esc_html__('DeepSeek API Key', 'mxchat'),
3350 - array($this, 'deepseek_api_key_callback'),
3351 - 'mxchat-chatbot',
3352 - 'mxchat_chatbot_section'
3353 - );
3354 -
3355 - add_settings_field(
3356 5114 'system_prompt_instructions',
3357 5115 esc_html__('AI Instructions (Behavior)', 'mxchat'),
3358 5116 array($this, 'system_prompt_instructions_callback'),
3359 5117 'mxchat-chatbot',
@@ -3359,24 +5117,25 @@
3359 5117 'mxchat-chatbot',
3360 5118 'mxchat_chatbot_section'
3361 5119 );
3362 5120
5121 +
3363 5122 add_settings_field(
3364 - 'model',
3365 - esc_html__('Model', 'mxchat'),
3366 - array($this, 'mxchat_model_callback'),
5123 + 'top_bar_title',
5124 + esc_html__('Top Bar Title', 'mxchat'),
5125 + array($this, 'mxchat_top_bar_title_callback'),
3367 5126 'mxchat-chatbot',
3368 5127 'mxchat_chatbot_section'
3369 5128 );
3370 5129
3371 5130 add_settings_field(
3372 - 'top_bar_title',
3373 - esc_html__('Top Bar Title', 'mxchat'),
3374 - array($this, 'mxchat_top_bar_title_callback'),
5131 + 'ai_agent_text',
5132 + esc_html__('AI Agent Text', 'mxchat'),
5133 + array($this, 'mxchat_ai_agent_text_callback'),
3375 5134 'mxchat-chatbot',
3376 5135 'mxchat_chatbot_section'
3377 5136 );
3378 -
5137 +
3379 5138 add_settings_field(
3380 5139 'enable_email_block',
3381 5140 esc_html__('Require Email To Chat', 'mxchat'),
3382 5141 array($this, 'enable_email_block_callback'),
@@ -3416,32 +5175,8 @@
3416 5175 'mxchat_chatbot_section'
3417 5176 );
3418 5177
3419 5178 add_settings_field(
3420 - 'rate_limit_logged_out',
3421 - __('Rate Limit for Logged-out Users', 'mxchat'),
3422 - array($this, 'mxchat_rate_limit_logged_out_callback'),
3423 - 'mxchat-chatbot',
3424 - 'mxchat_chatbot_section'
3425 - );
3426 -
3427 - add_settings_field(
3428 - 'rate_limit_roles',
3429 - __('Rate Limits by User Role', 'mxchat'),
3430 - array($this, 'mxchat_rate_limit_roles_callback'),
3431 - 'mxchat-chatbot',
3432 - 'mxchat_chatbot_section'
3433 - );
3434 -
3435 - add_settings_field(
3436 - 'rate_limit_message',
3437 - esc_html__('Rate Limit Message', 'mxchat'),
3438 - array($this, 'mxchat_rate_limit_message_callback'),
3439 - 'mxchat-chatbot',
3440 - 'mxchat_chatbot_section'
3441 - );
3442 -
3443 - add_settings_field(
3444 5179 'pre_chat_message',
3445 5180 esc_html__('Chat Teaser Pop-up', 'mxchat'),
3446 5181 array($this, 'mxchat_pre_chat_message_callback'),
3447 5182 'mxchat-chatbot',
@@ -3512,8 +5247,16 @@
3512 5247 'mxchat_chatbot_section'
3513 5248 );
3514 5249
3515 5250
5251 + add_settings_field(
5252 + 'rate_limits',
5253 + __('Rate Limits Settings', 'mxchat'),
5254 + array($this, 'mxchat_rate_limits_callback'),
5255 + 'mxchat-chatbot',
5256 + 'mxchat_chatbot_section'
5257 + );
5258 +
3516 5259 // Loops Settings Section
3517 5260 add_settings_section(
3518 5261 'mxchat_loops_section',
3519 5262 esc_html__('Loops Settings', 'mxchat'),
@@ -3624,8 +5367,26 @@
3624 5367 array($this, 'mxchat_chat_toolbar_toggle_callback'),
3625 5368 'mxchat-embed',
3626 5369 'mxchat_pdf_intent_section'
3627 5370 );
5371 +
5372 + // PDF Upload Button Toggle
5373 + add_settings_field(
5374 + 'show_pdf_upload_button',
5375 + __('Show PDF Upload Button', 'mxchat'),
5376 + array($this, 'mxchat_show_pdf_upload_button_callback'),
5377 + 'mxchat-embed',
5378 + 'mxchat_pdf_intent_section'
5379 + );
5380 +
5381 + // Word Upload Button Toggle
5382 + add_settings_field(
5383 + 'show_word_upload_button',
5384 + __('Show Word Upload Button', 'mxchat'),
5385 + array($this, 'mxchat_show_word_upload_button_callback'),
5386 + 'mxchat-embed',
5387 + 'mxchat_pdf_intent_section'
5388 + );
3628 5389
3629 5390 add_settings_field(
3630 5391 'pdf_intent_trigger_text',
3631 5392 __('Intent Trigger Text', 'mxchat'),
@@ -3722,9 +5483,9 @@
3722 5483
3723 5484 // General Settings Section
3724 5485 add_settings_section(
3725 5486 'mxchat_general_section',
3726 - esc_html__('Frequently Asked Questions (FAQ)', 'mxchat'),
5487 + esc_html__('YouTube Tutorials', 'mxchat'),
3727 5488 null,
3728 5489 'mxchat-general'
3729 5490 );
3730 5491 }
@@ -3895,80 +5656,207 @@
3895 5656 }
3896 5657 }
3897 5658
3898 5659
3899 -public function mxchat_rate_limit_logged_out_callback() {
3900 - // Load the entire 'mxchat_options' array
5660 +public function mxchat_rate_limits_callback() {
3901 5661 $all_options = get_option('mxchat_options', []);
3902 -
3903 - // Retrieve the saved rate limit or use the default value
3904 - $default_rate_limit = '10';
3905 - $selected_rate_limit = isset($all_options['rate_limit_logged_out']) ? $all_options['rate_limit_logged_out'] : $default_rate_limit;
3906 -
5662 +
3907 5663 // Define available rate limits
3908 - $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited');
3909 -
3910 - // Output the dropdown
5664 + $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
5665 +
5666 + // Define available timeframes
5667 + $timeframes = array(
5668 + 'hourly' => __('Per Hour', 'mxchat'),
5669 + 'daily' => __('Per Day', 'mxchat'),
5670 + 'weekly' => __('Per Week', 'mxchat'),
5671 + 'monthly' => __('Per Month', 'mxchat')
5672 + );
5673 +
5674 + // Get all roles plus a "logged_out" pseudo-role
5675 + $roles = wp_roles()->get_names();
5676 + $roles['logged_out'] = __('Logged Out Users', 'mxchat');
5677 +
5678 + // Start the wrapper
3911 5679 echo '<div class="pro-feature-wrapper active">';
3912 - echo '<select id="rate_limit_logged_out" name="rate_limit_logged_out">';
3913 - foreach ($rate_limits as $limit) {
3914 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
3915 - }
3916 - echo '</select>';
3917 - echo '<p class="description">' . esc_html__('Set the maximum number of messages a logged-out user can send within a 24-hour period.', 'mxchat') . '</p>';
3918 - echo '</div>';
3919 -}
3920 -
3921 -// Add this new callback function
3922 -public function mxchat_rate_limit_roles_callback() {
3923 - $all_options = get_option('mxchat_options', []);
3924 - $roles = wp_roles()->get_names();
3925 - $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited');
3926 -
3927 - echo '<div class="pro-feature-wrapper active mxchat-autosave-section">';
3928 -
5680 + echo '<div class="mxchat-rate-limits-container">';
5681 +
5682 + // Add improved styling
5683 + echo '<style>
5684 + .mxchat-rate-limits-container {
5685 + max-width: 900px;
5686 + }
5687 + .mxchat-rate-limit-row {
5688 + display: flex;
5689 + flex-wrap: wrap;
5690 + align-items: flex-start;
5691 + margin-bottom: 20px;
5692 + padding: 20px;
5693 + background: #fff;
5694 + border-radius: 8px;
5695 + border: 1px solid #e0e0e0;
5696 + box-shadow: 0 2px 4px rgba(0,0,0,0.04);
5697 + transition: all 0.2s ease;
5698 + }
5699 + .mxchat-rate-limit-row:hover {
5700 + box-shadow: 0 4px 8px rgba(0,0,0,0.08);
5701 + border-color: #c7c7c7;
5702 + }
5703 + .mxchat-rate-limit-role {
5704 + width: 160px;
5705 + font-weight: 600;
5706 + font-size: 15px;
5707 + margin-right: 20px;
5708 + padding-top: 4px;
5709 + color: #23282d;
5710 + }
5711 + .mxchat-rate-limit-controls-wrapper {
5712 + flex: 1;
5713 + }
5714 + .mxchat-rate-limit-controls {
5715 + display: flex;
5716 + flex-wrap: wrap;
5717 + gap: 15px;
5718 + align-items: center;
5719 + margin-bottom: 15px;
5720 + }
5721 + .mxchat-rate-limit-controls > div {
5722 + margin-bottom: 5px;
5723 + }
5724 + .mxchat-rate-limit-controls label {
5725 + display: block;
5726 + margin-bottom: 5px;
5727 + font-weight: 500;
5728 + color: #50575e;
5729 + }
5730 + .mxchat-rate-limit-message {
5731 + width: 100%;
5732 + margin-top: 15px;
5733 + }
5734 + .mxchat-rate-limit-message label {
5735 + display: block;
5736 + margin-bottom: 5px;
5737 + font-weight: 500;
5738 + color: #50575e;
5739 + }
5740 + .mxchat-rate-limit-message textarea {
5741 + width: 100%;
5742 + min-height: 70px;
5743 + padding: 8px 12px;
5744 + border-radius: 4px;
5745 + resize: vertical;
5746 + font-size: 14px;
5747 + }
5748 + .mxchat-rate-limit-controls select {
5749 + min-width: 120px;
5750 + padding: 6px 24px 6px 10px;
5751 + }
5752 + @media (max-width: 782px) {
5753 + .mxchat-rate-limit-row {
5754 + flex-direction: column;
5755 + }
5756 + .mxchat-rate-limit-role {
5757 + margin-bottom: 15px;
5758 + width: 100%;
5759 + font-size: 16px;
5760 + }
5761 + .mxchat-rate-limit-controls {
5762 + flex-direction: column;
5763 + align-items: flex-start;
5764 + gap: 12px;
5765 + }
5766 + .mxchat-rate-limit-controls > div {
5767 + width: 100%;
5768 + }
5769 + .mxchat-rate-limit-controls select {
5770 + width: 100%;
5771 + }
5772 + }
5773 + </style>';
5774 +
5775 + echo '<p class="description" style="margin-bottom: 20px;">' .
5776 + 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') .
5777 + '</p>';
5778 +
5779 + // Output the controls for each role
3929 5780 foreach ($roles as $role_id => $role_name) {
3930 - $default_rate_limit = '100';
3931 - $selected_rate_limit = isset($all_options['role_rate_limits'][$role_id])
3932 - ? $all_options['role_rate_limits'][$role_id]
3933 - : $default_rate_limit;
3934 -
3935 - echo '<div style="margin-bottom: 10px;">';
3936 - echo '<label style="display: inline-block; width: 150px;">' . esc_html($role_name) . ':</label>';
3937 - echo '<select
3938 - id="role_rate_limits_' . esc_attr($role_id) . '"
3939 - name="mxchat_options[role_rate_limits][' . esc_attr($role_id) . ']"
5781 + // Get saved options or defaults
5782 + $default_limit = ($role_id === 'logged_out') ? '10' : '100';
5783 + $default_timeframe = 'daily';
5784 + $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
5785 +
5786 + $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
5787 + ? $all_options['rate_limits'][$role_id]['limit']
5788 + : $default_limit;
5789 +
5790 + $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
5791 + ? $all_options['rate_limits'][$role_id]['timeframe']
5792 + : $default_timeframe;
5793 +
5794 + $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
5795 + ? $all_options['rate_limits'][$role_id]['message']
5796 + : $default_message;
5797 +
5798 + // Output the row
5799 + echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
5800 +
5801 + // Role label
5802 + echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
5803 +
5804 + // Controls section
5805 + echo '<div class="mxchat-rate-limit-controls-wrapper">';
5806 +
5807 + // Rate limit and timeframe controls
5808 + echo '<div class="mxchat-rate-limit-controls">';
5809 +
5810 + // Limit dropdown
5811 + echo '<div>';
5812 + echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
5813 + echo '<select
5814 + id="rate_limits_' . esc_attr($role_id) . '_limit"
5815 + name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
3940 5816 class="mxchat-autosave-field">';
3941 5817 foreach ($rate_limits as $limit) {
3942 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
5818 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
3943 5819 }
3944 5820 echo '</select>';
3945 5821 echo '</div>';
5822 +
5823 + // Timeframe dropdown
5824 + echo '<div>';
5825 + echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
5826 + echo '<select
5827 + id="rate_limits_' . esc_attr($role_id) . '_timeframe"
5828 + name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
5829 + class="mxchat-autosave-field">';
5830 + foreach ($timeframes as $value => $label) {
5831 + echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
5832 + }
5833 + echo '</select>';
5834 + echo '</div>';
5835 +
5836 + echo '</div>'; // End controls
5837 +
5838 + // Custom message textarea
5839 + echo '<div class="mxchat-rate-limit-message">';
5840 + echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
5841 + echo '<textarea
5842 + id="rate_limits_' . esc_attr($role_id) . '_message"
5843 + name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
5844 + class="mxchat-autosave-field"
5845 + placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
5846 + esc_textarea($custom_message) .
5847 + '</textarea>';
5848 + echo '</div>'; // End message
5849 +
5850 + echo '</div>'; // End controls wrapper
5851 +
5852 + echo '</div>'; // End row
3946 5853 }
3947 -
3948 - echo '<p class="description">' . esc_html__('Set the maximum number of messages users in each role can send within a 24-hour period.', 'mxchat') . '</p>';
3949 - echo '</div>';
5854 +
5855 + echo '</div>'; // End container
5856 +
5857 + echo '</div>'; // End pro-feature-wrapper
3950 5858 }
3951 -
3952 -public function mxchat_rate_limit_message_callback() {
3953 - // Load the entire 'mxchat_options' array
3954 - $all_options = get_option('mxchat_options', []);
3955 -
3956 - // Retrieve the saved message or use the default value
3957 - $default_message = esc_html__('Rate limit exceeded. Please try again later.', 'mxchat');
3958 - $rate_limit_message = isset($all_options['rate_limit_message']) ? $all_options['rate_limit_message'] : $default_message;
3959 -
3960 - // Output the textarea
3961 - echo '<div class="pro-feature-wrapper active">';
3962 - printf(
3963 - '<textarea id="rate_limit_message" name="rate_limit_message" rows="3" cols="50">%s</textarea>',
3964 - esc_textarea($rate_limit_message)
3965 - );
3966 - echo '<p class="description">' . esc_html__('This message will be displayed when a user exceeds the rate limit.', 'mxchat') . '</p>';
3967 - echo '</div>';
3968 -}
3969 -
3970 -
3971 5859 private function mxchat_add_option_field($id, $title, $callback = '') {
3972 5860 add_settings_field(
3973 5861 $id,
3974 5862 __($title, 'mxchat'),
@@ -3977,114 +5865,113 @@
3977 5865 'mxchat_setting_section_id',
3978 5866 $id === 'model' ? ['label_for' => 'model'] : []
3979 5867 );
3980 5868 }
3981 -
5869 +
5870 +// OpenAI API Key
3982 5871 public function api_key_callback() {
3983 - // Retrieve from your stored 'api_key' in the mxchat_options array
3984 5872 $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
3985 -
3986 - // Notice we changed the name to "api_key" (no array notation).
3987 - echo '<input type="password" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text" />';
5873 +
5874 + echo '<div class="api-key-wrapper" data-provider="openai">';
5875 + echo '<input type="password" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text" autocomplete="off" />';
3988 5876 echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
3989 - echo '<p class="description">' . wp_kses_post(__('The <strong>OpenAI API key is required even when using other models</strong> as it is used for vector embedding functionality. You must add credits to your OpenAI billing account before use.', 'mxchat')) . '</p>';
5877 + echo '<p class="description api-key-notice">' . esc_html__('Required for your selected chat model. Important: You must add credits before use.', 'mxchat') . '</p>';
5878 + echo '</div>';
3990 5879 }
5880 +
5881 +// X.AI API Key
3991 5882 public function xai_api_key_callback() {
3992 - // Check if the feature is activated (paid feature)
3993 - $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
3994 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
3995 -
3996 - // Retrieve the X.AI API key value
3997 5883 $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
3998 -
3999 - // Render the input field for the X.AI API key
4000 - echo '<div class="' . esc_attr($class) . '">';
4001 - printf(
4002 - '<input type="password" id="xai_api_key" name="xai_api_key" value="%s" class="regular-text" %s />',
4003 - $xaiApiKey,
4004 - $disabled
4005 - );
5884 +
5885 + echo '<div class="api-key-wrapper" data-provider="xai">';
5886 + echo '<input type="password" id="xai_api_key" name="xai_api_key" value="' . $xaiApiKey . '" class="regular-text" autocomplete="off" />';
4006 5887 echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
4007 -
4008 - // If the feature is not activated, show the overlay with a "Pro Only" message
4009 - if (!$this->is_activated) {
4010 - echo '<div class="pro-feature-overlay">';
4011 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
4012 - echo '</div>';
4013 - }
4014 -
5888 + echo '<p class="description api-key-notice">' . esc_html__('Required for your selected chat model. Important: You must add credits before use.', 'mxchat') . '</p>';
4015 5889 echo '</div>';
4016 5890 }
5891 +// Claude API Key
4017 5892 public function claude_api_key_callback() {
4018 - // Check if the feature is activated (paid feature)
4019 - $disabled = $this->is_activated ? '' : 'disabled';
4020 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4021 -
4022 - // Retrieve the Claude API key value directly like the others
4023 5893 $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
4024 5894
4025 - // Use direct name field like the other working API keys
4026 - echo '<div class="' . esc_attr($class) . '">';
4027 - printf(
4028 - '<input type="password" id="claude_api_key" name="claude_api_key" value="%s" class="regular-text" %s />',
4029 - $claudeApiKey,
4030 - $disabled
4031 - );
5895 + echo '<div class="api-key-wrapper" data-provider="claude">';
5896 + echo '<input type="password" id="claude_api_key" name="claude_api_key" value="' . $claudeApiKey . '" class="regular-text" autocomplete="off" />';
4032 5897 echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
4033 -
4034 - if (!$this->is_activated) {
4035 - echo '<div class="pro-feature-overlay">';
4036 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
4037 - echo '</div>';
4038 - }
5898 + echo '<p class="description api-key-notice">' . esc_html__('Required for your selected chat model. Important: You must add credits before use.', 'mxchat') . '</p>';
4039 5899 echo '</div>';
4040 5900 }
5901 +
5902 +// DeepSeek API Key
4041 5903 public function deepseek_api_key_callback() {
4042 - // Retrieve from your stored 'deepseek_api_key' in the mxchat_options array
4043 5904 $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
4044 -
4045 - // Notice we changed the name to "deepseek_api_key" (no array notation).
4046 - echo '<input type="password" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text" />';
5905 +
5906 + echo '<div class="api-key-wrapper" data-provider="deepseek">';
5907 + echo '<input type="password" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text" autocomplete="off" />';
4047 5908 echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5909 + echo '<p class="description api-key-notice">' . esc_html__('Required for your selected chat model. Important: You must add credits before use.', 'mxchat') . '</p>';
5910 + echo '</div>';
4048 5911 }
4049 5912
5913 +// Gemini API Key
5914 +public function gemini_api_key_callback() {
5915 + $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
5916 +
5917 + echo '<div class="api-key-wrapper" data-provider="gemini">';
5918 + echo '<input type="password" id="gemini_api_key" name="gemini_api_key" value="' . $geminiApiKey . '" class="regular-text" autocomplete="off" />';
5919 + echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5920 + echo '<p class="description api-key-notice">' . esc_html__('Required for Google Gemini models. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
5921 + echo '</div>';
5922 +}
4050 5923
5924 +// Voyage API Key
5925 +public function voyage_api_key_callback() {
5926 + $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
5927 +
5928 + echo '<div class="api-key-wrapper" data-provider="voyage">';
5929 + echo '<input type="password" id="voyage_api_key" name="voyage_api_key" value="' . $apiKey . '" class="regular-text" autocomplete="off" />';
5930 + echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5931 + echo '<p class="description api-key-notice">' . esc_html__('Required for your selected embedding model. Important: You must add credits before use.', 'mxchat') . '</p>';
5932 + echo '</div>';
5933 +}
4051 5934
4052 -
4053 -
4054 5935 public function mxchat_loops_api_key_callback() {
4055 - // Support both old and new format
4056 5936 $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
4057 -
4058 - echo '<div class="api-key-wrapper">';
5937 +
5938 + // Hidden fields to "trap" autofill
5939 + echo '<input type="text" style="display:none" autocomplete="username" />';
5940 + echo '<input type="password" style="display:none" autocomplete="current-password" />';
5941 +
5942 + echo '<div class="api-key-wrapper" data-provider="loops">';
4059 5943 echo sprintf(
4060 - '<input type="password" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text" />',
5944 + '<input type="password" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text" autocomplete="new-password" />',
4061 5945 $loops_api_key
4062 5946 );
4063 5947 echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
4064 5948 echo '</div>';
4065 - echo '<p class="description">' . esc_html__('Enter your Loops API Key here. (See FAQ for details)', 'mxchat') . '</p>';
5949 + echo '<p class="description">' . esc_html__('Enter your Loops API Key here. Once entered, refreshed page to load list (See FAQ for details)', 'mxchat') . '</p>';
4066 5950 }
4067 -
4068 5951 public function mxchat_loops_mailing_list_callback() {
4069 5952 // Add error handling and type checking
4070 5953 $loops_api_key = '';
4071 5954 $selected_list = '';
4072 -
5955 +
4073 5956 // Safely get the API key
4074 5957 if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
4075 5958 $loops_api_key = $this->options['loops_api_key'];
4076 5959 }
4077 -
5960 +
4078 5961 // Safely get the selected list
4079 5962 if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) {
4080 5963 $selected_list = $this->options['loops_mailing_list'];
4081 5964 }
4082 -
5965 +
4083 5966 if (!empty($loops_api_key)) {
4084 5967 $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
4085 5968 if (is_array($lists) && !empty($lists)) {
4086 5969 echo '<select id="loops_mailing_list" name="loops_mailing_list">';
5970 +
5971 + // Add a default "Select a list" option
5972 + echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
5973 +
4087 5974 foreach ($lists as $list) {
4088 5975 if (is_array($list) && isset($list['id']) && isset($list['name'])) {
4089 5976 echo sprintf(
4090 5977 '<option value="%s" %s>%s</option>',
@@ -4094,8 +5981,9 @@
4094 5981 );
4095 5982 }
4096 5983 }
4097 5984 echo '</select>';
5985 + echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
4098 5986 } else {
4099 5987 echo '<p class="description">' . esc_html__('No lists found. Please verify your API Key.', 'mxchat') . '</p>';
4100 5988 }
4101 5989 } else {
@@ -4164,10 +6052,19 @@
4164 6052
4165 6053 public function mxchat_model_callback() {
4166 6054 // Define available models grouped by provider
4167 6055 $models = array(
6056 + esc_html__('Google Gemini Models', 'mxchat') => array(
6057 + 'gemini-2.0-flash' => esc_html__('Gemini 2.0 Flash (Next-Gen Features)', 'mxchat'),
6058 + 'gemini-2.0-flash-lite' => esc_html__('Gemini 2.0 Flash-Lite (Cost-Efficient)', 'mxchat'),
6059 + 'gemini-1.5-pro' => esc_html__('Gemini 1.5 Pro (Complex Reasoning)', 'mxchat'),
6060 + 'gemini-1.5-flash' => esc_html__('Gemini 1.5 Flash (Fast & Versatile)', 'mxchat'),
6061 + ),
4168 6062 esc_html__('X.AI Models', 'mxchat') => array(
4169 - 'grok-beta' => esc_html__('grok-beta (Early Beta)', 'mxchat'),
6063 + 'grok-3-beta' => esc_html__('Grok-3 (Powerful)', 'mxchat'),
6064 + 'grok-3-fast-beta' => esc_html__('Grok-3 Fast (High Performance)', 'mxchat'),
6065 + 'grok-3-mini-beta' => esc_html__('Grok-3 Mini (Affordable)', 'mxchat'),
6066 + 'grok-3-mini-fast-beta' => esc_html__('Grok-3 Mini Fast (Quick Response)', 'mxchat'),
4170 6067 'grok-2' => esc_html__('Grok 2', 'mxchat')
4171 6068 ),
4172 6069 esc_html__('DeepSeek Models', 'mxchat') => array(
4173 6070 'deepseek-chat' => esc_html__('DeepSeek-V3', 'mxchat'),
@@ -4172,14 +6069,16 @@
4172 6069 esc_html__('DeepSeek Models', 'mxchat') => array(
4173 6070 'deepseek-chat' => esc_html__('DeepSeek-V3', 'mxchat'),
4174 6071 ),
4175 6072 esc_html__('Claude Models', 'mxchat') => array(
4176 - 'claude-3-5-sonnet-20241022' => esc_html__('Claude 3.5 Sonnet (Most Intelligent)', 'mxchat'),
6073 + 'claude-3-7-sonnet-20250219' => esc_html__('Claude 3.7 Sonnet (Most Intelligent)', 'mxchat'),
6074 + 'claude-3-5-sonnet-20241022' => esc_html__('Claude 3.5 Sonnet (Intelligent)', 'mxchat'),
4177 6075 'claude-3-opus-20240229' => esc_html__('Claude 3 Opus (Highly Complex Tasks)', 'mxchat'),
4178 6076 'claude-3-sonnet-20240229' => esc_html__('Claude 3 Sonnet (Balanced)', 'mxchat'),
4179 6077 'claude-3-haiku-20240307' => esc_html__('Claude 3 Haiku (Fastest)', 'mxchat')
4180 6078 ),
4181 6079 esc_html__('OpenAI Models', 'mxchat') => array(
6080 + 'gpt-4.1-2025-04-14' => esc_html__('GPT-4.1 (Flagship for Complex Tasks)', 'mxchat'),
4182 6081 'gpt-4o' => esc_html__('GPT-4o (Recommended)', 'mxchat'),
4183 6082 'gpt-4o-mini' => esc_html__('GPT-4o Mini (Fast and Lightweight)', 'mxchat'),
4184 6083 'gpt-4-turbo' => esc_html__('GPT-4 Turbo (High-Performance)', 'mxchat'),
4185 6084 'gpt-4' => esc_html__('GPT-4 (High Intelligence)', 'mxchat'),
@@ -4185,40 +6084,64 @@
4185 6084 'gpt-4' => esc_html__('GPT-4 (High Intelligence)', 'mxchat'),
4186 6085 'gpt-3.5-turbo' => esc_html__('GPT-3.5 Turbo (Affordable and Fast)', 'mxchat')
4187 6086 )
4188 6087 );
4189 -
6088 +
4190 6089 // Retrieve the currently selected model from saved options
4191 6090 $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-4o';
4192 -
6091 +
4193 6092 // Begin the select dropdown
4194 - echo '<select id="model" name="model">'; // No array notation in name attribute
4195 -
6093 + echo '<select id="model" name="model">';
6094 +
4196 6095 // Iterate over groups of models
4197 6096 foreach ($models as $group_label => $group_models) {
4198 6097 echo '<optgroup label="' . esc_attr($group_label) . '">';
4199 -
6098 +
4200 6099 foreach ($group_models as $model_value => $model_label) {
4201 - // Disable Pro-only models for non-activated users
4202 - $disabled = (!$this->is_activated && ($group_label === esc_html__('X.AI Models', 'mxchat') || $group_label === esc_html__('Claude Models', 'mxchat'))) ? 'disabled' : '';
4203 - $label_suffix = (!$this->is_activated && ($group_label === esc_html__('X.AI Models', 'mxchat') || $group_label === esc_html__('Claude Models', 'mxchat'))) ? esc_html__(' (Pro Only)', 'mxchat') : '';
4204 -
4205 - // Output the option element
4206 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . ' ' . $disabled . '>' . esc_html($model_label . $label_suffix) . '</option>';
6100 + // All models enabled - no disabled attribute or Pro Only label
6101 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
4207 6102 }
4208 -
6103 +
4209 6104 echo '</optgroup>';
4210 6105 }
4211 -
6106 +
4212 6107 // Close the select dropdown
4213 6108 echo '</select>';
6109 +
6110 + // Updated description to remove mention of Pro-only models
6111 + echo '<p class="description">' . esc_html__('Select the AI model your chatbot will use for chatting.', 'mxchat') . '</p>';
6112 +}
4214 6113
4215 - // Add a description below the dropdown
4216 - echo '<p class="description">' . esc_html__('Select the AI model to use for your chatbot. Pro-only models are marked accordingly.', 'mxchat') . '</p>';
6114 +
6115 +// Callback function for embedding model selection
6116 +public function embedding_model_callback() {
6117 + $models = array(
6118 + esc_html__('OpenAI Embeddings', 'mxchat') => array(
6119 + 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
6120 + 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
6121 + 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
6122 + ),
6123 + esc_html__('Voyage AI Embeddings', 'mxchat') => array(
6124 + 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
6125 + )
6126 + );
6127 +
6128 + $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
6129 +
6130 + echo '<select id="embedding_model" name="embedding_model">';
6131 + foreach ($models as $group_label => $group_models) {
6132 + echo '<optgroup label="' . esc_attr($group_label) . '">';
6133 + foreach ($group_models as $model_value => $model_label) {
6134 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
6135 + }
6136 + echo '</optgroup>';
6137 + }
6138 + echo '</select>';
6139 +echo '<p class="description"><span class="red-warning">IMPORTANT:</span> Select the model for vector embeddings. Changing models is not recommended; if you do, you must delete all existing knowledge & intent data and reconfigure them.</p>';
6140 +
4217 6141 }
4218 6142
4219 6143
4220 -
4221 6144 public function mxchat_top_bar_title_callback() {
4222 6145 // Retrieve the current value of the top bar title from saved options
4223 6146 $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
4224 6147
@@ -4227,9 +6150,16 @@
4227 6150
4228 6151 // Add a description
4229 6152 echo '<p class="description">' . esc_html__('Enter the title text that will appear on the top bar of the chatbot.', 'mxchat') . '</p>';
4230 6153 }
4231 -
6154 +public function mxchat_ai_agent_text_callback() {
6155 + // Retrieve the current value of the AI agent text from saved options
6156 + $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
6157 + // Render the input field
6158 + echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
6159 + // Add a description
6160 + echo '<p class="description">' . esc_html__('Enter the text that will appear for AI agents in the status indicator. Default: "AI Agent"', 'mxchat') . '</p>';
6161 +}
4232 6162 public function enable_email_block_callback() {
4233 6163 // Load full plugin options array
4234 6164 $all_options = get_option('mxchat_options', []);
4235 6165
@@ -4249,9 +6179,8 @@
4249 6179 echo '<p class="description">' . esc_html__('Their email will appear at the top of the transcript. Email form will show for users who are not logged in or have not provided an email within 24h.', 'mxchat') . '</p>';
4250 6180 }
4251 6181
4252 6182
4253 -
4254 6183 public function email_blocker_header_content_callback() {
4255 6184 // Load the entire 'mxchat_options' array
4256 6185 $all_options = get_option('mxchat_options', []);
4257 6186
@@ -4259,14 +6188,15 @@
4259 6188 $content = isset($all_options['email_blocker_header_content'])
4260 6189 ? $all_options['email_blocker_header_content']
4261 6190 : '';
4262 6191
4263 - // Render the textarea
6192 + // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
4264 6193 echo '<textarea
4265 6194 id="email_blocker_header_content"
4266 6195 name="email_blocker_header_content"
4267 6196 rows="5"
4268 6197 cols="70"
6198 + data-setting="email_blocker_header_content"
4269 6199 >' . esc_textarea($content) . '</textarea>';
4270 6200
4271 6201 echo '<p class="description">';
4272 6202 echo esc_html__('You may enter HTML here, such as &lt;h2&gt;Welcome&lt;/h2&gt; or &lt;p&gt;Let\'s get started&lt;/p&gt;.', 'mxchat');
@@ -4272,9 +6202,8 @@
4272 6202 echo esc_html__('You may enter HTML here, such as &lt;h2&gt;Welcome&lt;/h2&gt; or &lt;p&gt;Let\'s get started&lt;/p&gt;.', 'mxchat');
4273 6203 echo '</p>';
4274 6204 }
4275 6205
4276 -
4277 6206 public function email_blocker_button_text_callback() {
4278 6207 // Load the entire 'mxchat_options' array
4279 6208 $all_options = get_option('mxchat_options', []);
4280 6209
@@ -4295,23 +6224,20 @@
4295 6224
4296 6225 public function mxchat_intro_message_callback() {
4297 6226 // Load the entire 'mxchat_options' array
4298 6227 $all_options = get_option('mxchat_options', []);
4299 -
4300 6228 // Retrieve the saved intro message or use the default
4301 6229 $default_message = __('Hello! How can I assist you today?', 'mxchat');
4302 6230 $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
4303 -
4304 - // Output the textarea with the saved value
6231 + // Output the textarea with the saved value without escaping HTML
4305 6232 ?>
4306 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea($saved_message); ?></textarea>
6233 + <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo $saved_message; ?></textarea>
4307 6234 <p class="description">
4308 - <?php esc_html_e('Enter your message. Line breaks will be preserved.', 'mxchat'); ?>
6235 + <?php esc_html_e('Enter your message. HTML tags and line breaks will be preserved.', 'mxchat'); ?>
4309 6236 </p>
4310 6237 <?php
4311 6238 }
4312 6239
4313 -
4314 6240 public function mxchat_input_copy_callback() {
4315 6241 // Load the entire 'mxchat_options' array
4316 6242 $all_options = get_option('mxchat_options', []);
4317 6243
@@ -5075,141 +7001,116 @@
5075 7001 echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
5076 7002 }
5077 7003
5078 7004 public function mxchat_chat_toolbar_toggle_callback() {
5079 - // Get chat toolbar toggle value with fallback
5080 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
5081 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
5082 -
5083 - // Check if the plugin is activated (paid feature)
5084 - $disabled = $this->is_activated ? '' : 'disabled';
5085 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5086 -
5087 - echo '<div class="' . esc_attr($class) . '">';
5088 -
5089 - // Output the toggle switch
5090 - echo '<label class="toggle-switch">';
5091 - echo sprintf(
5092 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s %s />',
5093 - esc_attr($checked),
5094 - esc_attr($disabled)
5095 - );
5096 - echo '<span class="slider"></span>';
5097 - echo '</label>';
5098 -
5099 - // Pro feature overlay
5100 - if (!$this->is_activated) {
5101 - echo '<div class="pro-feature-overlay">';
5102 - echo '<a href="https://mxchat.ai/" target="_blank">';
5103 - echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="' . esc_attr__('Pro Only', 'mxchat') . '" />';
5104 - echo '</a>';
5105 - echo '</div>';
5106 - }
5107 -
5108 - echo '</div>';
5109 - 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>';
7005 + // Get chat toolbar toggle value with fallback
7006 + $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
7007 + $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
7008 +
7009 + // Output the toggle switch
7010 + echo '<label class="toggle-switch">';
7011 + echo sprintf(
7012 + '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
7013 + esc_attr($checked)
7014 + );
7015 + echo '<span class="slider"></span>';
7016 + echo '</label>';
7017 +
7018 + 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>';
5110 7019 }
7020 +/**
7021 + * Callback for PDF upload button toggle setting
7022 + */
7023 +public function mxchat_show_pdf_upload_button_callback() {
7024 + // Get toggle value with fallback
7025 + $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
7026 + $checked = ($show_pdf_button === 'on') ? 'checked' : '';
7027 +
7028 + // Output the toggle switch
7029 + echo '<label class="toggle-switch">';
7030 + echo sprintf(
7031 + '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
7032 + esc_attr($checked)
7033 + );
7034 + echo '<span class="slider"></span>';
7035 + echo '</label>';
7036 +
7037 + echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
7038 +}
7039 +/**
7040 + * Callback for Word upload button toggle setting
7041 + */
7042 +public function mxchat_show_word_upload_button_callback() {
7043 + // Get toggle value with fallback
7044 + $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
7045 + $checked = ($show_word_button === 'on') ? 'checked' : '';
7046 +
7047 + // Output the toggle switch
7048 + echo '<label class="toggle-switch">';
7049 + echo sprintf(
7050 + '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
7051 + esc_attr($checked)
7052 + );
7053 + echo '<span class="slider"></span>';
7054 + echo '</label>';
7055 +
7056 + echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
7057 +}
5111 7058
5112 -
5113 7059 public function mxchat_pdf_intent_trigger_text_callback() {
5114 - $disabled = $this->is_activated ? '' : 'disabled';
5115 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5116 7060 $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
5117 7061
5118 - echo '<div class="' . esc_attr($class) . '">';
5119 7062 echo sprintf(
5120 7063 '<textarea id="pdf_intent_trigger_text"
5121 7064 name="pdf_intent_trigger_text"
5122 7065 rows="3"
5123 7066 cols="50"
5124 - placeholder="%s"
5125 - %s>%s</textarea>',
7067 + placeholder="%s">%s</textarea>',
5126 7068 esc_attr__('Enter trigger text', 'mxchat'),
5127 - esc_attr($disabled),
5128 7069 isset($this->options['pdf_intent_trigger_text'])
5129 7070 ? esc_textarea($this->options['pdf_intent_trigger_text'])
5130 7071 : esc_textarea($default_text)
5131 7072 );
5132 7073 echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
5133 -
5134 - if (!$this->is_activated) {
5135 - echo '<div class="pro-feature-overlay">';
5136 - echo '<a href="https://mxchat.ai/" target="_blank">';
5137 - echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="' . esc_attr__('Pro Only', 'mxchat') . '" />';
5138 - echo '</a>';
5139 - echo '</div>';
5140 - }
5141 - echo '</div>';
5142 7074 }
5143 7075
5144 7076 public function mxchat_pdf_intent_success_text_callback() {
5145 - $disabled = $this->is_activated ? '' : 'disabled';
5146 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5147 7077 $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
5148 7078
5149 - echo '<div class="' . esc_attr($class) . '">';
5150 7079 echo sprintf(
5151 7080 '<textarea id="pdf_intent_success_text"
5152 7081 name="pdf_intent_success_text"
5153 7082 rows="3"
5154 7083 cols="50"
5155 - placeholder="%s"
5156 - %s>%s</textarea>',
7084 + placeholder="%s">%s</textarea>',
5157 7085 esc_attr__('Enter success text', 'mxchat'),
5158 - esc_attr($disabled),
5159 7086 isset($this->options['pdf_intent_success_text'])
5160 7087 ? esc_textarea($this->options['pdf_intent_success_text'])
5161 7088 : esc_textarea($default_text)
5162 7089 );
5163 7090 echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
5164 -
5165 - if (!$this->is_activated) {
5166 - echo '<div class="pro-feature-overlay">';
5167 - echo '<a href="https://mxchat.ai/" target="_blank">';
5168 - echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="' . esc_attr__('Pro Only', 'mxchat') . '" />';
5169 - echo '</a>';
5170 - echo '</div>';
5171 - }
5172 - echo '</div>';
5173 7091 }
5174 7092
5175 7093 public function mxchat_pdf_intent_error_text_callback() {
5176 - $disabled = $this->is_activated ? '' : 'disabled';
5177 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5178 7094 $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
5179 7095
5180 - echo '<div class="' . esc_attr($class) . '">';
5181 7096 echo sprintf(
5182 7097 '<textarea id="pdf_intent_error_text"
5183 7098 name="pdf_intent_error_text"
5184 7099 rows="3"
5185 7100 cols="50"
5186 - placeholder="%s"
5187 - %s>%s</textarea>',
7101 + placeholder="%s">%s</textarea>',
5188 7102 esc_attr__('Enter error text', 'mxchat'),
5189 - esc_attr($disabled),
5190 7103 isset($this->options['pdf_intent_error_text'])
5191 7104 ? esc_textarea($this->options['pdf_intent_error_text'])
5192 7105 : esc_textarea($default_text)
5193 7106 );
5194 7107 echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
5195 -
5196 - if (!$this->is_activated) {
5197 - echo '<div class="pro-feature-overlay">';
5198 - echo '<a href="https://mxchat.ai/" target="_blank">';
5199 - echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="' . esc_attr__('Pro Only', 'mxchat') . '" />';
5200 - echo '</a>';
5201 - echo '</div>';
5202 - }
5203 - echo '</div>';
5204 7108 }
5205 7109
5206 7110 public function mxchat_pdf_max_pages_callback() {
5207 - $disabled = $this->is_activated ? '' : 'disabled';
5208 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5209 7111 $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
5210 7112
5211 - echo '<div class="' . esc_attr($class) . '">';
5212 7113 echo sprintf(
5213 7114 '<input type="range"
5214 7115 id="pdf_max_pages"
5215 7116 name="pdf_max_pages"
@@ -5215,37 +7116,22 @@
5215 7116 name="pdf_max_pages"
5216 7117 min="1"
5217 7118 max="69"
5218 7119 value="%d"
5219 - %s
5220 7120 class="range-slider" />',
5221 - esc_attr($max_pages),
5222 - esc_attr($disabled)
7121 + esc_attr($max_pages)
5223 7122 );
5224 7123 echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
5225 7124 echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
5226 -
5227 - if (!$this->is_activated) {
5228 - echo '<div class="pro-feature-overlay">';
5229 - echo '<a href="https://mxchat.ai/" target="_blank">';
5230 - echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="' . esc_attr__('Pro Only', 'mxchat') . '" />';
5231 - echo '</a>';
5232 - echo '</div>';
5233 - }
5234 - echo '</div>';
5235 7125 }
5236 7126
5237 7127 public function mxchat_live_agent_status_callback() {
5238 - $disabled = $this->is_activated ? '' : 'disabled';
5239 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5240 7128 $status = isset($this->options['live_agent_status']) ? $this->options['live_agent_status'] : 'off';
5241 7129
5242 - echo '<div class="' . esc_attr($class) . '">';
5243 7130 echo '<label class="toggle-switch">';
5244 7131 echo sprintf(
5245 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s %s />',
5246 - checked($status, 'on', false),
5247 - esc_attr($disabled)
7132 + '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
7133 + checked($status, 'on', false)
5248 7134 );
5249 7135 echo '<span class="slider"></span>';
5250 7136 echo '</label>';
5251 7137 echo '<label for="live_agent_status" class="mxchat-status-label">';
@@ -5250,105 +7136,78 @@
5250 7136 echo '</label>';
5251 7137 echo '<label for="live_agent_status" class="mxchat-status-label">';
5252 7138 echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
5253 7139 echo '</label>';
5254 -
5255 - if (!$this->is_activated) {
5256 - echo '<div class="pro-feature-overlay">';
5257 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5258 - echo '</div>';
5259 - }
5260 - echo '</div>';
5261 7140 }
5262 7141
5263 -
5264 -// Away Message Callback
5265 7142 public function mxchat_live_agent_away_message_callback() {
5266 - $disabled = $this->is_activated ? '' : 'disabled';
5267 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5268 7143 $message = isset($this->options['live_agent_away_message'])
5269 7144 ? $this->options['live_agent_away_message']
5270 7145 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
5271 7146
5272 - echo '<div class="' . esc_attr($class) . '">';
5273 7147 printf(
5274 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50" %s>%s</textarea>',
5275 - esc_attr($disabled),
7148 + '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
5276 7149 esc_textarea($message)
5277 7150 );
5278 7151 echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
5279 -
5280 - if (!$this->is_activated) {
5281 - echo '<div class="pro-feature-overlay">';
5282 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5283 - echo '</div>';
5284 - }
5285 - echo '</div>';
5286 7152 }
5287 7153
5288 7154 public function mxchat_live_agent_notification_message_callback() {
5289 - $disabled = $this->is_activated ? '' : 'disabled';
5290 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5291 7155 $message = isset($this->options['live_agent_notification_message'])
5292 7156 ? $this->options['live_agent_notification_message']
5293 7157 : __('Live agent has been notified.', 'mxchat');
5294 7158
5295 - echo '<div class="' . esc_attr($class) . '">';
5296 7159 printf(
5297 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50" %s>%s</textarea>',
5298 - esc_attr($disabled),
7160 + '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
5299 7161 esc_textarea($message)
5300 7162 );
5301 7163 echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
5302 -
5303 - if (!$this->is_activated) {
5304 - echo '<div class="pro-feature-overlay">';
5305 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5306 - echo '</div>';
5307 - }
5308 - echo '</div>';
5309 7164 }
5310 7165
5311 7166 public function mxchat_live_agent_webhook_url_callback() {
5312 - $disabled = $this->is_activated ? '' : 'disabled';
5313 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5314 7167 $webhook_url = isset($this->options['live_agent_webhook_url'])
5315 7168 ? esc_url($this->options['live_agent_webhook_url'])
5316 7169 : esc_url(get_option('live_agent_webhook_url', ''));
5317 7170
5318 - echo '<div class="' . esc_attr($class) . '">';
5319 7171 printf(
5320 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" %s />',
5321 - $webhook_url,
5322 - esc_attr($disabled)
7172 + '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
7173 + $webhook_url
5323 7174 );
5324 7175 echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5325 7176 echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
7177 +}
5326 7178
5327 - if (!$this->is_activated) {
5328 - echo '<div class="pro-feature-overlay">';
5329 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5330 - echo '</div>';
5331 - }
5332 - echo '</div>';
7179 +public function mxchat_live_agent_secret_key_callback() {
7180 + printf(
7181 + '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
7182 + isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
7183 + );
7184 + echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7185 + echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
5333 7186 }
5334 7187
7188 +public function mxchat_live_agent_bot_token_callback() {
7189 + printf(
7190 + '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
7191 + isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
7192 + );
7193 + echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7194 + echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
7195 +}
5335 7196
5336 7197 public function mxchat_similarity_threshold_callback() {
5337 7198 // Load from mxchat_options array
5338 7199 $options = get_option('mxchat_options', []);
5339 -
5340 - // Get value with backwards compatibility
5341 - $threshold = isset($options['similarity_threshold'])
5342 - ? $options['similarity_threshold']
5343 - : get_option('mxchat_similarity_threshold', 80);
5344 -
7200 +
7201 + // Get value from options array with default of 80
7202 + $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
7203 +
5345 7204 echo '<div class="slider-container">';
5346 7205 echo sprintf(
5347 7206 '<input type="range"
5348 7207 id="similarity_threshold"
5349 7208 name="similarity_threshold"
5350 - min="70"
7209 + min="20"
5351 7210 max="85"
5352 7211 step="1"
5353 7212 value="%s"
5354 7213 class="range-slider" />',
@@ -5358,63 +7217,18 @@
5358 7217 '<span id="threshold_value" class="range-value">%s</span>',
5359 7218 esc_html($threshold)
5360 7219 );
5361 7220 echo '</div>';
5362 -
5363 7221 echo '<p class="description">';
5364 - echo esc_html__('Set the similarity threshold (recommended: 75) to balance accuracy; too high might limit your bot\'s ability to find relevant knowledge.', 'mxchat');
7222 + echo esc_html__('Set the similarity threshold to balance accuracy; too high might limit your bot\'s ability to find relevant knowledge. If your bot is not matching content, move to lowest setting to test.', 'mxchat');
5365 7223 echo '</p>';
5366 7224 }
5367 7225
5368 -
5369 -
5370 -public function mxchat_live_agent_secret_key_callback() {
5371 - $disabled = $this->is_activated ? '' : 'disabled';
5372 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5373 -
5374 - echo '<div class="' . esc_attr($class) . '">';
5375 - printf(
5376 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" %s />',
5377 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : '',
5378 - esc_attr($disabled)
5379 - );
5380 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5381 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
5382 -
5383 - if (!$this->is_activated) {
5384 - echo '<div class="pro-feature-overlay">';
5385 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5386 - echo '</div>';
5387 - }
5388 - echo '</div>';
5389 -}
5390 -
5391 -public function mxchat_live_agent_bot_token_callback() {
5392 - $disabled = $this->is_activated ? '' : 'disabled';
5393 - $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
5394 -
5395 - echo '<div class="' . esc_attr($class) . '">';
5396 - printf(
5397 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" %s />',
5398 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : '',
5399 - esc_attr($disabled)
5400 - );
5401 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
5402 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
5403 -
5404 - if (!$this->is_activated) {
5405 - echo '<div class="pro-feature-overlay">';
5406 - echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="' . esc_attr__('Pro Only', 'mxchat') . '" /></a>';
5407 - echo '</div>';
5408 - }
5409 - echo '</div>';
5410 -}
5411 -
5412 7226 public function mxchat_enqueue_admin_assets() {
5413 7227 wp_enqueue_style('wp-color-picker');
5414 7228
5415 7229 // Get the plugin version or file modification time for cache busting
5416 - $plugin_version = '2.0.5'; // Replace this with your plugin's version
7230 + $plugin_version = '2.1.7'; // Replace this with your plugin's version
5417 7231
5418 7232 // File paths
5419 7233 $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
5420 7234 $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
@@ -5420,8 +7234,10 @@
5420 7234 $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
5421 7235 $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
5422 7236 $knowledge_css_path = plugin_dir_path(__FILE__) . '../css/knowledge-style.css';
5423 7237 $intent_css_path = plugin_dir_path(__FILE__) . '../css/intent-style.css';
7238 + $transcripts_css_path = plugin_dir_path(__FILE__) . '../css/chat-transcripts.css';
7239 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
5424 7240
5425 7241 // Check if files exist and get modification times
5426 7242 $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
5427 7243 $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
@@ -5427,9 +7243,38 @@
5427 7243 $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
5428 7244 $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
5429 7245 $knowledge_css_version = file_exists($knowledge_css_path) ? filemtime($knowledge_css_path) : $plugin_version;
5430 7246 $intent_css_version = file_exists($intent_css_path) ? filemtime($intent_css_path) : $plugin_version;
5431 -
7247 + $transcripts_css_version = file_exists($transcripts_css_path) ? filemtime($transcripts_css_path) : $plugin_version;
7248 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
7249 +
7250 + $admin_status_js_path = plugin_dir_path(__FILE__) . '../js/admin-status.js';
7251 + $admin_status_js_version = file_exists($admin_status_js_path) ? filemtime($admin_status_js_path) : $plugin_version;
7252 +
7253 + // Check current admin page
7254 + $current_page = isset($_GET['page']) ? $_GET['page'] : '';
7255 +
7256 + // Only enqueue on the prompts page
7257 + if ($current_page === 'mxchat-prompts') {
7258 + wp_enqueue_script(
7259 + 'mxchat-status-updater',
7260 + plugin_dir_url(__FILE__) . '../js/admin-status.js',
7261 + array('jquery'),
7262 + $admin_status_js_version,
7263 + true
7264 + );
7265 +
7266 + // Add the nonce for the status updater
7267 + wp_localize_script(
7268 + 'mxchat-status-updater',
7269 + 'mxchat_status_data',
7270 + array(
7271 + 'ajax_url' => admin_url('admin-ajax.php'),
7272 + 'nonce' => wp_create_nonce('mxchat_status_nonce')
7273 + )
7274 + );
7275 + }
7276 +
5432 7277 // Enqueue scripts and styles with corrected paths
5433 7278 wp_enqueue_script(
5434 7279 'mxchat-color-picker',
5435 7280 plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
@@ -5453,15 +7298,23 @@
5453 7298 $plugin_version,
5454 7299 true
5455 7300 );
5456 7301
5457 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
5458 - 'ajax_url' => admin_url('admin-ajax.php'),
5459 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
5460 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
5461 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
5462 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
5463 - ));
7302 +wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
7303 + 'ajax_url' => admin_url('admin-ajax.php'),
7304 + 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
7305 + 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
7306 + 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
7307 + 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
7308 + 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
7309 + 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
7310 + 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
7311 + 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
7312 + 'is_activated' => $this->is_activated ? '1' : '0',
7313 + // Add these two new lines
7314 + 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
7315 + 'status_refresh_interval' => 5000, // Update every 5 seconds
7316 +));
5464 7317
5465 7318 // Enqueue the admin CSS
5466 7319 wp_enqueue_style(
5467 7320 'mxchat-admin-css',
@@ -5469,9 +7322,10 @@
5469 7322 array(),
5470 7323 $admin_css_version
5471 7324 );
5472 7325
5473 - if (isset($_GET['page']) && $_GET['page'] === 'mxchat-transcripts') {
7326 + // Conditional enqueue for transcripts page
7327 + if ($current_page === 'mxchat-transcripts') {
5474 7328 wp_enqueue_style(
5475 7329 'mxchat-chat-transcripts-css',
5476 7330 plugin_dir_url(__FILE__) . '../css/chat-transcripts.css',
5477 7331 array(),
@@ -5486,28 +7340,33 @@
5486 7340 true
5487 7341 );
5488 7342 }
5489 7343
5490 - wp_enqueue_style(
5491 - 'mxchat-knowledge-css',
5492 - plugin_dir_url(__FILE__) . '../css/knowledge-style.css',
5493 - array(),
5494 - $knowledge_css_version
5495 - );
7344 + // Only enqueue knowledge CSS on knowledge-related pages or all plugin pages
7345 + if (strpos($current_page, 'mxchat') !== false) {
7346 + wp_enqueue_style(
7347 + 'mxchat-knowledge-css',
7348 + plugin_dir_url(__FILE__) . '../css/knowledge-style.css',
7349 + array(),
7350 + $knowledge_css_version
7351 + );
7352 + }
5496 7353
7354 + // Only enqueue intent-style.css on the mxchat-actions page
7355 + if ($current_page === 'mxchat-actions') {
7356 + wp_enqueue_style(
7357 + 'mxchat-intent-css',
7358 + plugin_dir_url(__FILE__) . '../css/intent-style.css',
7359 + array(),
7360 + $intent_css_version
7361 + );
7362 + }
5497 7363
5498 - wp_enqueue_style(
5499 - 'mxchat-intent-css',
5500 - plugin_dir_url(__FILE__) . '../css/intent-style.css',
5501 - array(),
5502 - $intent_css_version
5503 - );
5504 -
5505 7364 // IMPORTANT: Use the same script handle as above for localizing mxchatPromptsAdmin
5506 - wp_localize_script( 'mxchat-admin-js', 'mxchatPromptsAdmin', array(
5507 - 'ajax_url' => admin_url( 'admin-ajax.php' ),
5508 - 'prompts_setting_nonce' => wp_create_nonce( 'mxchat_prompts_setting_nonce' ),
5509 - ) );
7365 + wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
7366 + 'ajax_url' => admin_url('admin-ajax.php'),
7367 + 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
7368 + ));
5510 7369
5511 7370 // Localize the script for color picker and settings
5512 7371 wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
5513 7372 'ajax_url' => admin_url('admin-ajax.php'),
@@ -5537,8 +7396,10 @@
5537 7396 'live_agent_bot_token' => $this->options['live_agent_bot_token'] ?? '',
5538 7397 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
5539 7398 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
5540 7399 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
7400 + 'show_pdf_upload_button' => $this->options['show_pdf_upload_button'] ?? 'on',
7401 + 'show_word_upload_button' => $this->options['show_word_upload_button'] ?? 'on',
5541 7402 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
5542 7403 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
5543 7404 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
5544 7405 ));
@@ -5553,9 +7414,9 @@
5553 7414 }
5554 7415
5555 7416 if (isset($input['similarity_threshold'])) {
5556 7417 $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
5557 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 70), 85); // Enforce range
7418 + $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
5558 7419 }
5559 7420
5560 7421 if (isset($input['xai_api_key'])) {
5561 7422 $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
@@ -5567,8 +7428,12 @@
5567 7428
5568 7429 if (isset($input['deepseek_api_key'])) {
5569 7430 $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
5570 7431 }
7432 +
7433 + if (isset($input['gemini_api_key'])) {
7434 + $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
7435 + }
5571 7436
5572 7437 if (isset($input['enable_woocommerce_integration'])) {
5573 7438 $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
5574 7439 }
@@ -5605,8 +7470,12 @@
5605 7470
5606 7471 if (isset($input['top_bar_title'])) {
5607 7472 $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
5608 7473 }
7474 +
7475 + if (isset($input['ai_agent_text'])) {
7476 + $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
7477 + }
5609 7478
5610 7479 if (isset($input['enable_email_block'])) {
5611 7480 $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
5612 7481 }
@@ -5619,9 +7488,9 @@
5619 7488 $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
5620 7489 }
5621 7490
5622 7491 if (isset($input['intro_message'])) {
5623 - $new_input['intro_message'] = sanitize_textarea_field($input['intro_message']); // Changed from sanitize_text_field
7492 + $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
5624 7493 }
5625 7494
5626 7495 if (isset($input['input_copy'])) {
5627 7496 $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
@@ -5630,53 +7499,89 @@
5630 7499 if (isset($input['rate_limit_message'])) {
5631 7500 $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
5632 7501 }
5633 7502
5634 - if (isset($input['rate_limit_logged_out'])) {
5635 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
5636 - $rate_limit = sanitize_text_field($input['rate_limit_logged_out']);
5637 -
5638 - if (in_array($rate_limit, $allowed_limits, true)) {
5639 - $new_input['rate_limit_logged_out'] = $rate_limit;
5640 - } else {
5641 - $new_input['rate_limit_logged_out'] = '10'; // Default for logged-out users
7503 +// Handle the new rate limits format
7504 +if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
7505 + $new_input['rate_limits'] = array();
7506 + $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
7507 + $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
7508 +
7509 + foreach ($input['rate_limits'] as $role_id => $settings) {
7510 + $new_input['rate_limits'][$role_id] = array();
7511 +
7512 + // Sanitize limit
7513 + if (isset($settings['limit'])) {
7514 + $limit = sanitize_text_field($settings['limit']);
7515 + if (in_array($limit, $allowed_limits, true)) {
7516 + $new_input['rate_limits'][$role_id]['limit'] = $limit;
7517 + } else {
7518 + $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
7519 + }
5642 7520 }
5643 - }
5644 -
5645 - // Handle role rate limits
5646 - if (isset($input['role_rate_limits']) && is_array($input['role_rate_limits'])) {
5647 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited');
5648 - $new_input['role_rate_limits'] = array();
5649 -
5650 - foreach ($input['role_rate_limits'] as $role_id => $rate_limit) {
5651 - $rate_limit = sanitize_text_field($rate_limit);
5652 - if (in_array($rate_limit, $allowed_limits, true)) {
5653 - $new_input['role_rate_limits'][$role_id] = $rate_limit;
7521 +
7522 + // Sanitize timeframe
7523 + if (isset($settings['timeframe'])) {
7524 + $timeframe = sanitize_text_field($settings['timeframe']);
7525 + if (in_array($timeframe, $allowed_timeframes, true)) {
7526 + $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
5654 7527 } else {
5655 - $new_input['role_rate_limits'][$role_id] = '100'; // Default
7528 + $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
5656 7529 }
5657 7530 }
7531 +
7532 + // Sanitize message
7533 + if (isset($settings['message'])) {
7534 + $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
7535 + }
5658 7536 }
7537 +}
5659 7538
5660 7539 if (isset($input['pre_chat_message'])) {
5661 7540 $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
5662 7541 }
7542 +
7543 + if (isset($input['voyage_api_key'])) {
7544 + $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
7545 + }
7546 +
7547 + // Add to your sanitize function
7548 + if (isset($input['embedding_model'])) {
7549 + $allowed_models = array(
7550 + 'text-embedding-ada-002',
7551 + 'text-embedding-3-small',
7552 + 'text-embedding-3-large',
7553 + 'voyage-3-large'
7554 + );
7555 + if (in_array($input['embedding_model'], $allowed_models)) {
7556 + $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
7557 + }
7558 + }
5663 7559
5664 - if (isset($input['model'])) {
7560 + if (isset($input['model'])) {
5665 7561 $allowed_models = array(
5666 - 'grok-beta',
5667 - 'grok-2',
5668 - 'deepseek-chat',
5669 - 'claude-3-5-sonnet-20241022',
5670 - 'claude-3-opus-20240229',
5671 - 'claude-3-sonnet-20240229',
5672 - 'claude-3-haiku-20240307',
5673 - 'gpt-4o',
5674 - 'gpt-4o-mini',
5675 - 'gpt-4-turbo',
5676 - 'gpt-4',
5677 - 'gpt-3.5-turbo',
5678 - );
7562 + 'gemini-2.0-flash',
7563 + 'gemini-2.0-flash-lite',
7564 + 'gemini-1.5-pro',
7565 + 'gemini-1.5-flash',
7566 + 'grok-3-beta',
7567 + 'grok-3-fast-beta',
7568 + 'grok-3-mini-beta',
7569 + 'grok-3-mini-fast-beta',
7570 + 'grok-2',
7571 + 'deepseek-chat',
7572 + 'claude-3-7-sonnet-20250219',
7573 + 'claude-3-5-sonnet-20241022',
7574 + 'claude-3-opus-20240229',
7575 + 'claude-3-sonnet-20240229',
7576 + 'claude-3-haiku-20240307',
7577 + 'gpt-4o',
7578 + 'gpt-4.1-2025-04-14',
7579 + 'gpt-4o-mini',
7580 + 'gpt-4-turbo',
7581 + 'gpt-4',
7582 + 'gpt-3.5-turbo',
7583 + );
5679 7584 if (in_array($input['model'], $allowed_models)) {
5680 7585 $new_input['model'] = sanitize_text_field($input['model']);
5681 7586 }
5682 7587 }
@@ -5835,8 +7740,22 @@
5835 7740
5836 7741 if (isset($input['chat_toolbar_toggle'])) {
5837 7742 $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
5838 7743 }
7744 +
7745 + // Sanitize PDF upload button toggle
7746 + if (isset($input['show_pdf_upload_button'])) {
7747 + $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
7748 + } else {
7749 + $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
7750 + }
7751 +
7752 + // Sanitize Word upload button toggle
7753 + if (isset($input['show_word_upload_button'])) {
7754 + $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
7755 + } else {
7756 + $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
7757 + }
5839 7758
5840 7759 if (isset($input['pdf_intent_trigger_text'])) {
5841 7760 $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
5842 7761 }
@@ -5891,62 +7810,10 @@
5891 7810 }
5892 7811
5893 7812
5894 7813
5895 -private static function mxchat_extract_main_content($html) {
5896 - if (empty($html)) {
5897 - //error_log('mxchat_extract_main_content: Empty HTML content received');
5898 - return '';
5899 - }
5900 7814
5901 - try {
5902 - $dom = new DOMDocument;
5903 - libxml_use_internal_errors(true); // Suppress HTML parsing errors
5904 7815
5905 - // Simple load of HTML, with @ to suppress warnings
5906 - @$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
5907 -
5908 - $xpath = new DOMXPath($dom);
5909 -
5910 - // Simplified selectors focusing on common content areas
5911 - $selectors = [
5912 - '//article',
5913 - '//*[@id="content"]',
5914 - '//*[@class="entry-content"]',
5915 - '//main'
5916 - ];
5917 -
5918 - foreach ($selectors as $selector) {
5919 - $nodes = $xpath->query($selector);
5920 - if ($nodes && $nodes->length > 0) {
5921 - $content = '';
5922 - foreach ($nodes as $node) {
5923 - $content .= $dom->saveHTML($node);
5924 - }
5925 - if (!empty($content)) {
5926 - return $content;
5927 - }
5928 - }
5929 - }
5930 -
5931 - // Fallback: Return the entire body content if no specific selector matches
5932 - $body = $dom->getElementsByTagName('body');
5933 - if ($body->length > 0) {
5934 - return $dom->saveHTML($body->item(0));
5935 - }
5936 -
5937 - // Last resort: return the original HTML
5938 - return $html;
5939 -
5940 - } catch (Exception $e) {
5941 - //error_log('mxchat_extract_main_content error: ' . $e->getMessage());
5942 - return $html; // Return original HTML if parsing fails
5943 - } finally {
5944 - libxml_clear_errors();
5945 - }
5946 -}
5947 -
5948 -
5949 7816 private function mxchat_fetch_loops_mailing_lists($api_key) {
5950 7817 $url = 'https://app.loops.so/api/v1/lists';
5951 7818 $response = wp_remote_get($url, array(
5952 7819 'headers' => array(
@@ -5991,8 +7858,81 @@
5991 7858 }
5992 7859 }
5993 7860
5994 7861
7862 +/**
7863 + * Update your existing display_admin_notices function to show notices on all MXChat pages
7864 + */
7865 +public function display_admin_notices() {
7866 + // Check if we're on a MXChat admin page
7867 + $screen = get_current_screen();
7868 + if (!$screen || strpos($screen->base, 'mxchat') === false) {
7869 + return;
7870 + }
7871 +
7872 + //error_log('MxChat admin_notices hook fired on screen: ' . $screen->base);
7873 +
7874 + // Check for error notices
7875 + $error_notice = get_transient('mxchat_admin_notice_error');
7876 + if ($error_notice) {
7877 + //error_log('Found error transient: ' . $error_notice);
7878 + echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p></div>';
7879 + delete_transient('mxchat_admin_notice_error');
7880 + //error_log('Displayed and deleted error transient');
7881 + } else {
7882 + //error_log('No error transient found');
7883 + }
7884 +
7885 + // Check for success notices
7886 + $success_notice = get_transient('mxchat_admin_notice_success');
7887 + if ($success_notice) {
7888 + //error_log('Found success transient: ' . $success_notice);
7889 + echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p></div>';
7890 + delete_transient('mxchat_admin_notice_success');
7891 + //error_log('Displayed and deleted success transient');
7892 + }
7893 +
7894 + // Check for info notices
7895 + $info_notice = get_transient('mxchat_admin_notice_info');
7896 + if ($info_notice) {
7897 + //error_log('Found info transient: ' . $info_notice);
7898 + echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p></div>';
7899 + delete_transient('mxchat_admin_notice_info');
7900 + //error_log('Displayed and deleted info transient');
7901 + }
7902 +
7903 + // Display active processing status
7904 + $this->display_processing_status();
7905 +}
7906 +
7907 +
7908 +
7909 +/**
7910 + * Display current processing status
7911 + */
7912 +private function display_processing_status() {
7913 + $pdf_url = get_transient('mxchat_last_pdf_url');
7914 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
7915 +
7916 + if (!$pdf_url && !$sitemap_url) {
7917 + return;
7918 + }
7919 +
7920 + $pdf_status = $pdf_url ? $this->get_pdf_processing_status($pdf_url) : false;
7921 + $sitemap_status = $sitemap_url ? $this->get_sitemap_processing_status($sitemap_url) : false;
7922 +
7923 + if ($sitemap_status && isset($sitemap_status['error']) && !empty($sitemap_status['error'])) {
7924 + echo '<div class="notice notice-error is-dismissible">';
7925 + echo '<p><strong>' . esc_html__('Sitemap Processing Error:', 'mxchat') . '</strong> ' . esc_html($sitemap_status['error']) . '</p>';
7926 + echo '</div>';
7927 + }
7928 +
7929 + if ($pdf_status && isset($pdf_status['error']) && !empty($pdf_status['error'])) {
7930 + echo '<div class="notice notice-error is-dismissible">';
7931 + echo '<p><strong>' . esc_html__('PDF Processing Error:', 'mxchat') . '</strong> ' . esc_html($pdf_status['error']) . '</p>';
7932 + echo '</div>';
7933 + }
7934 +}
5995 7935
5996 7936
5997 7937 }
5998 7938 ?>