PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.1.5
MxChat – AI Chatbot & Content Generation for WordPress v2.1.5
3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 All 153 releases
← All changes | includes/class-mxchat-integrator.php +4273 -3454 2.0.42.1.5 View file →
@@ -1,3454 +1,4273 @@
1 -<?php
2 -if (!defined('ABSPATH')) {
3 - exit;
4 -}
5 -
6 -class MxChat_Integrator {
7 - private $options;
8 - private $prompts_options;
9 - private $chat_count;
10 - private $fallbackResponse;
11 - private $productCardHtml;
12 - private $word_handler;
13 -
14 -public function __construct() {
15 - $this->options = get_option('mxchat_options');
16 - $this->prompts_options = get_option('mxchat_prompts_options', array());
17 -
18 - $this->chat_count = get_option('mxchat_chat_count', 0);
19 - $this->word_handler = new MXChat_Word_Handler($this->options);
20 -
21 - add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
22 - add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
23 - add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
24 -
25 - add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
26 - add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
27 - // Add the AJAX actions for checking if the pre-chat message was dismissed
28 - add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
29 - add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
30 -
31 - add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
32 - add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
33 -
34 - add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
35 - add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
36 -
37 - if (!wp_next_scheduled('mxchat_reset_rate_limits')) {
38 - wp_schedule_event(time(), 'daily', 'mxchat_reset_rate_limits');
39 - }
40 -
41 - // Add REST API routes registration
42 - add_action('rest_api_init', array($this, 'register_routes'));
43 -
44 - add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
45 - add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
46 -
47 - add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
48 -
49 - add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
50 - add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
51 - add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
52 - add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
53 -
54 - // Add these with your other add_action hooks
55 - add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
56 - add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
57 - add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
58 - add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
59 - add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
60 - add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
61 -
62 - add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
63 - add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
64 - add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
65 - add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
66 -}
67 -
68 -
69 - private function mxchat_increment_chat_count() {
70 - $chat_count = get_option('mxchat_chat_count', 0);
71 - $chat_count++;
72 - update_option('mxchat_chat_count', $chat_count);
73 - }
74 -
75 -function mxchat_fetch_conversation_history() {
76 - if (empty($_POST['session_id'])) {
77 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
78 - wp_die();
79 - }
80 -
81 - $session_id = sanitize_text_field($_POST['session_id']);
82 - $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
83 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
84 -
85 - if (empty($history)) {
86 - // Even if history is empty, return the chat mode
87 - wp_send_json_success([
88 - 'conversation' => [],
89 - 'chat_mode' => $chat_mode
90 - ]);
91 - wp_die();
92 - }
93 -
94 - wp_send_json_success([
95 - 'conversation' => $history,
96 - 'chat_mode' => $chat_mode
97 - ]);
98 - wp_die();
99 -}
100 -private function mxchat_fetch_conversation_history_for_ajax($session_id) {
101 - $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history based on session ID
102 - $formatted_history = [];
103 -
104 - // Format the history to align with the expected structure for OpenAI
105 - foreach ($history as $entry) {
106 - $formatted_history[] = [
107 - 'role' => $entry['role'], // Ensure this matches 'user' or 'assistant'
108 - 'content' => $entry['content']
109 - ];
110 - }
111 -
112 - return $formatted_history;
113 -}
114 -
115 -
116 -private function mxchat_fetch_conversation_history_for_ai($session_id) {
117 - $history = get_option("mxchat_history_{$session_id}", []);
118 - $formatted_history = [];
119 -
120 - // Adjusted for code-heavy conversations
121 - $max_tokens = 120000; // Context window size
122 - $reserved_tokens = 5000; // Space for system prompts + current query
123 - $current_token_count = 0;
124 -
125 - // Allowed HTML tags for content sanitization
126 - $allowed_tags = [
127 - 'pre' => ['class' => true],
128 - 'code' => ['class' => true],
129 - 'span' => ['class' => true],
130 - 'div' => ['class' => true],
131 - 'strong' => [],
132 - 'em' => []
133 - ];
134 -
135 - foreach (array_reverse($history) as $entry) {
136 - // Preserve code blocks while sanitizing other HTML
137 - $clean_content = wp_kses($entry['content'], $allowed_tags);
138 -
139 - // Detect code blocks in content
140 - $has_code = false;
141 -// Replace the HTML check with:
142 -// Allow messages that contain code blocks or are plain text
143 -if (strpos($clean_content, '<pre') === false &&
144 - strpos($clean_content, '<code') === false &&
145 - $clean_content !== strip_tags($entry['content'])) {
146 - continue;
147 -}
148 -
149 - // Skip entries that lost significant content during sanitization
150 - if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
151 - continue;
152 - }
153 -
154 - // More accurate token estimation (1 token ≈ 4 characters)
155 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
156 -
157 - // Check token budget with the new estimate
158 - if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
159 - // Try to fit partial content if it's the first entry
160 - if (empty($formatted_history)) {
161 - $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
162 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
163 - } else {
164 - break;
165 - }
166 - }
167 -
168 - // Add to formatted history
169 - $formatted_history[] = [
170 - 'role' => $entry['role'],
171 - 'content' => $clean_content
172 - ];
173 -
174 - $current_token_count += $token_estimate;
175 - }
176 -
177 - // Reverse back to maintain chronological order
178 - $formatted_history = array_reverse($formatted_history);
179 -
180 - // Add system message about code context
181 - array_unshift($formatted_history, [
182 - 'role' => 'system',
183 - 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
184 - . 'Maintain formatting and syntax highlighting when referencing code.'
185 - ]);
186 -
187 - return $formatted_history;
188 -}
189 -
190 -public function register_routes() {
191 - //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
192 -
193 - register_rest_route('mxchat/v1', '/stream', [
194 - 'methods' => 'GET',
195 - 'callback' => [$this, 'mxchat_stream_events'],
196 - 'permission_callback' => [$this, 'verify_chat_session'],
197 - ]);
198 -
199 - register_rest_route('mxchat/v1', '/agent-response', [
200 - 'methods' => 'POST',
201 - 'callback' => [$this, 'mxchat_handle_agent_response'],
202 - 'permission_callback' => [$this, 'verify_slack_request'],
203 - ]);
204 -
205 - register_rest_route('mxchat/v1', '/slack-interaction', [
206 - 'methods' => 'POST',
207 - 'callback' => [$this, 'handle_slack_interaction'],
208 - 'permission_callback' => [$this, 'verify_slack_request'],
209 - ]);
210 -
211 - //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
212 -}
213 -
214 -/**
215 - * Verify valid chat session
216 - */
217 -public function verify_chat_session($request) {
218 - $session_id = $request->get_param('session_id');
219 - if (empty($session_id)) {
220 - //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
221 - return false;
222 - }
223 -
224 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
225 - return $chat_mode === 'agent';
226 -}
227 -
228 -/**
229 - * Verify request is coming from Slack.
230 - *
231 - * @param WP_REST_Request $request
232 - * @return bool True if valid, false otherwise.
233 - */
234 -public function verify_slack_request($request) {
235 - // Get the Slack signing secret from your plugin options
236 - $valid_key = $this->options['live_agent_secret_key'] ?? '';
237 -
238 - if (empty($valid_key)) {
239 - //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
240 - return false;
241 - }
242 -
243 - $timestamp = $request->get_header('X-Slack-Request-Timestamp');
244 - $slack_signature = $request->get_header('X-Slack-Signature');
245 -
246 - // Verify timestamp to prevent replay attacks
247 - if (abs(time() - intval($timestamp)) > 300) {
248 - //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
249 - return false;
250 - }
251 -
252 - // Get raw request body
253 - $request_body = file_get_contents('php://input');
254 -
255 - // Create the signature base string
256 - $sig_basestring = "v0:{$timestamp}:{$request_body}";
257 -
258 - // Calculate expected signature
259 - $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
260 -
261 - // Compare signatures
262 - return hash_equals($my_signature, $slack_signature);
263 -}
264 -public function mxchat_stream_events(WP_REST_Request $request) {
265 - header('Content-Type: text/event-stream');
266 - header('Cache-Control: no-cache');
267 - header('Connection: keep-alive');
268 -
269 - $session_id = sanitize_text_field($request->get_param('session_id'));
270 - $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
271 -
272 - if (empty($session_id)) {
273 - echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
274 - flush();
275 - exit;
276 - }
277 -
278 - $history = get_option("mxchat_history_{$session_id}", []);
279 -
280 - // Filter only new messages
281 - $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
282 - return !empty($message['id']) && $message['id'] > $last_seen_id;
283 - });
284 -
285 - // Send new messages if available
286 - if (!empty($new_messages)) {
287 - echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
288 - } else {
289 - // Keep the connection alive
290 - echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
291 - }
292 - flush();
293 - exit;
294 -}
295 -
296 -
297 -
298 -
299 -private function mxchat_save_chat_message($session_id, $role, $message) {
300 - global $wpdb;
301 -
302 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
303 - //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
304 -
305 - // 1) Extract agent name if present
306 - $agent_name = '';
307 - if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
308 - $agent_name = $matches[1];
309 - $message = str_replace("Agent: $agent_name - ", '', $message);
310 -
311 - $session_meta_key = "mxchat_agent_name_{$session_id}";
312 - if (empty(get_option($session_meta_key))) {
313 - update_option($session_meta_key, $agent_name);
314 - //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
315 - }
316 - }
317 -
318 - // 2) Generate unique message_id
319 - $message_id = uniqid();
320 - //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
321 -
322 - // 3) Determine user_id
323 - $user_id = is_user_logged_in() ? get_current_user_id() : 0;
324 -
325 - // 4) Determine user_identifier
326 - $user_identifier = $agent_name
327 - ? $agent_name
328 - : MxChat_User::mxchat_get_user_identifier();
329 -
330 - // 5) Determine displayed_name
331 - $user_email = MxChat_User::mxchat_get_user_email();
332 - $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
333 -
334 - // 6) Check for a saved email in wp_options
335 - $email_option_key = "mxchat_email_{$session_id}";
336 - $saved_email = get_option($email_option_key);
337 - //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
338 -
339 - // If found, update DB user_email
340 - if ($saved_email) {
341 - $update_res = $wpdb->update(
342 - $table_name,
343 - ['user_email' => $saved_email],
344 - ['session_id' => $session_id],
345 - ['%s'],
346 - ['%s']
347 - );
348 - //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email update for session_id {$session_id}. update_res: {$update_res}");
349 - }
350 -
351 - // 7) Save to session history in wp_options
352 - $history_key = "mxchat_history_{$session_id}";
353 - $history = get_option($history_key, []);
354 - $history[] = [
355 - 'id' => $message_id,
356 - 'role' => $role,
357 - 'content' => $message,
358 - 'timestamp' => round(microtime(true) * 1000),
359 - 'agent_name' => $displayed_name,
360 - ];
361 - update_option($history_key, $history);
362 - //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
363 -
364 - // 8) Save the message to DB (INSERT)
365 - $insert_data = [
366 - 'user_id' => $user_id,
367 - 'user_identifier'=> $user_identifier,
368 - 'user_email' => $saved_email ?: $user_email,
369 - 'session_id' => $session_id,
370 - 'role' => $role,
371 - 'message' => $message,
372 - 'timestamp' => current_time('mysql', 1),
373 - ];
374 - $wpdb->insert($table_name, $insert_data);
375 - //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
376 -
377 - //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
378 - return $message_id;
379 -}
380 -
381 -public function mxchat_handle_save_email_and_response() {
382 - //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
383 -
384 - // Validate nonce
385 - if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
386 - error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
387 - wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
388 - wp_die();
389 - }
390 -
391 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
392 - $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
393 -
394 - //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}");
395 -
396 - if (empty($session_id) || empty($email)) {
397 - //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
398 - wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
399 - wp_die();
400 - }
401 -
402 - // 1) Always store in wp_options
403 - $option_key = "mxchat_email_{$session_id}";
404 - update_option($option_key, $email);
405 - //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$option_key} => {$email}");
406 -
407 - // 2) (Optional) Also store in DB if a row already exists
408 - global $wpdb;
409 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
410 -
411 - // Make sure we have a valid placeholder in prepare
412 - $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
413 - $session_count = $wpdb->get_var($sql);
414 -
415 - //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
416 -
417 - if ($session_count) {
418 - // Update user_email if row(s) exist
419 - $update_sql = $wpdb->prepare(
420 - "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
421 - $email,
422 - $session_id
423 - );
424 - $wpdb->query($update_sql);
425 - //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
426 - } else {
427 - //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email is only in wp_options.");
428 - }
429 -
430 - // Provide success response
431 - $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
432 - //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
433 - wp_send_json_success(['message' => $bot_message]);
434 - wp_die();
435 -}
436 -
437 -public function mxchat_check_email_provided() {
438 - //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
439 -
440 - if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
441 - //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
442 - wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
443 - }
444 -
445 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
446 - if (empty($session_id)) {
447 - //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
448 - wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
449 - }
450 -
451 - // Check if the user is logged in
452 - if (is_user_logged_in()) {
453 - $current_user = wp_get_current_user();
454 - //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
455 - wp_send_json_success(['logged_in' => true, 'email' => $current_user->user_email]);
456 - }
457 -
458 - $option_key = "mxchat_email_{$session_id}";
459 - $stored_email = get_option($option_key, '');
460 -
461 - //error_log("[DEBUG] mxchat_check_email_provided -> Checking option: {$option_key}, found: {$stored_email}");
462 -
463 - if (!empty($stored_email)) {
464 - //error_log("[DEBUG] mxchat_check_email_provided -> Email found, returning success");
465 - wp_send_json_success(['email' => $stored_email]);
466 - } else {
467 - //error_log("[DEBUG] mxchat_check_email_provided -> No email found, returning error");
468 - wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
469 - }
470 -}
471 -
472 -
473 -// First, add this helper function to get the highest rate limit for a user's roles
474 -private function get_user_role_rate_limit($user_id) {
475 - //error_log(esc_html__("Checking rate limit for user ID: ", 'mxchat') . $user_id);
476 -
477 - if (!$user_id) {
478 - //error_log(esc_html__("No user ID provided, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
479 - return $this->options['rate_limit_logged_out'] ?? '10';
480 - }
481 -
482 - $user = get_userdata($user_id);
483 - if (!$user || !$user->roles) {
484 - //error_log(esc_html__("No user data or roles found, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
485 - return $this->options['rate_limit_logged_out'] ?? '10';
486 - }
487 -
488 - //error_log(esc_html__("User roles: ", 'mxchat') . print_r($user->roles, true));
489 - //error_log(esc_html__("Available role rate limits: ", 'mxchat') . print_r($this->options['role_rate_limits'] ?? [], true));
490 -
491 - $max_limit = 0;
492 - foreach ($user->roles as $role) {
493 - //error_log(esc_html__("Checking limit for role: ", 'mxchat') . $role);
494 - if (isset($this->options['role_rate_limits'][$role])) {
495 - $role_limit = $this->options['role_rate_limits'][$role];
496 - //error_log(esc_html__("Found limit for role ", 'mxchat') . $role . esc_html__(": ", 'mxchat') . $role_limit);
497 -
498 - if ($role_limit === 'unlimited') {
499 - //error_log(esc_html__("Returning unlimited for role: ", 'mxchat') . $role);
500 - return 'unlimited';
501 - }
502 -
503 - $max_limit = max($max_limit, (int)$role_limit);
504 - //error_log(esc_html__("Current max limit: ", 'mxchat') . $max_limit);
505 - } else {
506 - //error_log(esc_html__("No limit found for role: ", 'mxchat') . $role);
507 - }
508 - }
509 -
510 - $final_limit = $max_limit > 0 ? (string)$max_limit : '100';
511 - //error_log(esc_html__("Final rate limit: ", 'mxchat') . $final_limit);
512 - return $final_limit;
513 -}
514 -
515 -
516 -// Add this to your plugin's main PHP file
517 -public function mxchat_check_new_messages() {
518 - if (!isset($_POST['session_id']) || !isset($_POST['last_seen_id'])) {
519 - wp_send_json_error(['message' => 'Missing required parameters']);
520 - wp_die();
521 - }
522 -
523 - $session_id = sanitize_text_field($_POST['session_id']);
524 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
525 -
526 - // Get chat history
527 - $history = get_option("mxchat_history_{$session_id}", []);
528 -
529 - if (empty($history)) {
530 - wp_send_json_success([
531 - 'hasNewMessages' => false,
532 - 'new_messages' => []
533 - ]);
534 - wp_die();
535 - }
536 -
537 - // Filter new messages
538 - $new_messages = array_filter($history, function($message) use ($last_seen_id) {
539 - return isset($message['id']) && $message['id'] > $last_seen_id;
540 - });
541 -
542 - // Sort by ID to ensure proper order
543 - usort($new_messages, function($a, $b) {
544 - return $a['id'] <=> $b['id'];
545 - });
546 -
547 - wp_send_json_success([
548 - 'hasNewMessages' => !empty($new_messages),
549 - 'new_messages' => array_values($new_messages),
550 - 'latestMessageId' => end($new_messages)['id'] ?? $last_seen_id
551 - ]);
552 - wp_die();
553 -}
554 -
555 -public function mxchat_handle_chat_request() {
556 - global $wpdb;
557 -
558 -
559 - // Check if MX Chat Moderation is active
560 - if (class_exists('MX_Chat_Moderation')) {
561 - // Get user email and IP
562 - $user_email = '';
563 - $user_ip = $_SERVER['REMOTE_ADDR'];
564 -
565 - // If user is logged in, get their email
566 - if (is_user_logged_in()) {
567 - $current_user = wp_get_current_user();
568 - $user_email = $current_user->user_email;
569 - }
570 -
571 - // Create ban handler instance
572 - $ban_handler = new MX_Chat_Ban_Handler();
573 -
574 - // Check if user is banned by IP
575 - if ($ban_handler->check_ban($user_ip, 'ip')) {
576 - wp_send_json([
577 - 'success' => false,
578 - 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
579 - 'status' => 'banned'
580 - ]);
581 - wp_die();
582 - }
583 -
584 - // If user is logged in, also check email
585 - if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
586 - wp_send_json([
587 - 'success' => false,
588 - 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
589 - 'status' => 'banned'
590 - ]);
591 - wp_die();
592 - }
593 - }
594 -
595 -
596 - // Reset fallback response at the start of each request
597 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
598 - $this->productCardHtml = '';
599 -
600 - // Get the actual WordPress user ID if logged in
601 - $is_logged_in = is_user_logged_in();
602 - if ($is_logged_in) {
603 - $user_id = get_current_user_id(); // This will get the actual WordPress user ID
604 - } else {
605 - // For logged-out users, use your existing identifier method
606 - $user_id = $this->mxchat_get_user_identifier();
607 - }
608 -
609 - // Get and sanitize the user identifier
610 - $user_id = sanitize_key($user_id);
611 -
612 - // Determine if user is logged in
613 - $is_logged_in = is_user_logged_in();
614 - //error_log("User logged in status: " . ($is_logged_in ? 'true' : 'false'));
615 -
616 - // Get rate limit based on user status
617 - // Get rate limit based on user status
618 - $rate_limit = $is_logged_in
619 - ? $this->get_user_role_rate_limit($user_id)
620 - : ($this->options['rate_limit_logged_out'] ?? '10');
621 -
622 - //error_log("Selected rate limit: " . $rate_limit);
623 -
624 - // Rest of your code remains the same
625 - // If rate limit is 'unlimited', skip rate limiting checks
626 - if ($rate_limit !== 'unlimited') {
627 - // Convert rate limit to integer
628 - $rate_limit = intval($rate_limit);
629 - // Setup rate limiting
630 - $rate_limit_transient_key = 'mxchat_chat_limit_' . $user_id;
631 - $chat_count = get_transient($rate_limit_transient_key);
632 - if ($chat_count === false) {
633 - // Initialize new counter if none exists
634 - $chat_count = 0;
635 - }
636 - // Check if user has exceeded their rate limit
637 - if ($chat_count >= $rate_limit) {
638 - // Get custom rate limit message or use default
639 - $rate_limit_message = isset($this->options['rate_limit_message'])
640 - ? $this->options['rate_limit_message']
641 - : esc_html__('Rate limit exceeded. Please try again later.', 'mxchat');
642 - // Replace placeholder if it exists in the message
643 - $rate_limit_message = str_replace(
644 - array('{limit}', '{count}', '{remaining}'),
645 - array($rate_limit, $chat_count, max(0, $rate_limit - $chat_count)),
646 - $rate_limit_message
647 - );
648 - wp_send_json([
649 - 'success' => false,
650 - 'message' => $rate_limit_message,
651 - 'status' => 'rate_limit_exceeded',
652 - 'limit' => $rate_limit,
653 - 'count' => $chat_count
654 - ]);
655 - wp_die();
656 - }
657 - // Increment the counter
658 - $chat_count++;
659 - // Store the updated count with 24-hour expiration
660 - set_transient($rate_limit_transient_key, $chat_count, DAY_IN_SECONDS);
661 - }
662 -
663 - // Rest of your existing code...
664 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
665 - //error_log("Session ID: $session_id");
666 -
667 - if (empty($session_id)) {
668 - //error_log("Error: Session ID is missing.");
669 - wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
670 - wp_die();
671 - }
672 -
673 - // Validate and sanitize the incoming message
674 - if (empty($_POST['message'])) {
675 - //error_log("Error: No message received.");
676 - wp_send_json_error(esc_html__('No message received.', 'mxchat'));
677 - wp_die();
678 - }
679 -
680 -
681 -// Modify the message sanitization to preserve PHP tags in code blocks
682 -$allowed_tags = [
683 - 'pre' => [],
684 - 'code' => ['class' => true],
685 - 'span' => ['class' => true],
686 - 'div' => ['class' => true],
687 -];
688 -
689 -// First preserve code blocks
690 -$message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
691 - return htmlspecialchars_decode($matches[0]);
692 -}, $_POST['message']);
693 -
694 -// Then apply sanitization
695 -$message = wp_kses($message, $allowed_tags);
696 -
697 -// Decode code blocks
698 -$message = preg_replace_callback('/(&lt;pre&gt;&lt;code.*?&gt;.*?&lt;\/code&gt;&lt;\/pre&gt;)/s', function($matches) {
699 - return htmlspecialchars_decode($matches[1]);
700 -}, $message);
701 -
702 -$message = trim($message);
703 -
704 -// Preserve code blocks from markdown conversion
705 -$message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
706 -
707 - // Save the user's message
708 - $this->mxchat_save_chat_message($session_id, 'user', $message);
709 -
710 - // Check if the message is an email address
711 - if (is_email($message)) {
712 - // Add the email to Loops
713 - $this->add_email_to_loops($message);
714 -
715 - // Send success response
716 - $response_message = $this->options['email_capture_response'] ??
717 - esc_html__('Thank you! Your coupon is on the way!', 'mxchat');
718 -
719 - wp_send_json([
720 - 'success' => true,
721 - 'status' => 'email_captured',
722 - 'message' => $response_message
723 - ]);
724 - wp_die();
725 - }
726 -
727 - $intent_info = '';
728 -
729 - // Check chat mode
730 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
731 - //error_log("Chat Mode: $chat_mode");
732 -
733 - // Handle agent mode
734 - if ($chat_mode === 'agent') {
735 - // First, check for switch intent before doing anything else
736 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
737 -
738 - // If we matched an intent and it's the switch intent, handle it
739 - if ($intent_matched && !empty($this->fallbackResponse['text'])) {
740 - //error_log("Switch to chatbot intent detected");
741 -
742 - // Update chat mode first
743 - update_option("mxchat_mode_{$session_id}", 'ai');
744 -
745 - // Clear any existing PDF context to start fresh
746 - $this->clear_pdf_transients($session_id);
747 -
748 - // Prepare clean switch response
749 - $response_data = [
750 - 'text' => $this->fallbackResponse['text'],
751 - 'html' => '',
752 - 'session_id' => $session_id,
753 - 'chat_mode' => 'ai'
754 - ];
755 -
756 - // Save the mode switch message
757 - $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
758 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
759 -
760 - // Send response and exit
761 - wp_send_json($response_data);
762 - wp_die();
763 - } elseif (!$intent_matched) {
764 - // No intent matched, handle live agent message
765 - try {
766 - $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
767 - //error_log("Message sent to agent.");
768 -
769 - wp_send_json_success([
770 - 'status' => 'waiting_for_agent',
771 - 'message' => esc_html__('Message sent to live agent.', 'mxchat')
772 - ]);
773 - } catch (\Exception $e) {
774 - //error_log("Error sending message to agent: " . $e->getMessage());
775 - wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
776 - }
777 - wp_die();
778 - }
779 - }
780 -
781 - // Step 1: Check for new PDF URL in the message
782 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
783 - $new_pdf_url = $matches[0];
784 -
785 - // Check if this is likely a PDF-related request
786 - $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
787 - $is_pdf_request = false;
788 -
789 - foreach ($pdf_keywords as $keyword) {
790 - if (stripos($message, $keyword) !== false) {
791 - $is_pdf_request = true;
792 - break;
793 - }
794 - }
795 -
796 - // If it looks like a PDF request or we're waiting for a PDF URL
797 - if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
798 - // Validate HTTPS
799 - if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
800 - // Extract filename from URL
801 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
802 -
803 - // Clear previous PDF transients
804 - $this->clear_pdf_transients($session_id);
805 -
806 - // Process new PDF
807 - $max_pages = $this->options['pdf_max_pages'] ?? 69;
808 - $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
809 -
810 - if ($embeddings === 'too_many_pages') {
811 - $error_text = sprintf(
812 - $this->options['pdf_intent_error_text'] ??
813 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
814 - $max_pages
815 - );
816 - $this->fallbackResponse['text'] = $error_text;
817 - } elseif ($embeddings) {
818 - // Store new PDF information
819 - // Create a more meaningful filename from URL
820 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
821 -
822 - // If the filename is generic (like results_download.php), create a more descriptive one
823 - if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
824 - strpos($pdf_filename, '.php') !== false) {
825 - // Create a timestamp-based name
826 - $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
827 - }
828 -
829 - set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
830 - set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
831 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
832 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
833 -
834 - $success_text = $this->options['pdf_intent_success_text'] ??
835 - esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
836 -
837 - // Return success with filename for UI update
838 - wp_send_json([
839 - 'success' => true,
840 - 'message' => $success_text,
841 - 'data' => [
842 - 'filename' => $pdf_filename
843 - ]
844 - ]);
845 - wp_die();
846 - } else {
847 - $error_text = $this->options['pdf_intent_error_text'] ??
848 - esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
849 - $this->fallbackResponse['text'] = $error_text;
850 - }
851 -
852 - wp_send_json([
853 - 'success' => false,
854 - 'message' => $this->fallbackResponse['text']
855 - ]);
856 - wp_die();
857 - }
858 - }
859 - }
860 -
861 - // Step 2: Detect intent and handle intent-based responses
862 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
863 - //error_log("Intent Matched: " . ($intent_matched ? "Yes" : "No"));
864 -
865 - // Step 3: If intent is matched and handled, respond immediately
866 - if ($intent_matched && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
867 - //error_log("Intent response triggered.");
868 - $response_data = [
869 - 'text' => $this->fallbackResponse['text'],
870 - 'html' => $this->fallbackResponse['html'],
871 - 'session_id' => $session_id
872 - ];
873 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text'] . $this->fallbackResponse['html']);
874 - wp_send_json($response_data);
875 - wp_die();
876 - }
877 -
878 - // If no intent matched or product not found, proceed with AI response
879 - //error_log("No matching intent or fallback. Generating AI response.");
880 -
881 - // Step 4: Generate AI response
882 - $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
883 - $this->mxchat_increment_chat_count();
884 -
885 - // Generate embedding for the user's query
886 - $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
887 - if (!is_array($user_message_embedding)) {
888 - //error_log("Failed to generate message embedding for session $session_id");
889 - wp_send_json_error(esc_html__('Error processing your message.', 'mxchat'));
890 - wp_die();
891 - }
892 -
893 - // Build context with both knowledge base and PDF content if available
894 - $context_content = "User asked: '{$message}'\n\n";
895 -
896 - // Get relevant content from knowledge base
897 - $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
898 - if (!empty($relevant_content)) {
899 - $context_content .= "Relevant content from knowledge database:\n" . $relevant_content . "\n\n";
900 - }
901 -
902 -
903 - // Check for and include PDF content
904 - $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
905 - $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
906 - $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
907 - if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
908 - $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
909 - if (!empty($relevant_pdf_pages)) {
910 - $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
911 - foreach ($relevant_pdf_pages as $page_data) {
912 - $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
913 - }
914 - $context_content .= "\n";
915 - }
916 - }
917 -
918 - // Check for and include Word content
919 - $word_url = get_transient('mxchat_word_url_' . $session_id);
920 - $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
921 - $word_filename = get_transient('mxchat_word_filename_' . $session_id);
922 - if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
923 - $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
924 - if (!empty($relevant_word_chunks)) {
925 - $context_content .= "Relevant content from Word document '{$word_filename}':\n";
926 - foreach ($relevant_word_chunks as $chunk_data) {
927 - $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
928 - }
929 - $context_content .= "\n";
930 - }
931 - }
932 - // Generate the response using the full context
933 - $response = $this->mxchat_generate_response(
934 - $context_content,
935 - $this->options['api_key'],
936 - $this->options['xai_api_key'],
937 - $this->options['claude_api_key'],
938 - $this->options['deepseek_api_key'],
939 - $conversation_history
940 - );
941 -
942 - $this->mxchat_save_chat_message($session_id, 'bot', $response);
943 -
944 - // Step 5: Save additional content if available
945 - if (!empty($this->productCardHtml)) {
946 - $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
947 - }
948 -
949 - if (!empty($this->fallbackResponse['html'])) {
950 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
951 - }
952 -
953 - // Step 6: Return the response
954 - $response_data = [
955 - 'text' => $response,
956 - 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
957 - 'session_id' => $session_id
958 - ];
959 -
960 - wp_send_json($response_data);
961 - wp_die();
962 -}
963 -
964 -// New function to check intents and invoke the callback function
965 -private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
966 - global $wpdb;
967 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
968 -
969 - //error_log('🔍 MXCHAT DEBUG: Intent Check Started ==================');
970 - //error_log("🔍 MXCHAT DEBUG: Message: '$message'");
971 - //error_log("🔍 MXCHAT DEBUG: Chat Mode: $chat_mode");
972 -
973 - // Generate the user embedding
974 - //error_log('🔄 MXCHAT DEBUG: Generating user embedding');
975 - $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
976 - if (!is_array($user_embedding)) {
977 - //error_log('❌ MXCHAT DEBUG: Failed to generate user embedding');
978 - return false;
979 - }
980 - //error_log('✅ MXCHAT DEBUG: User embedding generated successfully');
981 -
982 - // Fetch intents from the database
983 - $table_name = $wpdb->prefix . 'mxchat_intents';
984 - if ($chat_mode === 'agent') {
985 - //error_log('🔍 MXCHAT DEBUG: Agent mode - fetching only chatbot switch intent');
986 - $query = $wpdb->prepare(
987 - "SELECT * FROM $table_name WHERE callback_function = %s",
988 - 'mxchat_handle_switch_to_chatbot_intent'
989 - );
990 - $intents = $wpdb->get_results($query);
991 - } else {
992 - //error_log('🔍 MXCHAT DEBUG: AI mode - fetching all intents');
993 - $intents = $wpdb->get_results("SELECT * FROM $table_name");
994 - }
995 -
996 - //error_log('🔍 MXCHAT DEBUG: Found ' . count($intents) . ' intents to check');
997 -
998 - if (empty($intents)) {
999 - //error_log('❌ MXCHAT DEBUG: No intents found in database');
1000 - return false;
1001 - }
1002 -
1003 - $highest_similarity = -INF;
1004 - $matched_intent = null;
1005 -
1006 - //error_log('📊 MXCHAT DEBUG: Intent Similarity Scores ==================');
1007 - foreach ($intents as $intent) {
1008 - //error_log("🔄 MXCHAT DEBUG: Checking intent: '{$intent->intent_label}' (callback: {$intent->callback_function})");
1009 -
1010 - $intent_embedding_serialized = $intent->embedding_vector;
1011 - $intent_embedding = $intent_embedding_serialized
1012 - ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1013 - : null;
1014 -
1015 - if (!is_array($intent_embedding)) {
1016 - //error_log("❌ MXCHAT DEBUG: Invalid embedding for intent: {$intent->intent_label}");
1017 - continue;
1018 - }
1019 -
1020 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1021 - $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1022 -
1023 -
1024 - if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1025 - $highest_similarity = $similarity;
1026 - $matched_intent = $intent;
1027 - //error_log("✅ MXCHAT DEBUG: New best match: '{$intent->intent_label}' with similarity {$similarity}");
1028 - }
1029 - }
1030 - //error_log('📊 MXCHAT DEBUG: End Intent Scores ==================');
1031 -
1032 - if ($matched_intent) {
1033 - //error_log("🎯 MXCHAT DEBUG: Final Intent Match: '{$matched_intent->intent_label}'");
1034 - //error_log("🔄 MXCHAT DEBUG: Invoking callback: {$matched_intent->callback_function}");
1035 -
1036 - // If the callback is a method on this instance (core callback), call it directly
1037 - if (method_exists($this, $matched_intent->callback_function)) {
1038 - //error_log('🔍 MXCHAT DEBUG: Using direct method call for core callback');
1039 - $callback_result = call_user_func(
1040 - [$this, $matched_intent->callback_function],
1041 - $message,
1042 - $user_id,
1043 - $session_id,
1044 - $matched_intent,
1045 - $user_context // Add user context
1046 - );
1047 - } else {
1048 - //error_log('🔍 MXCHAT DEBUG: Using apply_filters for add-on callback');
1049 - // Otherwise, use apply_filters for add-on callbacks
1050 - $callback_result = apply_filters(
1051 - $matched_intent->callback_function,
1052 - false, // default return value
1053 - $message,
1054 - $user_id,
1055 - $session_id,
1056 - $matched_intent
1057 - );
1058 - }
1059 -
1060 - //error_log('🔍 MXCHAT DEBUG: Callback result type: ' . gettype($callback_result));
1061 - if ($callback_result !== false) {
1062 - //error_log('✅ MXCHAT DEBUG: Intent handled successfully');
1063 - $this->fallbackResponse = $callback_result;
1064 - return true;
1065 - }
1066 - //error_log('❌ MXCHAT DEBUG: Callback returned false');
1067 - } else {
1068 - //error_log('❌ MXCHAT DEBUG: No matching intent found');
1069 - }
1070 -
1071 - //error_log('🔍 MXCHAT DEBUG: Intent Check Completed ==================');
1072 - return false;
1073 -}
1074 -
1075 -
1076 -// Helper function to clear PDF and Word document related transients
1077 -private function clear_pdf_transients($session_id) {
1078 - // PDF transients
1079 - delete_transient('mxchat_pdf_url_' . $session_id);
1080 - delete_transient('mxchat_pdf_embeddings_' . $session_id);
1081 - delete_transient('mxchat_include_pdf_in_context_' . $session_id);
1082 - delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
1083 -
1084 - // Word document transients
1085 - delete_transient('mxchat_word_url_' . $session_id);
1086 - delete_transient('mxchat_word_filename_' . $session_id);
1087 - delete_transient('mxchat_word_embeddings_' . $session_id);
1088 - delete_transient('mxchat_include_word_in_context_' . $session_id);
1089 - delete_transient('mxchat_waiting_for_word_' . $session_id);
1090 -}
1091 -
1092 -
1093 -
1094 -//verified good
1095 -public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1096 - // Log the message safely
1097 - //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
1098 -
1099 - // Initiate email capture flow
1100 - $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
1101 -
1102 - set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1103 - $this->mxchat_save_chat_message($session_id, 'bot', $response);
1104 -
1105 - // Respond to the user
1106 - wp_send_json(['message' => $response]);
1107 - wp_die();
1108 -}
1109 -
1110 -//very good
1111 -public function mxchat_generate_image($message, $user_id, $session_id) {
1112 - // Prepare a prompt for DALL-E
1113 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1114 -
1115 - // Use the existing OpenAI API key
1116 - $openai_api_key = sanitize_text_field($this->options['api_key']);
1117 -
1118 - // Call DALL-E to generate an image
1119 - $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1120 -
1121 - // Check if the response contains an image URL
1122 - if (isset($image_response['imageUrl'])) {
1123 - $image_url = esc_url_raw($image_response['imageUrl']);
1124 -
1125 - // Construct the HTML with a CSS class instead of inline styles
1126 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1127 -
1128 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1129 - } else {
1130 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1131 - $response_html = '';
1132 - //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1133 - }
1134 -
1135 - // Save both text and HTML responses
1136 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text . "\n" . $response_html);
1137 -
1138 - // Prepare the response data
1139 - $response_data = [
1140 - 'message' => $response_text,
1141 - 'html' => $response_html,
1142 - 'image_url' => $image_url ?? '',
1143 - ];
1144 -
1145 - // Send the JSON response
1146 - header('Content-Type: application/json; charset=' . get_option('blog_charset'));
1147 - echo json_encode($response_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
1148 - wp_die();
1149 -}
1150 -private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1151 - $api_url = 'https://api.openai.com/v1/images/generations';
1152 - $body = json_encode([
1153 - 'prompt' => sanitize_text_field($prompt),
1154 - 'n' => 1,
1155 - 'size' => '1024x1024',
1156 - 'model' => sanitize_text_field($model),
1157 - ]);
1158 -
1159 - $args = [
1160 - 'body' => $body,
1161 - 'headers' => [
1162 - 'Content-Type' => 'application/json',
1163 - 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1164 - ],
1165 - 'method' => 'POST',
1166 - 'timeout' => absint($timeout),
1167 - ];
1168 -
1169 - $response = wp_remote_post($api_url, $args);
1170 -
1171 - if (is_wp_error($response)) {
1172 - //error_log("DALL-E request failed: " . $response->get_error_message());
1173 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1174 - }
1175 -
1176 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
1177 -
1178 - if (isset($response_body['data'][0]['url'])) {
1179 - return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1180 - } else {
1181 - //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1182 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1183 - }
1184 -}
1185 -
1186 -/**
1187 - * Handle web search requests.
1188 - *
1189 - * Sends the refined search query to the Brave Search API and displays neatly formatted,
1190 - * styled search results. Results are cached for performance.
1191 - *
1192 - * @since 1.0.0
1193 - * @param string $message The user's search query.
1194 - * @param string $user_id The user identifier.
1195 - * @param string $session_id The current session ID.
1196 - * @return void
1197 - */
1198 -public function mxchat_handle_search_request( $message, $user_id, $session_id ) {
1199 - // Step 1: Interpret and refine the search query
1200 - $refined_search_query = $this->mxchat_interpret_search_query( $message );
1201 -
1202 - if ( empty( $refined_search_query ) ) {
1203 - $this->fallbackResponse = array(
1204 - 'text' => esc_html__( 'I apologize, but could you please rephrase your search request?', 'mxchat' ),
1205 - );
1206 - return;
1207 - }
1208 -
1209 - // Retrieve and validate API settings
1210 - $options = get_option( 'mxchat_options' );
1211 - $api_key = isset( $options['brave_api_key'] ) ? sanitize_text_field( $options['brave_api_key'] ) : '';
1212 - $results_count = isset( $options['brave_results_count'] ) ? absint( $options['brave_results_count'] ) : 5;
1213 -
1214 - if ( empty( $api_key ) ) {
1215 - $this->fallbackResponse = array(
1216 - 'text' => esc_html__( 'Search functionality is temporarily unavailable. Please try again later.', 'mxchat' ),
1217 - );
1218 - return;
1219 - }
1220 -
1221 - // Build the API request URL
1222 - $api_url = add_query_arg(
1223 - array(
1224 - 'q' => rawurlencode( $refined_search_query ),
1225 - 'count' => $results_count,
1226 - 'text_decorations' => 'true',
1227 - 'rich_data' => 'true',
1228 - ),
1229 - 'https://api.search.brave.com/res/v1/web/search'
1230 - );
1231 -
1232 - // Attempt to retrieve cached results first
1233 - $transient_key = 'mxchat_search_' . md5( $refined_search_query );
1234 - $results = get_transient( $transient_key );
1235 -
1236 - if ( false === $results ) {
1237 - // Fetch new results from the Brave Search API
1238 - $response = wp_remote_get(
1239 - $api_url,
1240 - array(
1241 - 'headers' => array(
1242 - 'Accept' => 'application/json',
1243 - 'Accept-Encoding' => 'gzip',
1244 - 'X-Subscription-Token'=> $api_key,
1245 - ),
1246 - 'timeout' => 10,
1247 - )
1248 - );
1249 -
1250 - if ( is_wp_error( $response ) ) {
1251 - $this->fallbackResponse = array(
1252 - 'text' => esc_html__( 'I encountered an error while searching. Please try again.', 'mxchat' ),
1253 - );
1254 - return;
1255 - }
1256 -
1257 - $results = json_decode( wp_remote_retrieve_body( $response ), true );
1258 -
1259 - if ( json_last_error() !== JSON_ERROR_NONE ) {
1260 - $this->fallbackResponse = array(
1261 - 'text' => esc_html__( 'I received an invalid response from the search service.', 'mxchat' ),
1262 - );
1263 - return;
1264 - }
1265 -
1266 - // Cache results for one hour
1267 - set_transient( $transient_key, $results, HOUR_IN_SECONDS );
1268 - }
1269 -
1270 - // Process and display results
1271 - if ( ! empty( $results['web']['results'] ) && is_array( $results['web']['results'] ) ) {
1272 - $html = $this->generate_search_results_html( $results['web']['results'], $refined_search_query );
1273 -
1274 - // Only return HTML (no large text summary)
1275 - $this->fallbackResponse = array(
1276 - 'html' => $html,
1277 - );
1278 -
1279 - // Save to chat history
1280 - $this->mxchat_save_chat_message( $session_id, 'bot', $html );
1281 - } else {
1282 - $this->fallbackResponse = array(
1283 - 'text' => sprintf(
1284 - esc_html__( 'I couldn\'t find any relevant results for "%s". Would you like to try different search terms?', 'mxchat' ),
1285 - esc_html( $refined_search_query )
1286 - ),
1287 - );
1288 - }
1289 -}
1290 -
1291 -
1292 -/**
1293 - * Format search results into a natural text summary.
1294 - *
1295 - * @since 1.0.0
1296 - * @param array $results The search results from the API.
1297 - * @param string $query The original search query.
1298 - * @return string The text summary of the top results.
1299 - */
1300 -private function format_search_results( $results, $query ) {
1301 - $summary = sprintf(
1302 - esc_html__( 'Here are the most relevant results for "%s":', 'mxchat' ),
1303 - esc_html( $query )
1304 - ) . "\n\n";
1305 -
1306 - $max_results = min( count( $results ), 3 );
1307 - for ( $i = 0; $i < $max_results; $i++ ) {
1308 - $result = $results[ $i ];
1309 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1310 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1311 -
1312 - // Append title and description to the summary
1313 - $summary .= sprintf(
1314 - "%s\n%s\n\n",
1315 - esc_html( $title ),
1316 - esc_html( $description )
1317 - );
1318 - }
1319 -
1320 - return $summary;
1321 -}
1322 -
1323 -/**
1324 - * Generate HTML markup for search results.
1325 - *
1326 - * @since 1.0.0
1327 - * @param array $results The search results from the API.
1328 - * @param string $query The user-refined query.
1329 - * @return string The HTML markup for displaying the results.
1330 - */
1331 -private function generate_search_results_html( $results, $query ) {
1332 - ob_start();
1333 - ?>
1334 - <div class="mxchat-search-results">
1335 - <?php foreach ( $results as $result ) :
1336 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1337 - $url = isset( $result['url'] ) ? esc_url( $result['url'] ) : '#';
1338 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1339 - $favicon = isset( $result['meta_url']['favicon'] ) ? esc_url( $result['meta_url']['favicon'] ) : '';
1340 - $thumbnail = isset( $result['thumbnail']['src'] ) ? esc_url( $result['thumbnail']['src'] ) : '';
1341 - $domain = parse_url( $url, PHP_URL_HOST );
1342 - ?>
1343 - <div class="mxchat-search-item">
1344 - <div class="mxchat-search-header">
1345 - <?php if ( $favicon ) : ?>
1346 - <img
1347 - src="<?php echo esc_url( $favicon ); ?>"
1348 - class="mxchat-site-icon"
1349 - alt="<?php echo esc_attr__( 'Site icon', 'mxchat' ); ?>"
1350 - width="16"
1351 - height="16"
1352 - />
1353 - <?php endif; ?>
1354 - <div class="mxchat-site-url"><?php echo esc_html( $domain ); ?></div>
1355 - </div>
1356 -
1357 - <div class="mxchat-search-content">
1358 - <h3 class="mxchat-search-title">
1359 - <a href="<?php echo esc_url( $url ); ?>"
1360 - target="_blank"
1361 - rel="noopener noreferrer"
1362 - >
1363 - <?php echo esc_html( $title ); ?>
1364 - </a>
1365 - </h3>
1366 -
1367 - <?php if ( $thumbnail ) : ?>
1368 - <div class="mxchat-search-thumbnail">
1369 - <img
1370 - src="<?php echo esc_url( $thumbnail ); ?>"
1371 - alt="<?php echo esc_attr__( 'Thumbnail image', 'mxchat' ); ?>"
1372 - loading="lazy"
1373 - />
1374 - </div>
1375 - <?php endif; ?>
1376 -
1377 - <div class="mxchat-search-description">
1378 - <?php echo esc_html( $description ); ?>
1379 - </div>
1380 - </div>
1381 - </div>
1382 - <?php endforeach; ?>
1383 - </div>
1384 - <?php
1385 - return ob_get_clean();
1386 -}
1387 -
1388 -
1389 -//very good
1390 -public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
1391 -
1392 - // Step 1: Interpret the search query for better results
1393 - $refined_search_query = $this->mxchat_interpret_search_query($message);
1394 -
1395 -
1396 - // If no query was interpreted, return a fallback message
1397 - if (empty($refined_search_query)) {
1398 - $this->fallbackResponse = [
1399 - 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
1400 - 'html' => "",
1401 - ];
1402 - return;
1403 - }
1404 -
1405 - // Brave API URL
1406 - $api_url = 'https://api.search.brave.com/res/v1/images/search';
1407 -
1408 - // Retrieve Brave API settings
1409 - $options = get_option('mxchat_options');
1410 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1411 -
1412 - if (empty($api_key)) {
1413 -/*
1414 - if (defined('WP_DEBUG') && WP_DEBUG) {
1415 - error_log("Brave API key is missing.");
1416 - }
1417 -*/
1418 -
1419 - $this->fallbackResponse = [
1420 - 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
1421 - 'html' => "",
1422 - ];
1423 - return;
1424 - }
1425 -
1426 - $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
1427 - $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
1428 -
1429 - // Append query parameters based on settings
1430 - $api_url = add_query_arg([
1431 - 'q' => rawurlencode($refined_search_query),
1432 - 'count' => $image_count,
1433 - 'safesearch' => $safe_search,
1434 - ], $api_url);
1435 -
1436 -/*
1437 - // Log the final API URL for the search
1438 - if (defined('WP_DEBUG') && WP_DEBUG) {
1439 - error_log("Final API URL for Brave Image Search: " . esc_url_raw($api_url));
1440 - }
1441 -*/
1442 -
1443 -
1444 - // Implement caching
1445 - $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
1446 - $body = get_transient($transient_key);
1447 -
1448 - if (false === $body) {
1449 - $args = [
1450 - 'headers' => [
1451 - 'Accept' => 'application/json',
1452 - 'Accept-Encoding' => 'gzip',
1453 - 'X-Subscription-Token' => $api_key,
1454 - ],
1455 - 'timeout' => 10,
1456 - ];
1457 -
1458 - $response = wp_remote_get($api_url, $args);
1459 -
1460 - if (is_wp_error($response)) {
1461 -/*
1462 - if (defined('WP_DEBUG') && WP_DEBUG) {
1463 - error_log("Brave Image API request failed: " . $response->get_error_message());
1464 - }
1465 -*/
1466 -
1467 - $this->fallbackResponse = [
1468 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1469 - 'html' => "",
1470 - ];
1471 - return;
1472 - }
1473 -
1474 - $body = json_decode(wp_remote_retrieve_body($response), true);
1475 - set_transient($transient_key, $body, HOUR_IN_SECONDS);
1476 - }
1477 -
1478 - // Process the API response
1479 - if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
1480 - $html_output = '<div class="mxchat-image-gallery">';
1481 -
1482 - foreach ($body['results'] as $image) {
1483 - $image_url = isset($image['url']) ? esc_url($image['url']) : '';
1484 - $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
1485 - $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
1486 -
1487 - if ($image_url && $thumbnail_url) {
1488 - $html_output .= '<div class="mxchat-image-item">';
1489 - $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
1490 - $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
1491 - $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
1492 - $html_output .= '</a></div>';
1493 - }
1494 - }
1495 -
1496 - $html_output .= '</div>';
1497 -
1498 - $this->fallbackResponse = [
1499 - 'text' => "",
1500 - 'html' => $html_output,
1501 - ];
1502 -
1503 - // Save response in chat history
1504 - $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
1505 -
1506 - } else {
1507 -/*
1508 - if (defined('WP_DEBUG') && WP_DEBUG) {
1509 - error_log("Brave Image API response did not contain expected data structure or was empty: " . print_r($body, true));
1510 - }
1511 -*/
1512 -
1513 - $this->fallbackResponse = [
1514 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1515 - 'html' => "",
1516 - ];
1517 - }
1518 -}
1519 -public function mxchat_interpret_search_query($user_query) {
1520 - $system_prompt = esc_html__("Interpret the user's request to provide only the essential keywords or phrases for image searching. Remove conversational language, politeness, or extra context. Return a concise search query that doesn't lose any of the original meaning.", 'mxchat');
1521 -
1522 - // Retrieve OpenAI API key using 'api_key' as the option key
1523 - $api_key = isset($this->options['api_key']) ? sanitize_text_field($this->options['api_key']) : sanitize_text_field(get_option('mxchat_options')['api_key']);
1524 -
1525 - /*
1526 - // Log the API key check, without exposing the key
1527 - if (defined('WP_DEBUG') && WP_DEBUG) {
1528 - error_log("Retrieved OpenAI API Key: " . ($api_key ? "Present" : "Missing"));
1529 - }
1530 - */
1531 -
1532 - if (empty($api_key)) {
1533 - //error_log("OpenAI API key is missing.");
1534 - return sanitize_text_field($user_query); // Default to the original query if API key is missing
1535 - }
1536 -
1537 - $url = 'https://api.openai.com/v1/chat/completions';
1538 - $args = [
1539 - 'headers' => [
1540 - 'Authorization' => 'Bearer ' . $api_key,
1541 - 'Content-Type' => 'application/json',
1542 - ],
1543 - 'body' => wp_json_encode([
1544 - 'model' => 'gpt-3.5-turbo',
1545 - 'messages' => [
1546 - ['role' => 'system', 'content' => $system_prompt],
1547 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
1548 - ],
1549 - 'temperature' => 0.2,
1550 - 'max_tokens' => 20,
1551 - ]),
1552 - 'method' => 'POST',
1553 - ];
1554 -
1555 - $response = wp_remote_post($url, $args);
1556 -
1557 - if (is_wp_error($response)) {
1558 - //error_log("OpenAI request failed: " . $response->get_error_message());
1559 - return sanitize_text_field($user_query); // Fallback to the original query if there's an error
1560 - }
1561 -
1562 - $body = json_decode(wp_remote_retrieve_body($response), true);
1563 -
1564 - // Check for a valid response and sanitize output
1565 - if (isset($body['choices'][0]['message']['content'])) {
1566 - $interpreted_query = sanitize_text_field(trim($body['choices'][0]['message']['content']));
1567 -
1568 - /*
1569 - // Log the interpreted query for debugging
1570 - if (defined('WP_DEBUG') && WP_DEBUG) {
1571 - error_log("Interpreted search query: " . $interpreted_query);
1572 - }
1573 - */
1574 -
1575 - return $interpreted_query;
1576 - } else {
1577 - //error_log("Unexpected API response format: " . print_r($body, true));
1578 - return sanitize_text_field($user_query);
1579 - }
1580 -}
1581 -
1582 -
1583 -
1584 -private function find_product_in_message($message) {
1585 - global $wpdb;
1586 -
1587 - // Get embedding for the search query
1588 - $query_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1589 - if (!is_array($query_embedding)) {
1590 - return null;
1591 - }
1592 -
1593 - // Get relevant content as string
1594 - $relevant_content = $this->mxchat_find_relevant_products($query_embedding);
1595 - if (empty($relevant_content)) {
1596 - // Return null to indicate no results and set fallback response
1597 - $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Could you please be more specific about the product you're looking for?", 'mxchat');
1598 - return null;
1599 - }
1600 -
1601 - // Extract product URLs from the content
1602 - preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
1603 -
1604 - if (!empty($matches[0])) {
1605 - // Try each URL found
1606 - foreach ($matches[0] as $url) {
1607 - // Clean the URL
1608 - $url = rtrim($url, '/."\']');
1609 -
1610 - // Get the product slug
1611 - $path = parse_url($url, PHP_URL_PATH);
1612 - $slug = basename(rtrim($path, '/'));
1613 -
1614 - // Find product by slug
1615 - $args = array(
1616 - 'post_type' => 'product',
1617 - 'post_status' => 'publish',
1618 - 'name' => $slug,
1619 - 'posts_per_page' => 1
1620 - );
1621 -
1622 - $products = get_posts($args);
1623 -
1624 - if (!empty($products)) {
1625 - $product_id = $products[0]->ID;
1626 - $product = wc_get_product($product_id);
1627 -
1628 - if ($product && $product->is_purchasable()) {
1629 - return $product_id;
1630 - }
1631 - }
1632 - }
1633 - }
1634 -
1635 - // Fallback: Look for product names in the content
1636 - $products = wc_get_products([
1637 - 'status' => 'publish',
1638 - 'limit' => -1,
1639 - 'return' => 'all'
1640 - ]);
1641 -
1642 - foreach ($products as $product) {
1643 - $name = $product->get_name();
1644 - if (stripos($relevant_content, $name) !== false) {
1645 - if ($product->is_purchasable()) {
1646 - return $product->get_id();
1647 - }
1648 - }
1649 - }
1650 -
1651 - // If no product is found after all checks, set the fallback response
1652 - $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Try to be more specific", 'mxchat');
1653 - return null;
1654 -}
1655 -
1656 -// New method to handle intent responses
1657 -private function generate_intent_response($context_content, $session_id) {
1658 - // Convert the context array to a structured string for the AI
1659 - $context_string = $this->format_intent_context($context_content);
1660 -
1661 - // Generate AI response using the context
1662 - $response = $this->mxchat_generate_response(
1663 - $context_string,
1664 - $this->options['api_key'],
1665 - $this->options['xai_api_key'],
1666 - $this->options['claude_api_key'],
1667 - $this->options['deepseek_api_key'],
1668 - $this->mxchat_fetch_conversation_history_for_ai($session_id)
1669 - );
1670 -
1671 - $this->fallbackResponse['text'] = $response;
1672 - return true;
1673 -}
1674 -// Helper method to format intent context
1675 -private function format_intent_context($context) {
1676 - $context_string = esc_html__("INTENT CONTEXT:\n", 'mxchat');
1677 -
1678 - switch ($context['intent']) {
1679 - case 'add_to_cart':
1680 - if ($context['status'] === 'success') {
1681 - $context_string .= esc_html__("Action: Successfully added product to cart\n", 'mxchat');
1682 - $context_string .= sprintf(esc_html__("Product: %s\n", 'mxchat'), $context['product']['name']);
1683 - $context_string .= esc_html__("Available actions: ", 'mxchat') . implode(', ', $context['available_actions']) . "\n";
1684 - $context_string .= sprintf(esc_html__("Cart URL: %s\n", 'mxchat'), $context['cart_url']);
1685 - $context_string .= esc_html__("\nPlease inform the user of the successful addition and their available options.", 'mxchat');
1686 - } else {
1687 - $context_string .= esc_html__("Action: Failed to add product to cart\n", 'mxchat');
1688 - $context_string .= sprintf(esc_html__("Reason: %s\n", 'mxchat'), $context['reason']);
1689 - switch ($context['reason']) {
1690 - case 'woocommerce_not_available':
1691 - $context_string .= esc_html__("\nPlease inform the user that shopping features are not available.", 'mxchat');
1692 - break;
1693 - case 'no_product_context':
1694 - $context_string .= esc_html__("\nPlease ask the user to specify which product they want to add.", 'mxchat');
1695 - break;
1696 - case 'product_not_found':
1697 - $context_string .= esc_html__("\nPlease inform the user that the product couldn't be found and ask them to try again.", 'mxchat');
1698 - break;
1699 - case 'add_to_cart_failed':
1700 - $context_string .= esc_html__("\nPlease apologize to the user and suggest they try again or ask for assistance.", 'mxchat');
1701 - break;
1702 - }
1703 - }
1704 - break;
1705 - }
1706 -
1707 - return $context_string;
1708 -}
1709 -
1710 -
1711 -//very good
1712 -private function add_email_to_loops($email) {
1713 - // Sanitize the email
1714 - $email = sanitize_email($email);
1715 -
1716 - // Retrieve and sanitize options
1717 - $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
1718 - $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
1719 -
1720 - // Check for missing API key or mailing list ID
1721 - if (empty($api_key) || empty($mailing_list_id)) {
1722 - //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
1723 - return;
1724 - }
1725 -
1726 - $data = array(
1727 - 'email' => $email,
1728 - 'subscribed' => true,
1729 - 'source' => __('MxChat AI Chatbot', 'mxchat'),
1730 - 'mailingLists' => array($mailing_list_id => true),
1731 - );
1732 -
1733 - $url = 'https://app.loops.so/api/v1/contacts/create';
1734 - $args = array(
1735 - 'body' => wp_json_encode($data),
1736 - 'headers' => array(
1737 - 'Authorization' => 'Bearer ' . $api_key,
1738 - 'Content-Type' => 'application/json',
1739 - ),
1740 - 'method' => 'POST',
1741 - 'timeout' => 45,
1742 - );
1743 -
1744 - $response = wp_remote_post($url, $args);
1745 -
1746 - // Handle errors in the API request
1747 - if (is_wp_error($response)) {
1748 - //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
1749 - return;
1750 - }
1751 -
1752 - // Check for non-200 HTTP responses
1753 - $response_code = wp_remote_retrieve_response_code($response);
1754 - if ($response_code != 200) {
1755 - $response_body = wp_remote_retrieve_body($response);
1756 - //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
1757 - }
1758 -}
1759 -
1760 -public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
1761 - // Get the maximum number of pages allowed from admin settings
1762 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1763 -
1764 - // Retrieve options for dynamic texts
1765 - $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
1766 - $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
1767 - $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1768 -
1769 - // Check for explicit request for new PDF
1770 - $new_pdf_requested = stripos($message, 'new') !== false ||
1771 - stripos($message, 'another') !== false ||
1772 - stripos($message, 'different') !== false;
1773 -
1774 - // If user mentions adding/reading a PDF, set waiting flag
1775 - if (stripos($message, 'pdf') !== false ||
1776 - stripos($message, 'document') !== false ||
1777 - stripos($message, 'read') !== false) {
1778 - set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
1779 - $this->fallbackResponse['text'] = $trigger_text;
1780 - return;
1781 - }
1782 -
1783 - // If we're waiting for a URL or user requested new PDF
1784 - if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1785 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1786 - // Process URL... (rest of your existing URL processing code)
1787 - } else {
1788 - $this->fallbackResponse['text'] = $trigger_text;
1789 - }
1790 - return;
1791 - }
1792 -
1793 - // Default to proceeding with conversation if no specific PDF action is needed
1794 - $this->fallbackResponse['text'] = '';
1795 -}
1796 -private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
1797 - $upload_dir = wp_upload_dir();
1798 - $temp_file = null;
1799 -
1800 - try {
1801 - // Handle URL vs local file
1802 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1803 - // Validate and download the file from URL
1804 - $temp_file = wp_tempnam($pdf_source); // Safe temporary file name
1805 - $response = wp_remote_get($pdf_source, ['timeout' => 60]);
1806 -
1807 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1808 - //error_log(esc_html__("Failed to download PDF. Error: ", 'mxchat') . print_r($response, true));
1809 - return false;
1810 - }
1811 -
1812 - file_put_contents($temp_file, wp_remote_retrieve_body($response));
1813 -
1814 - // Validate that the downloaded file is a PDF
1815 - $mime_type = mime_content_type($temp_file);
1816 - if ($mime_type !== 'application/pdf') {
1817 - //error_log(esc_html__("Invalid MIME type detected for PDF: ", 'mxchat') . $mime_type);
1818 - unlink($temp_file);
1819 - return false;
1820 - }
1821 - } else {
1822 - // For local files, use the provided path directly
1823 - $temp_file = $pdf_source;
1824 - }
1825 -
1826 - // Parse and process the PDF
1827 - $parser = new \Smalot\PdfParser\Parser();
1828 - $pdf = $parser->parseFile($temp_file);
1829 - $pages = $pdf->getPages();
1830 -
1831 - if (count($pages) > $max_pages) {
1832 - //error_log(esc_html__("PDF exceeds the maximum allowed pages: ", 'mxchat') . count($pages));
1833 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1834 - unlink($temp_file);
1835 - }
1836 - return esc_html__('too_many_pages', 'mxchat');
1837 - }
1838 -
1839 - $embeddings = [];
1840 - foreach ($pages as $page_number => $page) {
1841 - $text = $page->getText();
1842 -
1843 - // Ensure text is non-empty before generating embeddings
1844 - if (empty(trim($text))) {
1845 - //error_log(esc_html__("Skipping empty page: ", 'mxchat') . ($page_number + 1));
1846 - continue;
1847 - }
1848 -
1849 - $embedding = $this->mxchat_generate_embedding(
1850 - esc_html__("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
1851 - $this->options['api_key']
1852 - );
1853 -
1854 - if ($embedding) {
1855 - $embeddings[] = [
1856 - 'page_number' => $page_number + 1,
1857 - 'embedding' => $embedding,
1858 - 'text' => $text,
1859 - ];
1860 - } else {
1861 - //error_log(esc_html__("Failed to generate embedding for page ", 'mxchat') . ($page_number + 1));
1862 - }
1863 - }
1864 -
1865 - // Clean up downloaded file if it was from URL
1866 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
1867 - unlink($temp_file);
1868 - }
1869 -
1870 - return $embeddings;
1871 -
1872 - } catch (\Exception $e) {
1873 - // error_log(esc_html__("Error parsing or processing PDF: ", 'mxchat') . $e->getMessage());
1874 -
1875 - // Cleanup in case of exception
1876 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
1877 - unlink($temp_file);
1878 - }
1879 -
1880 - return false;
1881 - }
1882 -}
1883 -private function find_relevant_pdf_pages($query_embedding, $embeddings) {
1884 - //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
1885 -
1886 - $most_relevant = null;
1887 - $highest_similarity = -INF;
1888 -
1889 - foreach ($embeddings as $page_data) {
1890 - $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
1891 -
1892 - if ($similarity > $highest_similarity) {
1893 - $highest_similarity = $similarity;
1894 - $most_relevant = $page_data['page_number'];
1895 - }
1896 - }
1897 -
1898 - if (!is_null($most_relevant)) {
1899 - $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
1900 - return array_filter($embeddings, function ($page) use ($page_numbers) {
1901 - return in_array($page['page_number'], $page_numbers);
1902 - });
1903 - }
1904 -
1905 - return [];
1906 -}
1907 -// Add this to your class
1908 -public function handle_pdf_upload() {
1909 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
1910 -
1911 - if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
1912 - wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
1913 - return;
1914 - }
1915 -
1916 - $file = $_FILES['pdf_file'];
1917 - $session_id = sanitize_text_field($_POST['session_id']);
1918 - $original_filename = sanitize_text_field($file['name']);
1919 -
1920 - $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
1921 - if ($file_type['type'] !== 'application/pdf') {
1922 - wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
1923 - return;
1924 - }
1925 -
1926 - $upload_dir = wp_upload_dir();
1927 - $pdf_filename = 'mxchat_' . $session_id . '_' . time() . '.pdf';
1928 - $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
1929 -
1930 - if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
1931 - wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
1932 - return;
1933 - }
1934 -
1935 - $this->clear_pdf_transients($session_id);
1936 -
1937 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1938 - $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
1939 -
1940 - if ($embeddings === 'too_many_pages') {
1941 - unlink($pdf_path);
1942 - $error_message = sprintf(
1943 - $this->options['pdf_intent_error_text'] ??
1944 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1945 - $max_pages
1946 - );
1947 - wp_send_json_error($error_message);
1948 - return;
1949 - }
1950 -
1951 - if ($embeddings === false || empty($embeddings)) {
1952 - unlink($pdf_path);
1953 - $error_message = $this->options['pdf_intent_error_text'] ??
1954 - esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
1955 - wp_send_json_error($error_message);
1956 - return;
1957 - }
1958 -
1959 - if (!empty($embeddings)) {
1960 - set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
1961 - set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
1962 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
1963 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
1964 -
1965 - $success_message = $this->options['pdf_intent_success_text'] ??
1966 - esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
1967 -
1968 - wp_send_json_success([
1969 - 'message' => $success_message,
1970 - 'filename' => $original_filename
1971 - ]);
1972 - return;
1973 - }
1974 -
1975 - unlink($pdf_path);
1976 - $error_message = $this->options['pdf_intent_error_text'] ??
1977 - esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
1978 - wp_send_json_error($error_message);
1979 - return;
1980 -}
1981 -public function handle_pdf_remove() {
1982 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
1983 -
1984 - if (empty($_POST['session_id'])) {
1985 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
1986 - wp_die();
1987 - }
1988 -
1989 - $session_id = sanitize_text_field($_POST['session_id']);
1990 - $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
1991 -
1992 - if ($pdf_path && file_exists($pdf_path)) {
1993 - unlink($pdf_path);
1994 - }
1995 -
1996 - $this->clear_pdf_transients($session_id);
1997 -
1998 - wp_send_json_success([
1999 - 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2000 - ]);
2001 - wp_die();
2002 -}
2003 -
2004 -
2005 -
2006 -
2007 -function mxchat_fetch_new_messages() {
2008 - $session_id = sanitize_text_field($_POST['session_id']);
2009 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2010 - $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2011 - $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2012 -
2013 - if (empty($session_id)) {
2014 - //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2015 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2016 - wp_die();
2017 - }
2018 -
2019 - $history = get_option("mxchat_history_{$session_id}", []);
2020 -
2021 - $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2022 - // If persistence is enabled, show all new messages
2023 - if ($persistence_enabled) {
2024 - return !empty($message['id']) &&
2025 - strcmp($message['id'], $last_seen_id) > 0 &&
2026 - $message['role'] === 'agent';
2027 - }
2028 -
2029 - // If persistence is disabled, only show messages after initial timestamp
2030 - return !empty($message['id']) &&
2031 - $message['role'] === 'agent' &&
2032 - $message['timestamp'] > $initial_timestamp;
2033 - });
2034 -
2035 - //error_log(esc_html__("New agent messages fetched for session $session_id. Last seen ID: $last_seen_id", 'mxchat'));
2036 -
2037 - wp_send_json_success([
2038 - 'new_messages' => array_values($new_messages)
2039 - ]);
2040 - wp_die();
2041 -}
2042 -
2043 -
2044 -public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2045 - // First check if live agents are available
2046 - $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2047 - if ($live_agent_available !== 'on') {
2048 - $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2049 - $this->fallbackResponse = [
2050 - 'text' => $away_message,
2051 - 'html' => '',
2052 - 'images' => [],
2053 - 'chat_mode' => 'ai'
2054 - ];
2055 - wp_send_json([
2056 - 'text' => $away_message,
2057 - 'html' => '',
2058 - 'chat_mode' => 'ai',
2059 - 'session_id' => $session_id
2060 - ]);
2061 - wp_die();
2062 - }
2063 -
2064 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2065 - if (empty($slack_webhook_url)) {
2066 - return false;
2067 - }
2068 -
2069 - // Get recent chat history (last 5 messages)
2070 - $history = get_option("mxchat_history_{$session_id}", []);
2071 - $recent_history = array_slice($history, -5); // Get last 5 messages
2072 -
2073 - // Format conversation history
2074 - $conversation_context = "";
2075 - if (!empty($recent_history)) {
2076 - $conversation_context = "*Recent Conversation:*\n";
2077 - foreach ($recent_history as $hist_message) {
2078 - $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
2079 - $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
2080 - }
2081 - $conversation_context .= "\n";
2082 - }
2083 -
2084 - update_option("mxchat_mode_{$session_id}", 'agent');
2085 -
2086 - $webhook_data = [
2087 - 'blocks' => [
2088 - [
2089 - 'type' => 'header',
2090 - 'text' => [
2091 - 'type' => 'plain_text',
2092 - 'text' => '🔔 New Live Agent Request',
2093 - 'emoji' => true
2094 - ]
2095 - ],
2096 - [
2097 - 'type' => 'section',
2098 - 'fields' => [
2099 - [
2100 - 'type' => 'mrkdwn',
2101 - 'text' => sprintf('*User ID:*\n`%s`', $user_id)
2102 - ],
2103 - [
2104 - 'type' => 'mrkdwn',
2105 - 'text' => sprintf('*Session ID:*\n`%s`', $session_id)
2106 - ]
2107 - ]
2108 - ]
2109 - ]
2110 - ];
2111 -
2112 - // Add conversation history if exists
2113 - if (!empty($conversation_context)) {
2114 - $webhook_data['blocks'][] = [
2115 - 'type' => 'section',
2116 - 'text' => [
2117 - 'type' => 'mrkdwn',
2118 - 'text' => $conversation_context
2119 - ]
2120 - ];
2121 - }
2122 -
2123 - // Add the current message
2124 - $webhook_data['blocks'][] = [
2125 - 'type' => 'section',
2126 - 'text' => [
2127 - 'type' => 'mrkdwn',
2128 - 'text' => sprintf('*Current Message:*\n%s', $message)
2129 - ]
2130 - ];
2131 -
2132 - // Add the reply button
2133 - $webhook_data['blocks'][] = [
2134 - 'type' => 'actions',
2135 - 'elements' => [
2136 - [
2137 - 'type' => 'button',
2138 - 'text' => [
2139 - 'type' => 'plain_text',
2140 - 'text' => '✍️ Reply',
2141 - 'emoji' => true
2142 - ],
2143 - 'value' => $session_id,
2144 - 'action_id' => 'reply_to_user',
2145 - 'style' => 'primary'
2146 - ]
2147 - ]
2148 - ];
2149 -
2150 - $response = wp_remote_post($slack_webhook_url, [
2151 - 'body' => json_encode($webhook_data),
2152 - 'headers' => [
2153 - 'Content-Type' => 'application/json',
2154 - ],
2155 - ]);
2156 -
2157 - if (is_wp_error($response)) {
2158 - return false;
2159 - }
2160 -
2161 - $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
2162 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
2163 -
2164 - $this->fallbackResponse = [
2165 - 'text' => $success_message,
2166 - 'html' => '',
2167 - 'images' => [],
2168 - 'chat_mode' => 'agent'
2169 - ];
2170 -
2171 - wp_send_json([
2172 - 'success' => true,
2173 - 'text' => $success_message,
2174 - 'html' => '',
2175 - 'chat_mode' => 'agent',
2176 - 'session_id' => $session_id,
2177 - 'fallbackResponse' => $this->fallbackResponse
2178 - ]);
2179 - wp_die();
2180 -}
2181 -public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
2182 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2183 -
2184 - if (empty($slack_webhook_url)) {
2185 - //error_log(esc_html__('Slack Webhook URL is not configured.', 'mxchat'));
2186 - return false;
2187 - }
2188 -
2189 - $webhook_data = [
2190 - 'blocks' => [
2191 - [
2192 - 'type' => 'header',
2193 - 'text' => [
2194 - 'type' => 'plain_text',
2195 - 'text' => esc_html__('📩 New Chat Message', 'mxchat'),
2196 - 'emoji' => true
2197 - ]
2198 - ],
2199 - [
2200 - 'type' => 'section',
2201 - 'fields' => [
2202 - [
2203 - 'type' => 'mrkdwn',
2204 - 'text' => sprintf(esc_html__('*User ID:*\n`%s`', 'mxchat'), $user_id)
2205 - ],
2206 - [
2207 - 'type' => 'mrkdwn',
2208 - 'text' => sprintf(esc_html__('*Session ID:*\n`%s`', 'mxchat'), $session_id)
2209 - ]
2210 - ]
2211 - ],
2212 - [
2213 - 'type' => 'section',
2214 - 'text' => [
2215 - 'type' => 'mrkdwn',
2216 - 'text' => sprintf(esc_html__('*Message:*\n%s', 'mxchat'), $message)
2217 - ]
2218 - ],
2219 - [
2220 - 'type' => 'actions',
2221 - 'elements' => [
2222 - [
2223 - 'type' => 'button',
2224 - 'text' => [
2225 - 'type' => 'plain_text',
2226 - 'text' => esc_html__('✍️ Reply', 'mxchat'),
2227 - 'emoji' => true
2228 - ],
2229 - 'value' => $session_id,
2230 - 'action_id' => 'reply_to_user',
2231 - 'style' => 'primary'
2232 - ]
2233 - ]
2234 - ]
2235 - ]
2236 - ];
2237 -
2238 - $response = wp_remote_post($slack_webhook_url, [
2239 - 'body' => json_encode($webhook_data),
2240 - 'headers' => [
2241 - 'Content-Type' => 'application/json',
2242 - ],
2243 - ]);
2244 -
2245 - if (is_wp_error($response)) {
2246 - //error_log(esc_html__('Error sending message to Slack: ', 'mxchat') . $response->get_error_message());
2247 - return false;
2248 - }
2249 -
2250 - //error_log(esc_html__('Message sent to Slack successfully.', 'mxchat'));
2251 - return true;
2252 -}
2253 -public function handle_slack_interaction(WP_REST_Request $request) {
2254 - //error_log('Received Slack interaction');
2255 -
2256 - $payload = json_decode($request->get_param('payload'), true);
2257 - //error_log('Payload: ' . print_r($payload, true));
2258 -
2259 - // Handle button click
2260 - if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
2261 - $session_id = $payload['actions'][0]['value'];
2262 - $trigger_id = $payload['trigger_id'];
2263 -
2264 - // Get Bot Token from settings
2265 - $slack_token = $this->options['live_agent_bot_token'] ?? '';
2266 -
2267 - if (empty($slack_token)) {
2268 - //error_log('Slack Bot Token not configured');
2269 - return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
2270 - }
2271 - $response = wp_remote_post('https://slack.com/api/views.open', [
2272 - 'headers' => [
2273 - 'Content-Type' => 'application/json',
2274 - 'Authorization' => 'Bearer ' . $slack_token
2275 - ],
2276 - 'body' => json_encode([
2277 - 'trigger_id' => $trigger_id,
2278 - 'view' => [
2279 - 'type' => 'modal',
2280 - 'callback_id' => 'reply_modal',
2281 - 'title' => [
2282 - 'type' => 'plain_text',
2283 - 'text' => __('Reply to User', 'mxchat')
2284 - ],
2285 - 'submit' => [
2286 - 'type' => 'plain_text',
2287 - 'text' => __('Send', 'mxchat')
2288 - ],
2289 - 'close' => [
2290 - 'type' => 'plain_text',
2291 - 'text' => __('Cancel', 'mxchat')
2292 - ],
2293 - 'blocks' => [
2294 - [
2295 - 'type' => 'input',
2296 - 'block_id' => 'reply_block',
2297 - 'label' => [
2298 - 'type' => 'plain_text',
2299 - 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
2300 - ],
2301 - 'element' => [
2302 - 'type' => 'plain_text_input',
2303 - 'action_id' => 'message',
2304 - 'multiline' => true,
2305 - 'placeholder' => [
2306 - 'type' => 'plain_text',
2307 - 'text' => __('Type your message here...', 'mxchat')
2308 - ]
2309 - ]
2310 - ]
2311 - ],
2312 - 'private_metadata' => $session_id
2313 - ]
2314 - ])
2315 - ]);
2316 -
2317 - //error_log('Views.open response: ' . print_r($response, true));
2318 -
2319 - // Return immediate acknowledgment
2320 - return new WP_REST_Response(['ok' => true]);
2321 - }
2322 -
2323 - // Handle modal submission
2324 -// Handle modal submission
2325 -if ($payload['type'] === 'view_submission') {
2326 - $session_id = $payload['view']['private_metadata'];
2327 - $message = $payload['view']['state']['values']['reply_block']['message']['value'];
2328 -
2329 - // Save the message (keep the message_id but don't include in response)
2330 - $this->mxchat_save_chat_message($session_id, 'agent', $message);
2331 -
2332 - // Keep the original response format for Slack
2333 - return new WP_REST_Response([
2334 - 'response_action' => 'clear'
2335 - ]);
2336 -}
2337 -
2338 - // Default acknowledgment
2339 - return new WP_REST_Response(['ok' => true]);
2340 -}
2341 -
2342 -public function mxchat_handle_agent_response(WP_REST_Request $request) {
2343 - //error_log('Received agent response request');
2344 - //error_log('Request data: ' . print_r($request->get_params(), true));
2345 - // error_log('Raw body: ' . file_get_contents('php://input'));
2346 -
2347 - // Get the data from Slack's slash command format
2348 - $command_text = $request->get_param('text');
2349 - // error_log('Command text: ' . $command_text);
2350 -
2351 - if (empty($command_text)) {
2352 - //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
2353 - return new WP_REST_Response([
2354 - 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
2355 - ], 400);
2356 - }
2357 -
2358 - // Split the command text into session_id and message
2359 - $parts = explode(' ', $command_text, 2);
2360 - if (count($parts) !== 2) {
2361 - //error_log('Agent response error: Invalid command format');
2362 - return new WP_REST_Response([
2363 - 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
2364 - ], 400);
2365 - }
2366 -
2367 - $session_id = sanitize_text_field($parts[0]);
2368 - $message = sanitize_text_field($parts[1]);
2369 -
2370 - //error_log("Processing agent response - Session ID: $session_id, Message: $message");
2371 -
2372 - // Save the message
2373 - $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
2374 -
2375 - if (!$message_id) {
2376 - // error_log('Failed to save agent message');
2377 - return new WP_REST_Response([
2378 - 'error' => esc_html__('Failed to save message', 'mxchat')
2379 - ], 500);
2380 - }
2381 -
2382 - // Return success response in Slack's expected format
2383 - return new WP_REST_Response([
2384 - 'response_type' => 'in_channel',
2385 - 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
2386 - ], 200);
2387 -}
2388 -
2389 -
2390 -public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
2391 - //error_log(esc_html__("Switching back to chatbot mode via intent.", 'mxchat'));
2392 -
2393 - // Just update mode to AI
2394 - update_option("mxchat_mode_{$session_id}", 'ai');
2395 -
2396 - // Initialize states
2397 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
2398 - $this->productCardHtml = '';
2399 -
2400 - // Set the response message
2401 - $this->fallbackResponse['text'] = esc_html__('You are now chatting with the AI chatbot.', 'mxchat');
2402 -
2403 - return true; // Intent was handled
2404 -}
2405 -
2406 -
2407 -
2408 -
2409 -// For the word upload handler
2410 -public function mxchat_handle_word_upload() {
2411 - // Delegate to word handler
2412 - $this->word_handler->mxchat_handle_word_upload();
2413 -}
2414 -
2415 -// For the word removal handler
2416 -public function mxchat_handle_word_remove() {
2417 - // Delegate to word handler
2418 - $this->word_handler->mxchat_handle_word_remove();
2419 -}
2420 -
2421 -// For the word status check
2422 -public function mxchat_check_word_status() {
2423 - // Delegate to word handler
2424 - $this->word_handler->mxchat_check_word_status();
2425 -}
2426 -
2427 -
2428 -private function mxchat_get_user_identifier() {
2429 - return MxChat_User::mxchat_get_user_identifier();
2430 -}
2431 -
2432 -private function mxchat_generate_embedding($text, $api_key) {
2433 - $endpoint = 'https://api.openai.com/v1/embeddings';
2434 -
2435 - $body = wp_json_encode([
2436 - 'input' => $text,
2437 - 'model' => 'text-embedding-ada-002'
2438 - ]);
2439 -
2440 - $args = [
2441 - 'body' => $body,
2442 - 'headers' => [
2443 - 'Content-Type' => 'application/json',
2444 - 'Authorization' => 'Bearer ' . $api_key,
2445 - ],
2446 - 'timeout' => 60,
2447 - 'redirection' => 5,
2448 - 'blocking' => true,
2449 - 'httpversion' => '1.0',
2450 - 'sslverify' => true,
2451 - ];
2452 -
2453 - $response = wp_remote_post($endpoint, $args);
2454 -
2455 - if (is_wp_error($response)) {
2456 - return null;
2457 - }
2458 -
2459 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
2460 -
2461 - if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
2462 - return $response_body['data'][0]['embedding'];
2463 - } else {
2464 - return null;
2465 - }
2466 - }
2467 -
2468 -
2469 -private function mxchat_find_relevant_content($user_embedding) {
2470 - //error_log('MXChat Vector Search: Starting content search...');
2471 -
2472 - // Retrieve the add-on settings from the database.
2473 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2474 -
2475 - // Determine whether Pinecone is enabled.
2476 - // We expect the sanitized setting to be a string '1' if enabled, otherwise '0'.
2477 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2478 -
2479 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
2480 -
2481 - if ($use_pinecone === 1) {
2482 - //error_log('MXChat Vector Search: Using Pinecone database');
2483 - return $this->find_relevant_content_pinecone($user_embedding);
2484 - } else {
2485 - //error_log('MXChat Vector Search: Using WordPress database');
2486 - return $this->find_relevant_content_wordpress($user_embedding);
2487 - }
2488 -}
2489 -
2490 -private function find_relevant_content_wordpress($user_embedding) {
2491 - global $wpdb;
2492 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2493 - $cache_key = 'mxchat_system_prompt_embeddings';
2494 - $batch_size = 500;
2495 -
2496 - // Retrieve embeddings from cache or database
2497 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2498 - if ($embeddings === false) {
2499 - $embeddings = [];
2500 - $offset = 0;
2501 -
2502 - // Load in batches and build cache
2503 - do {
2504 - $query = $wpdb->prepare(
2505 - "SELECT id, embedding_vector
2506 - FROM {$system_prompt_table}
2507 - LIMIT %d OFFSET %d",
2508 - $batch_size,
2509 - $offset
2510 - );
2511 -
2512 - $batch = $wpdb->get_results($query);
2513 - if (empty($batch)) {
2514 - break;
2515 - }
2516 -
2517 - $embeddings = array_merge($embeddings, $batch);
2518 - $offset += $batch_size;
2519 -
2520 - // Free memory
2521 - unset($batch);
2522 -
2523 - } while (true);
2524 -
2525 - if (empty($embeddings)) {
2526 - return ''; // Return an empty string if no embeddings found
2527 - }
2528 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2529 - }
2530 -
2531 - // Initialize array to store relevant results with similarity scores
2532 - $relevant_results = [];
2533 - // Iterate through embeddings to calculate similarity
2534 - foreach ($embeddings as $embedding) {
2535 - $database_embedding = $embedding->embedding_vector
2536 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2537 - : null;
2538 - if (is_array($database_embedding) && is_array($user_embedding)) {
2539 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2540 - $relevant_results[] = [
2541 - 'id' => $embedding->id,
2542 - 'similarity' => $similarity
2543 - ];
2544 - }
2545 - // Free memory
2546 - unset($database_embedding);
2547 - }
2548 -
2549 - // Retrieve the similarity threshold
2550 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
2551 -
2552 - // Filter and sort relevant results by similarity
2553 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2554 - return $result['similarity'] >= $similarity_threshold;
2555 - });
2556 - usort($relevant_results, function ($a, $b) {
2557 - return $b['similarity'] <=> $a['similarity'];
2558 - });
2559 -
2560 - // Limit to the top 5 results
2561 - $top_results = array_slice($relevant_results, 0, 5);
2562 -
2563 - // Initialize the final content
2564 - $content = '';
2565 -
2566 - // Fetch and combine content for the top results
2567 - foreach ($top_results as $result) {
2568 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
2569 - // Check if the content is PDF-related and add surrounding pages
2570 - if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
2571 - $surrounding_content = $wpdb->get_results($wpdb->prepare(
2572 - "SELECT article_content FROM {$system_prompt_table}
2573 - WHERE id IN (
2574 - (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
2575 - (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
2576 - )",
2577 - $result['id'],
2578 - $result['id']
2579 - ));
2580 - // Add previous content if it exists
2581 - if (!empty($surrounding_content[0])) {
2582 - $content .= $surrounding_content[0]->article_content . "\n\n";
2583 - }
2584 - // Add the main chunk content
2585 - $content .= $chunk_content . "\n\n";
2586 - // Add next content if it exists
2587 - if (!empty($surrounding_content[1])) {
2588 - $content .= $surrounding_content[1]->article_content . "\n\n";
2589 - }
2590 - } else {
2591 - // For non-PDF content, add directly
2592 - $content .= $chunk_content . "\n\n";
2593 - }
2594 - }
2595 -
2596 - return trim($content);
2597 -}
2598 -/**
2599 - * Find relevant content in Pinecone vector database
2600 - */
2601 -private function find_relevant_content_pinecone($user_embedding) {
2602 - $options = get_option('mxchat_pinecone_addon_options', array());
2603 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2604 - $host = $options['mxchat_pinecone_host'] ?? '';
2605 -
2606 - if (empty($host) || empty($api_key)) {
2607 - //error_log('Pinecone credentials not properly configured');
2608 - return '';
2609 - }
2610 -
2611 - // Get similarity threshold from WordPress settings
2612 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
2613 -
2614 - // Prepare the query request for Pinecone
2615 - $api_endpoint = "https://{$host}/query";
2616 -
2617 - $request_body = array(
2618 - 'vector' => $user_embedding,
2619 - 'topK' => 5,
2620 - 'includeMetadata' => true,
2621 - 'includeValues' => true
2622 - );
2623 -
2624 - $response = wp_remote_post($api_endpoint, array(
2625 - 'headers' => array(
2626 - 'Api-Key' => $api_key,
2627 - 'accept' => 'application/json',
2628 - 'content-type' => 'application/json'
2629 - ),
2630 - 'body' => wp_json_encode($request_body),
2631 - 'timeout' => 30
2632 - ));
2633 -
2634 - if (is_wp_error($response)) {
2635 - //error_log('Pinecone query error: ' . $response->get_error_message());
2636 - return '';
2637 - }
2638 -
2639 - $response_code = wp_remote_retrieve_response_code($response);
2640 - if ($response_code !== 200) {
2641 - //error_log('Pinecone API error: ' . wp_remote_retrieve_body($response));
2642 - return '';
2643 - }
2644 -
2645 - $results = json_decode(wp_remote_retrieve_body($response), true);
2646 - if (empty($results['matches'])) {
2647 - return '';
2648 - }
2649 -
2650 - // Initialize the final content
2651 - $content = '';
2652 -
2653 - // Process each match
2654 - foreach ($results['matches'] as $match) {
2655 - // Skip if similarity is below threshold
2656 - if ($match['score'] < $similarity_threshold) {
2657 - continue;
2658 - }
2659 -
2660 - if (!empty($match['metadata']['text']) && !empty($match['metadata']['source_url'])) {
2661 - // Add content with citation
2662 - $content .= $match['metadata']['text'] . "\n";
2663 - $content .= "Source: " . $match['metadata']['source_url'] . "\n\n";
2664 - }
2665 - }
2666 -
2667 - return trim($content);
2668 -}
2669 -
2670 -
2671 -private function mxchat_find_relevant_products($user_embedding) {
2672 - //error_log('MXChat Vector Search: Starting product search...');
2673 -
2674 - // Retrieve the add-on settings from the database
2675 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2676 -
2677 - // Determine whether Pinecone is enabled
2678 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2679 -
2680 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
2681 -
2682 - if ($use_pinecone === 1) {
2683 - //error_log('MXChat Vector Search: Using Pinecone database for products');
2684 - return $this->find_relevant_products_pinecone($user_embedding);
2685 - } else {
2686 - //error_log('MXChat Vector Search: Using WordPress database for products');
2687 - return $this->find_relevant_products_wordpress($user_embedding);
2688 - }
2689 -}
2690 -
2691 -private function find_relevant_products_wordpress($user_embedding) {
2692 - global $wpdb;
2693 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2694 - $cache_key = 'mxchat_system_prompt_embeddings';
2695 - $batch_size = 500;
2696 -
2697 - // Original WordPress database search logic
2698 - // [Previous implementation remains the same]
2699 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2700 - if ($embeddings === false) {
2701 - $embeddings = [];
2702 - $offset = 0;
2703 -
2704 - do {
2705 - $query = $wpdb->prepare(
2706 - "SELECT id, embedding_vector
2707 - FROM {$system_prompt_table}
2708 - LIMIT %d OFFSET %d",
2709 - $batch_size,
2710 - $offset
2711 - );
2712 -
2713 - $batch = $wpdb->get_results($query);
2714 - if (empty($batch)) {
2715 - break;
2716 - }
2717 -
2718 - $embeddings = array_merge($embeddings, $batch);
2719 - $offset += $batch_size;
2720 -
2721 - unset($batch);
2722 -
2723 - } while (true);
2724 -
2725 - if (empty($embeddings)) {
2726 - return '';
2727 - }
2728 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2729 - }
2730 -
2731 - $relevant_results = [];
2732 - foreach ($embeddings as $embedding) {
2733 - $database_embedding = $embedding->embedding_vector
2734 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2735 - : null;
2736 - if (is_array($database_embedding) && is_array($user_embedding)) {
2737 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2738 - $relevant_results[] = [
2739 - 'id' => $embedding->id,
2740 - 'similarity' => $similarity
2741 - ];
2742 - }
2743 - unset($database_embedding);
2744 - }
2745 -
2746 - // Use fixed threshold for products
2747 - $similarity_threshold = 0.85;
2748 -
2749 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2750 - return $result['similarity'] >= $similarity_threshold;
2751 - });
2752 - usort($relevant_results, function ($a, $b) {
2753 - return $b['similarity'] <=> $a['similarity'];
2754 - });
2755 -
2756 - $top_results = array_slice($relevant_results, 0, 5);
2757 - $content = '';
2758 -
2759 - foreach ($top_results as $result) {
2760 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
2761 - $content .= $chunk_content . "\n\n";
2762 - }
2763 -
2764 - return trim($content);
2765 -}
2766 -
2767 -// Modified search function with correct filter syntax
2768 -private function find_relevant_products_pinecone($user_embedding) {
2769 - //error_log('Starting Pinecone product search...');
2770 -
2771 - $options = get_option('mxchat_pinecone_addon_options', array());
2772 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2773 - $host = $options['mxchat_pinecone_host'] ?? '';
2774 -
2775 - if (empty($host) || empty($api_key)) {
2776 - //error_log('Pinecone credentials not properly configured for product search');
2777 - return '';
2778 - }
2779 -
2780 - $similarity_threshold = 0.85;
2781 - $api_endpoint = "https://{$host}/query";
2782 -
2783 - $request_body = array(
2784 - 'vector' => $user_embedding,
2785 - 'topK' => 5,
2786 - 'includeMetadata' => true,
2787 - 'includeValues' => true,
2788 - 'filter' => array(
2789 - 'type' => 'product'
2790 - )
2791 - );
2792 -
2793 - //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
2794 -
2795 - $response = wp_remote_post($api_endpoint, array(
2796 - 'headers' => array(
2797 - 'Api-Key' => $api_key,
2798 - 'accept' => 'application/json',
2799 - 'content-type' => 'application/json'
2800 - ),
2801 - 'body' => wp_json_encode($request_body),
2802 - 'timeout' => 30
2803 - ));
2804 -
2805 - if (is_wp_error($response)) {
2806 - //error_log('Pinecone product query error: ' . $response->get_error_message());
2807 - return '';
2808 - }
2809 -
2810 - $response_code = wp_remote_retrieve_response_code($response);
2811 - //error_log('Pinecone response code: ' . $response_code);
2812 -
2813 - if ($response_code !== 200) {
2814 - //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
2815 - return '';
2816 - }
2817 -
2818 - $results = json_decode(wp_remote_retrieve_body($response), true);
2819 - //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
2820 -
2821 - if (empty($results['matches'])) {
2822 - //error_log('No matches found in Pinecone response');
2823 - return '';
2824 - }
2825 -
2826 - $content = '';
2827 - foreach ($results['matches'] as $match) {
2828 - if ($match['score'] < $similarity_threshold) {
2829 - //error_log("Match below threshold: " . $match['score']);
2830 - continue;
2831 - }
2832 -
2833 - if (!empty($match['metadata']['text'])) {
2834 - $content .= $match['metadata']['text'];
2835 - if (!empty($match['metadata']['source_url'])) {
2836 - $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
2837 - }
2838 - $content .= "\n\n";
2839 - }
2840 - }
2841 -
2842 - return trim($content);
2843 -}
2844 -
2845 -
2846 -private function fetch_content_with_product_links($most_relevant_id) {
2847 - global $wpdb;
2848 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2849 -
2850 - // Fetch the article content and associated product URL
2851 - $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
2852 - $result = $wpdb->get_row($query);
2853 -
2854 - if ($result) {
2855 - // Append the product link to the content if available
2856 - $content = $result->article_content;
2857 - if (!empty($result->source_url)) {
2858 - $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
2859 - }
2860 - return $content;
2861 - }
2862 -
2863 - return null;
2864 -}
2865 -
2866 -// Function definition
2867 -private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $conversation_history) {
2868 - try {
2869 - if (!$relevant_content) {
2870 - return esc_html__("I'm sorry, I couldn't find relevant information on that topic.", 'mxchat');
2871 - }
2872 -
2873 - // Ensure conversation_history is an array
2874 - if (!is_array($conversation_history)) {
2875 - $conversation_history = array();
2876 - }
2877 -
2878 - // Get selected model with default fallback
2879 - $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
2880 -
2881 - // Extract model prefix to determine the provider
2882 - $model_parts = explode('-', $selected_model);
2883 - $provider = strtolower($model_parts[0]);
2884 -
2885 - // Handle model selection based on provider prefix
2886 - switch ($provider) {
2887 - case 'claude':
2888 - if (empty($claude_api_key)) {
2889 - throw new Exception(esc_html__('Claude API key is not configured', 'mxchat'));
2890 - }
2891 - return $this->mxchat_generate_response_claude(
2892 - $selected_model,
2893 - $claude_api_key,
2894 - $conversation_history,
2895 - $relevant_content
2896 - );
2897 -
2898 - case 'grok':
2899 - if (empty($xai_api_key)) {
2900 - throw new Exception(esc_html__('X.AI API key is not configured', 'mxchat'));
2901 - }
2902 - return $this->mxchat_generate_response_xai(
2903 - $selected_model,
2904 - $xai_api_key,
2905 - $conversation_history,
2906 - $relevant_content
2907 - );
2908 -
2909 - case 'deepseek':
2910 - if (empty($deepseek_api_key)) {
2911 - throw new Exception(esc_html__('DeepSeek API key is not configured', 'mxchat'));
2912 - }
2913 - return $this->mxchat_generate_response_deepseek(
2914 - $selected_model,
2915 - $deepseek_api_key,
2916 - $conversation_history,
2917 - $relevant_content
2918 - );
2919 -
2920 - case 'gpt':
2921 - if (empty($api_key)) {
2922 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
2923 - }
2924 - return $this->mxchat_generate_response_openai(
2925 - $selected_model,
2926 - $api_key,
2927 - $conversation_history,
2928 - $relevant_content
2929 - );
2930 -
2931 - default:
2932 - // Default to OpenAI for custom models or unrecognized prefixes
2933 - if (empty($api_key)) {
2934 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
2935 - }
2936 - return $this->mxchat_generate_response_openai(
2937 - $selected_model,
2938 - $api_key,
2939 - $conversation_history,
2940 - $relevant_content
2941 - );
2942 - }
2943 - } catch (Exception $e) {
2944 - //error_log('MXChat Error: ' . $e->getMessage());
2945 - return sprintf(
2946 - esc_html__('An error occurred: %s', 'mxchat'),
2947 - esc_html($e->getMessage())
2948 - );
2949 - }
2950 -}
2951 -
2952 -
2953 -private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
2954 - // Ensure conversation_history is an array
2955 - if (!is_array($conversation_history)) {
2956 - $conversation_history = array();
2957 - }
2958 -
2959 - // Get system prompt instructions from options
2960 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
2961 -
2962 - // Create a new array for the formatted conversation
2963 - $formatted_conversation = array();
2964 -
2965 - // Add system message first
2966 - $formatted_conversation[] = array(
2967 - 'role' => 'system',
2968 - 'content' => $system_prompt_instructions . " " . $relevant_content
2969 - );
2970 -
2971 - // Add the rest of the conversation history
2972 - foreach ($conversation_history as $message) {
2973 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
2974 - $role = $message['role'];
2975 -
2976 - // Convert roles to supported format
2977 - if ($role === 'bot' || $role === 'agent') {
2978 - $role = 'assistant';
2979 - }
2980 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
2981 - $role = 'user';
2982 - }
2983 -
2984 - $formatted_conversation[] = array(
2985 - 'role' => $role,
2986 - 'content' => $message['content']
2987 - );
2988 - }
2989 - }
2990 -
2991 - $body = json_encode([
2992 - 'model' => $selected_model,
2993 - 'messages' => $formatted_conversation,
2994 - 'temperature' => 0.8,
2995 - 'stream' => false
2996 - ]);
2997 -
2998 - $args = [
2999 - 'body' => $body,
3000 - 'headers' => [
3001 - 'Content-Type' => 'application/json',
3002 - 'Authorization' => 'Bearer ' . $deepseek_api_key,
3003 - ],
3004 - 'timeout' => 60,
3005 - 'redirection' => 5,
3006 - 'blocking' => true,
3007 - 'httpversion' => '1.0',
3008 - 'sslverify' => true,
3009 - ];
3010 -
3011 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
3012 -
3013 - if (is_wp_error($response)) {
3014 - //error_log('DeepSeek API Error: ' . $response->get_error_message());
3015 - return "Sorry, there was an error processing your request.";
3016 - }
3017 -
3018 - $response_body = wp_remote_retrieve_body($response);
3019 - $decoded_response = json_decode($response_body, true);
3020 -
3021 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3022 - return trim($decoded_response['choices'][0]['message']['content']);
3023 - } else {
3024 - //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
3025 - return "Sorry, I couldn't process that request.";
3026 - }
3027 -}
3028 -
3029 -private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
3030 - // Ensure conversation_history is an array
3031 - if (!is_array($conversation_history)) {
3032 - $conversation_history = array();
3033 - }
3034 -
3035 - // Get system prompt instructions from options
3036 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3037 -
3038 - // Create a new array for the formatted conversation
3039 - $formatted_conversation = array();
3040 -
3041 - // Add system message first
3042 - $formatted_conversation[] = array(
3043 - 'role' => 'system',
3044 - 'content' => $system_prompt_instructions . " " . $relevant_content
3045 - );
3046 -
3047 - // Add the rest of the conversation history
3048 - foreach ($conversation_history as $message) {
3049 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3050 - $role = $message['role'];
3051 -
3052 - // Convert roles to supported format
3053 - if ($role === 'bot' || $role === 'agent') {
3054 - $role = 'assistant';
3055 - }
3056 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3057 - $role = 'user';
3058 - }
3059 -
3060 - $formatted_conversation[] = array(
3061 - 'role' => $role,
3062 - 'content' => $message['content']
3063 - );
3064 - }
3065 - }
3066 -
3067 - $body = json_encode([
3068 - 'model' => $selected_model,
3069 - 'messages' => $formatted_conversation,
3070 - 'temperature' => 0.8,
3071 - 'stream' => false
3072 - ]);
3073 -
3074 - $args = [
3075 - 'body' => $body,
3076 - 'headers' => [
3077 - 'Content-Type' => 'application/json',
3078 - 'Authorization' => 'Bearer ' . $api_key,
3079 - ],
3080 - 'timeout' => 60,
3081 - 'redirection' => 5,
3082 - 'blocking' => true,
3083 - 'httpversion' => '1.0',
3084 - 'sslverify' => true,
3085 - ];
3086 -
3087 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
3088 -
3089 - if (is_wp_error($response)) {
3090 - //error_log('OpenAI API Error: ' . $response->get_error_message());
3091 - return "Sorry, there was an error processing your request.";
3092 - }
3093 -
3094 - $response_body = wp_remote_retrieve_body($response);
3095 - $decoded_response = json_decode($response_body, true);
3096 -
3097 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3098 - return trim($decoded_response['choices'][0]['message']['content']);
3099 - } else {
3100 - //error_log('OpenAI API Response Format Error: ' . print_r($decoded_response, true));
3101 - return "Sorry, I couldn't process that request.";
3102 - }
3103 -}
3104 -private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
3105 - // Get system prompt instructions from options
3106 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3107 -
3108 - // Add system prompt to relevant content
3109 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3110 -
3111 - // Prepend system instructions to the conversation history
3112 - array_unshift($conversation_history, [
3113 - 'role' => 'system',
3114 - 'content' => "Here are your instructions: " . $content_with_instructions
3115 - ]);
3116 -
3117 - // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
3118 - foreach ($conversation_history as &$message) {
3119 - if ($message['role'] === 'bot') {
3120 - $message['role'] = 'assistant';
3121 - } elseif ($message['role'] === 'agent') {
3122 - // Tag the message as coming from a live agent
3123 - $message['role'] = 'assistant';
3124 - if (!isset($message['metadata'])) {
3125 - $message['metadata'] = ['source' => 'live_agent'];
3126 - }
3127 - }
3128 -
3129 - // Ensure all roles are valid
3130 - if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
3131 - $message['role'] = 'user'; // Default to 'user'
3132 - }
3133 - }
3134 -
3135 -
3136 - // Build the request body
3137 - $body = json_encode([
3138 - 'model' => $selected_model,
3139 - 'messages' => $conversation_history,
3140 - 'temperature' => 0.8,
3141 - 'stream' => false
3142 - ]);
3143 -
3144 - // Set up the API request
3145 - $args = [
3146 - 'body' => $body,
3147 - 'headers' => [
3148 - 'Content-Type' => 'application/json',
3149 - 'Authorization' => 'Bearer ' . $xai_api_key,
3150 - ],
3151 - 'timeout' => 60,
3152 - 'redirection' => 5,
3153 - 'blocking' => true,
3154 - 'httpversion' => '1.0',
3155 - 'sslverify' => true,
3156 - ];
3157 -
3158 - // Make the API request
3159 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
3160 -
3161 - // Process the response
3162 - if (is_wp_error($response)) {
3163 - return "Sorry, there was an error processing your request.";
3164 - }
3165 -
3166 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3167 -
3168 - if (isset($response_body['choices'][0]['message']['content'])) {
3169 - return trim($response_body['choices'][0]['message']['content']);
3170 - } else {
3171 - return "Sorry, I couldn't process that request.";
3172 - }
3173 -}
3174 -
3175 -private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
3176 - // Get system prompt instructions from options
3177 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3178 -
3179 - // Clean and validate conversation history
3180 - foreach ($conversation_history as &$message) {
3181 - // Convert bot and agent roles to assistant
3182 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
3183 - $message['role'] = 'assistant';
3184 - }
3185 -
3186 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
3187 - if (!in_array($message['role'], ['assistant', 'user'])) {
3188 - $message['role'] = 'user';
3189 - }
3190 -
3191 - // Ensure content field exists
3192 - if (!isset($message['content']) || empty($message['content'])) {
3193 - $message['content'] = '';
3194 - }
3195 -
3196 - // Remove any unsupported fields
3197 - $message = array_intersect_key($message, array_flip(['role', 'content']));
3198 - }
3199 -
3200 - // Add relevant content as the latest user message
3201 - $conversation_history[] = [
3202 - 'role' => 'user',
3203 - 'content' => $relevant_content
3204 - ];
3205 -
3206 - // Build request body
3207 - $body = json_encode([
3208 - 'model' => $selected_model,
3209 - 'max_tokens' => 1000,
3210 - 'temperature' => 0.8,
3211 - 'messages' => $conversation_history,
3212 - 'system' => $system_prompt_instructions
3213 - ]);
3214 -
3215 - // Set up API request
3216 - $args = [
3217 - 'body' => $body,
3218 - 'headers' => [
3219 - 'Content-Type' => 'application/json',
3220 - 'x-api-key' => $claude_api_key,
3221 - 'anthropic-version' => '2023-06-01'
3222 - ],
3223 - 'timeout' => 60,
3224 - 'redirection' => 5,
3225 - 'blocking' => true,
3226 - 'httpversion' => '1.0',
3227 - 'sslverify' => true,
3228 - ];
3229 -
3230 - // Make API request
3231 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
3232 -
3233 - // Check for WordPress errors
3234 - if (is_wp_error($response)) {
3235 - //error_log("Claude API request error: " . $response->get_error_message());
3236 - return "Sorry, there was an error connecting to the API.";
3237 - }
3238 -
3239 - // Check HTTP response code
3240 - $http_code = wp_remote_retrieve_response_code($response);
3241 - if ($http_code !== 200) {
3242 - $error_body = wp_remote_retrieve_body($response);
3243 - //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
3244 -
3245 - // Try to extract error message from response
3246 - $error_data = json_decode($error_body, true);
3247 - $error_message = isset($error_data['error']['message']) ?
3248 - $error_data['error']['message'] :
3249 - "HTTP error " . $http_code;
3250 -
3251 - return "Sorry, the API returned an error: " . $error_message;
3252 - }
3253 -
3254 - // Parse response
3255 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3256 -
3257 - // Check for JSON decode errors
3258 - if (json_last_error() !== JSON_ERROR_NONE) {
3259 - //error_log("Claude API JSON decode error: " . json_last_error_msg());
3260 - return "Sorry, there was an error processing the API response.";
3261 - }
3262 -
3263 - // Extract and validate response content
3264 - if (isset($response_body['content']) &&
3265 - is_array($response_body['content']) &&
3266 - !empty($response_body['content']) &&
3267 - isset($response_body['content'][0]['text'])) {
3268 - return trim($response_body['content'][0]['text']);
3269 - }
3270 -
3271 - // Log unexpected response format
3272 - //error_log("Claude API unexpected response format: " . print_r($response_body, true));
3273 - return "Sorry, I received an unexpected response format from the API.";
3274 -}
3275 -public function mxchat_dismiss_pre_chat_message() {
3276 - // Get and sanitize the user identifier
3277 - $user_id = $this->mxchat_get_user_identifier();
3278 - $user_id = sanitize_key($user_id);
3279 -
3280 - // Set a transient to track that the user has dismissed the pre-chat message
3281 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3282 - set_transient($transient_key, true, DAY_IN_SECONDS);
3283 -
3284 - wp_send_json_success();
3285 -}
3286 -
3287 -public function mxchat_check_pre_chat_message_status() {
3288 - // Get and sanitize the user identifier
3289 - $user_id = $this->mxchat_get_user_identifier();
3290 - $user_id = sanitize_key($user_id);
3291 -
3292 - // Check if the transient exists (i.e., if the message was dismissed)
3293 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3294 - $dismissed = get_transient($transient_key);
3295 -
3296 - // Log the result to see if it's being set correctly
3297 - //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
3298 -
3299 - if ($dismissed) {
3300 - wp_send_json_success(['dismissed' => true]);
3301 - } else {
3302 - wp_send_json_success(['dismissed' => false]);
3303 - }
3304 -
3305 - wp_die();
3306 -}
3307 -
3308 -private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
3309 - if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
3310 - return 0;
3311 - }
3312 -
3313 - $dotProduct = array_sum(array_map(function ($a, $b) {
3314 - return $a * $b;
3315 - }, $vectorA, $vectorB));
3316 - $normA = sqrt(array_sum(array_map(function ($a) {
3317 - return $a * $a;
3318 - }, $vectorA)));
3319 - $normB = sqrt(array_sum(array_map(function ($b) {
3320 - return $b * $b;
3321 - }, $vectorB)));
3322 -
3323 - if ($normA == 0 || $normB == 0) {
3324 - return 0;
3325 - }
3326 -
3327 - return $dotProduct / ($normA * $normB);
3328 - }
3329 -
3330 -public function mxchat_enqueue_scripts_styles() {
3331 - // Define version numbers for the styles and scripts
3332 - $chat_style_version = '2.0.4'; // Replace with your actual version
3333 - $chat_script_version = '2.0.4'; // Replace with your actual version
3334 -
3335 - // Enqueue the script
3336 - wp_enqueue_script(
3337 - 'mxchat-chat-js',
3338 - plugin_dir_url(__FILE__) . '../js/chat-script.js',
3339 - array('jquery'),
3340 - $chat_script_version,
3341 - true
3342 - );
3343 -
3344 - // Enqueue the CSS
3345 - wp_enqueue_style(
3346 - 'mxchat-chat-css',
3347 - plugin_dir_url(__FILE__) . '../css/chat-style.css',
3348 - array(),
3349 - $chat_style_version
3350 - );
3351 -
3352 - // Fetch options from the database
3353 - $this->options = get_option('mxchat_options');
3354 - $prompts_options = get_option('mxchat_prompts_options', array());
3355 -
3356 - // Prepare settings for JavaScript
3357 - $style_settings = array(
3358 - 'ajax_url' => admin_url('admin-ajax.php'),
3359 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
3360 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
3361 - 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
3362 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
3363 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
3364 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
3365 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
3366 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
3367 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
3368 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
3369 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
3370 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
3371 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
3372 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
3373 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
3374 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
3375 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off', // Example for consistency
3376 -
3377 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
3378 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
3379 - 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
3380 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
3381 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
3382 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
3383 -
3384 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
3385 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
3386 - );
3387 -
3388 - // Pass the settings to the script
3389 - wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
3390 -}
3391 -
3392 -
3393 -public function mxchat_reset_rate_limits() {
3394 - global $wpdb;
3395 -
3396 - // Define a cache key pattern for rate limits
3397 - $cache_key_pattern = 'mxchat_chat_limit_%';
3398 -
3399 - // Retrieve all option names matching the pattern
3400 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
3401 - $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
3402 -
3403 - // db call ok; no-cache ok
3404 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- db call ok
3405 - $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
3406 -
3407 - // Clear the relevant cache entries
3408 - foreach ($option_names as $option_name) {
3409 - wp_cache_delete($option_name, 'options');
3410 - }
3411 -
3412 - // Optionally, clear a general cache if you have one
3413 - wp_cache_delete('mxchat_all_chat_limits', 'options');
3414 - }
3415 -
3416 -private function mxchat_fetch_woocommerce_products() {
3417 - // Ensure WooCommerce is active
3418 - if (!class_exists('WooCommerce')) {
3419 - return [];
3420 - }
3421 -
3422 - $args = array(
3423 - 'post_type' => 'product',
3424 - 'post_status' => 'publish',
3425 - 'posts_per_page' => -1,
3426 - );
3427 -
3428 - $products = get_posts($args);
3429 - $product_data = [];
3430 -
3431 - foreach ($products as $product) {
3432 - $product_id = $product->ID;
3433 - $product_obj = wc_get_product($product_id);
3434 -
3435 - $product_data[] = array(
3436 - 'id' => $product_id,
3437 - 'name' => $product_obj->get_name(),
3438 - 'description' => $product_obj->get_description(),
3439 - 'short_description' => $product_obj->get_short_description(),
3440 - 'url' => get_permalink($product_id),
3441 - 'price' => $product_obj->get_regular_price(),
3442 - 'sale_price' => $product_obj->get_sale_price(),
3443 - 'stock_status' => $product_obj->get_stock_status(),
3444 - 'sku' => $product_obj->get_sku(),
3445 - 'in_stock' => $product_obj->is_in_stock(),
3446 - 'total_sales' => $product_obj->get_total_sales(),
3447 - );
3448 - }
3449 -
3450 - return $product_data;
3451 -}
3452 -
3453 -}
3454 -?>
1 +<?php
2 +if (!defined('ABSPATH')) {
3 + exit;
4 +}
5 +
6 +class MxChat_Integrator {
7 + private $options;
8 + private $prompts_options;
9 + private $chat_count;
10 + private $fallbackResponse;
11 + private $productCardHtml;
12 + private $word_handler;
13 +
14 +public function __construct() {
15 + $this->options = get_option('mxchat_options');
16 + $this->prompts_options = get_option('mxchat_prompts_options', array());
17 +
18 + $this->chat_count = get_option('mxchat_chat_count', 0);
19 + $this->word_handler = new MXChat_Word_Handler($this->options);
20 +
21 + add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
22 + add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
23 + add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
24 +
25 + add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
26 + add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
27 + // Add the AJAX actions for checking if the pre-chat message was dismissed
28 + add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
29 + add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
30 +
31 + add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
32 + add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
33 +
34 + add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
35 + add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
36 +
37 + if (!wp_next_scheduled('mxchat_reset_rate_limits')) {
38 + wp_schedule_event(time(), 'daily', 'mxchat_reset_rate_limits');
39 + }
40 +
41 + // Add REST API routes registration
42 + add_action('rest_api_init', array($this, 'register_routes'));
43 +
44 + add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
45 + add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
46 +
47 + add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
48 +
49 + add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
50 + add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
51 + add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
52 + add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
53 +
54 + // Add these with your other add_action hooks
55 + add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
56 + add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
57 + add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
58 + add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
59 + add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
60 + add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
61 +
62 + add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
63 + add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
64 + add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
65 + add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
66 +}
67 +
68 +
69 + private function mxchat_increment_chat_count() {
70 + $chat_count = get_option('mxchat_chat_count', 0);
71 + $chat_count++;
72 + update_option('mxchat_chat_count', $chat_count);
73 + }
74 +
75 +function mxchat_fetch_conversation_history() {
76 + if (empty($_POST['session_id'])) {
77 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
78 + wp_die();
79 + }
80 +
81 + $session_id = sanitize_text_field($_POST['session_id']);
82 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
83 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
84 +
85 + if (empty($history)) {
86 + // Even if history is empty, return the chat mode
87 + wp_send_json_success([
88 + 'conversation' => [],
89 + 'chat_mode' => $chat_mode
90 + ]);
91 + wp_die();
92 + }
93 +
94 + wp_send_json_success([
95 + 'conversation' => $history,
96 + 'chat_mode' => $chat_mode
97 + ]);
98 + wp_die();
99 +}
100 +private function mxchat_fetch_conversation_history_for_ajax($session_id) {
101 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history based on session ID
102 + $formatted_history = [];
103 +
104 + // Format the history to align with the expected structure for OpenAI
105 + foreach ($history as $entry) {
106 + $formatted_history[] = [
107 + 'role' => $entry['role'], // Ensure this matches 'user' or 'assistant'
108 + 'content' => $entry['content']
109 + ];
110 + }
111 +
112 + return $formatted_history;
113 +}
114 +
115 +
116 +private function mxchat_fetch_conversation_history_for_ai($session_id) {
117 + $history = get_option("mxchat_history_{$session_id}", []);
118 + $formatted_history = [];
119 +
120 + // Adjusted for code-heavy conversations
121 + $max_tokens = 120000; // Context window size
122 + $reserved_tokens = 5000; // Space for system prompts + current query
123 + $current_token_count = 0;
124 +
125 + // Allowed HTML tags for content sanitization
126 + $allowed_tags = [
127 + 'pre' => ['class' => true],
128 + 'code' => ['class' => true],
129 + 'span' => ['class' => true],
130 + 'div' => ['class' => true],
131 + 'strong' => [],
132 + 'em' => []
133 + ];
134 +
135 + foreach (array_reverse($history) as $entry) {
136 + // Preserve code blocks while sanitizing other HTML
137 + $clean_content = wp_kses($entry['content'], $allowed_tags);
138 +
139 + // Detect code blocks in content
140 + $has_code = false;
141 +// Replace the HTML check with:
142 +// Allow messages that contain code blocks or are plain text
143 +if (strpos($clean_content, '<pre') === false &&
144 + strpos($clean_content, '<code') === false &&
145 + $clean_content !== strip_tags($entry['content'])) {
146 + continue;
147 +}
148 +
149 + // Skip entries that lost significant content during sanitization
150 + if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
151 + continue;
152 + }
153 +
154 + // More accurate token estimation (1 token ≈ 4 characters)
155 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
156 +
157 + // Check token budget with the new estimate
158 + if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
159 + // Try to fit partial content if it's the first entry
160 + if (empty($formatted_history)) {
161 + $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
162 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
163 + } else {
164 + break;
165 + }
166 + }
167 +
168 + // Add to formatted history
169 + $formatted_history[] = [
170 + 'role' => $entry['role'],
171 + 'content' => $clean_content
172 + ];
173 +
174 + $current_token_count += $token_estimate;
175 + }
176 +
177 + // Reverse back to maintain chronological order
178 + $formatted_history = array_reverse($formatted_history);
179 +
180 + // Add system message about code context
181 + array_unshift($formatted_history, [
182 + 'role' => 'system',
183 + 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
184 + . 'Maintain formatting and syntax highlighting when referencing code.'
185 + ]);
186 +
187 + return $formatted_history;
188 +}
189 +
190 +public function register_routes() {
191 + //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
192 +
193 + register_rest_route('mxchat/v1', '/stream', [
194 + 'methods' => 'GET',
195 + 'callback' => [$this, 'mxchat_stream_events'],
196 + 'permission_callback' => [$this, 'verify_chat_session'],
197 + ]);
198 +
199 + register_rest_route('mxchat/v1', '/agent-response', [
200 + 'methods' => 'POST',
201 + 'callback' => [$this, 'mxchat_handle_agent_response'],
202 + 'permission_callback' => [$this, 'verify_slack_request'],
203 + ]);
204 +
205 + register_rest_route('mxchat/v1', '/slack-interaction', [
206 + 'methods' => 'POST',
207 + 'callback' => [$this, 'handle_slack_interaction'],
208 + 'permission_callback' => [$this, 'verify_slack_request'],
209 + ]);
210 +
211 + //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
212 +}
213 +
214 +/**
215 + * Verify valid chat session
216 + */
217 +public function verify_chat_session($request) {
218 + $session_id = $request->get_param('session_id');
219 + if (empty($session_id)) {
220 + //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
221 + return false;
222 + }
223 +
224 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
225 + return $chat_mode === 'agent';
226 +}
227 +
228 +/**
229 + * Verify request is coming from Slack.
230 + *
231 + * @param WP_REST_Request $request
232 + * @return bool True if valid, false otherwise.
233 + */
234 +public function verify_slack_request($request) {
235 + // Get the Slack signing secret from your plugin options
236 + $valid_key = $this->options['live_agent_secret_key'] ?? '';
237 +
238 + if (empty($valid_key)) {
239 + //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
240 + return false;
241 + }
242 +
243 + $timestamp = $request->get_header('X-Slack-Request-Timestamp');
244 + $slack_signature = $request->get_header('X-Slack-Signature');
245 +
246 + // Verify timestamp to prevent replay attacks
247 + if (abs(time() - intval($timestamp)) > 300) {
248 + //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
249 + return false;
250 + }
251 +
252 + // Get raw request body
253 + $request_body = file_get_contents('php://input');
254 +
255 + // Create the signature base string
256 + $sig_basestring = "v0:{$timestamp}:{$request_body}";
257 +
258 + // Calculate expected signature
259 + $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
260 +
261 + // Compare signatures
262 + return hash_equals($my_signature, $slack_signature);
263 +}
264 +public function mxchat_stream_events(WP_REST_Request $request) {
265 + header('Content-Type: text/event-stream');
266 + header('Cache-Control: no-cache');
267 + header('Connection: keep-alive');
268 +
269 + $session_id = sanitize_text_field($request->get_param('session_id'));
270 + $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
271 +
272 + if (empty($session_id)) {
273 + echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
274 + flush();
275 + exit;
276 + }
277 +
278 + $history = get_option("mxchat_history_{$session_id}", []);
279 +
280 + // Filter only new messages
281 + $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
282 + return !empty($message['id']) && $message['id'] > $last_seen_id;
283 + });
284 +
285 + // Send new messages if available
286 + if (!empty($new_messages)) {
287 + echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
288 + } else {
289 + // Keep the connection alive
290 + echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
291 + }
292 + flush();
293 + exit;
294 +}
295 +
296 +
297 +
298 +
299 +private function mxchat_save_chat_message($session_id, $role, $message) {
300 + global $wpdb;
301 +
302 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
303 + //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
304 +
305 + // 1) Extract agent name if present
306 + $agent_name = '';
307 + if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
308 + $agent_name = $matches[1];
309 + $message = str_replace("Agent: $agent_name - ", '', $message);
310 +
311 + $session_meta_key = "mxchat_agent_name_{$session_id}";
312 + if (empty(get_option($session_meta_key))) {
313 + update_option($session_meta_key, $agent_name);
314 + //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
315 + }
316 + }
317 +
318 + // 2) Generate unique message_id
319 + $message_id = uniqid();
320 + //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
321 +
322 + // 3) Determine user_id
323 + $user_id = is_user_logged_in() ? get_current_user_id() : 0;
324 +
325 + // 4) Determine user_identifier
326 + $user_identifier = $agent_name
327 + ? $agent_name
328 + : MxChat_User::mxchat_get_user_identifier();
329 +
330 + // 5) Determine displayed_name
331 + $user_email = MxChat_User::mxchat_get_user_email();
332 + $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
333 +
334 + // 6) Check for a saved email in wp_options
335 + $email_option_key = "mxchat_email_{$session_id}";
336 + $saved_email = get_option($email_option_key);
337 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
338 +
339 + // If found, update DB user_email
340 + if ($saved_email) {
341 + $update_res = $wpdb->update(
342 + $table_name,
343 + ['user_email' => $saved_email],
344 + ['session_id' => $session_id],
345 + ['%s'],
346 + ['%s']
347 + );
348 + //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email update for session_id {$session_id}. update_res: {$update_res}");
349 + }
350 +
351 + // 7) Save to session history in wp_options
352 + $history_key = "mxchat_history_{$session_id}";
353 + $history = get_option($history_key, []);
354 + $history[] = [
355 + 'id' => $message_id,
356 + 'role' => $role,
357 + 'content' => $message,
358 + 'timestamp' => round(microtime(true) * 1000),
359 + 'agent_name' => $displayed_name,
360 + ];
361 + update_option($history_key, $history);
362 + //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
363 +
364 + // 8) Save the message to DB (INSERT)
365 + $insert_data = [
366 + 'user_id' => $user_id,
367 + 'user_identifier'=> $user_identifier,
368 + 'user_email' => $saved_email ?: $user_email,
369 + 'session_id' => $session_id,
370 + 'role' => $role,
371 + 'message' => $message,
372 + 'timestamp' => current_time('mysql', 1),
373 + ];
374 + $wpdb->insert($table_name, $insert_data);
375 + //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
376 +
377 + //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
378 + return $message_id;
379 +}
380 +
381 +public function mxchat_handle_save_email_and_response() {
382 + //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
383 +
384 + // Validate nonce
385 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
386 + //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
387 + wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
388 + wp_die();
389 + }
390 +
391 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
392 + $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
393 +
394 + //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}");
395 +
396 + if (empty($session_id) || empty($email)) {
397 + //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
398 + wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
399 + wp_die();
400 + }
401 +
402 + // 1) Always store in wp_options
403 + $option_key = "mxchat_email_{$session_id}";
404 + update_option($option_key, $email);
405 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$option_key} => {$email}");
406 +
407 + // 2) (Optional) Also store in DB if a row already exists
408 + global $wpdb;
409 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
410 +
411 + // Make sure we have a valid placeholder in prepare
412 + $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
413 + $session_count = $wpdb->get_var($sql);
414 +
415 + //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
416 +
417 + if ($session_count) {
418 + // Update user_email if row(s) exist
419 + $update_sql = $wpdb->prepare(
420 + "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
421 + $email,
422 + $session_id
423 + );
424 + $wpdb->query($update_sql);
425 + //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
426 + } else {
427 + //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email is only in wp_options.");
428 + }
429 +
430 + // Provide success response
431 + $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
432 + //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
433 + wp_send_json_success(['message' => $bot_message]);
434 + wp_die();
435 +}
436 +
437 +public function mxchat_check_email_provided() {
438 + //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
439 +
440 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
441 + //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
442 + wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
443 + }
444 +
445 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
446 + if (empty($session_id)) {
447 + //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
448 + wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
449 + }
450 +
451 + // Check if the user is logged in
452 + if (is_user_logged_in()) {
453 + $current_user = wp_get_current_user();
454 + //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
455 + wp_send_json_success(['logged_in' => true, 'email' => $current_user->user_email]);
456 + }
457 +
458 + $option_key = "mxchat_email_{$session_id}";
459 + $stored_email = get_option($option_key, '');
460 +
461 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking option: {$option_key}, found: {$stored_email}");
462 +
463 + if (!empty($stored_email)) {
464 + //error_log("[DEBUG] mxchat_check_email_provided -> Email found, returning success");
465 + wp_send_json_success(['email' => $stored_email]);
466 + } else {
467 + //error_log("[DEBUG] mxchat_check_email_provided -> No email found, returning error");
468 + wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
469 + }
470 +}
471 +
472 +
473 +// First, add this helper function to get the highest rate limit for a user's roles
474 +private function get_user_role_rate_limit($user_id) {
475 + //error_log(esc_html__("Checking rate limit for user ID: ", 'mxchat') . $user_id);
476 +
477 + if (!$user_id) {
478 + //error_log(esc_html__("No user ID provided, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
479 + return $this->options['rate_limit_logged_out'] ?? '10';
480 + }
481 +
482 + $user = get_userdata($user_id);
483 + if (!$user || !$user->roles) {
484 + //error_log(esc_html__("No user data or roles found, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
485 + return $this->options['rate_limit_logged_out'] ?? '10';
486 + }
487 +
488 + //error_log(esc_html__("User roles: ", 'mxchat') . print_r($user->roles, true));
489 + //error_log(esc_html__("Available role rate limits: ", 'mxchat') . print_r($this->options['role_rate_limits'] ?? [], true));
490 +
491 + $max_limit = 0;
492 + foreach ($user->roles as $role) {
493 + //error_log(esc_html__("Checking limit for role: ", 'mxchat') . $role);
494 + if (isset($this->options['role_rate_limits'][$role])) {
495 + $role_limit = $this->options['role_rate_limits'][$role];
496 + //error_log(esc_html__("Found limit for role ", 'mxchat') . $role . esc_html__(": ", 'mxchat') . $role_limit);
497 +
498 + if ($role_limit === 'unlimited') {
499 + //error_log(esc_html__("Returning unlimited for role: ", 'mxchat') . $role);
500 + return 'unlimited';
501 + }
502 +
503 + $max_limit = max($max_limit, (int)$role_limit);
504 + //error_log(esc_html__("Current max limit: ", 'mxchat') . $max_limit);
505 + } else {
506 + //error_log(esc_html__("No limit found for role: ", 'mxchat') . $role);
507 + }
508 + }
509 +
510 + $final_limit = $max_limit > 0 ? (string)$max_limit : '100';
511 + //error_log(esc_html__("Final rate limit: ", 'mxchat') . $final_limit);
512 + return $final_limit;
513 +}
514 +
515 +
516 +// Add this to your plugin's main PHP file
517 +public function mxchat_check_new_messages() {
518 + if (!isset($_POST['session_id']) || !isset($_POST['last_seen_id'])) {
519 + wp_send_json_error(['message' => 'Missing required parameters']);
520 + wp_die();
521 + }
522 +
523 + $session_id = sanitize_text_field($_POST['session_id']);
524 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
525 +
526 + // Get chat history
527 + $history = get_option("mxchat_history_{$session_id}", []);
528 +
529 + if (empty($history)) {
530 + wp_send_json_success([
531 + 'hasNewMessages' => false,
532 + 'new_messages' => []
533 + ]);
534 + wp_die();
535 + }
536 +
537 + // Filter new messages
538 + $new_messages = array_filter($history, function($message) use ($last_seen_id) {
539 + return isset($message['id']) && $message['id'] > $last_seen_id;
540 + });
541 +
542 + // Sort by ID to ensure proper order
543 + usort($new_messages, function($a, $b) {
544 + return $a['id'] <=> $b['id'];
545 + });
546 +
547 + wp_send_json_success([
548 + 'hasNewMessages' => !empty($new_messages),
549 + 'new_messages' => array_values($new_messages),
550 + 'latestMessageId' => end($new_messages)['id'] ?? $last_seen_id
551 + ]);
552 + wp_die();
553 +}
554 +
555 +public function mxchat_handle_chat_request() {
556 + global $wpdb;
557 +
558 +
559 + // Check if MX Chat Moderation is active
560 + if (class_exists('MX_Chat_Moderation')) {
561 + // Get user email and IP
562 + $user_email = '';
563 + $user_ip = $_SERVER['REMOTE_ADDR'];
564 +
565 + // If user is logged in, get their email
566 + if (is_user_logged_in()) {
567 + $current_user = wp_get_current_user();
568 + $user_email = $current_user->user_email;
569 + }
570 +
571 + // Create ban handler instance
572 + $ban_handler = new MX_Chat_Ban_Handler();
573 +
574 + // Check if user is banned by IP
575 + if ($ban_handler->check_ban($user_ip, 'ip')) {
576 + wp_send_json([
577 + 'success' => false,
578 + 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
579 + 'status' => 'banned'
580 + ]);
581 + wp_die();
582 + }
583 +
584 + // If user is logged in, also check email
585 + if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
586 + wp_send_json([
587 + 'success' => false,
588 + 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
589 + 'status' => 'banned'
590 + ]);
591 + wp_die();
592 + }
593 + }
594 +
595 +
596 + // Reset fallback response at the start of each request
597 + $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
598 + $this->productCardHtml = '';
599 +
600 + // Get the actual WordPress user ID if logged in
601 + $is_logged_in = is_user_logged_in();
602 + if ($is_logged_in) {
603 + $user_id = get_current_user_id(); // This will get the actual WordPress user ID
604 + } else {
605 + // For logged-out users, use your existing identifier method
606 + $user_id = $this->mxchat_get_user_identifier();
607 + }
608 +
609 + // Get and sanitize the user identifier
610 + $user_id = sanitize_key($user_id);
611 +
612 + // Determine if user is logged in
613 + $is_logged_in = is_user_logged_in();
614 + //error_log("User logged in status: " . ($is_logged_in ? 'true' : 'false'));
615 +
616 + // Get rate limit based on user status
617 + // Get rate limit based on user status
618 + $rate_limit = $is_logged_in
619 + ? $this->get_user_role_rate_limit($user_id)
620 + : ($this->options['rate_limit_logged_out'] ?? '10');
621 +
622 + //error_log("Selected rate limit: " . $rate_limit);
623 +
624 + // Rest of your code remains the same
625 + // If rate limit is 'unlimited', skip rate limiting checks
626 + if ($rate_limit !== 'unlimited') {
627 + // Convert rate limit to integer
628 + $rate_limit = intval($rate_limit);
629 + // Setup rate limiting
630 + $rate_limit_transient_key = 'mxchat_chat_limit_' . $user_id;
631 + $chat_count = get_transient($rate_limit_transient_key);
632 + if ($chat_count === false) {
633 + // Initialize new counter if none exists
634 + $chat_count = 0;
635 + }
636 + // Check if user has exceeded their rate limit
637 + if ($chat_count >= $rate_limit) {
638 + // Get custom rate limit message or use default
639 + $rate_limit_message = isset($this->options['rate_limit_message'])
640 + ? $this->options['rate_limit_message']
641 + : esc_html__('Rate limit exceeded. Please try again later.', 'mxchat');
642 + // Replace placeholder if it exists in the message
643 + $rate_limit_message = str_replace(
644 + array('{limit}', '{count}', '{remaining}'),
645 + array($rate_limit, $chat_count, max(0, $rate_limit - $chat_count)),
646 + $rate_limit_message
647 + );
648 + wp_send_json([
649 + 'success' => false,
650 + 'message' => $rate_limit_message,
651 + 'status' => 'rate_limit_exceeded',
652 + 'limit' => $rate_limit,
653 + 'count' => $chat_count
654 + ]);
655 + wp_die();
656 + }
657 + // Increment the counter
658 + $chat_count++;
659 + // Store the updated count with 24-hour expiration
660 + set_transient($rate_limit_transient_key, $chat_count, DAY_IN_SECONDS);
661 + }
662 +
663 + // Rest of your existing code...
664 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
665 + //error_log("Session ID: $session_id");
666 +
667 + if (empty($session_id)) {
668 + //error_log("Error: Session ID is missing.");
669 + wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
670 + wp_die();
671 + }
672 +
673 + // Validate and sanitize the incoming message
674 + if (empty($_POST['message'])) {
675 + //error_log("Error: No message received.");
676 + wp_send_json_error(esc_html__('No message received.', 'mxchat'));
677 + wp_die();
678 + }
679 +
680 +
681 +// Modify the message sanitization to preserve PHP tags in code blocks
682 +$allowed_tags = [
683 + 'pre' => [],
684 + 'code' => ['class' => true],
685 + 'span' => ['class' => true],
686 + 'div' => ['class' => true],
687 +];
688 +
689 +// First preserve code blocks
690 +$message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
691 + return htmlspecialchars_decode($matches[0]);
692 +}, $_POST['message']);
693 +
694 +// Then apply sanitization
695 +$message = wp_kses($message, $allowed_tags);
696 +
697 +// Decode code blocks
698 +$message = preg_replace_callback('/(&lt;pre&gt;&lt;code.*?&gt;.*?&lt;\/code&gt;&lt;\/pre&gt;)/s', function($matches) {
699 + return htmlspecialchars_decode($matches[1]);
700 +}, $message);
701 +
702 +$message = trim($message);
703 +
704 +// Preserve code blocks from markdown conversion
705 +$message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
706 +
707 +// Check if any add-ons want to pre-process this message (for web search etc.)
708 +$pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
709 +
710 +// If the pre-processing returned a result (not the original message), use it directly
711 +if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
712 + // Save the AI response
713 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
714 +
715 + // Save HTML content if provided
716 + if (!empty($pre_processed_result['html'])) {
717 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
718 + }
719 +
720 + // Return the response
721 + wp_send_json([
722 + 'text' => $pre_processed_result['text'],
723 + 'html' => $pre_processed_result['html'] ?? '',
724 + 'session_id' => $session_id
725 + ]);
726 + wp_die();
727 +}
728 +
729 + // Save the user's message
730 + $this->mxchat_save_chat_message($session_id, 'user', $message);
731 +
732 + // Check if the message is an email address
733 + if (is_email($message)) {
734 + // Add the email to Loops
735 + $this->add_email_to_loops($message);
736 +
737 + // Send success response
738 + $response_message = $this->options['email_capture_response'] ??
739 + esc_html__('Thank you! Your coupon is on the way!', 'mxchat');
740 +
741 + wp_send_json([
742 + 'success' => true,
743 + 'status' => 'email_captured',
744 + 'message' => $response_message
745 + ]);
746 + wp_die();
747 + }
748 +
749 + $intent_info = '';
750 +
751 + // Check chat mode
752 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
753 + //error_log("Chat Mode: $chat_mode");
754 +
755 + // Handle agent mode
756 + if ($chat_mode === 'agent') {
757 + // First, check for switch intent before doing anything else
758 + $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
759 +
760 + // If we matched an intent and it's the switch intent, handle it
761 + if ($intent_matched && !empty($this->fallbackResponse['text'])) {
762 + //error_log("Switch to chatbot intent detected");
763 +
764 + // Update chat mode first
765 + update_option("mxchat_mode_{$session_id}", 'ai');
766 +
767 + // Clear any existing PDF context to start fresh
768 + $this->clear_pdf_transients($session_id);
769 +
770 + // Prepare clean switch response
771 + $response_data = [
772 + 'text' => $this->fallbackResponse['text'],
773 + 'html' => '',
774 + 'session_id' => $session_id,
775 + 'chat_mode' => 'ai'
776 + ];
777 +
778 + // Save the mode switch message
779 + $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
780 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
781 +
782 + // Send response and exit
783 + wp_send_json($response_data);
784 + wp_die();
785 + } elseif (!$intent_matched) {
786 + // No intent matched, handle live agent message
787 + try {
788 + $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
789 + //error_log("Message sent to agent.");
790 +
791 + wp_send_json_success([
792 + 'status' => 'waiting_for_agent',
793 + 'message' => esc_html__('Message sent to live agent.', 'mxchat')
794 + ]);
795 + } catch (\Exception $e) {
796 + //error_log("Error sending message to agent: " . $e->getMessage());
797 + wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
798 + }
799 + wp_die();
800 + }
801 + }
802 +
803 + // Step 1: Check for new PDF URL in the message
804 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
805 + $new_pdf_url = $matches[0];
806 +
807 + // Check if this is likely a PDF-related request
808 + $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
809 + $is_pdf_request = false;
810 +
811 + foreach ($pdf_keywords as $keyword) {
812 + if (stripos($message, $keyword) !== false) {
813 + $is_pdf_request = true;
814 + break;
815 + }
816 + }
817 +
818 + // If it looks like a PDF request or we're waiting for a PDF URL
819 + if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
820 + // Validate HTTPS
821 + if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
822 + // Extract filename from URL
823 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
824 +
825 + // Clear previous PDF transients
826 + $this->clear_pdf_transients($session_id);
827 +
828 + // Process new PDF
829 + $max_pages = $this->options['pdf_max_pages'] ?? 69;
830 + $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
831 +
832 + if ($embeddings === 'too_many_pages') {
833 + $error_text = sprintf(
834 + $this->options['pdf_intent_error_text'] ??
835 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
836 + $max_pages
837 + );
838 + $this->fallbackResponse['text'] = $error_text;
839 + } elseif ($embeddings) {
840 + // Store new PDF information
841 + // Create a more meaningful filename from URL
842 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
843 +
844 + // If the filename is generic (like results_download.php), create a more descriptive one
845 + if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
846 + strpos($pdf_filename, '.php') !== false) {
847 + // Create a timestamp-based name
848 + $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
849 + }
850 +
851 + set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
852 + set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
853 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
854 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
855 +
856 + $success_text = $this->options['pdf_intent_success_text'] ??
857 + esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
858 +
859 + // Return success with filename for UI update
860 + wp_send_json([
861 + 'success' => true,
862 + 'message' => $success_text,
863 + 'data' => [
864 + 'filename' => $pdf_filename
865 + ]
866 + ]);
867 + wp_die();
868 + } else {
869 + $error_text = $this->options['pdf_intent_error_text'] ??
870 + esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
871 + $this->fallbackResponse['text'] = $error_text;
872 + }
873 +
874 + wp_send_json([
875 + 'success' => false,
876 + 'message' => $this->fallbackResponse['text']
877 + ]);
878 + wp_die();
879 + }
880 + }
881 + }
882 +
883 + // Step 2: Detect intent and handle intent-based responses
884 +$intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
885 +//error_log("Intent Result Type: " . gettype($intent_result));
886 +
887 +// Step 3: Handle the intent result appropriately
888 +if ($intent_result !== false) {
889 + // The intent was matched and handled
890 + //error_log("Intent was matched and handled.");
891 +
892 + if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
893 + // Intent returned a direct response array
894 + //error_log("Intent returned a direct response.");
895 + $response_data = [
896 + 'text' => $intent_result['text'] ?? '',
897 + 'html' => $intent_result['html'] ?? '',
898 + 'session_id' => $session_id
899 + ];
900 +
901 + wp_send_json($response_data);
902 + wp_die();
903 + }
904 + else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
905 + // Intent returned true and set fallbackResponse
906 + //error_log("Intent returned true with fallbackResponse set.");
907 + $response_data = [
908 + 'text' => $this->fallbackResponse['text'] ?? '',
909 + 'html' => $this->fallbackResponse['html'] ?? '',
910 + 'session_id' => $session_id
911 + ];
912 +
913 + wp_send_json($response_data);
914 + wp_die();
915 + }
916 +
917 + // Intent was matched but no usable response was provided
918 + // This shouldn't happen with proper intent implementation
919 + //error_log("Warning: Intent matched but no response provided.");
920 +}
921 +
922 + // If we get here, no intent matched OR the intent didn't provide a usable response
923 + //error_log("No matching intent or usable response. Generating AI response.");
924 +
925 + // Step 4: Generate AI response
926 + $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
927 + $this->mxchat_increment_chat_count();
928 +
929 + // Generate embedding for the user's query
930 + $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
931 +
932 + // Check if the embedding generation returned an error
933 + if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
934 + $error_message = $user_message_embedding['error'];
935 + $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
936 +
937 + //error_log("Embedding error for session $session_id: $error_message (Code: $error_code)");
938 +
939 + // Important: Structure the error data correctly for wp_send_json_error
940 + wp_send_json_error([
941 + 'error_message' => $error_message,
942 + 'error_code' => $error_code
943 + ]);
944 + wp_die();
945 + }
946 +
947 + // Check if the embedding is valid
948 + if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
949 + //error_log("Failed to generate message embedding for session $session_id");
950 + wp_send_json_error([
951 + 'error_message' => esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat'),
952 + 'error_code' => 'invalid_embedding'
953 + ]);
954 + wp_die();
955 + }
956 +
957 + // Build context with both knowledge base and PDF content if available
958 + $context_content = "User asked: '{$message}'\n\n";
959 +
960 +
961 + // Get relevant content from knowledge base
962 + $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
963 + if (!empty($relevant_content)) {
964 + $context_content .= "Relevant content from knowledge database:\n" . $relevant_content . "\n\n";
965 + }
966 +
967 +
968 + // Check for and include PDF content
969 + $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
970 + $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
971 + $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
972 + if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
973 + $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
974 + if (!empty($relevant_pdf_pages)) {
975 + $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
976 + foreach ($relevant_pdf_pages as $page_data) {
977 + $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
978 + }
979 + $context_content .= "\n";
980 + }
981 + }
982 +
983 + // Check for and include Word content
984 + $word_url = get_transient('mxchat_word_url_' . $session_id);
985 + $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
986 + $word_filename = get_transient('mxchat_word_filename_' . $session_id);
987 + if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
988 + $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
989 + if (!empty($relevant_word_chunks)) {
990 + $context_content .= "Relevant content from Word document '{$word_filename}':\n";
991 + foreach ($relevant_word_chunks as $chunk_data) {
992 + $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
993 + }
994 + $context_content .= "\n";
995 + }
996 + }
997 +
998 + $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
999 +
1000 + // Generate the response using the full context
1001 + $response = $this->mxchat_generate_response(
1002 + $context_content,
1003 + $this->options['api_key'],
1004 + $this->options['xai_api_key'],
1005 + $this->options['claude_api_key'],
1006 + $this->options['deepseek_api_key'],
1007 + $this->options['gemini_api_key'],
1008 + $conversation_history
1009 + );
1010 +
1011 + // Check if the response is an error array
1012 + if (is_array($response) && isset($response['error'])) {
1013 + //error_log("AI Response Error: " . $response['error'] . " (Code: " . ($response['error_code'] ?? 'unknown') . ")");
1014 +
1015 + // Send a user-friendly error message
1016 + wp_send_json_error([
1017 + 'error_message' => $response['error'],
1018 + 'error_code' => $response['error_code'] ?? 'api_error'
1019 + ]);
1020 + wp_die();
1021 + }
1022 +
1023 + // If we get here, the response is valid text
1024 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
1025 +
1026 + // Step 5: Save additional content if available
1027 + if (!empty($this->productCardHtml)) {
1028 + $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
1029 + }
1030 +
1031 + if (!empty($this->fallbackResponse['html'])) {
1032 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1033 + }
1034 +
1035 + // Step 6: Return the response
1036 + $response_data = [
1037 + 'text' => $response,
1038 + 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
1039 + 'session_id' => $session_id
1040 + ];
1041 +
1042 + wp_send_json($response_data);
1043 + wp_die();
1044 +}
1045 +
1046 +// Updated function to check intents and invoke the callback function
1047 +private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
1048 + global $wpdb;
1049 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1050 +
1051 + //error_log('🔍 MXCHAT DEBUG: Intent Check Started ==================');
1052 + //error_log("🔍 MXCHAT DEBUG: Message: '$message'");
1053 + //error_log("🔍 MXCHAT DEBUG: Chat Mode: $chat_mode");
1054 +
1055 + // Generate the user embedding
1056 + //error_log('🔄 MXCHAT DEBUG: Generating user embedding');
1057 + $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1058 +
1059 + // Check if embedding generation returned an error
1060 + if (is_array($user_embedding) && isset($user_embedding['error'])) {
1061 + $error_message = $user_embedding['error'];
1062 + $error_code = $user_embedding['error_code'] ?? 'embedding_error';
1063 +
1064 + //error_log("❌ MXCHAT DEBUG: Embedding error: $error_message (Code: $error_code)");
1065 +
1066 + // Send the error to the frontend
1067 + wp_send_json_error([
1068 + 'error_message' => $error_message,
1069 + 'error_code' => $error_code
1070 + ]);
1071 + wp_die();
1072 + }
1073 +
1074 + // Check if embedding is valid (not an error and is an array)
1075 + if (!is_array($user_embedding) || empty($user_embedding)) {
1076 + //error_log('❌ MXCHAT DEBUG: Failed to generate user embedding');
1077 +
1078 + // Send a generic error to the frontend
1079 + wp_send_json_error([
1080 + 'error_message' => esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat'),
1081 + 'error_code' => 'invalid_embedding'
1082 + ]);
1083 + wp_die();
1084 + }
1085 +
1086 + //error_log('✅ MXCHAT DEBUG: User embedding generated successfully');
1087 +
1088 + // Fetch intents from the database
1089 + $table_name = $wpdb->prefix . 'mxchat_intents';
1090 + if ($chat_mode === 'agent') {
1091 + //error_log('🔍 MXCHAT DEBUG: Agent mode - fetching only chatbot switch intent');
1092 + $query = $wpdb->prepare(
1093 + "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
1094 + 'mxchat_handle_switch_to_chatbot_intent'
1095 + );
1096 + $intents = $wpdb->get_results($query);
1097 + } else {
1098 + //error_log('🔍 MXCHAT DEBUG: AI mode - fetching all enabled intents');
1099 + // Only fetch enabled intents (either explicitly enabled with 1 or implicitly enabled with NULL for backward compatibility)
1100 + $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
1101 + }
1102 +
1103 + //error_log('🔍 MXCHAT DEBUG: Found ' . count($intents) . ' enabled intents to check');
1104 +
1105 + if (empty($intents)) {
1106 + //error_log('❌ MXCHAT DEBUG: No enabled intents found in database');
1107 + return false;
1108 + }
1109 +
1110 + $highest_similarity = -INF;
1111 + $matched_intent = null;
1112 +
1113 + //error_log('📊 MXCHAT DEBUG: Intent Similarity Scores ==================');
1114 + foreach ($intents as $intent) {
1115 + //error_log("🔄 MXCHAT DEBUG: Checking intent: '{$intent->intent_label}' (callback: {$intent->callback_function})");
1116 +
1117 + // Additional check for enabled state in case database structure was modified
1118 + $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
1119 + if (!$is_enabled) {
1120 + //error_log("⚠️ MXCHAT DEBUG: Skipping disabled intent: {$intent->intent_label}");
1121 + continue;
1122 + }
1123 +
1124 + $intent_embedding_serialized = $intent->embedding_vector;
1125 + $intent_embedding = $intent_embedding_serialized
1126 + ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1127 + : null;
1128 +
1129 + if (!is_array($intent_embedding)) {
1130 + //error_log("❌ MXCHAT DEBUG: Invalid embedding for intent: {$intent->intent_label}");
1131 + continue;
1132 + }
1133 +
1134 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1135 + $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1136 +
1137 + //error_log("📊 MXCHAT DEBUG: Intent '{$intent->intent_label}' similarity: {$similarity}, threshold: {$intent_threshold}");
1138 +
1139 + if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1140 + $highest_similarity = $similarity;
1141 + $matched_intent = $intent;
1142 + //error_log("✅ MXCHAT DEBUG: New best match: '{$intent->intent_label}' with similarity {$similarity}");
1143 + }
1144 + }
1145 + //error_log('📊 MXCHAT DEBUG: End Intent Scores ==================');
1146 +
1147 + if ($matched_intent) {
1148 + //error_log("🎯 MXCHAT DEBUG: Final Intent Match: '{$matched_intent->intent_label}'");
1149 + //error_log("🔄 MXCHAT DEBUG: Invoking callback: {$matched_intent->callback_function}");
1150 +
1151 + // If the callback is a method on this instance (core callback), call it directly
1152 + if (method_exists($this, $matched_intent->callback_function)) {
1153 + //error_log('🔍 MXCHAT DEBUG: Using direct method call for core callback');
1154 + $callback_result = call_user_func(
1155 + [$this, $matched_intent->callback_function],
1156 + $message,
1157 + $user_id,
1158 + $session_id,
1159 + $matched_intent,
1160 + $user_context
1161 + );
1162 + } else {
1163 + //error_log('🔍 MXCHAT DEBUG: Using apply_filters for add-on callback');
1164 + // Otherwise, use apply_filters for add-on callbacks
1165 + $callback_result = apply_filters(
1166 + $matched_intent->callback_function,
1167 + false, // default return value
1168 + $message,
1169 + $user_id,
1170 + $session_id,
1171 + $matched_intent
1172 + );
1173 + }
1174 +
1175 + //error_log('🔍 MXCHAT DEBUG: Callback result type: ' . gettype($callback_result));
1176 + if ($callback_result !== false) {
1177 + //error_log('✅ MXCHAT DEBUG: Intent handled successfully');
1178 + $this->fallbackResponse = $callback_result;
1179 + return true;
1180 + }
1181 + //error_log('❌ MXCHAT DEBUG: Callback returned false');
1182 + } else {
1183 + //error_log('❌ MXCHAT DEBUG: No matching intent found');
1184 + }
1185 +
1186 + //error_log('🔍 MXCHAT DEBUG: Intent Check Completed ==================');
1187 + return false;
1188 +}
1189 +
1190 +
1191 +
1192 +
1193 +// Helper function to clear PDF and Word document related transients
1194 +private function clear_pdf_transients($session_id) {
1195 + // PDF transients
1196 + delete_transient('mxchat_pdf_url_' . $session_id);
1197 + delete_transient('mxchat_pdf_embeddings_' . $session_id);
1198 + delete_transient('mxchat_include_pdf_in_context_' . $session_id);
1199 + delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
1200 +
1201 + // Word document transients
1202 + delete_transient('mxchat_word_url_' . $session_id);
1203 + delete_transient('mxchat_word_filename_' . $session_id);
1204 + delete_transient('mxchat_word_embeddings_' . $session_id);
1205 + delete_transient('mxchat_include_word_in_context_' . $session_id);
1206 + delete_transient('mxchat_waiting_for_word_' . $session_id);
1207 +}
1208 +
1209 +
1210 +
1211 +//verified good
1212 +public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1213 + // Log the message safely
1214 + //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
1215 +
1216 + // Initiate email capture flow
1217 + $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
1218 +
1219 + set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1220 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
1221 +
1222 + // Respond to the user
1223 + wp_send_json(['message' => $response]);
1224 + wp_die();
1225 +}
1226 +
1227 +public function mxchat_generate_image($message, $user_id, $session_id) {
1228 + //error_log("Starting image generation for message: " . $message);
1229 +
1230 + // Prepare a prompt for DALL-E
1231 + $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1232 +
1233 + // Use the existing OpenAI API key
1234 + $openai_api_key = sanitize_text_field($this->options['api_key']);
1235 +
1236 + // Call DALL-E to generate an image
1237 + $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1238 +
1239 + // Check if the response contains an image URL
1240 + if (isset($image_response['imageUrl'])) {
1241 + $image_url = esc_url_raw($image_response['imageUrl']);
1242 +
1243 + // Construct the HTML with a CSS class instead of inline styles
1244 + $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1245 + $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1246 +
1247 + // Save the bot message with both text and HTML
1248 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1249 + $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
1250 +
1251 + // Set the fallback response for the chat handler
1252 + $this->fallbackResponse = [
1253 + 'text' => $response_text,
1254 + 'html' => $response_html,
1255 + 'images' => [$image_url]
1256 + ];
1257 +
1258 + // For debugging/verification - Use json_encode to verify what's being set
1259 + //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
1260 +
1261 + // Return the response directly instead of relying on the property
1262 + return $this->fallbackResponse;
1263 + } else {
1264 + $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1265 +
1266 + // Save the error message
1267 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1268 +
1269 + // Set the fallback response for the chat handler
1270 + $this->fallbackResponse = [
1271 + 'text' => $response_text,
1272 + 'html' => '',
1273 + 'images' => []
1274 + ];
1275 +
1276 + //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1277 + //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
1278 +
1279 + // Return the response directly instead of relying on the property
1280 + return $this->fallbackResponse;
1281 + }
1282 +}
1283 +private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1284 + $api_url = 'https://api.openai.com/v1/images/generations';
1285 + $body = json_encode([
1286 + 'prompt' => sanitize_text_field($prompt),
1287 + 'n' => 1,
1288 + 'size' => '1024x1024',
1289 + 'model' => sanitize_text_field($model),
1290 + ]);
1291 +
1292 + $args = [
1293 + 'body' => $body,
1294 + 'headers' => [
1295 + 'Content-Type' => 'application/json',
1296 + 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1297 + ],
1298 + 'method' => 'POST',
1299 + 'timeout' => absint($timeout),
1300 + ];
1301 +
1302 + $response = wp_remote_post($api_url, $args);
1303 +
1304 + if (is_wp_error($response)) {
1305 + //error_log("DALL-E request failed: " . $response->get_error_message());
1306 + return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1307 + }
1308 +
1309 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
1310 +
1311 + if (isset($response_body['data'][0]['url'])) {
1312 + return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1313 + } else {
1314 + //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1315 + return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1316 + }
1317 +}
1318 +
1319 +/**
1320 + * Handle web search requests.
1321 + *
1322 + * Sends the refined search query to the Brave Search API and uses the
1323 + * results to generate a conversational response with the AI model.
1324 + *
1325 + * @since 1.0.0
1326 + * @param string $message The user's search query.
1327 + * @param string $user_id The user identifier.
1328 + * @param string $session_id The current session ID.
1329 + * @return array Response array containing text with embedded HTML links
1330 + */
1331 +public function mxchat_handle_search_request($message, $user_id, $session_id) {
1332 + // Step 1: Interpret and refine the search query
1333 + $refined_search_query = $this->mxchat_interpret_search_query($message);
1334 + if (empty($refined_search_query)) {
1335 + return array(
1336 + 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
1337 + 'html' => ''
1338 + );
1339 + }
1340 +
1341 + // Retrieve and validate API settings
1342 + $options = get_option('mxchat_options');
1343 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1344 + $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
1345 +
1346 + if (empty($api_key)) {
1347 + return array(
1348 + 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
1349 + 'html' => ''
1350 + );
1351 + }
1352 +
1353 + // Build the API request URL
1354 + $api_url = add_query_arg(
1355 + array(
1356 + 'q' => rawurlencode($refined_search_query),
1357 + 'count' => $results_count,
1358 + 'text_decorations' => 'true',
1359 + 'rich_data' => 'true',
1360 + ),
1361 + 'https://api.search.brave.com/res/v1/web/search'
1362 + );
1363 +
1364 + // Attempt to retrieve cached results first
1365 + $transient_key = 'mxchat_search_' . md5($refined_search_query);
1366 + $results = get_transient($transient_key);
1367 +
1368 + if (false === $results) {
1369 + // Fetch new results from the Brave Search API
1370 + $response = wp_remote_get(
1371 + $api_url,
1372 + array(
1373 + 'headers' => array(
1374 + 'Accept' => 'application/json',
1375 + 'Accept-Encoding' => 'gzip',
1376 + 'X-Subscription-Token'=> $api_key,
1377 + ),
1378 + 'timeout' => 10,
1379 + )
1380 + );
1381 +
1382 + if (is_wp_error($response)) {
1383 + return array(
1384 + 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
1385 + 'html' => ''
1386 + );
1387 + }
1388 +
1389 + $results = json_decode(wp_remote_retrieve_body($response), true);
1390 +
1391 + if (json_last_error() !== JSON_ERROR_NONE) {
1392 + return array(
1393 + 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
1394 + 'html' => ''
1395 + );
1396 + }
1397 +
1398 + // Cache results for one hour
1399 + set_transient($transient_key, $results, HOUR_IN_SECONDS);
1400 + }
1401 +
1402 + // Process results
1403 + if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
1404 + // Create a more straightforward summary with HTML links
1405 + $search_results_text = '';
1406 +
1407 + // Add a simple intro
1408 + $search_results_text .= sprintf(
1409 + esc_html__("Here's what I found about '%s':", 'mxchat'),
1410 + esc_html($refined_search_query)
1411 + );
1412 +
1413 + // Add the top results with HTML links
1414 + foreach (array_slice($results['web']['results'], 0, 5) as $result) {
1415 + $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
1416 + $url = isset($result['url']) ? esc_url($result['url']) : '';
1417 + $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
1418 +
1419 + // Add a line break after the intro
1420 + $search_results_text .= '<br><br>';
1421 +
1422 + // Add title as a link
1423 + $search_results_text .= sprintf(
1424 + '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
1425 + $url,
1426 + $title
1427 + );
1428 +
1429 + // Add a condensed description
1430 + $search_results_text .= sprintf("%s", $description);
1431 + }
1432 +
1433 + // Save to chat history
1434 + $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
1435 +
1436 + // Return the formatted text with embedded HTML links
1437 + return array(
1438 + 'text' => $search_results_text,
1439 + 'html' => ''
1440 + );
1441 + } else {
1442 + return array(
1443 + 'text' => sprintf(
1444 + esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
1445 + esc_html($refined_search_query)
1446 + ),
1447 + 'html' => ''
1448 + );
1449 + }
1450 +}
1451 +/**
1452 + * Format search results into a natural text summary.
1453 + *
1454 + * @since 1.0.0
1455 + * @param array $results The search results from the API.
1456 + * @param string $query The original search query.
1457 + * @return string The text summary of the top results.
1458 + */
1459 +private function format_search_results( $results, $query ) {
1460 + $summary = sprintf(
1461 + esc_html__( 'Here are the most relevant results for "%s":', 'mxchat' ),
1462 + esc_html( $query )
1463 + ) . "\n\n";
1464 +
1465 + $max_results = min( count( $results ), 3 );
1466 + for ( $i = 0; $i < $max_results; $i++ ) {
1467 + $result = $results[ $i ];
1468 + $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1469 + $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1470 +
1471 + // Append title and description to the summary
1472 + $summary .= sprintf(
1473 + "%s\n%s\n\n",
1474 + esc_html( $title ),
1475 + esc_html( $description )
1476 + );
1477 + }
1478 +
1479 + return $summary;
1480 +}
1481 +
1482 +/**
1483 + * Generate HTML markup for search results.
1484 + *
1485 + * @since 1.0.0
1486 + * @param array $results The search results from the API.
1487 + * @param string $query The user-refined query.
1488 + * @return string The HTML markup for displaying the results.
1489 + */
1490 +private function generate_search_results_html( $results, $query ) {
1491 + ob_start();
1492 + ?>
1493 + <div class="mxchat-search-results">
1494 + <?php foreach ( $results as $result ) :
1495 + $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1496 + $url = isset( $result['url'] ) ? esc_url( $result['url'] ) : '#';
1497 + $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1498 + $favicon = isset( $result['meta_url']['favicon'] ) ? esc_url( $result['meta_url']['favicon'] ) : '';
1499 + $thumbnail = isset( $result['thumbnail']['src'] ) ? esc_url( $result['thumbnail']['src'] ) : '';
1500 + $domain = parse_url( $url, PHP_URL_HOST );
1501 + ?>
1502 + <div class="mxchat-search-item">
1503 + <div class="mxchat-search-header">
1504 + <?php if ( $favicon ) : ?>
1505 + <img
1506 + src="<?php echo esc_url( $favicon ); ?>"
1507 + class="mxchat-site-icon"
1508 + alt="<?php echo esc_attr__( 'Site icon', 'mxchat' ); ?>"
1509 + width="16"
1510 + height="16"
1511 + />
1512 + <?php endif; ?>
1513 + <div class="mxchat-site-url"><?php echo esc_html( $domain ); ?></div>
1514 + </div>
1515 +
1516 + <div class="mxchat-search-content">
1517 + <h3 class="mxchat-search-title">
1518 + <a href="<?php echo esc_url( $url ); ?>"
1519 + target="_blank"
1520 + rel="noopener noreferrer"
1521 + >
1522 + <?php echo esc_html( $title ); ?>
1523 + </a>
1524 + </h3>
1525 +
1526 + <?php if ( $thumbnail ) : ?>
1527 + <div class="mxchat-search-thumbnail">
1528 + <img
1529 + src="<?php echo esc_url( $thumbnail ); ?>"
1530 + alt="<?php echo esc_attr__( 'Thumbnail image', 'mxchat' ); ?>"
1531 + loading="lazy"
1532 + />
1533 + </div>
1534 + <?php endif; ?>
1535 +
1536 + <div class="mxchat-search-description">
1537 + <?php echo esc_html( $description ); ?>
1538 + </div>
1539 + </div>
1540 + </div>
1541 + <?php endforeach; ?>
1542 + </div>
1543 + <?php
1544 + return ob_get_clean();
1545 +}
1546 +
1547 +
1548 +//very good
1549 +public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
1550 +
1551 + // Step 1: Interpret the search query for better results
1552 + $refined_search_query = $this->mxchat_interpret_search_query($message);
1553 +
1554 +
1555 + // If no query was interpreted, return a fallback message
1556 + if (empty($refined_search_query)) {
1557 + $this->fallbackResponse = [
1558 + 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
1559 + 'html' => "",
1560 + ];
1561 + return;
1562 + }
1563 +
1564 + // Brave API URL
1565 + $api_url = 'https://api.search.brave.com/res/v1/images/search';
1566 +
1567 + // Retrieve Brave API settings
1568 + $options = get_option('mxchat_options');
1569 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1570 +
1571 + if (empty($api_key)) {
1572 +/*
1573 + if (defined('WP_DEBUG') && WP_DEBUG) {
1574 + //error_log("Brave API key is missing.");
1575 + }
1576 +*/
1577 +
1578 + $this->fallbackResponse = [
1579 + 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
1580 + 'html' => "",
1581 + ];
1582 + return;
1583 + }
1584 +
1585 + $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
1586 + $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
1587 +
1588 + // Append query parameters based on settings
1589 + $api_url = add_query_arg([
1590 + 'q' => rawurlencode($refined_search_query),
1591 + 'count' => $image_count,
1592 + 'safesearch' => $safe_search,
1593 + ], $api_url);
1594 +
1595 +/*
1596 + // Log the final API URL for the search
1597 + if (defined('WP_DEBUG') && WP_DEBUG) {
1598 + //error_log("Final API URL for Brave Image Search: " . esc_url_raw($api_url));
1599 + }
1600 +*/
1601 +
1602 +
1603 + // Implement caching
1604 + $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
1605 + $body = get_transient($transient_key);
1606 +
1607 + if (false === $body) {
1608 + $args = [
1609 + 'headers' => [
1610 + 'Accept' => 'application/json',
1611 + 'Accept-Encoding' => 'gzip',
1612 + 'X-Subscription-Token' => $api_key,
1613 + ],
1614 + 'timeout' => 10,
1615 + ];
1616 +
1617 + $response = wp_remote_get($api_url, $args);
1618 +
1619 + if (is_wp_error($response)) {
1620 +/*
1621 + if (defined('WP_DEBUG') && WP_DEBUG) {
1622 + //error_log("Brave Image API request failed: " . $response->get_error_message());
1623 + }
1624 +*/
1625 +
1626 + $this->fallbackResponse = [
1627 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1628 + 'html' => "",
1629 + ];
1630 + return;
1631 + }
1632 +
1633 + $body = json_decode(wp_remote_retrieve_body($response), true);
1634 + set_transient($transient_key, $body, HOUR_IN_SECONDS);
1635 + }
1636 +
1637 + // Process the API response
1638 + if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
1639 + $html_output = '<div class="mxchat-image-gallery">';
1640 +
1641 + foreach ($body['results'] as $image) {
1642 + $image_url = isset($image['url']) ? esc_url($image['url']) : '';
1643 + $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
1644 + $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
1645 +
1646 + if ($image_url && $thumbnail_url) {
1647 + $html_output .= '<div class="mxchat-image-item">';
1648 + $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
1649 + $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
1650 + $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
1651 + $html_output .= '</a></div>';
1652 + }
1653 + }
1654 +
1655 + $html_output .= '</div>';
1656 +
1657 + $this->fallbackResponse = [
1658 + 'text' => "",
1659 + 'html' => $html_output,
1660 + ];
1661 +
1662 + // Save response in chat history
1663 + $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
1664 +
1665 + } else {
1666 +/*
1667 + if (defined('WP_DEBUG') && WP_DEBUG) {
1668 + //error_log("Brave Image API response did not contain expected data structure or was empty: " . print_r($body, true));
1669 + }
1670 +*/
1671 +
1672 + $this->fallbackResponse = [
1673 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1674 + 'html' => "",
1675 + ];
1676 + }
1677 +}
1678 +public function mxchat_interpret_search_query($user_query) {
1679 + $system_prompt = esc_html__("Interpret the user's request to provide only the essential keywords or phrases for image searching. Remove conversational language, politeness, or extra context. Return a concise search query that doesn't lose any of the original meaning.", 'mxchat');
1680 +
1681 + // Retrieve OpenAI API key using 'api_key' as the option key
1682 + $api_key = isset($this->options['api_key']) ? sanitize_text_field($this->options['api_key']) : sanitize_text_field(get_option('mxchat_options')['api_key']);
1683 +
1684 + /*
1685 + // Log the API key check, without exposing the key
1686 + if (defined('WP_DEBUG') && WP_DEBUG) {
1687 + //error_log("Retrieved OpenAI API Key: " . ($api_key ? "Present" : "Missing"));
1688 + }
1689 + */
1690 +
1691 + if (empty($api_key)) {
1692 + //error_log("OpenAI API key is missing.");
1693 + return sanitize_text_field($user_query); // Default to the original query if API key is missing
1694 + }
1695 +
1696 + $url = 'https://api.openai.com/v1/chat/completions';
1697 + $args = [
1698 + 'headers' => [
1699 + 'Authorization' => 'Bearer ' . $api_key,
1700 + 'Content-Type' => 'application/json',
1701 + ],
1702 + 'body' => wp_json_encode([
1703 + 'model' => 'gpt-3.5-turbo',
1704 + 'messages' => [
1705 + ['role' => 'system', 'content' => $system_prompt],
1706 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
1707 + ],
1708 + 'temperature' => 0.2,
1709 + 'max_tokens' => 20,
1710 + ]),
1711 + 'method' => 'POST',
1712 + ];
1713 +
1714 + $response = wp_remote_post($url, $args);
1715 +
1716 + if (is_wp_error($response)) {
1717 + //error_log("OpenAI request failed: " . $response->get_error_message());
1718 + return sanitize_text_field($user_query); // Fallback to the original query if there's an error
1719 + }
1720 +
1721 + $body = json_decode(wp_remote_retrieve_body($response), true);
1722 +
1723 + // Check for a valid response and sanitize output
1724 + if (isset($body['choices'][0]['message']['content'])) {
1725 + $interpreted_query = sanitize_text_field(trim($body['choices'][0]['message']['content']));
1726 +
1727 + /*
1728 + // Log the interpreted query for debugging
1729 + if (defined('WP_DEBUG') && WP_DEBUG) {
1730 + //error_log("Interpreted search query: " . $interpreted_query);
1731 + }
1732 + */
1733 +
1734 + return $interpreted_query;
1735 + } else {
1736 + //error_log("Unexpected API response format: " . print_r($body, true));
1737 + return sanitize_text_field($user_query);
1738 + }
1739 +}
1740 +
1741 +
1742 +
1743 +private function find_product_in_message($message) {
1744 + global $wpdb;
1745 +
1746 + // Get embedding for the search query
1747 + $query_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1748 +
1749 + // Check if embedding generation returned an error
1750 + if (is_array($query_embedding) && isset($query_embedding['error'])) {
1751 + $error_message = $query_embedding['error'];
1752 + $error_code = $query_embedding['error_code'] ?? 'embedding_error';
1753 +
1754 + //error_log("Product search embedding error: $error_message (Code: $error_code)");
1755 +
1756 + // Set a user-friendly fallback response
1757 + $this->fallbackResponse['text'] = esc_html__("I'm having trouble processing your product search. Please try again later or contact support if this persists.", 'mxchat');
1758 +
1759 + // Also store the technical error for admin users
1760 + $this->fallbackResponse['admin_error'] = $error_message;
1761 + $this->fallbackResponse['error_code'] = $error_code;
1762 +
1763 + return null;
1764 + }
1765 +
1766 + // Check if embedding is valid
1767 + if (!is_array($query_embedding) || empty($query_embedding)) {
1768 + //error_log("Failed to generate embedding for product search");
1769 + $this->fallbackResponse['text'] = esc_html__("I couldn't process your product search. Please try again with different wording.", 'mxchat');
1770 + return null;
1771 + }
1772 +
1773 + // Get relevant content as string
1774 + $relevant_content = $this->mxchat_find_relevant_products($query_embedding);
1775 + if (empty($relevant_content)) {
1776 + // Return null to indicate no results and set fallback response
1777 + $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Could you please be more specific about the product you're looking for?", 'mxchat');
1778 + return null;
1779 + }
1780 +
1781 +
1782 + // Extract product URLs from the content
1783 + preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
1784 +
1785 + if (!empty($matches[0])) {
1786 + // Try each URL found
1787 + foreach ($matches[0] as $url) {
1788 + // Clean the URL
1789 + $url = rtrim($url, '/."\']');
1790 +
1791 + // Get the product slug
1792 + $path = parse_url($url, PHP_URL_PATH);
1793 + $slug = basename(rtrim($path, '/'));
1794 +
1795 + // Find product by slug
1796 + $args = array(
1797 + 'post_type' => 'product',
1798 + 'post_status' => 'publish',
1799 + 'name' => $slug,
1800 + 'posts_per_page' => 1
1801 + );
1802 +
1803 + $products = get_posts($args);
1804 +
1805 + if (!empty($products)) {
1806 + $product_id = $products[0]->ID;
1807 + $product = wc_get_product($product_id);
1808 +
1809 + if ($product && $product->is_purchasable()) {
1810 + return $product_id;
1811 + }
1812 + }
1813 + }
1814 + }
1815 +
1816 + // Fallback: Look for product names in the content
1817 + $products = wc_get_products([
1818 + 'status' => 'publish',
1819 + 'limit' => -1,
1820 + 'return' => 'all'
1821 + ]);
1822 +
1823 + foreach ($products as $product) {
1824 + $name = $product->get_name();
1825 + if (stripos($relevant_content, $name) !== false) {
1826 + if ($product->is_purchasable()) {
1827 + return $product->get_id();
1828 + }
1829 + }
1830 + }
1831 +
1832 + // If no product is found after all checks, set the fallback response
1833 + $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Try to be more specific", 'mxchat');
1834 + return null;
1835 +}
1836 +
1837 +// New method to handle intent responses
1838 +private function generate_intent_response($context_content, $session_id) {
1839 + // Convert the context array to a structured string for the AI
1840 + $context_string = $this->format_intent_context($context_content);
1841 + // Generate AI response using the context
1842 + $response = $this->mxchat_generate_response(
1843 + $context_string,
1844 + $this->options['api_key'],
1845 + $this->options['xai_api_key'],
1846 + $this->options['claude_api_key'],
1847 + $this->options['deepseek_api_key'],
1848 + $this->options['gemini_api_key'], // Added Gemini API key
1849 + $this->mxchat_fetch_conversation_history_for_ai($session_id)
1850 + );
1851 + $this->fallbackResponse['text'] = $response;
1852 + return true;
1853 +}
1854 +
1855 +// Helper method to format intent context
1856 +private function format_intent_context($context) {
1857 + $context_string = esc_html__("INTENT CONTEXT:\n", 'mxchat');
1858 +
1859 + switch ($context['intent']) {
1860 + case 'add_to_cart':
1861 + if ($context['status'] === 'success') {
1862 + $context_string .= esc_html__("Action: Successfully added product to cart\n", 'mxchat');
1863 + $context_string .= sprintf(esc_html__("Product: %s\n", 'mxchat'), $context['product']['name']);
1864 + $context_string .= esc_html__("Available actions: ", 'mxchat') . implode(', ', $context['available_actions']) . "\n";
1865 + $context_string .= sprintf(esc_html__("Cart URL: %s\n", 'mxchat'), $context['cart_url']);
1866 + $context_string .= esc_html__("\nPlease inform the user of the successful addition and their available options.", 'mxchat');
1867 + } else {
1868 + $context_string .= esc_html__("Action: Failed to add product to cart\n", 'mxchat');
1869 + $context_string .= sprintf(esc_html__("Reason: %s\n", 'mxchat'), $context['reason']);
1870 + switch ($context['reason']) {
1871 + case 'woocommerce_not_available':
1872 + $context_string .= esc_html__("\nPlease inform the user that shopping features are not available.", 'mxchat');
1873 + break;
1874 + case 'no_product_context':
1875 + $context_string .= esc_html__("\nPlease ask the user to specify which product they want to add.", 'mxchat');
1876 + break;
1877 + case 'product_not_found':
1878 + $context_string .= esc_html__("\nPlease inform the user that the product couldn't be found and ask them to try again.", 'mxchat');
1879 + break;
1880 + case 'add_to_cart_failed':
1881 + $context_string .= esc_html__("\nPlease apologize to the user and suggest they try again or ask for assistance.", 'mxchat');
1882 + break;
1883 + }
1884 + }
1885 + break;
1886 + }
1887 +
1888 + return $context_string;
1889 +}
1890 +
1891 +
1892 +//very good
1893 +private function add_email_to_loops($email) {
1894 + // Sanitize the email
1895 + $email = sanitize_email($email);
1896 +
1897 + // Retrieve and sanitize options
1898 + $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
1899 + $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
1900 +
1901 + // Check for missing API key or mailing list ID
1902 + if (empty($api_key) || empty($mailing_list_id)) {
1903 + //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
1904 + return;
1905 + }
1906 +
1907 + $data = array(
1908 + 'email' => $email,
1909 + 'subscribed' => true,
1910 + 'source' => __('MxChat AI Chatbot', 'mxchat'),
1911 + 'mailingLists' => array($mailing_list_id => true),
1912 + );
1913 +
1914 + $url = 'https://app.loops.so/api/v1/contacts/create';
1915 + $args = array(
1916 + 'body' => wp_json_encode($data),
1917 + 'headers' => array(
1918 + 'Authorization' => 'Bearer ' . $api_key,
1919 + 'Content-Type' => 'application/json',
1920 + ),
1921 + 'method' => 'POST',
1922 + 'timeout' => 45,
1923 + );
1924 +
1925 + $response = wp_remote_post($url, $args);
1926 +
1927 + // Handle errors in the API request
1928 + if (is_wp_error($response)) {
1929 + //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
1930 + return;
1931 + }
1932 +
1933 + // Check for non-200 HTTP responses
1934 + $response_code = wp_remote_retrieve_response_code($response);
1935 + if ($response_code != 200) {
1936 + $response_body = wp_remote_retrieve_body($response);
1937 + //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
1938 + }
1939 +}
1940 +
1941 +public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
1942 + // Get the maximum number of pages allowed from admin settings
1943 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1944 +
1945 + // Retrieve options for dynamic texts
1946 + $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
1947 + $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
1948 + $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1949 +
1950 + // Check for explicit request for new PDF
1951 + $new_pdf_requested = stripos($message, 'new') !== false ||
1952 + stripos($message, 'another') !== false ||
1953 + stripos($message, 'different') !== false;
1954 +
1955 + // If user mentions adding/reading a PDF, set waiting flag
1956 + if (stripos($message, 'pdf') !== false ||
1957 + stripos($message, 'document') !== false ||
1958 + stripos($message, 'read') !== false) {
1959 + set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
1960 + $this->fallbackResponse['text'] = $trigger_text;
1961 + return;
1962 + }
1963 +
1964 + // If we're waiting for a URL or user requested new PDF
1965 + if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1966 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1967 + // Process URL... (rest of your existing URL processing code)
1968 + } else {
1969 + $this->fallbackResponse['text'] = $trigger_text;
1970 + }
1971 + return;
1972 + }
1973 +
1974 + // Default to proceeding with conversation if no specific PDF action is needed
1975 + $this->fallbackResponse['text'] = '';
1976 +}
1977 +
1978 +
1979 +private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
1980 + $upload_dir = wp_upload_dir();
1981 + $temp_file = null;
1982 +
1983 + try {
1984 + // Handle URL vs local file
1985 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1986 + // Validate and download the file from URL
1987 + $temp_file = wp_tempnam($pdf_source); // Safe temporary file name
1988 + $response = wp_remote_get($pdf_source, ['timeout' => 60]);
1989 +
1990 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1991 + //error_log(esc_html__("Failed to download PDF. Error: ", 'mxchat') . print_r($response, true));
1992 + return false;
1993 + }
1994 +
1995 + file_put_contents($temp_file, wp_remote_retrieve_body($response));
1996 +
1997 + // Validate that the downloaded file is a PDF
1998 + $mime_type = mime_content_type($temp_file);
1999 + if ($mime_type !== 'application/pdf') {
2000 + //error_log(esc_html__("Invalid MIME type detected for PDF: ", 'mxchat') . $mime_type);
2001 + unlink($temp_file);
2002 + return false;
2003 + }
2004 + } else {
2005 + // For local files, use the provided path directly
2006 + $temp_file = $pdf_source;
2007 + }
2008 +
2009 + // Parse and process the PDF
2010 + $parser = new \Smalot\PdfParser\Parser();
2011 + $pdf = $parser->parseFile($temp_file);
2012 + $pages = $pdf->getPages();
2013 +
2014 + if (count($pages) > $max_pages) {
2015 + //error_log(esc_html__("PDF exceeds the maximum allowed pages: ", 'mxchat') . count($pages));
2016 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
2017 + unlink($temp_file);
2018 + }
2019 + return esc_html__('too_many_pages', 'mxchat');
2020 + }
2021 +
2022 + $embeddings = [];
2023 + foreach ($pages as $page_number => $page) {
2024 + $text = $page->getText();
2025 +
2026 + // Ensure text is non-empty before generating embeddings
2027 + if (empty(trim($text))) {
2028 + //error_log(esc_html__("Skipping empty page: ", 'mxchat') . ($page_number + 1));
2029 + continue;
2030 + }
2031 +
2032 + $embedding = $this->mxchat_generate_embedding(
2033 + esc_html__("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
2034 + $this->options['api_key']
2035 + );
2036 +
2037 + if ($embedding) {
2038 + $embeddings[] = [
2039 + 'page_number' => $page_number + 1,
2040 + 'embedding' => $embedding,
2041 + 'text' => $text,
2042 + ];
2043 + } else {
2044 + //error_log(esc_html__("Failed to generate embedding for page ", 'mxchat') . ($page_number + 1));
2045 + }
2046 + }
2047 +
2048 + // Clean up downloaded file if it was from URL
2049 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
2050 + unlink($temp_file);
2051 + }
2052 +
2053 + return $embeddings;
2054 +
2055 + } catch (\Exception $e) {
2056 + // //error_log(esc_html__("Error parsing or processing PDF: ", 'mxchat') . $e->getMessage());
2057 +
2058 + // Cleanup in case of exception
2059 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2060 + unlink($temp_file);
2061 + }
2062 +
2063 + return false;
2064 + }
2065 +}
2066 +private function find_relevant_pdf_pages($query_embedding, $embeddings) {
2067 + //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
2068 +
2069 + $most_relevant = null;
2070 + $highest_similarity = -INF;
2071 +
2072 + foreach ($embeddings as $page_data) {
2073 + $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
2074 +
2075 + if ($similarity > $highest_similarity) {
2076 + $highest_similarity = $similarity;
2077 + $most_relevant = $page_data['page_number'];
2078 + }
2079 + }
2080 +
2081 + if (!is_null($most_relevant)) {
2082 + $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
2083 + return array_filter($embeddings, function ($page) use ($page_numbers) {
2084 + return in_array($page['page_number'], $page_numbers);
2085 + });
2086 + }
2087 +
2088 + return [];
2089 +}
2090 +// Add this to your class
2091 +public function handle_pdf_upload() {
2092 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2093 +
2094 + if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
2095 + wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
2096 + return;
2097 + }
2098 +
2099 + $file = $_FILES['pdf_file'];
2100 + $session_id = sanitize_text_field($_POST['session_id']);
2101 + $original_filename = sanitize_text_field($file['name']);
2102 +
2103 + $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
2104 + if ($file_type['type'] !== 'application/pdf') {
2105 + wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
2106 + return;
2107 + }
2108 +
2109 + $upload_dir = wp_upload_dir();
2110 + $pdf_filename = 'mxchat_' . $session_id . '_' . time() . '.pdf';
2111 + $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
2112 +
2113 + if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
2114 + wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
2115 + return;
2116 + }
2117 +
2118 + $this->clear_pdf_transients($session_id);
2119 +
2120 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2121 + $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
2122 +
2123 + if ($embeddings === 'too_many_pages') {
2124 + unlink($pdf_path);
2125 + $error_message = sprintf(
2126 + $this->options['pdf_intent_error_text'] ??
2127 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
2128 + $max_pages
2129 + );
2130 + wp_send_json_error($error_message);
2131 + return;
2132 + }
2133 +
2134 + if ($embeddings === false || empty($embeddings)) {
2135 + unlink($pdf_path);
2136 + $error_message = $this->options['pdf_intent_error_text'] ??
2137 + esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
2138 + wp_send_json_error($error_message);
2139 + return;
2140 + }
2141 +
2142 + if (!empty($embeddings)) {
2143 + set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
2144 + set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
2145 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
2146 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
2147 +
2148 + $success_message = $this->options['pdf_intent_success_text'] ??
2149 + esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
2150 +
2151 + wp_send_json_success([
2152 + 'message' => $success_message,
2153 + 'filename' => $original_filename
2154 + ]);
2155 + return;
2156 + }
2157 +
2158 + unlink($pdf_path);
2159 + $error_message = $this->options['pdf_intent_error_text'] ??
2160 + esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
2161 + wp_send_json_error($error_message);
2162 + return;
2163 +}
2164 +public function handle_pdf_remove() {
2165 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2166 +
2167 + if (empty($_POST['session_id'])) {
2168 + wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
2169 + wp_die();
2170 + }
2171 +
2172 + $session_id = sanitize_text_field($_POST['session_id']);
2173 + $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
2174 +
2175 + if ($pdf_path && file_exists($pdf_path)) {
2176 + unlink($pdf_path);
2177 + }
2178 +
2179 + $this->clear_pdf_transients($session_id);
2180 +
2181 + wp_send_json_success([
2182 + 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2183 + ]);
2184 + wp_die();
2185 +}
2186 +
2187 +
2188 +
2189 +
2190 +function mxchat_fetch_new_messages() {
2191 + $session_id = sanitize_text_field($_POST['session_id']);
2192 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2193 + $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2194 + $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2195 +
2196 + if (empty($session_id)) {
2197 + //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2198 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2199 + wp_die();
2200 + }
2201 +
2202 + $history = get_option("mxchat_history_{$session_id}", []);
2203 +
2204 + $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2205 + // If persistence is enabled, show all new messages
2206 + if ($persistence_enabled) {
2207 + return !empty($message['id']) &&
2208 + strcmp($message['id'], $last_seen_id) > 0 &&
2209 + $message['role'] === 'agent';
2210 + }
2211 +
2212 + // If persistence is disabled, only show messages after initial timestamp
2213 + return !empty($message['id']) &&
2214 + $message['role'] === 'agent' &&
2215 + $message['timestamp'] > $initial_timestamp;
2216 + });
2217 +
2218 + //error_log(esc_html__("New agent messages fetched for session $session_id. Last seen ID: $last_seen_id", 'mxchat'));
2219 +
2220 + wp_send_json_success([
2221 + 'new_messages' => array_values($new_messages)
2222 + ]);
2223 + wp_die();
2224 +}
2225 +
2226 +
2227 +public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2228 + // First check if live agents are available
2229 + $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2230 + if ($live_agent_available !== 'on') {
2231 + $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2232 + $this->fallbackResponse = [
2233 + 'text' => $away_message,
2234 + 'html' => '',
2235 + 'images' => [],
2236 + 'chat_mode' => 'ai'
2237 + ];
2238 + wp_send_json([
2239 + 'text' => $away_message,
2240 + 'html' => '',
2241 + 'chat_mode' => 'ai',
2242 + 'session_id' => $session_id
2243 + ]);
2244 + wp_die();
2245 + }
2246 +
2247 + $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2248 + if (empty($slack_webhook_url)) {
2249 + return false;
2250 + }
2251 +
2252 + // Get recent chat history (last 5 messages)
2253 + $history = get_option("mxchat_history_{$session_id}", []);
2254 + $recent_history = array_slice($history, -5); // Get last 5 messages
2255 +
2256 + // Format conversation history
2257 + $conversation_context = "";
2258 + if (!empty($recent_history)) {
2259 + $conversation_context = "*Recent Conversation:*\n";
2260 + foreach ($recent_history as $hist_message) {
2261 + $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
2262 + $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
2263 + }
2264 + $conversation_context .= "\n";
2265 + }
2266 +
2267 + update_option("mxchat_mode_{$session_id}", 'agent');
2268 +
2269 + $webhook_data = [
2270 + 'blocks' => [
2271 + [
2272 + 'type' => 'header',
2273 + 'text' => [
2274 + 'type' => 'plain_text',
2275 + 'text' => '🔔 New Live Agent Request',
2276 + 'emoji' => true
2277 + ]
2278 + ],
2279 + [
2280 + 'type' => 'section',
2281 + 'fields' => [
2282 + [
2283 + 'type' => 'mrkdwn',
2284 + 'text' => sprintf('*User ID:*\n`%s`', $user_id)
2285 + ],
2286 + [
2287 + 'type' => 'mrkdwn',
2288 + 'text' => sprintf('*Session ID:*\n`%s`', $session_id)
2289 + ]
2290 + ]
2291 + ]
2292 + ]
2293 + ];
2294 +
2295 + // Add conversation history if exists
2296 + if (!empty($conversation_context)) {
2297 + $webhook_data['blocks'][] = [
2298 + 'type' => 'section',
2299 + 'text' => [
2300 + 'type' => 'mrkdwn',
2301 + 'text' => $conversation_context
2302 + ]
2303 + ];
2304 + }
2305 +
2306 + // Add the current message
2307 + $webhook_data['blocks'][] = [
2308 + 'type' => 'section',
2309 + 'text' => [
2310 + 'type' => 'mrkdwn',
2311 + 'text' => sprintf('*Current Message:*\n%s', $message)
2312 + ]
2313 + ];
2314 +
2315 + // Add the reply button
2316 + $webhook_data['blocks'][] = [
2317 + 'type' => 'actions',
2318 + 'elements' => [
2319 + [
2320 + 'type' => 'button',
2321 + 'text' => [
2322 + 'type' => 'plain_text',
2323 + 'text' => '✍️ Reply',
2324 + 'emoji' => true
2325 + ],
2326 + 'value' => $session_id,
2327 + 'action_id' => 'reply_to_user',
2328 + 'style' => 'primary'
2329 + ]
2330 + ]
2331 + ];
2332 +
2333 + $response = wp_remote_post($slack_webhook_url, [
2334 + 'body' => json_encode($webhook_data),
2335 + 'headers' => [
2336 + 'Content-Type' => 'application/json',
2337 + ],
2338 + ]);
2339 +
2340 + if (is_wp_error($response)) {
2341 + return false;
2342 + }
2343 +
2344 + $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
2345 + $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
2346 +
2347 + $this->fallbackResponse = [
2348 + 'text' => $success_message,
2349 + 'html' => '',
2350 + 'images' => [],
2351 + 'chat_mode' => 'agent'
2352 + ];
2353 +
2354 + wp_send_json([
2355 + 'success' => true,
2356 + 'text' => $success_message,
2357 + 'html' => '',
2358 + 'chat_mode' => 'agent',
2359 + 'session_id' => $session_id,
2360 + 'fallbackResponse' => $this->fallbackResponse
2361 + ]);
2362 + wp_die();
2363 +}
2364 +public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
2365 + $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2366 +
2367 + if (empty($slack_webhook_url)) {
2368 + //error_log(esc_html__('Slack Webhook URL is not configured.', 'mxchat'));
2369 + return false;
2370 + }
2371 +
2372 + $webhook_data = [
2373 + 'blocks' => [
2374 + [
2375 + 'type' => 'header',
2376 + 'text' => [
2377 + 'type' => 'plain_text',
2378 + 'text' => esc_html__('📩 New Chat Message', 'mxchat'),
2379 + 'emoji' => true
2380 + ]
2381 + ],
2382 + [
2383 + 'type' => 'section',
2384 + 'fields' => [
2385 + [
2386 + 'type' => 'mrkdwn',
2387 + 'text' => sprintf(esc_html__('*User ID:*\n`%s`', 'mxchat'), $user_id)
2388 + ],
2389 + [
2390 + 'type' => 'mrkdwn',
2391 + 'text' => sprintf(esc_html__('*Session ID:*\n`%s`', 'mxchat'), $session_id)
2392 + ]
2393 + ]
2394 + ],
2395 + [
2396 + 'type' => 'section',
2397 + 'text' => [
2398 + 'type' => 'mrkdwn',
2399 + 'text' => sprintf(esc_html__('*Message:*\n%s', 'mxchat'), $message)
2400 + ]
2401 + ],
2402 + [
2403 + 'type' => 'actions',
2404 + 'elements' => [
2405 + [
2406 + 'type' => 'button',
2407 + 'text' => [
2408 + 'type' => 'plain_text',
2409 + 'text' => esc_html__('✍️ Reply', 'mxchat'),
2410 + 'emoji' => true
2411 + ],
2412 + 'value' => $session_id,
2413 + 'action_id' => 'reply_to_user',
2414 + 'style' => 'primary'
2415 + ]
2416 + ]
2417 + ]
2418 + ]
2419 + ];
2420 +
2421 + $response = wp_remote_post($slack_webhook_url, [
2422 + 'body' => json_encode($webhook_data),
2423 + 'headers' => [
2424 + 'Content-Type' => 'application/json',
2425 + ],
2426 + ]);
2427 +
2428 + if (is_wp_error($response)) {
2429 + //error_log(esc_html__('Error sending message to Slack: ', 'mxchat') . $response->get_error_message());
2430 + return false;
2431 + }
2432 +
2433 + //error_log(esc_html__('Message sent to Slack successfully.', 'mxchat'));
2434 + return true;
2435 +}
2436 +public function handle_slack_interaction(WP_REST_Request $request) {
2437 + //error_log('Received Slack interaction');
2438 +
2439 + $payload = json_decode($request->get_param('payload'), true);
2440 + //error_log('Payload: ' . print_r($payload, true));
2441 +
2442 + // Handle button click
2443 + if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
2444 + $session_id = $payload['actions'][0]['value'];
2445 + $trigger_id = $payload['trigger_id'];
2446 +
2447 + // Get Bot Token from settings
2448 + $slack_token = $this->options['live_agent_bot_token'] ?? '';
2449 +
2450 + if (empty($slack_token)) {
2451 + //error_log('Slack Bot Token not configured');
2452 + return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
2453 + }
2454 + $response = wp_remote_post('https://slack.com/api/views.open', [
2455 + 'headers' => [
2456 + 'Content-Type' => 'application/json',
2457 + 'Authorization' => 'Bearer ' . $slack_token
2458 + ],
2459 + 'body' => json_encode([
2460 + 'trigger_id' => $trigger_id,
2461 + 'view' => [
2462 + 'type' => 'modal',
2463 + 'callback_id' => 'reply_modal',
2464 + 'title' => [
2465 + 'type' => 'plain_text',
2466 + 'text' => __('Reply to User', 'mxchat')
2467 + ],
2468 + 'submit' => [
2469 + 'type' => 'plain_text',
2470 + 'text' => __('Send', 'mxchat')
2471 + ],
2472 + 'close' => [
2473 + 'type' => 'plain_text',
2474 + 'text' => __('Cancel', 'mxchat')
2475 + ],
2476 + 'blocks' => [
2477 + [
2478 + 'type' => 'input',
2479 + 'block_id' => 'reply_block',
2480 + 'label' => [
2481 + 'type' => 'plain_text',
2482 + 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
2483 + ],
2484 + 'element' => [
2485 + 'type' => 'plain_text_input',
2486 + 'action_id' => 'message',
2487 + 'multiline' => true,
2488 + 'placeholder' => [
2489 + 'type' => 'plain_text',
2490 + 'text' => __('Type your message here...', 'mxchat')
2491 + ]
2492 + ]
2493 + ]
2494 + ],
2495 + 'private_metadata' => $session_id
2496 + ]
2497 + ])
2498 + ]);
2499 +
2500 + //error_log('Views.open response: ' . print_r($response, true));
2501 +
2502 + // Return immediate acknowledgment
2503 + return new WP_REST_Response(['ok' => true]);
2504 + }
2505 +
2506 + // Handle modal submission
2507 +// Handle modal submission
2508 +if ($payload['type'] === 'view_submission') {
2509 + $session_id = $payload['view']['private_metadata'];
2510 + $message = $payload['view']['state']['values']['reply_block']['message']['value'];
2511 +
2512 + // Save the message (keep the message_id but don't include in response)
2513 + $this->mxchat_save_chat_message($session_id, 'agent', $message);
2514 +
2515 + // Keep the original response format for Slack
2516 + return new WP_REST_Response([
2517 + 'response_action' => 'clear'
2518 + ]);
2519 +}
2520 +
2521 + // Default acknowledgment
2522 + return new WP_REST_Response(['ok' => true]);
2523 +}
2524 +
2525 +public function mxchat_handle_agent_response(WP_REST_Request $request) {
2526 + //error_log('Received agent response request');
2527 + //error_log('Request data: ' . print_r($request->get_params(), true));
2528 + // //error_log('Raw body: ' . file_get_contents('php://input'));
2529 +
2530 + // Get the data from Slack's slash command format
2531 + $command_text = $request->get_param('text');
2532 + // //error_log('Command text: ' . $command_text);
2533 +
2534 + if (empty($command_text)) {
2535 + //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
2536 + return new WP_REST_Response([
2537 + 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
2538 + ], 400);
2539 + }
2540 +
2541 + // Split the command text into session_id and message
2542 + $parts = explode(' ', $command_text, 2);
2543 + if (count($parts) !== 2) {
2544 + //error_log('Agent response error: Invalid command format');
2545 + return new WP_REST_Response([
2546 + 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
2547 + ], 400);
2548 + }
2549 +
2550 + $session_id = sanitize_text_field($parts[0]);
2551 + $message = sanitize_text_field($parts[1]);
2552 +
2553 + //error_log("Processing agent response - Session ID: $session_id, Message: $message");
2554 +
2555 + // Save the message
2556 + $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
2557 +
2558 + if (!$message_id) {
2559 + // //error_log('Failed to save agent message');
2560 + return new WP_REST_Response([
2561 + 'error' => esc_html__('Failed to save message', 'mxchat')
2562 + ], 500);
2563 + }
2564 +
2565 + // Return success response in Slack's expected format
2566 + return new WP_REST_Response([
2567 + 'response_type' => 'in_channel',
2568 + 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
2569 + ], 200);
2570 +}
2571 +
2572 +
2573 +public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
2574 + //error_log(esc_html__("Switching back to chatbot mode via intent.", 'mxchat'));
2575 +
2576 + // Just update mode to AI
2577 + update_option("mxchat_mode_{$session_id}", 'ai');
2578 +
2579 + // Initialize states
2580 + $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
2581 + $this->productCardHtml = '';
2582 +
2583 + // Set the response message
2584 + $this->fallbackResponse['text'] = esc_html__('You are now chatting with the AI chatbot.', 'mxchat');
2585 +
2586 + return true; // Intent was handled
2587 +}
2588 +
2589 +
2590 +
2591 +
2592 +// For the word upload handler
2593 +public function mxchat_handle_word_upload() {
2594 + // Delegate to word handler
2595 + $this->word_handler->mxchat_handle_word_upload();
2596 +}
2597 +
2598 +// For the word removal handler
2599 +public function mxchat_handle_word_remove() {
2600 + // Delegate to word handler
2601 + $this->word_handler->mxchat_handle_word_remove();
2602 +}
2603 +
2604 +// For the word status check
2605 +public function mxchat_check_word_status() {
2606 + // Delegate to word handler
2607 + $this->word_handler->mxchat_check_word_status();
2608 +}
2609 +
2610 +
2611 +private function mxchat_get_user_identifier() {
2612 + return MxChat_User::mxchat_get_user_identifier();
2613 +}
2614 +
2615 +private function mxchat_generate_embedding($text, $api_key) {
2616 + try {
2617 + // Get options and selected model
2618 + $options = get_option('mxchat_options');
2619 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
2620 +
2621 + // Determine endpoint and API key based on model
2622 + if (strpos($selected_model, 'voyage') === 0) {
2623 + $endpoint = 'https://api.voyageai.com/v1/embeddings';
2624 + $api_key = $options['voyage_api_key'] ?? '';
2625 +
2626 + // Check if Voyage API key is missing
2627 + if (empty($api_key)) {
2628 + //error_log('Voyage API key is missing');
2629 + return [
2630 + 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
2631 + 'error_code' => 'missing_voyage_api_key'
2632 + ];
2633 + }
2634 + } else {
2635 + $endpoint = 'https://api.openai.com/v1/embeddings';
2636 + // Use the passed API key for OpenAI
2637 +
2638 + // Check if OpenAI API key is missing
2639 + if (empty($api_key)) {
2640 + //error_log('OpenAI API key is missing');
2641 + return [
2642 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
2643 + 'error_code' => 'missing_openai_api_key'
2644 + ];
2645 + }
2646 + }
2647 +
2648 + // Check if text is empty
2649 + if (empty($text)) {
2650 + //error_log('Empty text provided for embedding generation');
2651 + return [
2652 + 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
2653 + 'error_code' => 'empty_embedding_text'
2654 + ];
2655 + }
2656 +
2657 + // Prepare request body with conditional output_dimension
2658 + $request_body = [
2659 + 'input' => $text,
2660 + 'model' => $selected_model
2661 + ];
2662 +
2663 + // Add output_dimension for voyage-3-large
2664 + if ($selected_model === 'voyage-3-large') {
2665 + $request_body['output_dimension'] = 2048;
2666 + }
2667 +
2668 + // Prepare request arguments
2669 + $args = [
2670 + 'body' => wp_json_encode($request_body),
2671 + 'headers' => [
2672 + 'Content-Type' => 'application/json',
2673 + 'Authorization' => 'Bearer ' . $api_key,
2674 + ],
2675 + 'timeout' => 60,
2676 + 'redirection' => 5,
2677 + 'blocking' => true,
2678 + 'httpversion' => '1.0',
2679 + 'sslverify' => true,
2680 + ];
2681 +
2682 + // Make the request
2683 + $response = wp_remote_post($endpoint, $args);
2684 +
2685 + // Handle WordPress errors
2686 + if (is_wp_error($response)) {
2687 + $error_message = $response->get_error_message();
2688 + //error_log('Embedding Generation Error: ' . $error_message);
2689 + return [
2690 + 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($error_message),
2691 + 'error_code' => 'embedding_connection_error'
2692 + ];
2693 + }
2694 +
2695 + // Check HTTP status code
2696 + $status_code = wp_remote_retrieve_response_code($response);
2697 + if ($status_code !== 200) {
2698 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
2699 +
2700 + $error_message = isset($response_body['error']['message'])
2701 + ? $response_body['error']['message']
2702 + : 'HTTP Error ' . $status_code;
2703 +
2704 + $error_type = isset($response_body['error']['type'])
2705 + ? $response_body['error']['type']
2706 + : 'unknown';
2707 +
2708 + //error_log('Embedding API HTTP Error: ' . $status_code . ' - ' . $error_message);
2709 +
2710 + // Handle specific error types
2711 + switch ($error_type) {
2712 + case 'invalid_request_error':
2713 + if (strpos($error_message, 'API key') !== false) {
2714 + return [
2715 + 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
2716 + 'error_code' => 'embedding_invalid_api_key'
2717 + ];
2718 + }
2719 + break;
2720 +
2721 + case 'authentication_error':
2722 + return [
2723 + 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
2724 + 'error_code' => 'embedding_auth_error'
2725 + ];
2726 +
2727 + case 'rate_limit_exceeded':
2728 + return [
2729 + 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
2730 + 'error_code' => 'embedding_rate_limit'
2731 + ];
2732 +
2733 + case 'quota_exceeded':
2734 + return [
2735 + 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
2736 + 'error_code' => 'embedding_quota_exceeded'
2737 + ];
2738 + }
2739 +
2740 + // Generic error fallback
2741 + return [
2742 + 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($error_message),
2743 + 'error_code' => 'embedding_api_error',
2744 + 'status_code' => $status_code
2745 + ];
2746 + }
2747 +
2748 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
2749 +
2750 + if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
2751 + return $response_body['data'][0]['embedding'];
2752 + } else {
2753 + //error_log('Invalid embedding response: ' . wp_json_encode($response_body));
2754 + return [
2755 + 'error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'),
2756 + 'error_code' => 'invalid_embedding_response'
2757 + ];
2758 + }
2759 + } catch (Exception $e) {
2760 + //error_log('Embedding Exception: ' . $e->getMessage());
2761 + return [
2762 + 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
2763 + 'error_code' => 'embedding_exception'
2764 + ];
2765 + }
2766 +}
2767 +
2768 +
2769 +private function mxchat_find_relevant_content($user_embedding) {
2770 + //error_log('MXChat Vector Search: Starting content search...');
2771 +
2772 + // Retrieve the add-on settings from the database.
2773 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
2774 +
2775 + // Determine whether Pinecone is enabled.
2776 + // We expect the sanitized setting to be a string '1' if enabled, otherwise '0'.
2777 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2778 +
2779 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
2780 +
2781 + if ($use_pinecone === 1) {
2782 + //error_log('MXChat Vector Search: Using Pinecone database');
2783 + return $this->find_relevant_content_pinecone($user_embedding);
2784 + } else {
2785 + //error_log('MXChat Vector Search: Using WordPress database');
2786 + return $this->find_relevant_content_wordpress($user_embedding);
2787 + }
2788 +}
2789 +
2790 +
2791 +private function find_relevant_content_wordpress($user_embedding) {
2792 + global $wpdb;
2793 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2794 + $cache_key = 'mxchat_system_prompt_embeddings';
2795 + $batch_size = 500;
2796 +
2797 + // Log start of matching process
2798 + //error_log('[MXCHAT] Starting similarity matching process');
2799 +
2800 + // Retrieve embeddings from cache or database
2801 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2802 + if ($embeddings === false) {
2803 + //error_log('[MXCHAT] Cache miss - loading embeddings from database');
2804 + $embeddings = [];
2805 + $offset = 0;
2806 +
2807 + // Load in batches and build cache
2808 + do {
2809 + $query = $wpdb->prepare(
2810 + "SELECT id, embedding_vector
2811 + FROM {$system_prompt_table}
2812 + LIMIT %d OFFSET %d",
2813 + $batch_size,
2814 + $offset
2815 + );
2816 +
2817 + $batch = $wpdb->get_results($query);
2818 + if (empty($batch)) {
2819 + break;
2820 + }
2821 +
2822 + $embeddings = array_merge($embeddings, $batch);
2823 + $offset += $batch_size;
2824 +
2825 + // Free memory
2826 + unset($batch);
2827 +
2828 + } while (true);
2829 +
2830 + if (empty($embeddings)) {
2831 + //error_log('[MXCHAT] No embeddings found in database');
2832 + return ''; // Return an empty string if no embeddings found
2833 + }
2834 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2835 + //error_log('[MXCHAT] Cached ' . count($embeddings) . ' embeddings');
2836 + } else {
2837 + //error_log('[MXCHAT] Using ' . count($embeddings) . ' cached embeddings');
2838 + }
2839 +
2840 + // Initialize array to store relevant results with similarity scores
2841 + $relevant_results = [];
2842 +
2843 + // Get the similarity threshold from the main options array only
2844 + $main_options = get_option('mxchat_options', []);
2845 + $similarity_threshold = isset($main_options['similarity_threshold'])
2846 + ? ((int) $main_options['similarity_threshold']) / 100
2847 + : 0.8; // Default to 80%
2848 +
2849 + //error_log('[MXCHAT] Using similarity threshold: ' . ($similarity_threshold * 100) . '%');
2850 +
2851 + // Iterate through embeddings to calculate similarity
2852 + foreach ($embeddings as $embedding) {
2853 + $database_embedding = $embedding->embedding_vector
2854 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2855 + : null;
2856 + if (is_array($database_embedding) && is_array($user_embedding)) {
2857 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2858 +
2859 + // Log each similarity score over 0.5 to reduce log spam
2860 + if ($similarity > 0.1) {
2861 + //error_log(sprintf('[MXCHAT] ID: %d | Similarity Score: %.4f', $embedding->id, $similarity));
2862 + }
2863 +
2864 + $relevant_results[] = [
2865 + 'id' => $embedding->id,
2866 + 'similarity' => $similarity
2867 + ];
2868 + }
2869 + // Free memory
2870 + unset($database_embedding);
2871 + }
2872 +
2873 + // Filter and sort relevant results by similarity
2874 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2875 + return $result['similarity'] >= $similarity_threshold;
2876 + });
2877 + usort($relevant_results, function ($a, $b) {
2878 + return $b['similarity'] <=> $a['similarity'];
2879 + });
2880 +
2881 + // Log number of results that met threshold
2882 + //error_log('[MXCHAT] ' . count($relevant_results) . ' results met the similarity threshold');
2883 +
2884 + // Limit to the top 5 results
2885 + $top_results = array_slice($relevant_results, 0, 5);
2886 +
2887 + // Log the top matches
2888 + //error_log('[MXCHAT] Top matching results:');
2889 + foreach ($top_results as $index => $result) {
2890 +
2891 + }
2892 +
2893 + // Initialize the final content
2894 + $content = '';
2895 +
2896 + // Fetch and combine content for the top results
2897 + foreach ($top_results as $result) {
2898 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
2899 + // Check if the content is PDF-related and add surrounding pages
2900 + if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
2901 + //error_log('[MXCHAT] ID ' . $result['id'] . ' is PDF content, adding surrounding pages');
2902 + $surrounding_content = $wpdb->get_results($wpdb->prepare(
2903 + "SELECT id, article_content FROM {$system_prompt_table}
2904 + WHERE id IN (
2905 + (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
2906 + (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
2907 + )",
2908 + $result['id'],
2909 + $result['id']
2910 + ));
2911 + // Add previous content if it exists
2912 + if (!empty($surrounding_content[0])) {
2913 + $content .= $surrounding_content[0]->article_content . "\n\n";
2914 + }
2915 + // Add the main chunk content
2916 + $content .= $chunk_content . "\n\n";
2917 + // Add next content if it exists
2918 + if (!empty($surrounding_content[1])) {
2919 + $content .= $surrounding_content[1]->article_content . "\n\n";
2920 + }
2921 + } else {
2922 + // For non-PDF content, add directly
2923 + $content .= $chunk_content . "\n\n";
2924 + }
2925 + }
2926 +
2927 + // Log content length
2928 + //error_log('[MXCHAT] Retrieved content length: ' . strlen(trim($content)) . ' characters');
2929 +
2930 + return trim($content);
2931 +}
2932 +
2933 +
2934 +private function find_relevant_content_pinecone($user_embedding) {
2935 + $options = get_option('mxchat_pinecone_addon_options', array());
2936 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2937 + $host = $options['mxchat_pinecone_host'] ?? '';
2938 +
2939 + if (empty($host) || empty($api_key)) {
2940 + //error_log('[MXCHAT Debug] Pinecone credentials not properly configured');
2941 + return '';
2942 + }
2943 +
2944 + // Get the similarity threshold from the main options array only
2945 + $main_options = get_option('mxchat_options', []);
2946 + $similarity_threshold = isset($main_options['similarity_threshold'])
2947 + ? ((int) $main_options['similarity_threshold']) / 100
2948 + : 0.8; // Default to 80%
2949 +
2950 + //error_log('[MXCHAT Debug] Using similarity threshold: ' . ($similarity_threshold * 100) . '%');
2951 +
2952 + // Prepare the query request for Pinecone
2953 + $api_endpoint = "https://{$host}/query";
2954 +
2955 + //error_log('[MXCHAT Debug] Querying Pinecone at: ' . $api_endpoint);
2956 +
2957 + $request_body = array(
2958 + 'vector' => $user_embedding,
2959 + 'topK' => 5,
2960 + 'includeMetadata' => true,
2961 + 'includeValues' => true
2962 + );
2963 +
2964 + $response = wp_remote_post($api_endpoint, array(
2965 + 'headers' => array(
2966 + 'Api-Key' => $api_key,
2967 + 'accept' => 'application/json',
2968 + 'content-type' => 'application/json'
2969 + ),
2970 + 'body' => wp_json_encode($request_body),
2971 + 'timeout' => 30
2972 + ));
2973 +
2974 + if (is_wp_error($response)) {
2975 + //error_log('[MXCHAT Debug] Pinecone query error: ' . $response->get_error_message());
2976 + return '';
2977 + }
2978 +
2979 + $response_code = wp_remote_retrieve_response_code($response);
2980 + if ($response_code !== 200) {
2981 + //error_log('[MXCHAT Debug] Pinecone API error: ' . wp_remote_retrieve_body($response));
2982 + return '';
2983 + }
2984 +
2985 + $results = json_decode(wp_remote_retrieve_body($response), true);
2986 + if (empty($results['matches'])) {
2987 + //error_log('[MXCHAT Debug] No matches found in Pinecone response');
2988 + return '';
2989 + }
2990 +
2991 + //error_log('[MXCHAT Debug] Found ' . count($results['matches']) . ' matches in Pinecone');
2992 +
2993 + // Initialize the final content
2994 + $content = '';
2995 + $matches_above_threshold = 0;
2996 +
2997 + // Process each match
2998 + foreach ($results['matches'] as $index => $match) {
2999 + // Log score for each match
3000 +
3001 + // Skip if similarity is below threshold
3002 + if ($match['score'] < $similarity_threshold) {
3003 + continue;
3004 + }
3005 +
3006 + $matches_above_threshold++;
3007 +
3008 + if (!empty($match['metadata']['text']) && !empty($match['metadata']['source_url'])) {
3009 + // Add content with citation
3010 + $content .= $match['metadata']['text'] . "\n";
3011 + $content .= "Source: " . $match['metadata']['source_url'] . "\n\n";
3012 + }
3013 + }
3014 +
3015 + //error_log('[MXCHAT Debug] Total matches used (above threshold): ' . $matches_above_threshold);
3016 + //error_log('[MXCHAT Debug] Content length returned: ' . strlen(trim($content)) . ' characters');
3017 +
3018 + return trim($content);
3019 +}
3020 +
3021 +private function mxchat_find_relevant_products($user_embedding) {
3022 + //error_log('MXChat Vector Search: Starting product search...');
3023 +
3024 + // Retrieve the add-on settings from the database
3025 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
3026 +
3027 + // Determine whether Pinecone is enabled
3028 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
3029 +
3030 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
3031 +
3032 + if ($use_pinecone === 1) {
3033 + //error_log('MXChat Vector Search: Using Pinecone database for products');
3034 + return $this->find_relevant_products_pinecone($user_embedding);
3035 + } else {
3036 + //error_log('MXChat Vector Search: Using WordPress database for products');
3037 + return $this->find_relevant_products_wordpress($user_embedding);
3038 + }
3039 +}
3040 +
3041 +private function find_relevant_products_wordpress($user_embedding) {
3042 + global $wpdb;
3043 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3044 + $cache_key = 'mxchat_system_prompt_embeddings';
3045 + $batch_size = 500;
3046 +
3047 + // Original WordPress database search logic
3048 + // [Previous implementation remains the same]
3049 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
3050 + if ($embeddings === false) {
3051 + $embeddings = [];
3052 + $offset = 0;
3053 +
3054 + do {
3055 + $query = $wpdb->prepare(
3056 + "SELECT id, embedding_vector
3057 + FROM {$system_prompt_table}
3058 + LIMIT %d OFFSET %d",
3059 + $batch_size,
3060 + $offset
3061 + );
3062 +
3063 + $batch = $wpdb->get_results($query);
3064 + if (empty($batch)) {
3065 + break;
3066 + }
3067 +
3068 + $embeddings = array_merge($embeddings, $batch);
3069 + $offset += $batch_size;
3070 +
3071 + unset($batch);
3072 +
3073 + } while (true);
3074 +
3075 + if (empty($embeddings)) {
3076 + return '';
3077 + }
3078 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
3079 + }
3080 +
3081 + $relevant_results = [];
3082 + foreach ($embeddings as $embedding) {
3083 + $database_embedding = $embedding->embedding_vector
3084 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
3085 + : null;
3086 + if (is_array($database_embedding) && is_array($user_embedding)) {
3087 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
3088 + $relevant_results[] = [
3089 + 'id' => $embedding->id,
3090 + 'similarity' => $similarity
3091 + ];
3092 + }
3093 + unset($database_embedding);
3094 + }
3095 +
3096 + // Use fixed threshold for products
3097 + $similarity_threshold = 0.85;
3098 +
3099 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
3100 + return $result['similarity'] >= $similarity_threshold;
3101 + });
3102 + usort($relevant_results, function ($a, $b) {
3103 + return $b['similarity'] <=> $a['similarity'];
3104 + });
3105 +
3106 + $top_results = array_slice($relevant_results, 0, 5);
3107 + $content = '';
3108 +
3109 + foreach ($top_results as $result) {
3110 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
3111 + $content .= $chunk_content . "\n\n";
3112 + }
3113 +
3114 + return trim($content);
3115 +}
3116 +
3117 +// Modified search function with correct filter syntax
3118 +private function find_relevant_products_pinecone($user_embedding) {
3119 + //error_log('Starting Pinecone product search...');
3120 +
3121 + $options = get_option('mxchat_pinecone_addon_options', array());
3122 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
3123 + $host = $options['mxchat_pinecone_host'] ?? '';
3124 +
3125 + if (empty($host) || empty($api_key)) {
3126 + //error_log('Pinecone credentials not properly configured for product search');
3127 + return '';
3128 + }
3129 +
3130 + $similarity_threshold = 0.85;
3131 + $api_endpoint = "https://{$host}/query";
3132 +
3133 + $request_body = array(
3134 + 'vector' => $user_embedding,
3135 + 'topK' => 5,
3136 + 'includeMetadata' => true,
3137 + 'includeValues' => true,
3138 + 'filter' => array(
3139 + 'type' => 'product'
3140 + )
3141 + );
3142 +
3143 + //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
3144 +
3145 + $response = wp_remote_post($api_endpoint, array(
3146 + 'headers' => array(
3147 + 'Api-Key' => $api_key,
3148 + 'accept' => 'application/json',
3149 + 'content-type' => 'application/json'
3150 + ),
3151 + 'body' => wp_json_encode($request_body),
3152 + 'timeout' => 30
3153 + ));
3154 +
3155 + if (is_wp_error($response)) {
3156 + //error_log('Pinecone product query error: ' . $response->get_error_message());
3157 + return '';
3158 + }
3159 +
3160 + $response_code = wp_remote_retrieve_response_code($response);
3161 + //error_log('Pinecone response code: ' . $response_code);
3162 +
3163 + if ($response_code !== 200) {
3164 + //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
3165 + return '';
3166 + }
3167 +
3168 + $results = json_decode(wp_remote_retrieve_body($response), true);
3169 + //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
3170 +
3171 + if (empty($results['matches'])) {
3172 + //error_log('No matches found in Pinecone response');
3173 + return '';
3174 + }
3175 +
3176 + $content = '';
3177 + foreach ($results['matches'] as $match) {
3178 + if ($match['score'] < $similarity_threshold) {
3179 + //error_log("Match below threshold: " . $match['score']);
3180 + continue;
3181 + }
3182 +
3183 + if (!empty($match['metadata']['text'])) {
3184 + $content .= $match['metadata']['text'];
3185 + if (!empty($match['metadata']['source_url'])) {
3186 + $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
3187 + }
3188 + $content .= "\n\n";
3189 + }
3190 + }
3191 +
3192 + return trim($content);
3193 +}
3194 +
3195 +
3196 +private function fetch_content_with_product_links($most_relevant_id) {
3197 + global $wpdb;
3198 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3199 +
3200 + // Fetch the article content and associated product URL
3201 + $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
3202 + $result = $wpdb->get_row($query);
3203 +
3204 + if ($result) {
3205 + // Append the product link to the content if available
3206 + $content = $result->article_content;
3207 + if (!empty($result->source_url)) {
3208 + $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
3209 + }
3210 + return $content;
3211 + }
3212 +
3213 + return null;
3214 +}
3215 +
3216 +private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $gemini_api_key, $conversation_history) {
3217 + try {
3218 + if (!$relevant_content) {
3219 + return [
3220 + 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
3221 + 'error_code' => 'no_relevant_content'
3222 + ];
3223 + }
3224 +
3225 + // Ensure conversation_history is an array
3226 + if (!is_array($conversation_history)) {
3227 + $conversation_history = array();
3228 + }
3229 +
3230 + // Get selected model with default fallback
3231 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
3232 +
3233 + // Extract model prefix to determine the provider
3234 + $model_parts = explode('-', $selected_model);
3235 + $provider = strtolower($model_parts[0]);
3236 +
3237 + // Handle model selection based on provider prefix
3238 + switch ($provider) {
3239 + case 'gemini':
3240 + if (empty($gemini_api_key)) {
3241 + return [
3242 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
3243 + 'error_code' => 'missing_gemini_api_key'
3244 + ];
3245 + }
3246 + $response = $this->mxchat_generate_response_gemini(
3247 + $selected_model,
3248 + $gemini_api_key,
3249 + $conversation_history,
3250 + $relevant_content
3251 + );
3252 + break;
3253 +
3254 + case 'claude':
3255 + if (empty($claude_api_key)) {
3256 + return [
3257 + 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
3258 + 'error_code' => 'missing_claude_api_key'
3259 + ];
3260 + }
3261 + $response = $this->mxchat_generate_response_claude(
3262 + $selected_model,
3263 + $claude_api_key,
3264 + $conversation_history,
3265 + $relevant_content
3266 + );
3267 + break;
3268 +
3269 + case 'grok':
3270 + if (empty($xai_api_key)) {
3271 + return [
3272 + 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
3273 + 'error_code' => 'missing_xai_api_key'
3274 + ];
3275 + }
3276 + $response = $this->mxchat_generate_response_xai(
3277 + $selected_model,
3278 + $xai_api_key,
3279 + $conversation_history,
3280 + $relevant_content
3281 + );
3282 + break;
3283 +
3284 + case 'deepseek':
3285 + if (empty($deepseek_api_key)) {
3286 + return [
3287 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
3288 + 'error_code' => 'missing_deepseek_api_key'
3289 + ];
3290 + }
3291 + $response = $this->mxchat_generate_response_deepseek(
3292 + $selected_model,
3293 + $deepseek_api_key,
3294 + $conversation_history,
3295 + $relevant_content
3296 + );
3297 + break;
3298 +
3299 + case 'gpt':
3300 + if (empty($api_key)) {
3301 + return [
3302 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3303 + 'error_code' => 'missing_openai_api_key'
3304 + ];
3305 + }
3306 + $response = $this->mxchat_generate_response_openai(
3307 + $selected_model,
3308 + $api_key,
3309 + $conversation_history,
3310 + $relevant_content
3311 + );
3312 + break;
3313 +
3314 + default:
3315 + // Default to OpenAI for custom models or unrecognized prefixes
3316 + if (empty($api_key)) {
3317 + return [
3318 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3319 + 'error_code' => 'missing_openai_api_key'
3320 + ];
3321 + }
3322 + $response = $this->mxchat_generate_response_openai(
3323 + $selected_model,
3324 + $api_key,
3325 + $conversation_history,
3326 + $relevant_content
3327 + );
3328 + break;
3329 + }
3330 +
3331 + // Check if the response is an error array from the provider-specific function
3332 + if (is_array($response) && isset($response['error'])) {
3333 + return $response; // Pass through the error
3334 + }
3335 +
3336 + return $response;
3337 +
3338 + } catch (Exception $e) {
3339 + //error_log('MXChat Error: ' . $e->getMessage());
3340 + return [
3341 + 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
3342 + 'error_code' => 'system_exception',
3343 + 'exception_details' => $e->getMessage()
3344 + ];
3345 + }
3346 +}
3347 +
3348 +private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
3349 + try {
3350 + // Ensure conversation_history is an array
3351 + if (!is_array($conversation_history)) {
3352 + $conversation_history = array();
3353 + }
3354 +
3355 + // Get system prompt instructions from options
3356 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3357 +
3358 + // Create a new array for the formatted conversation
3359 + $formatted_conversation = array();
3360 +
3361 + // Add system message first
3362 + $formatted_conversation[] = array(
3363 + 'role' => 'system',
3364 + 'content' => $system_prompt_instructions . " " . $relevant_content
3365 + );
3366 +
3367 + // Add the rest of the conversation history
3368 + foreach ($conversation_history as $message) {
3369 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3370 + $role = $message['role'];
3371 +
3372 + // Convert roles to supported format
3373 + if ($role === 'bot' || $role === 'agent') {
3374 + $role = 'assistant';
3375 + }
3376 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3377 + $role = 'user';
3378 + }
3379 +
3380 + $formatted_conversation[] = array(
3381 + 'role' => $role,
3382 + 'content' => $message['content']
3383 + );
3384 + }
3385 + }
3386 +
3387 + $body = json_encode([
3388 + 'model' => $selected_model,
3389 + 'messages' => $formatted_conversation,
3390 + 'temperature' => 0.8,
3391 + 'stream' => false
3392 + ]);
3393 +
3394 + $args = [
3395 + 'body' => $body,
3396 + 'headers' => [
3397 + 'Content-Type' => 'application/json',
3398 + 'Authorization' => 'Bearer ' . $deepseek_api_key,
3399 + ],
3400 + 'timeout' => 60,
3401 + 'redirection' => 5,
3402 + 'blocking' => true,
3403 + 'httpversion' => '1.0',
3404 + 'sslverify' => true,
3405 + ];
3406 +
3407 + $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
3408 +
3409 + if (is_wp_error($response)) {
3410 + $error_message = $response->get_error_message();
3411 + //error_log('DeepSeek API Error: ' . $error_message);
3412 + return [
3413 + 'error' => esc_html__('Connection error when contacting DeepSeek: ', 'mxchat') . esc_html($error_message),
3414 + 'error_code' => 'deepseek_connection_error',
3415 + 'provider' => 'deepseek'
3416 + ];
3417 + }
3418 +
3419 + $status_code = wp_remote_retrieve_response_code($response);
3420 + if ($status_code !== 200) {
3421 + $response_body = wp_remote_retrieve_body($response);
3422 + $decoded_response = json_decode($response_body, true);
3423 +
3424 + $error_message = isset($decoded_response['error']['message'])
3425 + ? $decoded_response['error']['message']
3426 + : 'HTTP Error ' . $status_code;
3427 +
3428 + $error_type = isset($decoded_response['error']['type'])
3429 + ? $decoded_response['error']['type']
3430 + : 'unknown';
3431 +
3432 + //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
3433 +
3434 + // Handle specific error types
3435 + switch ($status_code) {
3436 + case 401:
3437 + return [
3438 + 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
3439 + 'error_code' => 'deepseek_auth_error',
3440 + 'provider' => 'deepseek'
3441 + ];
3442 +
3443 + case 400:
3444 + if (strpos($error_message, 'API key') !== false) {
3445 + return [
3446 + 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
3447 + 'error_code' => 'deepseek_invalid_api_key',
3448 + 'provider' => 'deepseek'
3449 + ];
3450 + }
3451 + break;
3452 +
3453 + case 429:
3454 + if (strpos($error_message, 'quota') !== false) {
3455 + return [
3456 + 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
3457 + 'error_code' => 'deepseek_quota_exceeded',
3458 + 'provider' => 'deepseek'
3459 + ];
3460 + } else {
3461 + return [
3462 + 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
3463 + 'error_code' => 'deepseek_rate_limit',
3464 + 'provider' => 'deepseek'
3465 + ];
3466 + }
3467 +
3468 + case 500:
3469 + case 502:
3470 + case 503:
3471 + case 504:
3472 + return [
3473 + 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
3474 + 'error_code' => 'deepseek_service_unavailable',
3475 + 'provider' => 'deepseek'
3476 + ];
3477 + }
3478 +
3479 + // Generic error fallback
3480 + return [
3481 + 'error' => esc_html__('DeepSeek API error: ', 'mxchat') . esc_html($error_message),
3482 + 'error_code' => 'deepseek_api_error',
3483 + 'provider' => 'deepseek',
3484 + 'status_code' => $status_code
3485 + ];
3486 + }
3487 +
3488 + $response_body = wp_remote_retrieve_body($response);
3489 + $decoded_response = json_decode($response_body, true);
3490 +
3491 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3492 + return trim($decoded_response['choices'][0]['message']['content']);
3493 + } else {
3494 + //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
3495 + return [
3496 + 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
3497 + 'error_code' => 'deepseek_response_format_error',
3498 + 'provider' => 'deepseek'
3499 + ];
3500 + }
3501 + } catch (Exception $e) {
3502 + //error_log('DeepSeek Exception: ' . $e->getMessage());
3503 + return [
3504 + 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
3505 + 'error_code' => 'deepseek_exception',
3506 + 'provider' => 'deepseek'
3507 + ];
3508 + }
3509 +}
3510 +
3511 +private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
3512 + try {
3513 + // Ensure conversation_history is an array
3514 + if (!is_array($conversation_history)) {
3515 + $conversation_history = array();
3516 + }
3517 +
3518 + // Get system prompt instructions from options
3519 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3520 +
3521 + // Create a new array for the formatted conversation
3522 + $formatted_conversation = array();
3523 +
3524 + // Add system message first
3525 + $formatted_conversation[] = array(
3526 + 'role' => 'system',
3527 + 'content' => $system_prompt_instructions . " " . $relevant_content
3528 + );
3529 +
3530 + // Add the rest of the conversation history
3531 + foreach ($conversation_history as $message) {
3532 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3533 + $role = $message['role'];
3534 +
3535 + // Convert roles to supported format
3536 + if ($role === 'bot' || $role === 'agent') {
3537 + $role = 'assistant';
3538 + }
3539 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3540 + $role = 'user';
3541 + }
3542 +
3543 + $formatted_conversation[] = array(
3544 + 'role' => $role,
3545 + 'content' => $message['content']
3546 + );
3547 + }
3548 + }
3549 +
3550 + $body = json_encode([
3551 + 'model' => $selected_model,
3552 + 'messages' => $formatted_conversation,
3553 + 'temperature' => 0.8,
3554 + 'stream' => false
3555 + ]);
3556 +
3557 + $args = [
3558 + 'body' => $body,
3559 + 'headers' => [
3560 + 'Content-Type' => 'application/json',
3561 + 'Authorization' => 'Bearer ' . $api_key,
3562 + ],
3563 + 'timeout' => 60,
3564 + 'redirection' => 5,
3565 + 'blocking' => true,
3566 + 'httpversion' => '1.0',
3567 + 'sslverify' => true,
3568 + ];
3569 +
3570 + $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
3571 +
3572 + if (is_wp_error($response)) {
3573 + $error_message = $response->get_error_message();
3574 + //error_log('OpenAI API Error: ' . $error_message);
3575 + return [
3576 + 'error' => esc_html__('Connection error when contacting OpenAI: ', 'mxchat') . esc_html($error_message),
3577 + 'error_code' => 'openai_connection_error',
3578 + 'provider' => 'openai'
3579 + ];
3580 + }
3581 +
3582 + $status_code = wp_remote_retrieve_response_code($response);
3583 + if ($status_code !== 200) {
3584 + $response_body = wp_remote_retrieve_body($response);
3585 + $decoded_response = json_decode($response_body, true);
3586 +
3587 + $error_message = isset($decoded_response['error']['message'])
3588 + ? $decoded_response['error']['message']
3589 + : 'HTTP Error ' . $status_code;
3590 +
3591 + $error_type = isset($decoded_response['error']['type'])
3592 + ? $decoded_response['error']['type']
3593 + : 'unknown';
3594 +
3595 + //error_log('OpenAI API HTTP Error: ' . $status_code . ' - ' . $error_message);
3596 +
3597 + // Handle specific error types
3598 + switch ($error_type) {
3599 + case 'invalid_request_error':
3600 + if (strpos($error_message, 'API key') !== false) {
3601 + return [
3602 + 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
3603 + 'error_code' => 'openai_invalid_api_key',
3604 + 'provider' => 'openai'
3605 + ];
3606 + }
3607 + break;
3608 +
3609 + case 'authentication_error':
3610 + return [
3611 + 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
3612 + 'error_code' => 'openai_auth_error',
3613 + 'provider' => 'openai'
3614 + ];
3615 +
3616 + case 'rate_limit_exceeded':
3617 + return [
3618 + 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
3619 + 'error_code' => 'openai_rate_limit',
3620 + 'provider' => 'openai'
3621 + ];
3622 +
3623 + case 'quota_exceeded':
3624 + return [
3625 + 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
3626 + 'error_code' => 'openai_quota_exceeded',
3627 + 'provider' => 'openai'
3628 + ];
3629 + }
3630 +
3631 + // Generic error fallback
3632 + return [
3633 + 'error' => esc_html__('OpenAI API error: ', 'mxchat') . esc_html($error_message),
3634 + 'error_code' => 'openai_api_error',
3635 + 'provider' => 'openai',
3636 + 'status_code' => $status_code
3637 + ];
3638 + }
3639 +
3640 + $response_body = wp_remote_retrieve_body($response);
3641 + $decoded_response = json_decode($response_body, true);
3642 +
3643 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3644 + return trim($decoded_response['choices'][0]['message']['content']);
3645 + } else {
3646 + //error_log('OpenAI API Response Format Error: ' . print_r($decoded_response, true));
3647 + return [
3648 + 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
3649 + 'error_code' => 'openai_response_format_error',
3650 + 'provider' => 'openai'
3651 + ];
3652 + }
3653 + } catch (Exception $e) {
3654 + //error_log('OpenAI Exception: ' . $e->getMessage());
3655 + return [
3656 + 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
3657 + 'error_code' => 'openai_exception',
3658 + 'provider' => 'openai'
3659 + ];
3660 + }
3661 +}
3662 +private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
3663 + try {
3664 + // Get system prompt instructions from options
3665 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3666 +
3667 + // Add system prompt to relevant content
3668 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3669 +
3670 + // Prepend system instructions to the conversation history
3671 + array_unshift($conversation_history, [
3672 + 'role' => 'system',
3673 + 'content' => "Here are your instructions: " . $content_with_instructions
3674 + ]);
3675 +
3676 + // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
3677 + foreach ($conversation_history as &$message) {
3678 + if ($message['role'] === 'bot') {
3679 + $message['role'] = 'assistant';
3680 + } elseif ($message['role'] === 'agent') {
3681 + // Tag the message as coming from a live agent
3682 + $message['role'] = 'assistant';
3683 + if (!isset($message['metadata'])) {
3684 + $message['metadata'] = ['source' => 'live_agent'];
3685 + }
3686 + }
3687 +
3688 + // Ensure all roles are valid
3689 + if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
3690 + $message['role'] = 'user'; // Default to 'user'
3691 + }
3692 + }
3693 +
3694 + // Build the request body
3695 + $body = json_encode([
3696 + 'model' => $selected_model,
3697 + 'messages' => $conversation_history,
3698 + 'temperature' => 0.8,
3699 + 'stream' => false
3700 + ]);
3701 +
3702 + // Set up the API request
3703 + $args = [
3704 + 'body' => $body,
3705 + 'headers' => [
3706 + 'Content-Type' => 'application/json',
3707 + 'Authorization' => 'Bearer ' . $xai_api_key,
3708 + ],
3709 + 'timeout' => 60,
3710 + 'redirection' => 5,
3711 + 'blocking' => true,
3712 + 'httpversion' => '1.0',
3713 + 'sslverify' => true,
3714 + ];
3715 +
3716 + // Make the API request
3717 + $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
3718 +
3719 + // Process the response
3720 + if (is_wp_error($response)) {
3721 + $error_message = $response->get_error_message();
3722 + //error_log('X.AI API Error: ' . $error_message);
3723 + return [
3724 + 'error' => esc_html__('Connection error when contacting X.AI: ', 'mxchat') . esc_html($error_message),
3725 + 'error_code' => 'xai_connection_error',
3726 + 'provider' => 'xai'
3727 + ];
3728 + }
3729 +
3730 + $status_code = wp_remote_retrieve_response_code($response);
3731 + if ($status_code !== 200) {
3732 + $response_body = wp_remote_retrieve_body($response);
3733 + $decoded_response = json_decode($response_body, true);
3734 +
3735 + // Log the full response for debugging
3736 + //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
3737 +
3738 + // Extract error message from X.AI's specific format
3739 + $error_message = '';
3740 +
3741 + // Check for direct error string (as seen in your logs)
3742 + if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
3743 + $error_message = $decoded_response['error'];
3744 + }
3745 + // Check for nested error object (OpenAI style)
3746 + elseif (isset($decoded_response['error']['message'])) {
3747 + $error_message = $decoded_response['error']['message'];
3748 + }
3749 + // Check for top-level message
3750 + elseif (isset($decoded_response['message'])) {
3751 + $error_message = $decoded_response['message'];
3752 + }
3753 + // Fallback
3754 + else {
3755 + $error_message = 'HTTP Error ' . $status_code;
3756 + }
3757 +
3758 + //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
3759 +
3760 + // Check for API key errors using string matching
3761 + if (stripos($error_message, 'api key') !== false ||
3762 + stripos($error_message, 'incorrect api key') !== false ||
3763 + stripos($error_message, 'invalid api key') !== false) {
3764 + return [
3765 + 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
3766 + 'error_code' => 'xai_invalid_api_key',
3767 + 'provider' => 'xai'
3768 + ];
3769 + }
3770 +
3771 + // Authentication errors
3772 + if ($status_code === 401 || $status_code === 403 ||
3773 + stripos($error_message, 'auth') !== false) {
3774 + return [
3775 + 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat'),
3776 + 'error_code' => 'xai_auth_error',
3777 + 'provider' => 'xai'
3778 + ];
3779 + }
3780 +
3781 + // Model errors
3782 + if (stripos($error_message, 'model') !== false) {
3783 + return [
3784 + 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat'),
3785 + 'error_code' => 'xai_invalid_model',
3786 + 'provider' => 'xai'
3787 + ];
3788 + }
3789 +
3790 + // Rate limit errors
3791 + if ($status_code === 429 ||
3792 + stripos($error_message, 'rate') !== false ||
3793 + stripos($error_message, 'limit') !== false) {
3794 + return [
3795 + 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
3796 + 'error_code' => 'xai_rate_limit',
3797 + 'provider' => 'xai'
3798 + ];
3799 + }
3800 +
3801 + // Quota errors
3802 + if (stripos($error_message, 'quota') !== false ||
3803 + stripos($error_message, 'billing') !== false) {
3804 + return [
3805 + 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
3806 + 'error_code' => 'xai_quota_exceeded',
3807 + 'provider' => 'xai'
3808 + ];
3809 + }
3810 +
3811 + // Server errors
3812 + if ($status_code >= 500) {
3813 + return [
3814 + 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
3815 + 'error_code' => 'xai_service_unavailable',
3816 + 'provider' => 'xai'
3817 + ];
3818 + }
3819 +
3820 + // Generic error fallback with the actual error message
3821 + return [
3822 + 'error' => esc_html__('X.AI API error: ', 'mxchat') . esc_html($error_message),
3823 + 'error_code' => 'xai_api_error',
3824 + 'provider' => 'xai',
3825 + 'status_code' => $status_code
3826 + ];
3827 + }
3828 +
3829 + $response_body = wp_remote_retrieve_body($response);
3830 + $decoded_response = json_decode($response_body, true);
3831 +
3832 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3833 + return trim($decoded_response['choices'][0]['message']['content']);
3834 + } else {
3835 + //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
3836 + return [
3837 + 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
3838 + 'error_code' => 'xai_response_format_error',
3839 + 'provider' => 'xai'
3840 + ];
3841 + }
3842 +} catch (Exception $e) {
3843 + //error_log('X.AI Exception: ' . $e->getMessage());
3844 + return [
3845 + 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
3846 + 'error_code' => 'xai_exception',
3847 + 'provider' => 'xai'
3848 + ];
3849 +}
3850 +}
3851 +private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
3852 + // Get system prompt instructions from options
3853 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3854 +
3855 + // Clean and validate conversation history
3856 + foreach ($conversation_history as &$message) {
3857 + // Convert bot and agent roles to assistant
3858 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
3859 + $message['role'] = 'assistant';
3860 + }
3861 +
3862 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
3863 + if (!in_array($message['role'], ['assistant', 'user'])) {
3864 + $message['role'] = 'user';
3865 + }
3866 +
3867 + // Ensure content field exists
3868 + if (!isset($message['content']) || empty($message['content'])) {
3869 + $message['content'] = '';
3870 + }
3871 +
3872 + // Remove any unsupported fields
3873 + $message = array_intersect_key($message, array_flip(['role', 'content']));
3874 + }
3875 +
3876 + // Add relevant content as the latest user message
3877 + $conversation_history[] = [
3878 + 'role' => 'user',
3879 + 'content' => $relevant_content
3880 + ];
3881 +
3882 + // Build request body
3883 + $body = json_encode([
3884 + 'model' => $selected_model,
3885 + 'max_tokens' => 1000,
3886 + 'temperature' => 0.8,
3887 + 'messages' => $conversation_history,
3888 + 'system' => $system_prompt_instructions
3889 + ]);
3890 +
3891 + // Set up API request
3892 + $args = [
3893 + 'body' => $body,
3894 + 'headers' => [
3895 + 'Content-Type' => 'application/json',
3896 + 'x-api-key' => $claude_api_key,
3897 + 'anthropic-version' => '2023-06-01'
3898 + ],
3899 + 'timeout' => 60,
3900 + 'redirection' => 5,
3901 + 'blocking' => true,
3902 + 'httpversion' => '1.0',
3903 + 'sslverify' => true,
3904 + ];
3905 +
3906 + // Make API request
3907 + $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
3908 +
3909 + // Check for WordPress errors
3910 + if (is_wp_error($response)) {
3911 + //error_log("Claude API request error: " . $response->get_error_message());
3912 + return "Sorry, there was an error connecting to the API.";
3913 + }
3914 +
3915 + // Check HTTP response code
3916 + $http_code = wp_remote_retrieve_response_code($response);
3917 + if ($http_code !== 200) {
3918 + $error_body = wp_remote_retrieve_body($response);
3919 + //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
3920 +
3921 + // Try to extract error message from response
3922 + $error_data = json_decode($error_body, true);
3923 + $error_message = isset($error_data['error']['message']) ?
3924 + $error_data['error']['message'] :
3925 + "HTTP error " . $http_code;
3926 +
3927 + return "Sorry, the API returned an error: " . $error_message;
3928 + }
3929 +
3930 + // Parse response
3931 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3932 +
3933 + // Check for JSON decode errors
3934 + if (json_last_error() !== JSON_ERROR_NONE) {
3935 + //error_log("Claude API JSON decode error: " . json_last_error_msg());
3936 + return "Sorry, there was an error processing the API response.";
3937 + }
3938 +
3939 + // Extract and validate response content
3940 + if (isset($response_body['content']) &&
3941 + is_array($response_body['content']) &&
3942 + !empty($response_body['content']) &&
3943 + isset($response_body['content'][0]['text'])) {
3944 + return trim($response_body['content'][0]['text']);
3945 + }
3946 +
3947 + // Log unexpected response format
3948 + //error_log("Claude API unexpected response format: " . print_r($response_body, true));
3949 + return "Sorry, I received an unexpected response format from the API.";
3950 +}
3951 +private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content) {
3952 + // Get system prompt instructions from options
3953 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3954 +
3955 + // Add system prompt to relevant content
3956 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3957 +
3958 + // Format messages for Gemini API
3959 + $formatted_messages = [];
3960 +
3961 + // Add system message as the first user message with role prefix
3962 + // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
3963 + $formatted_messages[] = [
3964 + 'role' => 'user',
3965 + 'parts' => [
3966 + ['text' => "[System Instructions] " . $content_with_instructions]
3967 + ]
3968 + ];
3969 +
3970 + // Add model response to acknowledge system instructions
3971 + $formatted_messages[] = [
3972 + 'role' => 'model',
3973 + 'parts' => [
3974 + ['text' => "I understand and will follow these instructions."]
3975 + ]
3976 + ];
3977 +
3978 + // Process the rest of the conversation history
3979 + $current_role = null;
3980 + $current_parts = [];
3981 +
3982 + foreach ($conversation_history as $message) {
3983 + // Skip the first system message as we already handled it
3984 + if ($message['role'] === 'system') {
3985 + continue;
3986 + }
3987 +
3988 + // Map roles to Gemini format
3989 + $gemini_role = '';
3990 + if ($message['role'] === 'user') {
3991 + $gemini_role = 'user';
3992 + } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
3993 + $gemini_role = 'model';
3994 + } else {
3995 + // Skip unsupported roles
3996 + continue;
3997 + }
3998 +
3999 + // If we have a new role, add the previous message
4000 + if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
4001 + $formatted_messages[] = [
4002 + 'role' => $current_role,
4003 + 'parts' => $current_parts
4004 + ];
4005 + $current_parts = [];
4006 + }
4007 +
4008 + // Set current role and add text to parts
4009 + $current_role = $gemini_role;
4010 + $current_parts[] = ['text' => $message['content']];
4011 + }
4012 +
4013 + // Add the last message if there's content
4014 + if ($current_role !== null && !empty($current_parts)) {
4015 + $formatted_messages[] = [
4016 + 'role' => $current_role,
4017 + 'parts' => $current_parts
4018 + ];
4019 + }
4020 +
4021 + // Build the request body
4022 + $body = json_encode([
4023 + 'contents' => $formatted_messages,
4024 + 'generationConfig' => [
4025 + 'temperature' => 0.7,
4026 + 'topP' => 0.95,
4027 + 'topK' => 40,
4028 + 'maxOutputTokens' => 8192,
4029 + ],
4030 + 'safetySettings' => [
4031 + [
4032 + 'category' => 'HARM_CATEGORY_HARASSMENT',
4033 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4034 + ],
4035 + [
4036 + 'category' => 'HARM_CATEGORY_HATE_SPEECH',
4037 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4038 + ],
4039 + [
4040 + 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
4041 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4042 + ],
4043 + [
4044 + 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
4045 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4046 + ]
4047 + ]
4048 + ]);
4049 +
4050 + // Prepare the API endpoint
4051 + $api_endpoint = 'https://generativelanguage.googleapis.com/v1/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
4052 +
4053 + // Set up the API request
4054 + $args = [
4055 + 'body' => $body,
4056 + 'headers' => [
4057 + 'Content-Type' => 'application/json',
4058 + ],
4059 + 'timeout' => 60,
4060 + 'redirection' => 5,
4061 + 'blocking' => true,
4062 + 'httpversion' => '1.0',
4063 + 'sslverify' => true,
4064 + ];
4065 +
4066 + // Make the API request
4067 + $response = wp_remote_post($api_endpoint, $args);
4068 +
4069 + // Process the response
4070 + if (is_wp_error($response)) {
4071 + return "Sorry, there was an error processing your request: " . $response->get_error_message();
4072 + }
4073 +
4074 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
4075 +
4076 + // Handle potential errors in the response
4077 + if (isset($response_body['error'])) {
4078 + //error_log('Gemini API Error: ' . json_encode($response_body['error']));
4079 + return "Sorry, there was an error with the Gemini API: " .
4080 + (isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error');
4081 + }
4082 +
4083 + // Extract the response text
4084 + if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
4085 + return trim($response_body['candidates'][0]['content']['parts'][0]['text']);
4086 + } else {
4087 + //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
4088 + return "Sorry, I couldn't process that request. The response format was unexpected.";
4089 + }
4090 +}
4091 +
4092 +
4093 +
4094 +public function mxchat_dismiss_pre_chat_message() {
4095 + // Get and sanitize the user identifier
4096 + $user_id = $this->mxchat_get_user_identifier();
4097 + $user_id = sanitize_key($user_id);
4098 +
4099 + // Set a transient to track that the user has dismissed the pre-chat message
4100 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
4101 + set_transient($transient_key, true, DAY_IN_SECONDS);
4102 +
4103 + wp_send_json_success();
4104 +}
4105 +
4106 +public function mxchat_check_pre_chat_message_status() {
4107 + // Get and sanitize the user identifier
4108 + $user_id = $this->mxchat_get_user_identifier();
4109 + $user_id = sanitize_key($user_id);
4110 +
4111 + // Check if the transient exists (i.e., if the message was dismissed)
4112 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
4113 + $dismissed = get_transient($transient_key);
4114 +
4115 + // Log the result to see if it's being set correctly
4116 + //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
4117 +
4118 + if ($dismissed) {
4119 + wp_send_json_success(['dismissed' => true]);
4120 + } else {
4121 + wp_send_json_success(['dismissed' => false]);
4122 + }
4123 +
4124 + wp_die();
4125 +}
4126 +
4127 +private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
4128 + if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
4129 + return 0;
4130 + }
4131 +
4132 + $dotProduct = array_sum(array_map(function ($a, $b) {
4133 + return $a * $b;
4134 + }, $vectorA, $vectorB));
4135 + $normA = sqrt(array_sum(array_map(function ($a) {
4136 + return $a * $a;
4137 + }, $vectorA)));
4138 + $normB = sqrt(array_sum(array_map(function ($b) {
4139 + return $b * $b;
4140 + }, $vectorB)));
4141 +
4142 + if ($normA == 0 || $normB == 0) {
4143 + return 0;
4144 + }
4145 +
4146 + return $dotProduct / ($normA * $normB);
4147 + }
4148 +
4149 +public function mxchat_enqueue_scripts_styles() {
4150 + // Define version numbers for the styles and scripts
4151 + $chat_style_version = '2.1.5'; // Replace with your actual version
4152 + $chat_script_version = '2.1.5'; // Replace with your actual version
4153 +
4154 + // Enqueue the script
4155 + wp_enqueue_script(
4156 + 'mxchat-chat-js',
4157 + plugin_dir_url(__FILE__) . '../js/chat-script.js',
4158 + array('jquery'),
4159 + $chat_script_version,
4160 + true
4161 + );
4162 +
4163 + // Enqueue the CSS
4164 + wp_enqueue_style(
4165 + 'mxchat-chat-css',
4166 + plugin_dir_url(__FILE__) . '../css/chat-style.css',
4167 + array(),
4168 + $chat_style_version
4169 + );
4170 +
4171 + // Fetch options from the database
4172 + $this->options = get_option('mxchat_options');
4173 + $prompts_options = get_option('mxchat_prompts_options', array());
4174 +
4175 + // Prepare settings for JavaScript
4176 + $style_settings = array(
4177 + 'ajax_url' => admin_url('admin-ajax.php'),
4178 + 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
4179 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
4180 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
4181 + 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
4182 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
4183 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
4184 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
4185 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
4186 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
4187 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
4188 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
4189 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
4190 + 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
4191 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
4192 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
4193 + 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
4194 + 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off', // Example for consistency
4195 +
4196 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
4197 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
4198 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
4199 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
4200 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
4201 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
4202 +
4203 + 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
4204 + 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
4205 + );
4206 +
4207 + // Pass the settings to the script
4208 + wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
4209 +}
4210 +
4211 +
4212 +public function mxchat_reset_rate_limits() {
4213 + global $wpdb;
4214 +
4215 + // Define a cache key pattern for rate limits
4216 + $cache_key_pattern = 'mxchat_chat_limit_%';
4217 +
4218 + // Retrieve all option names matching the pattern
4219 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
4220 + $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
4221 +
4222 + // db call ok; no-cache ok
4223 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- db call ok
4224 + $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
4225 +
4226 + // Clear the relevant cache entries
4227 + foreach ($option_names as $option_name) {
4228 + wp_cache_delete($option_name, 'options');
4229 + }
4230 +
4231 + // Optionally, clear a general cache if you have one
4232 + wp_cache_delete('mxchat_all_chat_limits', 'options');
4233 + }
4234 +
4235 +private function mxchat_fetch_woocommerce_products() {
4236 + // Ensure WooCommerce is active
4237 + if (!class_exists('WooCommerce')) {
4238 + return [];
4239 + }
4240 +
4241 + $args = array(
4242 + 'post_type' => 'product',
4243 + 'post_status' => 'publish',
4244 + 'posts_per_page' => -1,
4245 + );
4246 +
4247 + $products = get_posts($args);
4248 + $product_data = [];
4249 +
4250 + foreach ($products as $product) {
4251 + $product_id = $product->ID;
4252 + $product_obj = wc_get_product($product_id);
4253 +
4254 + $product_data[] = array(
4255 + 'id' => $product_id,
4256 + 'name' => $product_obj->get_name(),
4257 + 'description' => $product_obj->get_description(),
4258 + 'short_description' => $product_obj->get_short_description(),
4259 + 'url' => get_permalink($product_id),
4260 + 'price' => $product_obj->get_regular_price(),
4261 + 'sale_price' => $product_obj->get_sale_price(),
4262 + 'stock_status' => $product_obj->get_stock_status(),
4263 + 'sku' => $product_obj->get_sku(),
4264 + 'in_stock' => $product_obj->is_in_stock(),
4265 + 'total_sales' => $product_obj->get_total_sales(),
4266 + );
4267 + }
4268 +
4269 + return $product_data;
4270 +}
4271 +
4272 +}
4273 +?>