PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.5.6
MxChat – AI Chatbot & Content Generation for WordPress v2.5.6
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-integrator.php +8252 -4101 2.0.32.5.6 View file →
@@ -1,4101 +1,8252 @@
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 -
965 -// Helper function to clear PDF and Word document related transients
966 -private function clear_pdf_transients($session_id) {
967 - // PDF transients
968 - delete_transient('mxchat_pdf_url_' . $session_id);
969 - delete_transient('mxchat_pdf_embeddings_' . $session_id);
970 - delete_transient('mxchat_include_pdf_in_context_' . $session_id);
971 - delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
972 -
973 - // Word document transients
974 - delete_transient('mxchat_word_url_' . $session_id);
975 - delete_transient('mxchat_word_filename_' . $session_id);
976 - delete_transient('mxchat_word_embeddings_' . $session_id);
977 - delete_transient('mxchat_include_word_in_context_' . $session_id);
978 - delete_transient('mxchat_waiting_for_word_' . $session_id);
979 -}
980 -
981 -// New function to check intents and invoke the callback function
982 -private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
983 - global $wpdb;
984 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
985 -
986 - //error_log("[MxChat] Checking intents for message: " . $message);
987 -
988 - // Generate the user embedding
989 - $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
990 - if (!is_array($user_embedding)) {
991 - //error_log("[MxChat] Failed to generate user embedding");
992 - return false;
993 - }
994 -
995 - // Fetch intents from the database
996 - $table_name = $wpdb->prefix . 'mxchat_intents';
997 - if ($chat_mode === 'agent') {
998 - $query = $wpdb->prepare(
999 - "SELECT * FROM $table_name WHERE callback_function = %s",
1000 - 'mxchat_handle_switch_to_chatbot_intent'
1001 - );
1002 - $intents = $wpdb->get_results($query);
1003 - } else {
1004 - $intents = $wpdb->get_results("SELECT * FROM $table_name");
1005 - }
1006 -
1007 - //error_log("[MxChat] Found " . count($intents) . " intents to check");
1008 -
1009 - if (empty($intents)) {
1010 - //error_log("[MxChat] No intents found in database");
1011 - return false;
1012 - }
1013 -
1014 - $highest_similarity = -INF;
1015 - $matched_intent = null;
1016 -
1017 - foreach ($intents as $intent) {
1018 - //error_log("[MxChat] Checking intent: " . $intent->intent_label . " (callback: " . $intent->callback_function . ")");
1019 -
1020 - $intent_embedding_serialized = $intent->embedding_vector;
1021 - $intent_embedding = $intent_embedding_serialized
1022 - ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1023 - : null;
1024 -
1025 - if (!is_array($intent_embedding)) {
1026 - //error_log("[MxChat] Invalid embedding for intent: " . $intent->intent_label);
1027 - continue;
1028 - }
1029 -
1030 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1031 - $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1032 -
1033 - //error_log("[MxChat] Similarity for {$intent->intent_label}: {$similarity} (threshold: {$intent_threshold})");
1034 -
1035 - if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1036 - $highest_similarity = $similarity;
1037 - $matched_intent = $intent;
1038 - //error_log("[MxChat] New best match: {$intent->intent_label} with similarity {$similarity}");
1039 - }
1040 - }
1041 -
1042 - if ($matched_intent) {
1043 - //error_log("[MxChat] Invoking callback: " . $matched_intent->callback_function);
1044 -
1045 - // If the callback is a method on this instance (core callback), call it directly
1046 - if (method_exists($this, $matched_intent->callback_function)) {
1047 - $callback_result = call_user_func(
1048 - [$this, $matched_intent->callback_function],
1049 - $message,
1050 - $user_id,
1051 - $session_id,
1052 - $matched_intent
1053 - );
1054 - } else {
1055 - // Otherwise, use apply_filters for add-on callbacks
1056 - $callback_result = apply_filters(
1057 - $matched_intent->callback_function,
1058 - false, // default return value
1059 - $message,
1060 - $user_id,
1061 - $session_id,
1062 - $matched_intent
1063 - );
1064 - }
1065 -
1066 - //error_log("[MxChat] Callback result: " . print_r($callback_result, true));
1067 - if ($callback_result !== false) {
1068 - $this->fallbackResponse = $callback_result;
1069 - return true;
1070 - }
1071 - }
1072 -
1073 - //error_log("[MxChat] No matching intent found");
1074 - return false;
1075 -}
1076 -
1077 -
1078 -//verified good
1079 -public function mxchat_handle_order_history($message, $user_id, $session_id) {
1080 - if (!class_exists('WooCommerce')) {
1081 - $this->fallbackResponse['text'] = esc_html__("I can't access order information right now. The order system seems to be unavailable.", 'mxchat');
1082 - return true;
1083 - }
1084 -
1085 - $orderDetails = MxChat_WooCommerce::mxchat_fetch_user_orders_details('all');
1086 -
1087 - if (empty($orderDetails)) {
1088 - $this->fallbackResponse['text'] = esc_html__("I don't see any orders associated with your account. Are you logged in?", 'mxchat');
1089 - return true;
1090 - }
1091 -
1092 - // Generate AI prompt with context
1093 - $prompt = __("User asked about their orders:", 'mxchat') . " '{$message}'\n\n";
1094 - $prompt .= __("Order information:", 'mxchat') . "\n";
1095 - foreach ($orderDetails as $order) {
1096 - $items_list = array_map(function($item) {
1097 - return "{$item['name']} ({$item['quantity']})";
1098 - }, $order['items']);
1099 -
1100 - $prompt .= __("Order #", 'mxchat') . "{$order['order_id']}: {$order['formatted_total']} " . __("on", 'mxchat') . " {$order['date']}\n";
1101 - $prompt .= __("Items:", 'mxchat') . " " . implode(', ', $items_list) . "\n";
1102 - }
1103 -
1104 - $prompt .= __("\nProvide a natural, conversational response focusing on the specific information the user asked about. ", 'mxchat');
1105 - $prompt .= __("If they ask about a specific order or detail, provide just that information. ", 'mxchat');
1106 - $prompt .= __("If they ask about license keys or sensitive information, inform them to check their email or contact support.", 'mxchat');
1107 -
1108 - // Get AI response
1109 - $ai_response = $this->mxchat_call_ai_api($prompt);
1110 - $this->fallbackResponse['text'] = $ai_response['text'];
1111 -
1112 - return true;
1113 -}
1114 -
1115 -
1116 -public function mxchat_handle_product_inquiry($message, $user_id, $session_id) {
1117 - //error_log("PRODUCT INQUIRY START - Message: $message, User ID: $user_id");
1118 -
1119 - // Sanitize user ID
1120 - $sanitized_user_id = sanitize_key($user_id);
1121 - //error_log("Sanitized User ID: $sanitized_user_id");
1122 -
1123 - // Find product
1124 - $product_id = $this->find_product_in_message($message);
1125 - //error_log("Initial product ID from message: " . ($product_id ?? 'null'));
1126 -
1127 - // Check transient if no product found
1128 - if (!$product_id) {
1129 - $product_id = get_transient('mxchat_last_discussed_product_' . $sanitized_user_id);
1130 - //error_log("Product ID from transient: " . ($product_id ?? 'null'));
1131 - }
1132 -
1133 - // Handle product inquiries
1134 - if ($product_id && class_exists('WooCommerce')) {
1135 - $product = wc_get_product($product_id);
1136 - if ($product) {
1137 - //error_log("Found product: " . $product->get_name() . " (ID: $product_id)");
1138 -
1139 - // Prepare product details
1140 - $product_name = esc_html($product->get_name());
1141 - $product_price = $product->get_price_html();
1142 - $product_image_url = esc_url(wp_get_attachment_url($product->get_image_id()));
1143 - $product_url = esc_url(get_permalink($product_id));
1144 - $product_id_attr = esc_attr($product_id);
1145 -
1146 - // Get product description
1147 - $product_description = $product->get_description() ?: $product->get_short_description();
1148 -
1149 - // Log embeddings process
1150 - //error_log("Generating embedding for message: $message");
1151 - $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1152 - //error_log("Finding relevant content for product inquiry");
1153 - $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
1154 -
1155 - // Build AI prompt
1156 - $ai_prompt = esc_html__("You are a knowledgeable product assistant. ", 'mxchat');
1157 - $ai_prompt .= esc_html__("Respond to this user query: '{$message}'\n\n", 'mxchat');
1158 -
1159 - if (!empty($relevant_content)) {
1160 - $ai_prompt .= esc_html__("Relevant information from our knowledge base:\n{$relevant_content}\n\n", 'mxchat');
1161 - }
1162 -
1163 - $ai_prompt .= esc_html__("Product details:\n", 'mxchat');
1164 - $ai_prompt .= esc_html__("Name: {$product_name}\n", 'mxchat');
1165 - $ai_prompt .= esc_html__("Price: ", 'mxchat') . strip_tags($product_price) . "\n";
1166 - if ($product_description) {
1167 - $ai_prompt .= esc_html__("Description: {$product_description}\n", 'mxchat');
1168 - }
1169 -
1170 - $ai_prompt .= esc_html__("\nInstructions:\n", 'mxchat');
1171 - $ai_prompt .= esc_html__("1. Address the user's specific question or concern about the product\n", 'mxchat');
1172 - $ai_prompt .= esc_html__("2. Incorporate relevant information from our knowledge base if provided\n", 'mxchat');
1173 - $ai_prompt .= esc_html__("3. Highlight key product features that relate to their query\n", 'mxchat');
1174 - $ai_prompt .= esc_html__("4. Include a natural suggestion to check out the product\n", 'mxchat');
1175 - $ai_prompt .= esc_html__("5. Keep the response conversational and helpful\n", 'mxchat');
1176 -
1177 - //error_log("Sending AI prompt: " . $ai_prompt);
1178 -
1179 - // Build and log AI response
1180 - $ai_response = $this->mxchat_call_ai_api($ai_prompt);
1181 - //error_log("AI Response received for product inquiry: " . print_r($ai_response, true));
1182 -
1183 - // Generate and log product card
1184 - $product_card_html = <<<HTML
1185 -<div class="mxchat-product-card">
1186 - <a href="{$product_url}" target="_blank">
1187 - <img src="{$product_image_url}" alt="{$product_name}" class="mxchat-product-image" />
1188 - <h3 class="mxchat-product-name">{$product_name}</h3>
1189 - </a>
1190 - <div class="mxchat-product-price">{$product_price}</div>
1191 - <button class="mxchat-add-to-cart-button" data-product-id="{$product_id_attr}">Add to Cart</button>
1192 -</div>
1193 -HTML;
1194 -
1195 - // Save response and set transient
1196 - $this->productCardHtml = $product_card_html;
1197 - $this->fallbackResponse = [
1198 - 'text' => $ai_response['text'],
1199 - 'html' => $this->productCardHtml,
1200 - ];
1201 -
1202 - //error_log("Setting transient for product: $product_id with key: mxchat_last_discussed_product_$sanitized_user_id");
1203 - set_transient('mxchat_last_discussed_product_' . $sanitized_user_id, $product_id, HOUR_IN_SECONDS);
1204 -
1205 - // Verify transient was set
1206 - $verify_transient = get_transient('mxchat_last_discussed_product_' . $sanitized_user_id);
1207 - //error_log("Verification - Retrieved transient value: " . ($verify_transient ?? 'null'));
1208 -
1209 - return true;
1210 - }
1211 - }
1212 -
1213 - //error_log("PRODUCT INQUIRY END - No product found or WooCommerce not available");
1214 - return false;
1215 -}
1216 -
1217 -//verified good
1218 -public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1219 - // Log the message safely
1220 - //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
1221 -
1222 - // Initiate email capture flow
1223 - $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
1224 -
1225 - set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1226 - $this->mxchat_save_chat_message($session_id, 'bot', $response);
1227 -
1228 - // Respond to the user
1229 - wp_send_json(['message' => $response]);
1230 - wp_die();
1231 -}
1232 -
1233 -//very good
1234 -public function mxchat_generate_image($message, $user_id, $session_id) {
1235 - // Prepare a prompt for DALL-E
1236 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1237 -
1238 - // Use the existing OpenAI API key
1239 - $openai_api_key = sanitize_text_field($this->options['api_key']);
1240 -
1241 - // Call DALL-E to generate an image
1242 - $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1243 -
1244 - // Check if the response contains an image URL
1245 - if (isset($image_response['imageUrl'])) {
1246 - $image_url = esc_url_raw($image_response['imageUrl']);
1247 -
1248 - // Construct the HTML with a CSS class instead of inline styles
1249 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1250 -
1251 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1252 - } else {
1253 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1254 - $response_html = '';
1255 - //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1256 - }
1257 -
1258 - // Save both text and HTML responses
1259 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text . "\n" . $response_html);
1260 -
1261 - // Prepare the response data
1262 - $response_data = [
1263 - 'message' => $response_text,
1264 - 'html' => $response_html,
1265 - 'image_url' => $image_url ?? '',
1266 - ];
1267 -
1268 - // Send the JSON response
1269 - header('Content-Type: application/json; charset=' . get_option('blog_charset'));
1270 - echo json_encode($response_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
1271 - wp_die();
1272 -}
1273 -private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1274 - $api_url = 'https://api.openai.com/v1/images/generations';
1275 - $body = json_encode([
1276 - 'prompt' => sanitize_text_field($prompt),
1277 - 'n' => 1,
1278 - 'size' => '1024x1024',
1279 - 'model' => sanitize_text_field($model),
1280 - ]);
1281 -
1282 - $args = [
1283 - 'body' => $body,
1284 - 'headers' => [
1285 - 'Content-Type' => 'application/json',
1286 - 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1287 - ],
1288 - 'method' => 'POST',
1289 - 'timeout' => absint($timeout),
1290 - ];
1291 -
1292 - $response = wp_remote_post($api_url, $args);
1293 -
1294 - if (is_wp_error($response)) {
1295 - //error_log("DALL-E request failed: " . $response->get_error_message());
1296 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1297 - }
1298 -
1299 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
1300 -
1301 - if (isset($response_body['data'][0]['url'])) {
1302 - return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1303 - } else {
1304 - //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1305 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1306 - }
1307 -}
1308 -
1309 -/**
1310 - * Handle web search requests.
1311 - *
1312 - * Sends the refined search query to the Brave Search API and displays neatly formatted,
1313 - * styled search results. Results are cached for performance.
1314 - *
1315 - * @since 1.0.0
1316 - * @param string $message The user's search query.
1317 - * @param string $user_id The user identifier.
1318 - * @param string $session_id The current session ID.
1319 - * @return void
1320 - */
1321 -public function mxchat_handle_search_request( $message, $user_id, $session_id ) {
1322 - // Step 1: Interpret and refine the search query
1323 - $refined_search_query = $this->mxchat_interpret_search_query( $message );
1324 -
1325 - if ( empty( $refined_search_query ) ) {
1326 - $this->fallbackResponse = array(
1327 - 'text' => esc_html__( 'I apologize, but could you please rephrase your search request?', 'mxchat' ),
1328 - );
1329 - return;
1330 - }
1331 -
1332 - // Retrieve and validate API settings
1333 - $options = get_option( 'mxchat_options' );
1334 - $api_key = isset( $options['brave_api_key'] ) ? sanitize_text_field( $options['brave_api_key'] ) : '';
1335 - $results_count = isset( $options['brave_results_count'] ) ? absint( $options['brave_results_count'] ) : 5;
1336 -
1337 - if ( empty( $api_key ) ) {
1338 - $this->fallbackResponse = array(
1339 - 'text' => esc_html__( 'Search functionality is temporarily unavailable. Please try again later.', 'mxchat' ),
1340 - );
1341 - return;
1342 - }
1343 -
1344 - // Build the API request URL
1345 - $api_url = add_query_arg(
1346 - array(
1347 - 'q' => rawurlencode( $refined_search_query ),
1348 - 'count' => $results_count,
1349 - 'text_decorations' => 'true',
1350 - 'rich_data' => 'true',
1351 - ),
1352 - 'https://api.search.brave.com/res/v1/web/search'
1353 - );
1354 -
1355 - // Attempt to retrieve cached results first
1356 - $transient_key = 'mxchat_search_' . md5( $refined_search_query );
1357 - $results = get_transient( $transient_key );
1358 -
1359 - if ( false === $results ) {
1360 - // Fetch new results from the Brave Search API
1361 - $response = wp_remote_get(
1362 - $api_url,
1363 - array(
1364 - 'headers' => array(
1365 - 'Accept' => 'application/json',
1366 - 'Accept-Encoding' => 'gzip',
1367 - 'X-Subscription-Token'=> $api_key,
1368 - ),
1369 - 'timeout' => 10,
1370 - )
1371 - );
1372 -
1373 - if ( is_wp_error( $response ) ) {
1374 - $this->fallbackResponse = array(
1375 - 'text' => esc_html__( 'I encountered an error while searching. Please try again.', 'mxchat' ),
1376 - );
1377 - return;
1378 - }
1379 -
1380 - $results = json_decode( wp_remote_retrieve_body( $response ), true );
1381 -
1382 - if ( json_last_error() !== JSON_ERROR_NONE ) {
1383 - $this->fallbackResponse = array(
1384 - 'text' => esc_html__( 'I received an invalid response from the search service.', 'mxchat' ),
1385 - );
1386 - return;
1387 - }
1388 -
1389 - // Cache results for one hour
1390 - set_transient( $transient_key, $results, HOUR_IN_SECONDS );
1391 - }
1392 -
1393 - // Process and display results
1394 - if ( ! empty( $results['web']['results'] ) && is_array( $results['web']['results'] ) ) {
1395 - $html = $this->generate_search_results_html( $results['web']['results'], $refined_search_query );
1396 -
1397 - // Only return HTML (no large text summary)
1398 - $this->fallbackResponse = array(
1399 - 'html' => $html,
1400 - );
1401 -
1402 - // Save to chat history
1403 - $this->mxchat_save_chat_message( $session_id, 'bot', $html );
1404 - } else {
1405 - $this->fallbackResponse = array(
1406 - 'text' => sprintf(
1407 - esc_html__( 'I couldn\'t find any relevant results for "%s". Would you like to try different search terms?', 'mxchat' ),
1408 - esc_html( $refined_search_query )
1409 - ),
1410 - );
1411 - }
1412 -}
1413 -
1414 -
1415 -/**
1416 - * Format search results into a natural text summary.
1417 - *
1418 - * @since 1.0.0
1419 - * @param array $results The search results from the API.
1420 - * @param string $query The original search query.
1421 - * @return string The text summary of the top results.
1422 - */
1423 -private function format_search_results( $results, $query ) {
1424 - $summary = sprintf(
1425 - esc_html__( 'Here are the most relevant results for "%s":', 'mxchat' ),
1426 - esc_html( $query )
1427 - ) . "\n\n";
1428 -
1429 - $max_results = min( count( $results ), 3 );
1430 - for ( $i = 0; $i < $max_results; $i++ ) {
1431 - $result = $results[ $i ];
1432 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1433 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1434 -
1435 - // Append title and description to the summary
1436 - $summary .= sprintf(
1437 - "%s\n%s\n\n",
1438 - esc_html( $title ),
1439 - esc_html( $description )
1440 - );
1441 - }
1442 -
1443 - return $summary;
1444 -}
1445 -
1446 -/**
1447 - * Generate HTML markup for search results.
1448 - *
1449 - * @since 1.0.0
1450 - * @param array $results The search results from the API.
1451 - * @param string $query The user-refined query.
1452 - * @return string The HTML markup for displaying the results.
1453 - */
1454 -private function generate_search_results_html( $results, $query ) {
1455 - ob_start();
1456 - ?>
1457 - <div class="mxchat-search-results">
1458 - <?php foreach ( $results as $result ) :
1459 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1460 - $url = isset( $result['url'] ) ? esc_url( $result['url'] ) : '#';
1461 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1462 - $favicon = isset( $result['meta_url']['favicon'] ) ? esc_url( $result['meta_url']['favicon'] ) : '';
1463 - $thumbnail = isset( $result['thumbnail']['src'] ) ? esc_url( $result['thumbnail']['src'] ) : '';
1464 - $domain = parse_url( $url, PHP_URL_HOST );
1465 - ?>
1466 - <div class="mxchat-search-item">
1467 - <div class="mxchat-search-header">
1468 - <?php if ( $favicon ) : ?>
1469 - <img
1470 - src="<?php echo esc_url( $favicon ); ?>"
1471 - class="mxchat-site-icon"
1472 - alt="<?php echo esc_attr__( 'Site icon', 'mxchat' ); ?>"
1473 - width="16"
1474 - height="16"
1475 - />
1476 - <?php endif; ?>
1477 - <div class="mxchat-site-url"><?php echo esc_html( $domain ); ?></div>
1478 - </div>
1479 -
1480 - <div class="mxchat-search-content">
1481 - <h3 class="mxchat-search-title">
1482 - <a href="<?php echo esc_url( $url ); ?>"
1483 - target="_blank"
1484 - rel="noopener noreferrer"
1485 - >
1486 - <?php echo esc_html( $title ); ?>
1487 - </a>
1488 - </h3>
1489 -
1490 - <?php if ( $thumbnail ) : ?>
1491 - <div class="mxchat-search-thumbnail">
1492 - <img
1493 - src="<?php echo esc_url( $thumbnail ); ?>"
1494 - alt="<?php echo esc_attr__( 'Thumbnail image', 'mxchat' ); ?>"
1495 - loading="lazy"
1496 - />
1497 - </div>
1498 - <?php endif; ?>
1499 -
1500 - <div class="mxchat-search-description">
1501 - <?php echo esc_html( $description ); ?>
1502 - </div>
1503 - </div>
1504 - </div>
1505 - <?php endforeach; ?>
1506 - </div>
1507 - <?php
1508 - return ob_get_clean();
1509 -}
1510 -
1511 -
1512 -//very good
1513 -public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
1514 -
1515 - // Step 1: Interpret the search query for better results
1516 - $refined_search_query = $this->mxchat_interpret_search_query($message);
1517 -
1518 -
1519 - // If no query was interpreted, return a fallback message
1520 - if (empty($refined_search_query)) {
1521 - $this->fallbackResponse = [
1522 - 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
1523 - 'html' => "",
1524 - ];
1525 - return;
1526 - }
1527 -
1528 - // Brave API URL
1529 - $api_url = 'https://api.search.brave.com/res/v1/images/search';
1530 -
1531 - // Retrieve Brave API settings
1532 - $options = get_option('mxchat_options');
1533 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1534 -
1535 - if (empty($api_key)) {
1536 -/*
1537 - if (defined('WP_DEBUG') && WP_DEBUG) {
1538 - error_log("Brave API key is missing.");
1539 - }
1540 -*/
1541 -
1542 - $this->fallbackResponse = [
1543 - 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
1544 - 'html' => "",
1545 - ];
1546 - return;
1547 - }
1548 -
1549 - $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
1550 - $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
1551 -
1552 - // Append query parameters based on settings
1553 - $api_url = add_query_arg([
1554 - 'q' => rawurlencode($refined_search_query),
1555 - 'count' => $image_count,
1556 - 'safesearch' => $safe_search,
1557 - ], $api_url);
1558 -
1559 -/*
1560 - // Log the final API URL for the search
1561 - if (defined('WP_DEBUG') && WP_DEBUG) {
1562 - error_log("Final API URL for Brave Image Search: " . esc_url_raw($api_url));
1563 - }
1564 -*/
1565 -
1566 -
1567 - // Implement caching
1568 - $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
1569 - $body = get_transient($transient_key);
1570 -
1571 - if (false === $body) {
1572 - $args = [
1573 - 'headers' => [
1574 - 'Accept' => 'application/json',
1575 - 'Accept-Encoding' => 'gzip',
1576 - 'X-Subscription-Token' => $api_key,
1577 - ],
1578 - 'timeout' => 10,
1579 - ];
1580 -
1581 - $response = wp_remote_get($api_url, $args);
1582 -
1583 - if (is_wp_error($response)) {
1584 -/*
1585 - if (defined('WP_DEBUG') && WP_DEBUG) {
1586 - error_log("Brave Image API request failed: " . $response->get_error_message());
1587 - }
1588 -*/
1589 -
1590 - $this->fallbackResponse = [
1591 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1592 - 'html' => "",
1593 - ];
1594 - return;
1595 - }
1596 -
1597 - $body = json_decode(wp_remote_retrieve_body($response), true);
1598 - set_transient($transient_key, $body, HOUR_IN_SECONDS);
1599 - }
1600 -
1601 - // Process the API response
1602 - if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
1603 - $html_output = '<div class="mxchat-image-gallery">';
1604 -
1605 - foreach ($body['results'] as $image) {
1606 - $image_url = isset($image['url']) ? esc_url($image['url']) : '';
1607 - $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
1608 - $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
1609 -
1610 - if ($image_url && $thumbnail_url) {
1611 - $html_output .= '<div class="mxchat-image-item">';
1612 - $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
1613 - $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
1614 - $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
1615 - $html_output .= '</a></div>';
1616 - }
1617 - }
1618 -
1619 - $html_output .= '</div>';
1620 -
1621 - $this->fallbackResponse = [
1622 - 'text' => "",
1623 - 'html' => $html_output,
1624 - ];
1625 -
1626 - // Save response in chat history
1627 - $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
1628 -
1629 - } else {
1630 -/*
1631 - if (defined('WP_DEBUG') && WP_DEBUG) {
1632 - error_log("Brave Image API response did not contain expected data structure or was empty: " . print_r($body, true));
1633 - }
1634 -*/
1635 -
1636 - $this->fallbackResponse = [
1637 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1638 - 'html' => "",
1639 - ];
1640 - }
1641 -}
1642 -public function mxchat_interpret_search_query($user_query) {
1643 - $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');
1644 -
1645 - // Retrieve OpenAI API key using 'api_key' as the option key
1646 - $api_key = isset($this->options['api_key']) ? sanitize_text_field($this->options['api_key']) : sanitize_text_field(get_option('mxchat_options')['api_key']);
1647 -
1648 - /*
1649 - // Log the API key check, without exposing the key
1650 - if (defined('WP_DEBUG') && WP_DEBUG) {
1651 - error_log("Retrieved OpenAI API Key: " . ($api_key ? "Present" : "Missing"));
1652 - }
1653 - */
1654 -
1655 - if (empty($api_key)) {
1656 - //error_log("OpenAI API key is missing.");
1657 - return sanitize_text_field($user_query); // Default to the original query if API key is missing
1658 - }
1659 -
1660 - $url = 'https://api.openai.com/v1/chat/completions';
1661 - $args = [
1662 - 'headers' => [
1663 - 'Authorization' => 'Bearer ' . $api_key,
1664 - 'Content-Type' => 'application/json',
1665 - ],
1666 - 'body' => wp_json_encode([
1667 - 'model' => 'gpt-3.5-turbo',
1668 - 'messages' => [
1669 - ['role' => 'system', 'content' => $system_prompt],
1670 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
1671 - ],
1672 - 'temperature' => 0.2,
1673 - 'max_tokens' => 20,
1674 - ]),
1675 - 'method' => 'POST',
1676 - ];
1677 -
1678 - $response = wp_remote_post($url, $args);
1679 -
1680 - if (is_wp_error($response)) {
1681 - //error_log("OpenAI request failed: " . $response->get_error_message());
1682 - return sanitize_text_field($user_query); // Fallback to the original query if there's an error
1683 - }
1684 -
1685 - $body = json_decode(wp_remote_retrieve_body($response), true);
1686 -
1687 - // Check for a valid response and sanitize output
1688 - if (isset($body['choices'][0]['message']['content'])) {
1689 - $interpreted_query = sanitize_text_field(trim($body['choices'][0]['message']['content']));
1690 -
1691 - /*
1692 - // Log the interpreted query for debugging
1693 - if (defined('WP_DEBUG') && WP_DEBUG) {
1694 - error_log("Interpreted search query: " . $interpreted_query);
1695 - }
1696 - */
1697 -
1698 - return $interpreted_query;
1699 - } else {
1700 - //error_log("Unexpected API response format: " . print_r($body, true));
1701 - return sanitize_text_field($user_query);
1702 - }
1703 -}
1704 -
1705 -public function mxchat_handle_add_to_cart_intent($message, $user_id, $session_id) {
1706 - //error_log("ADD TO CART START - Message: $message, User ID: $user_id");
1707 -
1708 - if (!class_exists('WooCommerce')) {
1709 - //error_log("WooCommerce not available");
1710 - return $this->generate_intent_response([
1711 - 'intent' => 'add_to_cart',
1712 - 'status' => 'error',
1713 - 'reason' => esc_html__('woocommerce_not_available', 'mxchat')
1714 - ], $session_id);
1715 - }
1716 -
1717 - $sanitized_user_id = sanitize_key($user_id);
1718 - // error_log("Sanitized User ID: $sanitized_user_id");
1719 - $product_id = null;
1720 -
1721 - // If button click, use transient
1722 - if ($message === '!addtocart') {
1723 - //error_log("Button click detected - using transient");
1724 - $product_id = get_transient('mxchat_last_discussed_product_' . $sanitized_user_id);
1725 - //error_log("Product ID from transient: " . ($product_id ?? 'null'));
1726 - } else {
1727 - // For text commands, search message first
1728 - //error_log("Text command detected - searching message first");
1729 - $product_id = $this->find_product_in_message($message);
1730 - //error_log("Product ID from message search: " . ($product_id ?? 'null'));
1731 -
1732 - // Only use transient as fallback if no product found in message
1733 - if (!$product_id) {
1734 - //error_log("No product found in message, checking transient as fallback");
1735 - $product_id = get_transient('mxchat_last_discussed_product_' . $sanitized_user_id);
1736 - //error_log("Product ID from transient fallback: " . ($product_id ?? 'null'));
1737 - }
1738 - }
1739 -
1740 - // Handle no product found
1741 - if (!$product_id) {
1742 - //error_log("No product ID found through any method");
1743 - return $this->generate_intent_response([
1744 - 'intent' => 'add_to_cart',
1745 - 'status' => 'error',
1746 - 'reason' => esc_html__('no_product_context', 'mxchat'),
1747 - 'action_needed' => esc_html__('request_product_name', 'mxchat'),
1748 - 'searched_message' => $message
1749 - ], $session_id);
1750 - }
1751 -
1752 - // Get and verify product
1753 - $product = wc_get_product($product_id);
1754 - if (!$product) {
1755 - //error_log("Product not found with ID: $product_id");
1756 - return $this->generate_intent_response([
1757 - 'intent' => 'add_to_cart',
1758 - 'status' => 'error',
1759 - 'reason' => esc_html__('product_not_found', 'mxchat'),
1760 - 'product_id' => $product_id
1761 - ], $session_id);
1762 - }
1763 -
1764 - //error_log("Found product: " . $product->get_name() . " (ID: $product_id)");
1765 -
1766 - // Add to cart
1767 - $added = WC()->cart->add_to_cart($product_id);
1768 - if ($added) {
1769 - //error_log("Successfully added to cart: " . $product->get_name());
1770 - return $this->generate_intent_response([
1771 - 'intent' => 'add_to_cart',
1772 - 'status' => 'success',
1773 - 'product' => [
1774 - 'name' => $product->get_name(),
1775 - 'id' => $product_id
1776 - ],
1777 - 'cart_url' => wc_get_cart_url(),
1778 - 'available_actions' => [
1779 - esc_html__('view_cart', 'mxchat'),
1780 - esc_html__('checkout', 'mxchat'),
1781 - esc_html__('continue_shopping', 'mxchat')
1782 - ]
1783 - ], $session_id);
1784 - } else {
1785 - //error_log("Failed to add to cart: " . $product->get_name());
1786 - return $this->generate_intent_response([
1787 - 'intent' => 'add_to_cart',
1788 - 'status' => 'error',
1789 - 'reason' => esc_html__('add_to_cart_failed', 'mxchat'),
1790 - 'product' => [
1791 - 'name' => $product->get_name(),
1792 - 'id' => $product_id
1793 - ]
1794 - ], $session_id);
1795 - }
1796 -}
1797 -private function find_product_in_message($message) {
1798 - global $wpdb;
1799 -
1800 - // Get embedding for the search query
1801 - $query_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1802 - if (!is_array($query_embedding)) {
1803 - return null;
1804 - }
1805 -
1806 - // Get relevant content as string
1807 - $relevant_content = $this->mxchat_find_relevant_products($query_embedding);
1808 - if (empty($relevant_content)) {
1809 - // Return null to indicate no results and set fallback response
1810 - $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');
1811 - return null;
1812 - }
1813 -
1814 - // Extract product URLs from the content
1815 - preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
1816 -
1817 - if (!empty($matches[0])) {
1818 - // Try each URL found
1819 - foreach ($matches[0] as $url) {
1820 - // Clean the URL
1821 - $url = rtrim($url, '/."\']');
1822 -
1823 - // Get the product slug
1824 - $path = parse_url($url, PHP_URL_PATH);
1825 - $slug = basename(rtrim($path, '/'));
1826 -
1827 - // Find product by slug
1828 - $args = array(
1829 - 'post_type' => 'product',
1830 - 'post_status' => 'publish',
1831 - 'name' => $slug,
1832 - 'posts_per_page' => 1
1833 - );
1834 -
1835 - $products = get_posts($args);
1836 -
1837 - if (!empty($products)) {
1838 - $product_id = $products[0]->ID;
1839 - $product = wc_get_product($product_id);
1840 -
1841 - if ($product && $product->is_purchasable()) {
1842 - return $product_id;
1843 - }
1844 - }
1845 - }
1846 - }
1847 -
1848 - // Fallback: Look for product names in the content
1849 - $products = wc_get_products([
1850 - 'status' => 'publish',
1851 - 'limit' => -1,
1852 - 'return' => 'all'
1853 - ]);
1854 -
1855 - foreach ($products as $product) {
1856 - $name = $product->get_name();
1857 - if (stripos($relevant_content, $name) !== false) {
1858 - if ($product->is_purchasable()) {
1859 - return $product->get_id();
1860 - }
1861 - }
1862 - }
1863 -
1864 - // If no product is found after all checks, set the fallback response
1865 - $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Try to be more specific", 'mxchat');
1866 - return null;
1867 -}
1868 -
1869 -// New method to handle intent responses
1870 -private function generate_intent_response($context_content, $session_id) {
1871 - // Convert the context array to a structured string for the AI
1872 - $context_string = $this->format_intent_context($context_content);
1873 -
1874 - // Generate AI response using the context
1875 - $response = $this->mxchat_generate_response(
1876 - $context_string,
1877 - $this->options['api_key'],
1878 - $this->options['xai_api_key'],
1879 - $this->options['claude_api_key'],
1880 - $this->options['deepseek_api_key'],
1881 - $this->mxchat_fetch_conversation_history_for_ai($session_id)
1882 - );
1883 -
1884 - $this->fallbackResponse['text'] = $response;
1885 - return true;
1886 -}
1887 -// Helper method to format intent context
1888 -private function format_intent_context($context) {
1889 - $context_string = esc_html__("INTENT CONTEXT:\n", 'mxchat');
1890 -
1891 - switch ($context['intent']) {
1892 - case 'add_to_cart':
1893 - if ($context['status'] === 'success') {
1894 - $context_string .= esc_html__("Action: Successfully added product to cart\n", 'mxchat');
1895 - $context_string .= sprintf(esc_html__("Product: %s\n", 'mxchat'), $context['product']['name']);
1896 - $context_string .= esc_html__("Available actions: ", 'mxchat') . implode(', ', $context['available_actions']) . "\n";
1897 - $context_string .= sprintf(esc_html__("Cart URL: %s\n", 'mxchat'), $context['cart_url']);
1898 - $context_string .= esc_html__("\nPlease inform the user of the successful addition and their available options.", 'mxchat');
1899 - } else {
1900 - $context_string .= esc_html__("Action: Failed to add product to cart\n", 'mxchat');
1901 - $context_string .= sprintf(esc_html__("Reason: %s\n", 'mxchat'), $context['reason']);
1902 - switch ($context['reason']) {
1903 - case 'woocommerce_not_available':
1904 - $context_string .= esc_html__("\nPlease inform the user that shopping features are not available.", 'mxchat');
1905 - break;
1906 - case 'no_product_context':
1907 - $context_string .= esc_html__("\nPlease ask the user to specify which product they want to add.", 'mxchat');
1908 - break;
1909 - case 'product_not_found':
1910 - $context_string .= esc_html__("\nPlease inform the user that the product couldn't be found and ask them to try again.", 'mxchat');
1911 - break;
1912 - case 'add_to_cart_failed':
1913 - $context_string .= esc_html__("\nPlease apologize to the user and suggest they try again or ask for assistance.", 'mxchat');
1914 - break;
1915 - }
1916 - }
1917 - break;
1918 - }
1919 -
1920 - return $context_string;
1921 -}
1922 -
1923 -
1924 -public function mxchat_handle_checkout_intent($message, $user_id, $session_id) {
1925 - if (!class_exists('WooCommerce')) {
1926 - $this->fallbackResponse['text'] = esc_html__("I apologize, but the checkout feature isn't available at the moment.", 'mxchat');
1927 - return true;
1928 - }
1929 -
1930 - // Check if cart has items
1931 - if (WC()->cart->is_empty()) {
1932 - $this->fallbackResponse['text'] = esc_html__("Your cart is empty at the moment. Would you like to see our products?", 'mxchat');
1933 - return true;
1934 - }
1935 -
1936 - // Get cart summary
1937 - $cart_count = WC()->cart->get_cart_contents_count();
1938 - $cart_total = WC()->cart->get_total();
1939 -
1940 - // Get and validate checkout URL
1941 - $checkout_url = wc_get_checkout_url();
1942 - if (!$checkout_url) {
1943 - $this->fallbackResponse['text'] = esc_html__("I'm having trouble accessing the checkout page. Please try again in a moment.", 'mxchat');
1944 - return true;
1945 - }
1946 -
1947 - wp_send_json([
1948 - 'text' => sprintf(
1949 - esc_html__("You have %d item%s in your cart totaling %s. I'll redirect you to checkout now.", 'mxchat'),
1950 - $cart_count,
1951 - $cart_count > 1 ? esc_html__('s', 'mxchat') : '',
1952 - strip_tags($cart_total)
1953 - ),
1954 - 'redirect_url' => esc_url_raw($checkout_url)
1955 - ]);
1956 - wp_die();
1957 -}
1958 -
1959 -
1960 -//very good
1961 -private function add_email_to_loops($email) {
1962 - // Sanitize the email
1963 - $email = sanitize_email($email);
1964 -
1965 - // Retrieve and sanitize options
1966 - $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
1967 - $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
1968 -
1969 - // Check for missing API key or mailing list ID
1970 - if (empty($api_key) || empty($mailing_list_id)) {
1971 - //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
1972 - return;
1973 - }
1974 -
1975 - $data = array(
1976 - 'email' => $email,
1977 - 'subscribed' => true,
1978 - 'source' => __('MxChat AI Chatbot', 'mxchat'),
1979 - 'mailingLists' => array($mailing_list_id => true),
1980 - );
1981 -
1982 - $url = 'https://app.loops.so/api/v1/contacts/create';
1983 - $args = array(
1984 - 'body' => wp_json_encode($data),
1985 - 'headers' => array(
1986 - 'Authorization' => 'Bearer ' . $api_key,
1987 - 'Content-Type' => 'application/json',
1988 - ),
1989 - 'method' => 'POST',
1990 - 'timeout' => 45,
1991 - );
1992 -
1993 - $response = wp_remote_post($url, $args);
1994 -
1995 - // Handle errors in the API request
1996 - if (is_wp_error($response)) {
1997 - //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
1998 - return;
1999 - }
2000 -
2001 - // Check for non-200 HTTP responses
2002 - $response_code = wp_remote_retrieve_response_code($response);
2003 - if ($response_code != 200) {
2004 - $response_body = wp_remote_retrieve_body($response);
2005 - //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
2006 - }
2007 -}
2008 -
2009 -public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
2010 - // Get the maximum number of pages allowed from admin settings
2011 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2012 -
2013 - // Retrieve options for dynamic texts
2014 - $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
2015 - $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
2016 - $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
2017 -
2018 - // Check for explicit request for new PDF
2019 - $new_pdf_requested = stripos($message, 'new') !== false ||
2020 - stripos($message, 'another') !== false ||
2021 - stripos($message, 'different') !== false;
2022 -
2023 - // If user mentions adding/reading a PDF, set waiting flag
2024 - if (stripos($message, 'pdf') !== false ||
2025 - stripos($message, 'document') !== false ||
2026 - stripos($message, 'read') !== false) {
2027 - set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
2028 - $this->fallbackResponse['text'] = $trigger_text;
2029 - return;
2030 - }
2031 -
2032 - // If we're waiting for a URL or user requested new PDF
2033 - if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
2034 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
2035 - // Process URL... (rest of your existing URL processing code)
2036 - } else {
2037 - $this->fallbackResponse['text'] = $trigger_text;
2038 - }
2039 - return;
2040 - }
2041 -
2042 - // Default to proceeding with conversation if no specific PDF action is needed
2043 - $this->fallbackResponse['text'] = '';
2044 -}
2045 -private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
2046 - $upload_dir = wp_upload_dir();
2047 - $temp_file = null;
2048 -
2049 - try {
2050 - // Handle URL vs local file
2051 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
2052 - // Validate and download the file from URL
2053 - $temp_file = wp_tempnam($pdf_source); // Safe temporary file name
2054 - $response = wp_remote_get($pdf_source, ['timeout' => 60]);
2055 -
2056 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2057 - //error_log(esc_html__("Failed to download PDF. Error: ", 'mxchat') . print_r($response, true));
2058 - return false;
2059 - }
2060 -
2061 - file_put_contents($temp_file, wp_remote_retrieve_body($response));
2062 -
2063 - // Validate that the downloaded file is a PDF
2064 - $mime_type = mime_content_type($temp_file);
2065 - if ($mime_type !== 'application/pdf') {
2066 - //error_log(esc_html__("Invalid MIME type detected for PDF: ", 'mxchat') . $mime_type);
2067 - unlink($temp_file);
2068 - return false;
2069 - }
2070 - } else {
2071 - // For local files, use the provided path directly
2072 - $temp_file = $pdf_source;
2073 - }
2074 -
2075 - // Parse and process the PDF
2076 - $parser = new \Smalot\PdfParser\Parser();
2077 - $pdf = $parser->parseFile($temp_file);
2078 - $pages = $pdf->getPages();
2079 -
2080 - if (count($pages) > $max_pages) {
2081 - //error_log(esc_html__("PDF exceeds the maximum allowed pages: ", 'mxchat') . count($pages));
2082 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
2083 - unlink($temp_file);
2084 - }
2085 - return esc_html__('too_many_pages', 'mxchat');
2086 - }
2087 -
2088 - $embeddings = [];
2089 - foreach ($pages as $page_number => $page) {
2090 - $text = $page->getText();
2091 -
2092 - // Ensure text is non-empty before generating embeddings
2093 - if (empty(trim($text))) {
2094 - //error_log(esc_html__("Skipping empty page: ", 'mxchat') . ($page_number + 1));
2095 - continue;
2096 - }
2097 -
2098 - $embedding = $this->mxchat_generate_embedding(
2099 - esc_html__("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
2100 - $this->options['api_key']
2101 - );
2102 -
2103 - if ($embedding) {
2104 - $embeddings[] = [
2105 - 'page_number' => $page_number + 1,
2106 - 'embedding' => $embedding,
2107 - 'text' => $text,
2108 - ];
2109 - } else {
2110 - //error_log(esc_html__("Failed to generate embedding for page ", 'mxchat') . ($page_number + 1));
2111 - }
2112 - }
2113 -
2114 - // Clean up downloaded file if it was from URL
2115 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
2116 - unlink($temp_file);
2117 - }
2118 -
2119 - return $embeddings;
2120 -
2121 - } catch (\Exception $e) {
2122 - // error_log(esc_html__("Error parsing or processing PDF: ", 'mxchat') . $e->getMessage());
2123 -
2124 - // Cleanup in case of exception
2125 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2126 - unlink($temp_file);
2127 - }
2128 -
2129 - return false;
2130 - }
2131 -}
2132 -private function find_relevant_pdf_pages($query_embedding, $embeddings) {
2133 - //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
2134 -
2135 - $most_relevant = null;
2136 - $highest_similarity = -INF;
2137 -
2138 - foreach ($embeddings as $page_data) {
2139 - $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
2140 -
2141 - if ($similarity > $highest_similarity) {
2142 - $highest_similarity = $similarity;
2143 - $most_relevant = $page_data['page_number'];
2144 - }
2145 - }
2146 -
2147 - if (!is_null($most_relevant)) {
2148 - $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
2149 - return array_filter($embeddings, function ($page) use ($page_numbers) {
2150 - return in_array($page['page_number'], $page_numbers);
2151 - });
2152 - }
2153 -
2154 - return [];
2155 -}
2156 -// Add this to your class
2157 -public function handle_pdf_upload() {
2158 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
2159 -
2160 - if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
2161 - wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
2162 - return;
2163 - }
2164 -
2165 - $file = $_FILES['pdf_file'];
2166 - $session_id = sanitize_text_field($_POST['session_id']);
2167 - $original_filename = sanitize_text_field($file['name']);
2168 -
2169 - $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
2170 - if ($file_type['type'] !== 'application/pdf') {
2171 - wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
2172 - return;
2173 - }
2174 -
2175 - $upload_dir = wp_upload_dir();
2176 - $pdf_filename = 'mxchat_' . $session_id . '_' . time() . '.pdf';
2177 - $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
2178 -
2179 - if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
2180 - wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
2181 - return;
2182 - }
2183 -
2184 - $this->clear_pdf_transients($session_id);
2185 -
2186 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2187 - $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
2188 -
2189 - if ($embeddings === 'too_many_pages') {
2190 - unlink($pdf_path);
2191 - $error_message = sprintf(
2192 - $this->options['pdf_intent_error_text'] ??
2193 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
2194 - $max_pages
2195 - );
2196 - wp_send_json_error($error_message);
2197 - return;
2198 - }
2199 -
2200 - if ($embeddings === false || empty($embeddings)) {
2201 - unlink($pdf_path);
2202 - $error_message = $this->options['pdf_intent_error_text'] ??
2203 - esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
2204 - wp_send_json_error($error_message);
2205 - return;
2206 - }
2207 -
2208 - if (!empty($embeddings)) {
2209 - set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
2210 - set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
2211 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
2212 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
2213 -
2214 - $success_message = $this->options['pdf_intent_success_text'] ??
2215 - esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
2216 -
2217 - wp_send_json_success([
2218 - 'message' => $success_message,
2219 - 'filename' => $original_filename
2220 - ]);
2221 - return;
2222 - }
2223 -
2224 - unlink($pdf_path);
2225 - $error_message = $this->options['pdf_intent_error_text'] ??
2226 - esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
2227 - wp_send_json_error($error_message);
2228 - return;
2229 -}
2230 -public function handle_pdf_remove() {
2231 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
2232 -
2233 - if (empty($_POST['session_id'])) {
2234 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
2235 - wp_die();
2236 - }
2237 -
2238 - $session_id = sanitize_text_field($_POST['session_id']);
2239 - $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
2240 -
2241 - if ($pdf_path && file_exists($pdf_path)) {
2242 - unlink($pdf_path);
2243 - }
2244 -
2245 - $this->clear_pdf_transients($session_id);
2246 -
2247 - wp_send_json_success([
2248 - 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2249 - ]);
2250 - wp_die();
2251 -}
2252 -
2253 -
2254 -/**
2255 - * Calls the AI API with the provided prompt.
2256 - *
2257 - * @param string $prompt The prompt to send to the AI.
2258 - * @return array An array containing the AI's response text.
2259 - */
2260 -private function mxchat_call_ai_api( $prompt ) {
2261 - //error_log( esc_html__( 'Calling AI API with the provided prompt.', 'mxchat' ) );
2262 -
2263 - $api_key = $this->options['api_key'];
2264 - if ( empty( $api_key ) ) {
2265 - //error_log( esc_html__( 'API key is not set.', 'mxchat' ) );
2266 - return [ 'text' => esc_html__( 'API key is not set.', 'mxchat' ) ];
2267 - }
2268 -
2269 - $url = 'https://api.openai.com/v1/chat/completions';
2270 - $messages = [
2271 - [
2272 - 'role' => 'system',
2273 - 'content' => __( 'You are a helpful assistant that provides concise and personalized product recommendations. Someone has asked you for some recommendations please respond very concisely appropriate for an AI chatbot.', 'mxchat' ),
2274 - ],
2275 - [
2276 - 'role' => 'user',
2277 - 'content' => $prompt,
2278 - ],
2279 - ];
2280 -
2281 - $args = [
2282 - 'headers' => [
2283 - 'Authorization' => 'Bearer ' . $api_key,
2284 - 'Content-Type' => 'application/json',
2285 - ],
2286 - 'body' => wp_json_encode(
2287 - [
2288 - 'model' => 'gpt-4o',
2289 - 'messages' => $messages,
2290 - 'temperature' => 0.7,
2291 - ]
2292 - ),
2293 - 'timeout' => 10,
2294 - 'method' => 'POST',
2295 - ];
2296 -
2297 - $response = wp_remote_post( $url, $args );
2298 -
2299 - if ( is_wp_error( $response ) ) {
2300 - //error_log( esc_html__( 'Error communicating with AI API: ', 'mxchat' ) . $response->get_error_message() );
2301 - return [ 'text' => esc_html__( 'Error communicating with AI API.', 'mxchat' ) ];
2302 - }
2303 -
2304 - $body = wp_remote_retrieve_body( $response );
2305 - //error_log( esc_html__( 'API response body: ', 'mxchat' ) . $body );
2306 -
2307 - $decoded_body = json_decode( $body, true );
2308 - if ( isset( $decoded_body['choices'][0]['message']['content'] ) ) {
2309 - return [ 'text' => $decoded_body['choices'][0]['message']['content'] ];
2310 - } else {
2311 - //error_log( esc_html__( 'Unexpected API response format: ', 'mxchat' ) . wp_json_encode( $decoded_body ) );
2312 - return [ 'text' => esc_html__( 'No response received from AI.', 'mxchat' ) ];
2313 - }
2314 -}
2315 -
2316 -/**
2317 - * Fetches the AI response for the given prompt.
2318 - *
2319 - * @param string $prompt The prompt to send to the AI.
2320 - * @return string|null The AI's response text or null if not available.
2321 - */
2322 -private function mxchat_fetch_ai_response( $prompt ) {
2323 - $response = $this->mxchat_call_ai_api( $prompt );
2324 - return isset( $response['text'] ) ? $response['text'] : null;
2325 -}
2326 -/**
2327 - * Generates the AI prompt for product recommendations.
2328 - *
2329 - * @param array $recommendations An array of product recommendations.
2330 - * @return string The generated AI prompt.
2331 - */
2332 -private function mxchat_generate_ai_recommendation_prompt($recommendations) {
2333 - $recommendation_list = '';
2334 - foreach ($recommendations as $index => $rec) {
2335 - $number = $index + 1;
2336 - $name = $rec['name'];
2337 - $price = $rec['price'];
2338 - $url = $rec['url'];
2339 - $image = $rec['image'];
2340 - $recommendation_list .= "{$number}. " . esc_html__('Product:', 'mxchat') . " {$name} (" . esc_html__('Price:', 'mxchat') . " \\${$price})\n";
2341 - $recommendation_list .= " [Link]({$url})\n";
2342 - $recommendation_list .= " ![Image]({$image})\n\n";
2343 - }
2344 -
2345 - $prompt = esc_html__('Based on the following list of products, generate a unique, friendly, and personalized response to a user. ', 'mxchat');
2346 - $prompt .= esc_html__('If some products aren\'t exactly what the user asked for but share similar styles or patterns, acknowledge this and explain why you\'re suggesting them. ', 'mxchat');
2347 - $prompt .= esc_html__('For each product, provide a brief justification that clearly explains why it\'s relevant, especially if it\'s a different type of product than requested. ', 'mxchat');
2348 - $prompt .= esc_html__('Please number your responses to match the product numbers.', 'mxchat') . "\n\n";
2349 - $prompt .= esc_html__('Products:', 'mxchat') . "\n\n{$recommendation_list}";
2350 - $prompt .= esc_html__('Please ensure that the number of each product matches the order in which the products are listed.', 'mxchat');
2351 -
2352 - return $prompt;
2353 -}
2354 -private function mxchat_generate_recommendations($user_id, $message) {
2355 - // 1. Gather user context
2356 - $user_context = $this->mxchat_get_user_context($user_id);
2357 -
2358 - // Get cart item IDs for filtering
2359 - $cart_item_ids = [];
2360 - if (!empty($user_context['cart_items'])) {
2361 - $cart_item_ids = array_map(function($item) {
2362 - return $item['product_id'];
2363 - }, $user_context['cart_items']);
2364 - }
2365 -
2366 - // 2. Get AI recommendation based on context
2367 - $ai_suggestion = $this->mxchat_get_ai_shopping_suggestion($message, $user_context);
2368 - //error_log("AI Shopping Suggestion: " . $ai_suggestion);
2369 -
2370 - // 3. Generate embedding for the AI suggestion
2371 - $suggestion_embedding = $this->mxchat_generate_embedding($ai_suggestion, $this->options['api_key']);
2372 - if (!$suggestion_embedding) {
2373 - //error_log("Could not generate embedding for AI suggestion");
2374 - return ['recommendations' => [], 'sources' => []];
2375 - }
2376 -
2377 - // 4. Use existing relevant content function to find matches
2378 - $relevant_content = $this->mxchat_find_relevant_content($suggestion_embedding);
2379 -
2380 - // 5. Extract product URLs from the relevant content
2381 - preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
2382 -
2383 - $found_products = [];
2384 - if (!empty($matches[0])) {
2385 - foreach ($matches[0] as $url) {
2386 - // Clean the URL
2387 - $url = rtrim($url, '/."\']');
2388 -
2389 - // Get the product slug
2390 - $path = parse_url($url, PHP_URL_PATH);
2391 - $slug = basename(rtrim($path, '/'));
2392 -
2393 - // Find product by slug
2394 - $args = array(
2395 - 'post_type' => 'product',
2396 - 'post_status' => 'publish',
2397 - 'name' => $slug,
2398 - 'posts_per_page' => 1
2399 - );
2400 -
2401 - $products = get_posts($args);
2402 -
2403 - if (!empty($products)) {
2404 - $product_id = $products[0]->ID;
2405 -
2406 - // Skip if product is in cart
2407 - if (in_array($product_id, $cart_item_ids)) {
2408 - //error_log("Skipping product ID $product_id - already in cart");
2409 - continue;
2410 - }
2411 -
2412 - $product = wc_get_product($product_id);
2413 -
2414 - if ($product && $product->is_purchasable() && !in_array($product_id, array_map(function($p) {
2415 - return $p->get_id();
2416 - }, $found_products))) {
2417 - $found_products[] = $product;
2418 - }
2419 - }
2420 - }
2421 - }
2422 -
2423 - // If no products found by URLs, look for product names in the content
2424 - if (empty($found_products)) {
2425 - $products = wc_get_products([
2426 - 'status' => 'publish',
2427 - 'limit' => -1,
2428 - 'return' => 'objects'
2429 - ]);
2430 -
2431 - foreach ($products as $product) {
2432 - // Skip if product is in cart
2433 - if (in_array($product->get_id(), $cart_item_ids)) {
2434 - continue;
2435 - }
2436 -
2437 - $name = $product->get_name();
2438 - if (stripos($relevant_content, $name) !== false) {
2439 - if ($product->is_purchasable() && !in_array($product->get_id(), array_map(function($p) {
2440 - return $p->get_id();
2441 - }, $found_products))) {
2442 - $found_products[] = $product;
2443 - }
2444 - }
2445 - }
2446 - }
2447 -
2448 - // Keep searching until we have 4 products or run out of options
2449 - $formatted_recommendations = [];
2450 - foreach ($found_products as $product) {
2451 - if (count($formatted_recommendations) >= 4) break;
2452 -
2453 - $formatted_recommendations[] = [
2454 - 'name' => $product->get_name(),
2455 - 'price' => $product->get_price(),
2456 - 'url' => get_permalink($product->get_id()),
2457 - 'image' => wp_get_attachment_url($product->get_image_id())
2458 - ];
2459 - }
2460 -
2461 - return [
2462 - 'recommendations' => $formatted_recommendations,
2463 - 'sources' => [__('AI-powered personalized recommendations', 'mxchat')]
2464 - ];
2465 -}
2466 -private function mxchat_get_ai_shopping_suggestion($message, $user_context) {
2467 - $prompt = esc_html__("As a shopping assistant, analyze this user's context and generate a specific product search suggestion. ", 'mxchat');
2468 - $prompt .= esc_html__("User's Question: \"{$message}\"\n\n", 'mxchat');
2469 -
2470 - if (!empty($user_context['order_history'])) {
2471 - $prompt .= esc_html__("Their recent orders include:\n", 'mxchat');
2472 - foreach ($user_context['order_history'] as $order) {
2473 - $prompt .= esc_html__("- {$order['name']} ({$order['date']})\n", 'mxchat');
2474 - }
2475 - }
2476 -
2477 - if (!empty($user_context['cart_items'])) {
2478 - $prompt .= esc_html__("\nThey currently have in their cart:\n", 'mxchat');
2479 - foreach ($user_context['cart_items'] as $item) {
2480 - $prompt .= esc_html__("- {$item['name']}\n", 'mxchat');
2481 - }
2482 - }
2483 -
2484 - $prompt .= esc_html__("\nBased on their question and history, suggest a specific search query that would help find the most relevant products. ", 'mxchat');
2485 - $prompt .= esc_html__("Respond with ONLY the search query, nothing else.", 'mxchat');
2486 -
2487 - $response = $this->mxchat_call_ai_api($prompt);
2488 - return isset($response['text']) ? trim($response['text']) : $message;
2489 -}
2490 -public function mxchat_handle_product_recommendations($message, $user_id, $session_id) {
2491 - try {
2492 - //error_log("Starting product recommendations for user: $user_id, session: $session_id");
2493 -
2494 - // Pass the message to get context-aware recommendations
2495 - $recommendation_data = $this->mxchat_generate_recommendations($user_id, $message);
2496 - //error_log('Generated recommendation data: ' . wp_json_encode($recommendation_data));
2497 -
2498 - if (empty($recommendation_data['recommendations'])) {
2499 - //error_log("No recommendations found for user: $user_id");
2500 - $this->fallbackResponse = [
2501 - 'text' => __("I couldn't find any product recommendations for you right now. Please try again later!", 'mxchat'),
2502 - ];
2503 - return;
2504 - }
2505 -
2506 - // Remove duplicates and limit to top 4 recommendations
2507 - $unique_recommendations = [];
2508 - foreach ($recommendation_data['recommendations'] as $rec) {
2509 - $unique_recommendations[$rec['url']] = $rec;
2510 - }
2511 -
2512 - $unique_recommendations = array_slice($unique_recommendations, 0, 4);
2513 - //error_log('Top 4 recommendations: ' . wp_json_encode($unique_recommendations));
2514 -
2515 - $recommendations_summary = [];
2516 - foreach ($unique_recommendations as $rec) {
2517 - $recommendations_summary[] = [
2518 - 'name' => $rec['name'],
2519 - 'price' => strip_tags($rec['price']),
2520 - 'url' => $rec['url'],
2521 - 'image' => $rec['image'],
2522 - ];
2523 - }
2524 -
2525 - // Generate AI prompt and fetch response
2526 - $ai_prompt = $this->mxchat_generate_ai_recommendation_prompt($recommendations_summary);
2527 - $ai_response = $this->mxchat_fetch_ai_response($ai_prompt);
2528 -
2529 - if (empty($ai_response)) {
2530 - $this->fallbackResponse = [
2531 - 'text' => __('An unexpected error occurred while generating recommendations. Please try again later.', 'mxchat'),
2532 - ];
2533 - return;
2534 - }
2535 -
2536 - // Split the AI's response into lines
2537 - $ai_lines = preg_split('/\r\n|\r|\n/', $ai_response);
2538 -
2539 - // Initialize variables
2540 - $formatted_response = '';
2541 - $justifications = [];
2542 - $current_number = 0;
2543 - $in_introduction = true;
2544 - $introduction = '';
2545 -
2546 - // Parse the AI response to separate the introduction and the justifications
2547 - foreach ($ai_lines as $line) {
2548 - if (preg_match('/^\s*(\d+)\.\s*(.*)$/', $line, $matches)) {
2549 - // This line is a numbered justification
2550 - $current_number = intval($matches[1]) - 1;
2551 - $justifications[$current_number] = $matches[2];
2552 - $in_introduction = false;
2553 - } elseif ($in_introduction) {
2554 - // This line is part of the introduction
2555 - $introduction .= $line . ' ';
2556 - } else {
2557 - // This line is a continuation of the current justification
2558 - if (isset($justifications[$current_number])) {
2559 - $justifications[$current_number] .= ' ' . $line;
2560 - }
2561 - }
2562 - }
2563 -
2564 - // Build the formatted response
2565 - if (!empty($introduction)) {
2566 - $formatted_response .= esc_html(trim($introduction)) . "<br><br>";
2567 - }
2568 -
2569 - foreach ($recommendations_summary as $index => $rec) {
2570 - $name = esc_html($rec['name']);
2571 - $price = number_format((float)$rec['price'], 2, '.', '');
2572 - $url = esc_url($rec['url']);
2573 - $image = esc_url($rec['image']);
2574 -
2575 - $formatted_response .= ($index + 1) . ". <strong>" . $name . "</strong> - <strong>$" . $price . "</strong><br>";
2576 - $formatted_response .= "<img src=\"{$image}\" alt=\"{$name}\" style=\"max-width: 200px; height: auto; display: block; margin: 10px 0;\" /><br>";
2577 -
2578 - if (isset($justifications[$index])) {
2579 - $formatted_response .= "<em>" . esc_html(trim($justifications[$index])) . "</em><br><br>";
2580 - }
2581 - }
2582 -
2583 - $this->fallbackResponse = [
2584 - 'text' => $formatted_response,
2585 - ];
2586 - //error_log('Final formatted response set.');
2587 - } catch (Exception $e) {
2588 - //error_log('Error in mxchat_handle_product_recommendations: ' . $e->getMessage());
2589 - $this->fallbackResponse = [
2590 - 'text' => __('An unexpected error occurred while generating recommendations. Please try again later.', 'mxchat'),
2591 - ];
2592 - }
2593 -}
2594 -private function mxchat_get_user_context($user_id) {
2595 - $context = [
2596 - 'order_history' => [],
2597 - 'cart_items' => [],
2598 - 'recently_viewed' => [],
2599 - ];
2600 -
2601 - // Get order history
2602 - if (is_user_logged_in() && $user_id) {
2603 - $orders = wc_get_orders([
2604 - 'customer_id' => $user_id,
2605 - 'limit' => 5, // Last 5 orders
2606 - 'orderby' => 'date',
2607 - 'order' => 'DESC',
2608 - ]);
2609 -
2610 - foreach ($orders as $order) {
2611 - foreach ($order->get_items() as $item) {
2612 - $context['order_history'][] = [
2613 - 'name' => $item->get_name(),
2614 - 'product_id' => $item->get_product_id(),
2615 - 'date' => $order->get_date_created()->format('Y-m-d')
2616 - ];
2617 - }
2618 - }
2619 - }
2620 -
2621 - // Get cart items
2622 - if (WC()->cart && WC()->cart->get_cart_contents_count() > 0) {
2623 - foreach (WC()->cart->get_cart() as $cart_item) {
2624 - $product = wc_get_product($cart_item['product_id']);
2625 - if ($product) {
2626 - $context['cart_items'][] = [
2627 - 'name' => $product->get_name(),
2628 - 'product_id' => $product->get_id()
2629 - ];
2630 - }
2631 - }
2632 - }
2633 -
2634 - // Get recently viewed items from session
2635 - $viewed_products = WC()->session->get('recently_viewed_products', []);
2636 - foreach ($viewed_products as $product_id) {
2637 - $product = wc_get_product($product_id);
2638 - if ($product) {
2639 - $context['recently_viewed'][] = [
2640 - 'name' => $product->get_name(),
2641 - 'product_id' => $product->get_id()
2642 - ];
2643 - }
2644 - }
2645 -
2646 - return $context;
2647 -}
2648 -
2649 -
2650 -
2651 -
2652 -
2653 -
2654 -function mxchat_fetch_new_messages() {
2655 - $session_id = sanitize_text_field($_POST['session_id']);
2656 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2657 - $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2658 - $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2659 -
2660 - if (empty($session_id)) {
2661 - //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2662 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2663 - wp_die();
2664 - }
2665 -
2666 - $history = get_option("mxchat_history_{$session_id}", []);
2667 -
2668 - $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2669 - // If persistence is enabled, show all new messages
2670 - if ($persistence_enabled) {
2671 - return !empty($message['id']) &&
2672 - strcmp($message['id'], $last_seen_id) > 0 &&
2673 - $message['role'] === 'agent';
2674 - }
2675 -
2676 - // If persistence is disabled, only show messages after initial timestamp
2677 - return !empty($message['id']) &&
2678 - $message['role'] === 'agent' &&
2679 - $message['timestamp'] > $initial_timestamp;
2680 - });
2681 -
2682 - //error_log(esc_html__("New agent messages fetched for session $session_id. Last seen ID: $last_seen_id", 'mxchat'));
2683 -
2684 - wp_send_json_success([
2685 - 'new_messages' => array_values($new_messages)
2686 - ]);
2687 - wp_die();
2688 -}
2689 -
2690 -
2691 -public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2692 - // First check if live agents are available
2693 - $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2694 - if ($live_agent_available !== 'on') {
2695 - $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2696 - $this->fallbackResponse = [
2697 - 'text' => $away_message,
2698 - 'html' => '',
2699 - 'images' => [],
2700 - 'chat_mode' => 'ai'
2701 - ];
2702 - wp_send_json([
2703 - 'text' => $away_message,
2704 - 'html' => '',
2705 - 'chat_mode' => 'ai',
2706 - 'session_id' => $session_id
2707 - ]);
2708 - wp_die();
2709 - }
2710 -
2711 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2712 - if (empty($slack_webhook_url)) {
2713 - return false;
2714 - }
2715 -
2716 - // Get recent chat history (last 5 messages)
2717 - $history = get_option("mxchat_history_{$session_id}", []);
2718 - $recent_history = array_slice($history, -5); // Get last 5 messages
2719 -
2720 - // Format conversation history
2721 - $conversation_context = "";
2722 - if (!empty($recent_history)) {
2723 - $conversation_context = "*Recent Conversation:*\n";
2724 - foreach ($recent_history as $hist_message) {
2725 - $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
2726 - $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
2727 - }
2728 - $conversation_context .= "\n";
2729 - }
2730 -
2731 - update_option("mxchat_mode_{$session_id}", 'agent');
2732 -
2733 - $webhook_data = [
2734 - 'blocks' => [
2735 - [
2736 - 'type' => 'header',
2737 - 'text' => [
2738 - 'type' => 'plain_text',
2739 - 'text' => '🔔 New Live Agent Request',
2740 - 'emoji' => true
2741 - ]
2742 - ],
2743 - [
2744 - 'type' => 'section',
2745 - 'fields' => [
2746 - [
2747 - 'type' => 'mrkdwn',
2748 - 'text' => sprintf('*User ID:*\n`%s`', $user_id)
2749 - ],
2750 - [
2751 - 'type' => 'mrkdwn',
2752 - 'text' => sprintf('*Session ID:*\n`%s`', $session_id)
2753 - ]
2754 - ]
2755 - ]
2756 - ]
2757 - ];
2758 -
2759 - // Add conversation history if exists
2760 - if (!empty($conversation_context)) {
2761 - $webhook_data['blocks'][] = [
2762 - 'type' => 'section',
2763 - 'text' => [
2764 - 'type' => 'mrkdwn',
2765 - 'text' => $conversation_context
2766 - ]
2767 - ];
2768 - }
2769 -
2770 - // Add the current message
2771 - $webhook_data['blocks'][] = [
2772 - 'type' => 'section',
2773 - 'text' => [
2774 - 'type' => 'mrkdwn',
2775 - 'text' => sprintf('*Current Message:*\n%s', $message)
2776 - ]
2777 - ];
2778 -
2779 - // Add the reply button
2780 - $webhook_data['blocks'][] = [
2781 - 'type' => 'actions',
2782 - 'elements' => [
2783 - [
2784 - 'type' => 'button',
2785 - 'text' => [
2786 - 'type' => 'plain_text',
2787 - 'text' => '✍️ Reply',
2788 - 'emoji' => true
2789 - ],
2790 - 'value' => $session_id,
2791 - 'action_id' => 'reply_to_user',
2792 - 'style' => 'primary'
2793 - ]
2794 - ]
2795 - ];
2796 -
2797 - $response = wp_remote_post($slack_webhook_url, [
2798 - 'body' => json_encode($webhook_data),
2799 - 'headers' => [
2800 - 'Content-Type' => 'application/json',
2801 - ],
2802 - ]);
2803 -
2804 - if (is_wp_error($response)) {
2805 - return false;
2806 - }
2807 -
2808 - $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
2809 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
2810 -
2811 - $this->fallbackResponse = [
2812 - 'text' => $success_message,
2813 - 'html' => '',
2814 - 'images' => [],
2815 - 'chat_mode' => 'agent'
2816 - ];
2817 -
2818 - wp_send_json([
2819 - 'success' => true,
2820 - 'text' => $success_message,
2821 - 'html' => '',
2822 - 'chat_mode' => 'agent',
2823 - 'session_id' => $session_id,
2824 - 'fallbackResponse' => $this->fallbackResponse
2825 - ]);
2826 - wp_die();
2827 -}
2828 -public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
2829 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2830 -
2831 - if (empty($slack_webhook_url)) {
2832 - //error_log(esc_html__('Slack Webhook URL is not configured.', 'mxchat'));
2833 - return false;
2834 - }
2835 -
2836 - $webhook_data = [
2837 - 'blocks' => [
2838 - [
2839 - 'type' => 'header',
2840 - 'text' => [
2841 - 'type' => 'plain_text',
2842 - 'text' => esc_html__('📩 New Chat Message', 'mxchat'),
2843 - 'emoji' => true
2844 - ]
2845 - ],
2846 - [
2847 - 'type' => 'section',
2848 - 'fields' => [
2849 - [
2850 - 'type' => 'mrkdwn',
2851 - 'text' => sprintf(esc_html__('*User ID:*\n`%s`', 'mxchat'), $user_id)
2852 - ],
2853 - [
2854 - 'type' => 'mrkdwn',
2855 - 'text' => sprintf(esc_html__('*Session ID:*\n`%s`', 'mxchat'), $session_id)
2856 - ]
2857 - ]
2858 - ],
2859 - [
2860 - 'type' => 'section',
2861 - 'text' => [
2862 - 'type' => 'mrkdwn',
2863 - 'text' => sprintf(esc_html__('*Message:*\n%s', 'mxchat'), $message)
2864 - ]
2865 - ],
2866 - [
2867 - 'type' => 'actions',
2868 - 'elements' => [
2869 - [
2870 - 'type' => 'button',
2871 - 'text' => [
2872 - 'type' => 'plain_text',
2873 - 'text' => esc_html__('✍️ Reply', 'mxchat'),
2874 - 'emoji' => true
2875 - ],
2876 - 'value' => $session_id,
2877 - 'action_id' => 'reply_to_user',
2878 - 'style' => 'primary'
2879 - ]
2880 - ]
2881 - ]
2882 - ]
2883 - ];
2884 -
2885 - $response = wp_remote_post($slack_webhook_url, [
2886 - 'body' => json_encode($webhook_data),
2887 - 'headers' => [
2888 - 'Content-Type' => 'application/json',
2889 - ],
2890 - ]);
2891 -
2892 - if (is_wp_error($response)) {
2893 - //error_log(esc_html__('Error sending message to Slack: ', 'mxchat') . $response->get_error_message());
2894 - return false;
2895 - }
2896 -
2897 - //error_log(esc_html__('Message sent to Slack successfully.', 'mxchat'));
2898 - return true;
2899 -}
2900 -public function handle_slack_interaction(WP_REST_Request $request) {
2901 - //error_log('Received Slack interaction');
2902 -
2903 - $payload = json_decode($request->get_param('payload'), true);
2904 - //error_log('Payload: ' . print_r($payload, true));
2905 -
2906 - // Handle button click
2907 - if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
2908 - $session_id = $payload['actions'][0]['value'];
2909 - $trigger_id = $payload['trigger_id'];
2910 -
2911 - // Get Bot Token from settings
2912 - $slack_token = $this->options['live_agent_bot_token'] ?? '';
2913 -
2914 - if (empty($slack_token)) {
2915 - //error_log('Slack Bot Token not configured');
2916 - return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
2917 - }
2918 - $response = wp_remote_post('https://slack.com/api/views.open', [
2919 - 'headers' => [
2920 - 'Content-Type' => 'application/json',
2921 - 'Authorization' => 'Bearer ' . $slack_token
2922 - ],
2923 - 'body' => json_encode([
2924 - 'trigger_id' => $trigger_id,
2925 - 'view' => [
2926 - 'type' => 'modal',
2927 - 'callback_id' => 'reply_modal',
2928 - 'title' => [
2929 - 'type' => 'plain_text',
2930 - 'text' => __('Reply to User', 'mxchat')
2931 - ],
2932 - 'submit' => [
2933 - 'type' => 'plain_text',
2934 - 'text' => __('Send', 'mxchat')
2935 - ],
2936 - 'close' => [
2937 - 'type' => 'plain_text',
2938 - 'text' => __('Cancel', 'mxchat')
2939 - ],
2940 - 'blocks' => [
2941 - [
2942 - 'type' => 'input',
2943 - 'block_id' => 'reply_block',
2944 - 'label' => [
2945 - 'type' => 'plain_text',
2946 - 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
2947 - ],
2948 - 'element' => [
2949 - 'type' => 'plain_text_input',
2950 - 'action_id' => 'message',
2951 - 'multiline' => true,
2952 - 'placeholder' => [
2953 - 'type' => 'plain_text',
2954 - 'text' => __('Type your message here...', 'mxchat')
2955 - ]
2956 - ]
2957 - ]
2958 - ],
2959 - 'private_metadata' => $session_id
2960 - ]
2961 - ])
2962 - ]);
2963 -
2964 - //error_log('Views.open response: ' . print_r($response, true));
2965 -
2966 - // Return immediate acknowledgment
2967 - return new WP_REST_Response(['ok' => true]);
2968 - }
2969 -
2970 - // Handle modal submission
2971 -// Handle modal submission
2972 -if ($payload['type'] === 'view_submission') {
2973 - $session_id = $payload['view']['private_metadata'];
2974 - $message = $payload['view']['state']['values']['reply_block']['message']['value'];
2975 -
2976 - // Save the message (keep the message_id but don't include in response)
2977 - $this->mxchat_save_chat_message($session_id, 'agent', $message);
2978 -
2979 - // Keep the original response format for Slack
2980 - return new WP_REST_Response([
2981 - 'response_action' => 'clear'
2982 - ]);
2983 -}
2984 -
2985 - // Default acknowledgment
2986 - return new WP_REST_Response(['ok' => true]);
2987 -}
2988 -
2989 -public function mxchat_handle_agent_response(WP_REST_Request $request) {
2990 - //error_log('Received agent response request');
2991 - //error_log('Request data: ' . print_r($request->get_params(), true));
2992 - // error_log('Raw body: ' . file_get_contents('php://input'));
2993 -
2994 - // Get the data from Slack's slash command format
2995 - $command_text = $request->get_param('text');
2996 - // error_log('Command text: ' . $command_text);
2997 -
2998 - if (empty($command_text)) {
2999 - //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
3000 - return new WP_REST_Response([
3001 - 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
3002 - ], 400);
3003 - }
3004 -
3005 - // Split the command text into session_id and message
3006 - $parts = explode(' ', $command_text, 2);
3007 - if (count($parts) !== 2) {
3008 - //error_log('Agent response error: Invalid command format');
3009 - return new WP_REST_Response([
3010 - 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
3011 - ], 400);
3012 - }
3013 -
3014 - $session_id = sanitize_text_field($parts[0]);
3015 - $message = sanitize_text_field($parts[1]);
3016 -
3017 - //error_log("Processing agent response - Session ID: $session_id, Message: $message");
3018 -
3019 - // Save the message
3020 - $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
3021 -
3022 - if (!$message_id) {
3023 - // error_log('Failed to save agent message');
3024 - return new WP_REST_Response([
3025 - 'error' => esc_html__('Failed to save message', 'mxchat')
3026 - ], 500);
3027 - }
3028 -
3029 - // Return success response in Slack's expected format
3030 - return new WP_REST_Response([
3031 - 'response_type' => 'in_channel',
3032 - 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
3033 - ], 200);
3034 -}
3035 -
3036 -
3037 -public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
3038 - //error_log(esc_html__("Switching back to chatbot mode via intent.", 'mxchat'));
3039 -
3040 - // Just update mode to AI
3041 - update_option("mxchat_mode_{$session_id}", 'ai');
3042 -
3043 - // Initialize states
3044 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
3045 - $this->productCardHtml = '';
3046 -
3047 - // Set the response message
3048 - $this->fallbackResponse['text'] = esc_html__('You are now chatting with the AI chatbot.', 'mxchat');
3049 -
3050 - return true; // Intent was handled
3051 -}
3052 -
3053 -
3054 -
3055 -
3056 -// For the word upload handler
3057 -public function mxchat_handle_word_upload() {
3058 - // Delegate to word handler
3059 - $this->word_handler->mxchat_handle_word_upload();
3060 -}
3061 -
3062 -// For the word removal handler
3063 -public function mxchat_handle_word_remove() {
3064 - // Delegate to word handler
3065 - $this->word_handler->mxchat_handle_word_remove();
3066 -}
3067 -
3068 -// For the word status check
3069 -public function mxchat_check_word_status() {
3070 - // Delegate to word handler
3071 - $this->word_handler->mxchat_check_word_status();
3072 -}
3073 -
3074 -
3075 -private function mxchat_get_user_identifier() {
3076 - return MxChat_User::mxchat_get_user_identifier();
3077 -}
3078 -
3079 -private function mxchat_generate_embedding($text, $api_key) {
3080 - $endpoint = 'https://api.openai.com/v1/embeddings';
3081 -
3082 - $body = wp_json_encode([
3083 - 'input' => $text,
3084 - 'model' => 'text-embedding-ada-002'
3085 - ]);
3086 -
3087 - $args = [
3088 - 'body' => $body,
3089 - 'headers' => [
3090 - 'Content-Type' => 'application/json',
3091 - 'Authorization' => 'Bearer ' . $api_key,
3092 - ],
3093 - 'timeout' => 60,
3094 - 'redirection' => 5,
3095 - 'blocking' => true,
3096 - 'httpversion' => '1.0',
3097 - 'sslverify' => true,
3098 - ];
3099 -
3100 - $response = wp_remote_post($endpoint, $args);
3101 -
3102 - if (is_wp_error($response)) {
3103 - return null;
3104 - }
3105 -
3106 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3107 -
3108 - if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
3109 - return $response_body['data'][0]['embedding'];
3110 - } else {
3111 - return null;
3112 - }
3113 - }
3114 -
3115 -
3116 -private function mxchat_find_relevant_content($user_embedding) {
3117 - //error_log('MXChat Vector Search: Starting content search...');
3118 -
3119 - // Retrieve the add-on settings from the database.
3120 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
3121 -
3122 - // Determine whether Pinecone is enabled.
3123 - // We expect the sanitized setting to be a string '1' if enabled, otherwise '0'.
3124 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
3125 -
3126 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
3127 -
3128 - if ($use_pinecone === 1) {
3129 - //error_log('MXChat Vector Search: Using Pinecone database');
3130 - return $this->find_relevant_content_pinecone($user_embedding);
3131 - } else {
3132 - //error_log('MXChat Vector Search: Using WordPress database');
3133 - return $this->find_relevant_content_wordpress($user_embedding);
3134 - }
3135 -}
3136 -
3137 -private function find_relevant_content_wordpress($user_embedding) {
3138 - global $wpdb;
3139 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3140 - $cache_key = 'mxchat_system_prompt_embeddings';
3141 - $batch_size = 500;
3142 -
3143 - // Retrieve embeddings from cache or database
3144 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
3145 - if ($embeddings === false) {
3146 - $embeddings = [];
3147 - $offset = 0;
3148 -
3149 - // Load in batches and build cache
3150 - do {
3151 - $query = $wpdb->prepare(
3152 - "SELECT id, embedding_vector
3153 - FROM {$system_prompt_table}
3154 - LIMIT %d OFFSET %d",
3155 - $batch_size,
3156 - $offset
3157 - );
3158 -
3159 - $batch = $wpdb->get_results($query);
3160 - if (empty($batch)) {
3161 - break;
3162 - }
3163 -
3164 - $embeddings = array_merge($embeddings, $batch);
3165 - $offset += $batch_size;
3166 -
3167 - // Free memory
3168 - unset($batch);
3169 -
3170 - } while (true);
3171 -
3172 - if (empty($embeddings)) {
3173 - return ''; // Return an empty string if no embeddings found
3174 - }
3175 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
3176 - }
3177 -
3178 - // Initialize array to store relevant results with similarity scores
3179 - $relevant_results = [];
3180 - // Iterate through embeddings to calculate similarity
3181 - foreach ($embeddings as $embedding) {
3182 - $database_embedding = $embedding->embedding_vector
3183 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
3184 - : null;
3185 - if (is_array($database_embedding) && is_array($user_embedding)) {
3186 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
3187 - $relevant_results[] = [
3188 - 'id' => $embedding->id,
3189 - 'similarity' => $similarity
3190 - ];
3191 - }
3192 - // Free memory
3193 - unset($database_embedding);
3194 - }
3195 -
3196 - // Retrieve the similarity threshold
3197 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
3198 -
3199 - // Filter and sort relevant results by similarity
3200 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
3201 - return $result['similarity'] >= $similarity_threshold;
3202 - });
3203 - usort($relevant_results, function ($a, $b) {
3204 - return $b['similarity'] <=> $a['similarity'];
3205 - });
3206 -
3207 - // Limit to the top 5 results
3208 - $top_results = array_slice($relevant_results, 0, 5);
3209 -
3210 - // Initialize the final content
3211 - $content = '';
3212 -
3213 - // Fetch and combine content for the top results
3214 - foreach ($top_results as $result) {
3215 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
3216 - // Check if the content is PDF-related and add surrounding pages
3217 - if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
3218 - $surrounding_content = $wpdb->get_results($wpdb->prepare(
3219 - "SELECT article_content FROM {$system_prompt_table}
3220 - WHERE id IN (
3221 - (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
3222 - (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
3223 - )",
3224 - $result['id'],
3225 - $result['id']
3226 - ));
3227 - // Add previous content if it exists
3228 - if (!empty($surrounding_content[0])) {
3229 - $content .= $surrounding_content[0]->article_content . "\n\n";
3230 - }
3231 - // Add the main chunk content
3232 - $content .= $chunk_content . "\n\n";
3233 - // Add next content if it exists
3234 - if (!empty($surrounding_content[1])) {
3235 - $content .= $surrounding_content[1]->article_content . "\n\n";
3236 - }
3237 - } else {
3238 - // For non-PDF content, add directly
3239 - $content .= $chunk_content . "\n\n";
3240 - }
3241 - }
3242 -
3243 - return trim($content);
3244 -}
3245 -/**
3246 - * Find relevant content in Pinecone vector database
3247 - */
3248 -private function find_relevant_content_pinecone($user_embedding) {
3249 - $options = get_option('mxchat_pinecone_addon_options', array());
3250 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
3251 - $host = $options['mxchat_pinecone_host'] ?? '';
3252 -
3253 - if (empty($host) || empty($api_key)) {
3254 - //error_log('Pinecone credentials not properly configured');
3255 - return '';
3256 - }
3257 -
3258 - // Get similarity threshold from WordPress settings
3259 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
3260 -
3261 - // Prepare the query request for Pinecone
3262 - $api_endpoint = "https://{$host}/query";
3263 -
3264 - $request_body = array(
3265 - 'vector' => $user_embedding,
3266 - 'topK' => 5,
3267 - 'includeMetadata' => true,
3268 - 'includeValues' => true
3269 - );
3270 -
3271 - $response = wp_remote_post($api_endpoint, array(
3272 - 'headers' => array(
3273 - 'Api-Key' => $api_key,
3274 - 'accept' => 'application/json',
3275 - 'content-type' => 'application/json'
3276 - ),
3277 - 'body' => wp_json_encode($request_body),
3278 - 'timeout' => 30
3279 - ));
3280 -
3281 - if (is_wp_error($response)) {
3282 - //error_log('Pinecone query error: ' . $response->get_error_message());
3283 - return '';
3284 - }
3285 -
3286 - $response_code = wp_remote_retrieve_response_code($response);
3287 - if ($response_code !== 200) {
3288 - //error_log('Pinecone API error: ' . wp_remote_retrieve_body($response));
3289 - return '';
3290 - }
3291 -
3292 - $results = json_decode(wp_remote_retrieve_body($response), true);
3293 - if (empty($results['matches'])) {
3294 - return '';
3295 - }
3296 -
3297 - // Initialize the final content
3298 - $content = '';
3299 -
3300 - // Process each match
3301 - foreach ($results['matches'] as $match) {
3302 - // Skip if similarity is below threshold
3303 - if ($match['score'] < $similarity_threshold) {
3304 - continue;
3305 - }
3306 -
3307 - if (!empty($match['metadata']['text']) && !empty($match['metadata']['source_url'])) {
3308 - // Add content with citation
3309 - $content .= $match['metadata']['text'] . "\n";
3310 - $content .= "Source: " . $match['metadata']['source_url'] . "\n\n";
3311 - }
3312 - }
3313 -
3314 - return trim($content);
3315 -}
3316 -
3317 -
3318 -private function mxchat_find_relevant_products($user_embedding) {
3319 - //error_log('MXChat Vector Search: Starting product search...');
3320 -
3321 - // Retrieve the add-on settings from the database
3322 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
3323 -
3324 - // Determine whether Pinecone is enabled
3325 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
3326 -
3327 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
3328 -
3329 - if ($use_pinecone === 1) {
3330 - //error_log('MXChat Vector Search: Using Pinecone database for products');
3331 - return $this->find_relevant_products_pinecone($user_embedding);
3332 - } else {
3333 - //error_log('MXChat Vector Search: Using WordPress database for products');
3334 - return $this->find_relevant_products_wordpress($user_embedding);
3335 - }
3336 -}
3337 -
3338 -private function find_relevant_products_wordpress($user_embedding) {
3339 - global $wpdb;
3340 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3341 - $cache_key = 'mxchat_system_prompt_embeddings';
3342 - $batch_size = 500;
3343 -
3344 - // Original WordPress database search logic
3345 - // [Previous implementation remains the same]
3346 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
3347 - if ($embeddings === false) {
3348 - $embeddings = [];
3349 - $offset = 0;
3350 -
3351 - do {
3352 - $query = $wpdb->prepare(
3353 - "SELECT id, embedding_vector
3354 - FROM {$system_prompt_table}
3355 - LIMIT %d OFFSET %d",
3356 - $batch_size,
3357 - $offset
3358 - );
3359 -
3360 - $batch = $wpdb->get_results($query);
3361 - if (empty($batch)) {
3362 - break;
3363 - }
3364 -
3365 - $embeddings = array_merge($embeddings, $batch);
3366 - $offset += $batch_size;
3367 -
3368 - unset($batch);
3369 -
3370 - } while (true);
3371 -
3372 - if (empty($embeddings)) {
3373 - return '';
3374 - }
3375 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
3376 - }
3377 -
3378 - $relevant_results = [];
3379 - foreach ($embeddings as $embedding) {
3380 - $database_embedding = $embedding->embedding_vector
3381 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
3382 - : null;
3383 - if (is_array($database_embedding) && is_array($user_embedding)) {
3384 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
3385 - $relevant_results[] = [
3386 - 'id' => $embedding->id,
3387 - 'similarity' => $similarity
3388 - ];
3389 - }
3390 - unset($database_embedding);
3391 - }
3392 -
3393 - // Use fixed threshold for products
3394 - $similarity_threshold = 0.85;
3395 -
3396 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
3397 - return $result['similarity'] >= $similarity_threshold;
3398 - });
3399 - usort($relevant_results, function ($a, $b) {
3400 - return $b['similarity'] <=> $a['similarity'];
3401 - });
3402 -
3403 - $top_results = array_slice($relevant_results, 0, 5);
3404 - $content = '';
3405 -
3406 - foreach ($top_results as $result) {
3407 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
3408 - $content .= $chunk_content . "\n\n";
3409 - }
3410 -
3411 - return trim($content);
3412 -}
3413 -
3414 -// Modified search function with correct filter syntax
3415 -private function find_relevant_products_pinecone($user_embedding) {
3416 - //error_log('Starting Pinecone product search...');
3417 -
3418 - $options = get_option('mxchat_pinecone_addon_options', array());
3419 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
3420 - $host = $options['mxchat_pinecone_host'] ?? '';
3421 -
3422 - if (empty($host) || empty($api_key)) {
3423 - //error_log('Pinecone credentials not properly configured for product search');
3424 - return '';
3425 - }
3426 -
3427 - $similarity_threshold = 0.85;
3428 - $api_endpoint = "https://{$host}/query";
3429 -
3430 - $request_body = array(
3431 - 'vector' => $user_embedding,
3432 - 'topK' => 5,
3433 - 'includeMetadata' => true,
3434 - 'includeValues' => true,
3435 - 'filter' => array(
3436 - 'type' => 'product'
3437 - )
3438 - );
3439 -
3440 - //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
3441 -
3442 - $response = wp_remote_post($api_endpoint, array(
3443 - 'headers' => array(
3444 - 'Api-Key' => $api_key,
3445 - 'accept' => 'application/json',
3446 - 'content-type' => 'application/json'
3447 - ),
3448 - 'body' => wp_json_encode($request_body),
3449 - 'timeout' => 30
3450 - ));
3451 -
3452 - if (is_wp_error($response)) {
3453 - //error_log('Pinecone product query error: ' . $response->get_error_message());
3454 - return '';
3455 - }
3456 -
3457 - $response_code = wp_remote_retrieve_response_code($response);
3458 - //error_log('Pinecone response code: ' . $response_code);
3459 -
3460 - if ($response_code !== 200) {
3461 - //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
3462 - return '';
3463 - }
3464 -
3465 - $results = json_decode(wp_remote_retrieve_body($response), true);
3466 - //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
3467 -
3468 - if (empty($results['matches'])) {
3469 - //error_log('No matches found in Pinecone response');
3470 - return '';
3471 - }
3472 -
3473 - $content = '';
3474 - foreach ($results['matches'] as $match) {
3475 - if ($match['score'] < $similarity_threshold) {
3476 - //error_log("Match below threshold: " . $match['score']);
3477 - continue;
3478 - }
3479 -
3480 - if (!empty($match['metadata']['text'])) {
3481 - $content .= $match['metadata']['text'];
3482 - if (!empty($match['metadata']['source_url'])) {
3483 - $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
3484 - }
3485 - $content .= "\n\n";
3486 - }
3487 - }
3488 -
3489 - return trim($content);
3490 -}
3491 -
3492 -
3493 -private function fetch_content_with_product_links($most_relevant_id) {
3494 - global $wpdb;
3495 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3496 -
3497 - // Fetch the article content and associated product URL
3498 - $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
3499 - $result = $wpdb->get_row($query);
3500 -
3501 - if ($result) {
3502 - // Append the product link to the content if available
3503 - $content = $result->article_content;
3504 - if (!empty($result->source_url)) {
3505 - $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
3506 - }
3507 - return $content;
3508 - }
3509 -
3510 - return null;
3511 -}
3512 -
3513 -// Function definition
3514 -private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $conversation_history) {
3515 - try {
3516 - if (!$relevant_content) {
3517 - return esc_html__("I'm sorry, I couldn't find relevant information on that topic.", 'mxchat');
3518 - }
3519 -
3520 - // Ensure conversation_history is an array
3521 - if (!is_array($conversation_history)) {
3522 - $conversation_history = array();
3523 - }
3524 -
3525 - // Get selected model with default fallback
3526 - $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
3527 -
3528 - // Extract model prefix to determine the provider
3529 - $model_parts = explode('-', $selected_model);
3530 - $provider = strtolower($model_parts[0]);
3531 -
3532 - // Handle model selection based on provider prefix
3533 - switch ($provider) {
3534 - case 'claude':
3535 - if (empty($claude_api_key)) {
3536 - throw new Exception(esc_html__('Claude API key is not configured', 'mxchat'));
3537 - }
3538 - return $this->mxchat_generate_response_claude(
3539 - $selected_model,
3540 - $claude_api_key,
3541 - $conversation_history,
3542 - $relevant_content
3543 - );
3544 -
3545 - case 'grok':
3546 - if (empty($xai_api_key)) {
3547 - throw new Exception(esc_html__('X.AI API key is not configured', 'mxchat'));
3548 - }
3549 - return $this->mxchat_generate_response_xai(
3550 - $selected_model,
3551 - $xai_api_key,
3552 - $conversation_history,
3553 - $relevant_content
3554 - );
3555 -
3556 - case 'deepseek':
3557 - if (empty($deepseek_api_key)) {
3558 - throw new Exception(esc_html__('DeepSeek API key is not configured', 'mxchat'));
3559 - }
3560 - return $this->mxchat_generate_response_deepseek(
3561 - $selected_model,
3562 - $deepseek_api_key,
3563 - $conversation_history,
3564 - $relevant_content
3565 - );
3566 -
3567 - case 'gpt':
3568 - if (empty($api_key)) {
3569 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
3570 - }
3571 - return $this->mxchat_generate_response_openai(
3572 - $selected_model,
3573 - $api_key,
3574 - $conversation_history,
3575 - $relevant_content
3576 - );
3577 -
3578 - default:
3579 - // Default to OpenAI for custom models or unrecognized prefixes
3580 - if (empty($api_key)) {
3581 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
3582 - }
3583 - return $this->mxchat_generate_response_openai(
3584 - $selected_model,
3585 - $api_key,
3586 - $conversation_history,
3587 - $relevant_content
3588 - );
3589 - }
3590 - } catch (Exception $e) {
3591 - //error_log('MXChat Error: ' . $e->getMessage());
3592 - return sprintf(
3593 - esc_html__('An error occurred: %s', 'mxchat'),
3594 - esc_html($e->getMessage())
3595 - );
3596 - }
3597 -}
3598 -
3599 -
3600 -private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
3601 - // Ensure conversation_history is an array
3602 - if (!is_array($conversation_history)) {
3603 - $conversation_history = array();
3604 - }
3605 -
3606 - // Get system prompt instructions from options
3607 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3608 -
3609 - // Create a new array for the formatted conversation
3610 - $formatted_conversation = array();
3611 -
3612 - // Add system message first
3613 - $formatted_conversation[] = array(
3614 - 'role' => 'system',
3615 - 'content' => $system_prompt_instructions . " " . $relevant_content
3616 - );
3617 -
3618 - // Add the rest of the conversation history
3619 - foreach ($conversation_history as $message) {
3620 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3621 - $role = $message['role'];
3622 -
3623 - // Convert roles to supported format
3624 - if ($role === 'bot' || $role === 'agent') {
3625 - $role = 'assistant';
3626 - }
3627 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3628 - $role = 'user';
3629 - }
3630 -
3631 - $formatted_conversation[] = array(
3632 - 'role' => $role,
3633 - 'content' => $message['content']
3634 - );
3635 - }
3636 - }
3637 -
3638 - $body = json_encode([
3639 - 'model' => $selected_model,
3640 - 'messages' => $formatted_conversation,
3641 - 'temperature' => 0.8,
3642 - 'stream' => false
3643 - ]);
3644 -
3645 - $args = [
3646 - 'body' => $body,
3647 - 'headers' => [
3648 - 'Content-Type' => 'application/json',
3649 - 'Authorization' => 'Bearer ' . $deepseek_api_key,
3650 - ],
3651 - 'timeout' => 60,
3652 - 'redirection' => 5,
3653 - 'blocking' => true,
3654 - 'httpversion' => '1.0',
3655 - 'sslverify' => true,
3656 - ];
3657 -
3658 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
3659 -
3660 - if (is_wp_error($response)) {
3661 - //error_log('DeepSeek API Error: ' . $response->get_error_message());
3662 - return "Sorry, there was an error processing your request.";
3663 - }
3664 -
3665 - $response_body = wp_remote_retrieve_body($response);
3666 - $decoded_response = json_decode($response_body, true);
3667 -
3668 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3669 - return trim($decoded_response['choices'][0]['message']['content']);
3670 - } else {
3671 - //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
3672 - return "Sorry, I couldn't process that request.";
3673 - }
3674 -}
3675 -
3676 -private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
3677 - // Ensure conversation_history is an array
3678 - if (!is_array($conversation_history)) {
3679 - $conversation_history = array();
3680 - }
3681 -
3682 - // Get system prompt instructions from options
3683 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3684 -
3685 - // Create a new array for the formatted conversation
3686 - $formatted_conversation = array();
3687 -
3688 - // Add system message first
3689 - $formatted_conversation[] = array(
3690 - 'role' => 'system',
3691 - 'content' => $system_prompt_instructions . " " . $relevant_content
3692 - );
3693 -
3694 - // Add the rest of the conversation history
3695 - foreach ($conversation_history as $message) {
3696 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3697 - $role = $message['role'];
3698 -
3699 - // Convert roles to supported format
3700 - if ($role === 'bot' || $role === 'agent') {
3701 - $role = 'assistant';
3702 - }
3703 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3704 - $role = 'user';
3705 - }
3706 -
3707 - $formatted_conversation[] = array(
3708 - 'role' => $role,
3709 - 'content' => $message['content']
3710 - );
3711 - }
3712 - }
3713 -
3714 - $body = json_encode([
3715 - 'model' => $selected_model,
3716 - 'messages' => $formatted_conversation,
3717 - 'temperature' => 0.8,
3718 - 'stream' => false
3719 - ]);
3720 -
3721 - $args = [
3722 - 'body' => $body,
3723 - 'headers' => [
3724 - 'Content-Type' => 'application/json',
3725 - 'Authorization' => 'Bearer ' . $api_key,
3726 - ],
3727 - 'timeout' => 60,
3728 - 'redirection' => 5,
3729 - 'blocking' => true,
3730 - 'httpversion' => '1.0',
3731 - 'sslverify' => true,
3732 - ];
3733 -
3734 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
3735 -
3736 - if (is_wp_error($response)) {
3737 - //error_log('OpenAI API Error: ' . $response->get_error_message());
3738 - return "Sorry, there was an error processing your request.";
3739 - }
3740 -
3741 - $response_body = wp_remote_retrieve_body($response);
3742 - $decoded_response = json_decode($response_body, true);
3743 -
3744 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3745 - return trim($decoded_response['choices'][0]['message']['content']);
3746 - } else {
3747 - //error_log('OpenAI API Response Format Error: ' . print_r($decoded_response, true));
3748 - return "Sorry, I couldn't process that request.";
3749 - }
3750 -}
3751 -private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
3752 - // Get system prompt instructions from options
3753 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3754 -
3755 - // Add system prompt to relevant content
3756 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3757 -
3758 - // Prepend system instructions to the conversation history
3759 - array_unshift($conversation_history, [
3760 - 'role' => 'system',
3761 - 'content' => "Here are your instructions: " . $content_with_instructions
3762 - ]);
3763 -
3764 - // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
3765 - foreach ($conversation_history as &$message) {
3766 - if ($message['role'] === 'bot') {
3767 - $message['role'] = 'assistant';
3768 - } elseif ($message['role'] === 'agent') {
3769 - // Tag the message as coming from a live agent
3770 - $message['role'] = 'assistant';
3771 - if (!isset($message['metadata'])) {
3772 - $message['metadata'] = ['source' => 'live_agent'];
3773 - }
3774 - }
3775 -
3776 - // Ensure all roles are valid
3777 - if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
3778 - $message['role'] = 'user'; // Default to 'user'
3779 - }
3780 - }
3781 -
3782 -
3783 - // Build the request body
3784 - $body = json_encode([
3785 - 'model' => $selected_model,
3786 - 'messages' => $conversation_history,
3787 - 'temperature' => 0.8,
3788 - 'stream' => false
3789 - ]);
3790 -
3791 - // Set up the API request
3792 - $args = [
3793 - 'body' => $body,
3794 - 'headers' => [
3795 - 'Content-Type' => 'application/json',
3796 - 'Authorization' => 'Bearer ' . $xai_api_key,
3797 - ],
3798 - 'timeout' => 60,
3799 - 'redirection' => 5,
3800 - 'blocking' => true,
3801 - 'httpversion' => '1.0',
3802 - 'sslverify' => true,
3803 - ];
3804 -
3805 - // Make the API request
3806 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
3807 -
3808 - // Process the response
3809 - if (is_wp_error($response)) {
3810 - return "Sorry, there was an error processing your request.";
3811 - }
3812 -
3813 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3814 -
3815 - if (isset($response_body['choices'][0]['message']['content'])) {
3816 - return trim($response_body['choices'][0]['message']['content']);
3817 - } else {
3818 - return "Sorry, I couldn't process that request.";
3819 - }
3820 -}
3821 -
3822 -private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
3823 - // Get system prompt instructions from options
3824 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3825 -
3826 - // Clean and validate conversation history
3827 - foreach ($conversation_history as &$message) {
3828 - // Convert bot and agent roles to assistant
3829 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
3830 - $message['role'] = 'assistant';
3831 - }
3832 -
3833 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
3834 - if (!in_array($message['role'], ['assistant', 'user'])) {
3835 - $message['role'] = 'user';
3836 - }
3837 -
3838 - // Ensure content field exists
3839 - if (!isset($message['content']) || empty($message['content'])) {
3840 - $message['content'] = '';
3841 - }
3842 -
3843 - // Remove any unsupported fields
3844 - $message = array_intersect_key($message, array_flip(['role', 'content']));
3845 - }
3846 -
3847 - // Add relevant content as the latest user message
3848 - $conversation_history[] = [
3849 - 'role' => 'user',
3850 - 'content' => $relevant_content
3851 - ];
3852 -
3853 - // Build request body
3854 - $body = json_encode([
3855 - 'model' => $selected_model,
3856 - 'max_tokens' => 1000,
3857 - 'temperature' => 0.8,
3858 - 'messages' => $conversation_history,
3859 - 'system' => $system_prompt_instructions
3860 - ]);
3861 -
3862 - // Set up API request
3863 - $args = [
3864 - 'body' => $body,
3865 - 'headers' => [
3866 - 'Content-Type' => 'application/json',
3867 - 'x-api-key' => $claude_api_key,
3868 - 'anthropic-version' => '2023-06-01'
3869 - ],
3870 - 'timeout' => 60,
3871 - 'redirection' => 5,
3872 - 'blocking' => true,
3873 - 'httpversion' => '1.0',
3874 - 'sslverify' => true,
3875 - ];
3876 -
3877 - // Make API request
3878 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
3879 -
3880 - // Check for WordPress errors
3881 - if (is_wp_error($response)) {
3882 - //error_log("Claude API request error: " . $response->get_error_message());
3883 - return "Sorry, there was an error connecting to the API.";
3884 - }
3885 -
3886 - // Check HTTP response code
3887 - $http_code = wp_remote_retrieve_response_code($response);
3888 - if ($http_code !== 200) {
3889 - $error_body = wp_remote_retrieve_body($response);
3890 - //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
3891 -
3892 - // Try to extract error message from response
3893 - $error_data = json_decode($error_body, true);
3894 - $error_message = isset($error_data['error']['message']) ?
3895 - $error_data['error']['message'] :
3896 - "HTTP error " . $http_code;
3897 -
3898 - return "Sorry, the API returned an error: " . $error_message;
3899 - }
3900 -
3901 - // Parse response
3902 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3903 -
3904 - // Check for JSON decode errors
3905 - if (json_last_error() !== JSON_ERROR_NONE) {
3906 - //error_log("Claude API JSON decode error: " . json_last_error_msg());
3907 - return "Sorry, there was an error processing the API response.";
3908 - }
3909 -
3910 - // Extract and validate response content
3911 - if (isset($response_body['content']) &&
3912 - is_array($response_body['content']) &&
3913 - !empty($response_body['content']) &&
3914 - isset($response_body['content'][0]['text'])) {
3915 - return trim($response_body['content'][0]['text']);
3916 - }
3917 -
3918 - // Log unexpected response format
3919 - //error_log("Claude API unexpected response format: " . print_r($response_body, true));
3920 - return "Sorry, I received an unexpected response format from the API.";
3921 -}
3922 -public function mxchat_dismiss_pre_chat_message() {
3923 - // Get and sanitize the user identifier
3924 - $user_id = $this->mxchat_get_user_identifier();
3925 - $user_id = sanitize_key($user_id);
3926 -
3927 - // Set a transient to track that the user has dismissed the pre-chat message
3928 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3929 - set_transient($transient_key, true, DAY_IN_SECONDS);
3930 -
3931 - wp_send_json_success();
3932 -}
3933 -
3934 -public function mxchat_check_pre_chat_message_status() {
3935 - // Get and sanitize the user identifier
3936 - $user_id = $this->mxchat_get_user_identifier();
3937 - $user_id = sanitize_key($user_id);
3938 -
3939 - // Check if the transient exists (i.e., if the message was dismissed)
3940 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3941 - $dismissed = get_transient($transient_key);
3942 -
3943 - // Log the result to see if it's being set correctly
3944 - //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
3945 -
3946 - if ($dismissed) {
3947 - wp_send_json_success(['dismissed' => true]);
3948 - } else {
3949 - wp_send_json_success(['dismissed' => false]);
3950 - }
3951 -
3952 - wp_die();
3953 -}
3954 -
3955 -private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
3956 - if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
3957 - return 0;
3958 - }
3959 -
3960 - $dotProduct = array_sum(array_map(function ($a, $b) {
3961 - return $a * $b;
3962 - }, $vectorA, $vectorB));
3963 - $normA = sqrt(array_sum(array_map(function ($a) {
3964 - return $a * $a;
3965 - }, $vectorA)));
3966 - $normB = sqrt(array_sum(array_map(function ($b) {
3967 - return $b * $b;
3968 - }, $vectorB)));
3969 -
3970 - if ($normA == 0 || $normB == 0) {
3971 - return 0;
3972 - }
3973 -
3974 - return $dotProduct / ($normA * $normB);
3975 - }
3976 -
3977 -public function mxchat_enqueue_scripts_styles() {
3978 - // Define version numbers for the styles and scripts
3979 - $chat_style_version = '2.0.3'; // Replace with your actual version
3980 - $chat_script_version = '2.0.3'; // Replace with your actual version
3981 -
3982 - // Enqueue the script
3983 - wp_enqueue_script(
3984 - 'mxchat-chat-js',
3985 - plugin_dir_url(__FILE__) . '../js/chat-script.js',
3986 - array('jquery'),
3987 - $chat_script_version,
3988 - true
3989 - );
3990 -
3991 - // Enqueue the CSS
3992 - wp_enqueue_style(
3993 - 'mxchat-chat-css',
3994 - plugin_dir_url(__FILE__) . '../css/chat-style.css',
3995 - array(),
3996 - $chat_style_version
3997 - );
3998 -
3999 - // Fetch options from the database
4000 - $this->options = get_option('mxchat_options');
4001 - $prompts_options = get_option('mxchat_prompts_options', array());
4002 -
4003 - // Prepare settings for JavaScript
4004 - $style_settings = array(
4005 - 'ajax_url' => admin_url('admin-ajax.php'),
4006 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
4007 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
4008 - 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
4009 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
4010 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
4011 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
4012 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
4013 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
4014 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
4015 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
4016 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
4017 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
4018 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
4019 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
4020 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
4021 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
4022 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off', // Example for consistency
4023 -
4024 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
4025 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
4026 - 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
4027 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
4028 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
4029 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
4030 -
4031 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
4032 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
4033 - );
4034 -
4035 - // Pass the settings to the script
4036 - wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
4037 -}
4038 -
4039 -
4040 -public function mxchat_reset_rate_limits() {
4041 - global $wpdb;
4042 -
4043 - // Define a cache key pattern for rate limits
4044 - $cache_key_pattern = 'mxchat_chat_limit_%';
4045 -
4046 - // Retrieve all option names matching the pattern
4047 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
4048 - $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
4049 -
4050 - // db call ok; no-cache ok
4051 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- db call ok
4052 - $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
4053 -
4054 - // Clear the relevant cache entries
4055 - foreach ($option_names as $option_name) {
4056 - wp_cache_delete($option_name, 'options');
4057 - }
4058 -
4059 - // Optionally, clear a general cache if you have one
4060 - wp_cache_delete('mxchat_all_chat_limits', 'options');
4061 - }
4062 -
4063 -private function mxchat_fetch_woocommerce_products() {
4064 - // Ensure WooCommerce is active
4065 - if (!class_exists('WooCommerce')) {
4066 - return [];
4067 - }
4068 -
4069 - $args = array(
4070 - 'post_type' => 'product',
4071 - 'post_status' => 'publish',
4072 - 'posts_per_page' => -1,
4073 - );
4074 -
4075 - $products = get_posts($args);
4076 - $product_data = [];
4077 -
4078 - foreach ($products as $product) {
4079 - $product_id = $product->ID;
4080 - $product_obj = wc_get_product($product_id);
4081 -
4082 - $product_data[] = array(
4083 - 'id' => $product_id,
4084 - 'name' => $product_obj->get_name(),
4085 - 'description' => $product_obj->get_description(),
4086 - 'short_description' => $product_obj->get_short_description(),
4087 - 'url' => get_permalink($product_id),
4088 - 'price' => $product_obj->get_regular_price(),
4089 - 'sale_price' => $product_obj->get_sale_price(),
4090 - 'stock_status' => $product_obj->get_stock_status(),
4091 - 'sku' => $product_obj->get_sku(),
4092 - 'in_stock' => $product_obj->is_in_stock(),
4093 - 'total_sales' => $product_obj->get_total_sales(),
4094 - );
4095 - }
4096 -
4097 - return $product_data;
4098 -}
4099 -
4100 -}
4101 -?>
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 + private $last_similarity_analysis = null;
14 + private $current_valid_urls = [];
15 + private $is_streaming = false; // ADDED: Track if current request is streaming
16 +
17 +/**
18 + * Class constructor
19 + */
20 +public function __construct() {
21 + $this->options = get_option('mxchat_options');
22 + $this->prompts_options = get_option('mxchat_prompts_options', array());
23 + $this->chat_count = get_option('mxchat_chat_count', 0);
24 + $this->word_handler = new MXChat_Word_Handler($this->options);
25 +
26 + // Add all action hooks
27 + add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
28 + add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
29 + add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
30 + add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
31 + add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
32 +
33 + // Add the AJAX actions for checking if the pre-chat message was dismissed
34 + add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
35 + add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
36 + add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
37 + add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
38 + add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
39 + add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
40 +
41 + // Add REST API routes registration
42 + add_action('rest_api_init', array($this, 'register_routes'));
43 + add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
44 + add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
45 +
46 + // Rate limit action - notice we removed the old schedule setup
47 + add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
48 +
49 + // File upload and handling actions
50 + add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
51 + add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
52 + add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
53 + add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
54 +
55 + // Word document handling actions
56 + add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
57 + add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
58 + add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
59 + add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
60 + add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
61 + add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
62 +
63 + // Email handling actions
64 + add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
65 + add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
66 + add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
67 + add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
68 +
69 + add_action('wp_ajax_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
70 + add_action('wp_ajax_nopriv_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
71 +
72 + // Testing panel AJAX actions
73 + add_action('wp_ajax_mxchat_get_system_info', array($this, 'mxchat_get_system_info'));
74 + add_action('wp_ajax_mxchat_get_similarity_threshold', array($this, 'mxchat_get_similarity_threshold'));
75 + add_action('wp_ajax_mxchat_get_kb_status', array($this, 'mxchat_get_kb_status'));
76 + add_action('wp_ajax_mxchat_start_fresh_session', array($this, 'mxchat_start_fresh_session'));
77 + // Add to your existing constructor, in the section with other AJAX actions:
78 + add_action('wp_ajax_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
79 + add_action('wp_ajax_nopriv_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
80 + add_action('wp_ajax_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
81 + add_action('wp_ajax_nopriv_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
82 + // Add chat mode checking actions
83 + add_action('wp_ajax_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
84 + add_action('wp_ajax_nopriv_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
85 +
86 + add_filter('mxchat_check_actions_only', array($this, 'check_actions_for_addons'), 10, 4);
87 +
88 +
89 +}
90 +
91 +// In your core plugin's check_actions_for_addons method:
92 +public function check_actions_for_addons($default, $message, $user_id, $session_id) {
93 + //error_log('MxChat Core: check_actions_for_addons called with message: ' . $message);
94 +
95 + $result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
96 +
97 + //error_log('MxChat Core: Intent check result = ' . ($result === false ? 'false' : 'true'));
98 +
99 + return $result;
100 +}
101 +
102 + private function mxchat_increment_chat_count() {
103 + $chat_count = get_option('mxchat_chat_count', 0);
104 + $chat_count++;
105 + update_option('mxchat_chat_count', $chat_count);
106 + }
107 +
108 +function mxchat_fetch_conversation_history() {
109 + if (empty($_POST['session_id'])) {
110 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
111 + wp_die();
112 + }
113 +
114 + $session_id = sanitize_text_field($_POST['session_id']);
115 +
116 + // SECURITY FIX: Verify session ownership before retrieving data
117 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
118 +
119 + // Check if this session has an owner recorded
120 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
121 +
122 + // If session has an owner and it doesn't match current user, deny access
123 + if ($session_owner && $session_owner !== $current_user_identifier) {
124 + wp_send_json_error(['message' => esc_html__('Unauthorized access.', 'mxchat')]);
125 + wp_die();
126 + }
127 +
128 + // If no owner is set yet, claim ownership (for legacy sessions)
129 + if (!$session_owner) {
130 + update_option("mxchat_session_owner_{$session_id}", $current_user_identifier, 'no');
131 + }
132 +
133 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
134 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
135 +
136 + if (empty($history)) {
137 + // Even if history is empty, return the chat mode
138 + wp_send_json_success([
139 + 'conversation' => [],
140 + 'chat_mode' => $chat_mode
141 + ]);
142 + wp_die();
143 + }
144 +
145 + wp_send_json_success([
146 + 'conversation' => $history,
147 + 'chat_mode' => $chat_mode
148 + ]);
149 + wp_die();
150 +}
151 +private function mxchat_fetch_conversation_history_for_ai($session_id) {
152 + $history = get_option("mxchat_history_{$session_id}", []);
153 + $formatted_history = [];
154 +
155 + // Adjusted for code-heavy conversations
156 + $max_tokens = 120000; // Context window size
157 + $reserved_tokens = 5000; // Space for system prompts + current query
158 + $current_token_count = 0;
159 +
160 + // Allowed HTML tags for content sanitization
161 + $allowed_tags = [
162 + 'pre' => ['class' => true],
163 + 'code' => ['class' => true],
164 + 'span' => ['class' => true],
165 + 'div' => ['class' => true],
166 + 'strong' => [],
167 + 'em' => []
168 + ];
169 +
170 + foreach (array_reverse($history) as $entry) {
171 + // Preserve code blocks while sanitizing other HTML
172 + $clean_content = wp_kses($entry['content'], $allowed_tags);
173 +
174 + // Detect code blocks in content
175 + $has_code = false;
176 +// Replace the HTML check with:
177 +// Allow messages that contain code blocks or are plain text
178 +if (strpos($clean_content, '<pre') === false &&
179 + strpos($clean_content, '<code') === false &&
180 + $clean_content !== strip_tags($entry['content'])) {
181 + continue;
182 +}
183 +
184 + // Skip entries that lost significant content during sanitization
185 + if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
186 + continue;
187 + }
188 +
189 + // More accurate token estimation (1 token ≈ 4 characters)
190 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
191 +
192 + // Check token budget with the new estimate
193 + if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
194 + // Try to fit partial content if it's the first entry
195 + if (empty($formatted_history)) {
196 + $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
197 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
198 + } else {
199 + break;
200 + }
201 + }
202 +
203 + // Add to formatted history
204 + $formatted_history[] = [
205 + 'role' => $entry['role'],
206 + 'content' => $clean_content
207 + ];
208 +
209 + $current_token_count += $token_estimate;
210 + }
211 +
212 + // Reverse back to maintain chronological order
213 + $formatted_history = array_reverse($formatted_history);
214 +
215 + // Add system message about code context
216 + array_unshift($formatted_history, [
217 + 'role' => 'system',
218 + 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
219 + . 'Maintain formatting and syntax highlighting when referencing code.'
220 + ]);
221 +
222 + return $formatted_history;
223 +}
224 +
225 +public function register_routes() {
226 + //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
227 +
228 + register_rest_route('mxchat/v1', '/stream', [
229 + 'methods' => 'GET',
230 + 'callback' => [$this, 'mxchat_stream_events'],
231 + 'permission_callback' => [$this, 'verify_chat_session'],
232 + ]);
233 +
234 + register_rest_route('mxchat/v1', '/agent-response', [
235 + 'methods' => 'POST',
236 + 'callback' => [$this, 'mxchat_handle_agent_response'],
237 + 'permission_callback' => [$this, 'verify_slack_request'],
238 + ]);
239 +
240 + register_rest_route('mxchat/v1', '/slack-interaction', [
241 + 'methods' => 'POST',
242 + 'callback' => [$this, 'handle_slack_interaction'],
243 + 'permission_callback' => [$this, 'verify_slack_request'],
244 + ]);
245 +
246 + register_rest_route('mxchat/v1', '/slack-messages', [
247 + 'methods' => 'POST',
248 + 'callback' => [$this, 'handle_slack_messages'],
249 + 'permission_callback' => [$this, 'verify_slack_request'],
250 + ]);
251 +
252 + //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
253 +}
254 +
255 +/**
256 + * Verify valid chat session
257 + */
258 +public function verify_chat_session($request) {
259 + $session_id = $request->get_param('session_id');
260 + if (empty($session_id)) {
261 + //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
262 + return false;
263 + }
264 +
265 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
266 + return $chat_mode === 'agent';
267 +}
268 +
269 +/**
270 + * Verify request is coming from Slack.
271 + *
272 + * @param WP_REST_Request $request
273 + * @return bool True if valid, false otherwise.
274 + */
275 +public function verify_slack_request($request) {
276 + // Get the Slack signing secret from your plugin options
277 + $valid_key = $this->options['live_agent_secret_key'] ?? '';
278 +
279 + if (empty($valid_key)) {
280 + //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
281 + return false;
282 + }
283 +
284 + $timestamp = $request->get_header('X-Slack-Request-Timestamp');
285 + $slack_signature = $request->get_header('X-Slack-Signature');
286 +
287 + // Verify timestamp to prevent replay attacks
288 + if (abs(time() - intval($timestamp)) > 300) {
289 + //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
290 + return false;
291 + }
292 +
293 + // Get raw request body
294 + $request_body = file_get_contents('php://input');
295 +
296 + // Create the signature base string
297 + $sig_basestring = "v0:{$timestamp}:{$request_body}";
298 +
299 + // Calculate expected signature
300 + $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
301 +
302 + // Compare signatures
303 + return hash_equals($my_signature, $slack_signature);
304 +}
305 +public function mxchat_stream_events(WP_REST_Request $request) {
306 + header('Content-Type: text/event-stream');
307 + header('Cache-Control: no-cache');
308 + header('Connection: keep-alive');
309 +
310 + $session_id = sanitize_text_field($request->get_param('session_id'));
311 + $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
312 +
313 + if (empty($session_id)) {
314 + echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
315 + flush();
316 + exit;
317 + }
318 +
319 + $history = get_option("mxchat_history_{$session_id}", []);
320 +
321 + // Filter only new messages
322 + $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
323 + return !empty($message['id']) && $message['id'] > $last_seen_id;
324 + });
325 +
326 + // Send new messages if available
327 + if (!empty($new_messages)) {
328 + echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
329 + } else {
330 + // Keep the connection alive
331 + echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
332 + }
333 + flush();
334 + exit;
335 +}
336 +
337 +
338 +
339 +
340 +private function mxchat_save_chat_message($session_id, $role, $message, $originating_page = null) {
341 + global $wpdb;
342 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
343 + //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
344 +
345 + // Check if this is the first message in a new session (before any other database operations)
346 + $is_new_session = false;
347 + if ($role === 'user') { // Only check for user messages, not bot responses
348 + $existing_messages = $wpdb->get_var($wpdb->prepare(
349 + "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
350 + $session_id
351 + ));
352 + $is_new_session = ($existing_messages == 0);
353 +
354 + // Log for debugging
355 + if ($is_new_session) {
356 + //error_log("[DEBUG] This is a NEW session - first message");
357 + }
358 + }
359 +
360 + // SECURITY FIX: Set session ownership for new sessions
361 + if ($is_new_session && $role === 'user') {
362 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
363 + $session_owner_key = "mxchat_session_owner_{$session_id}";
364 +
365 + // Only set ownership if not already set
366 + if (!get_option($session_owner_key)) {
367 + update_option($session_owner_key, $current_user_identifier, 'no');
368 + //error_log("[DEBUG] Set session ownership for {$session_id} to {$current_user_identifier}");
369 + }
370 + }
371 +
372 + // 1) Extract agent name if present
373 + $agent_name = '';
374 + if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
375 + $agent_name = $matches[1];
376 + $message = str_replace("Agent: $agent_name - ", '', $message);
377 + $session_meta_key = "mxchat_agent_name_{$session_id}";
378 + if (empty(get_option($session_meta_key))) {
379 + update_option($session_meta_key, $agent_name);
380 + //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
381 + }
382 + }
383 +
384 + // 2) Generate unique message_id
385 + $message_id = uniqid();
386 + //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
387 +
388 + // 3) Determine user_id
389 + $user_id = is_user_logged_in() ? get_current_user_id() : 0;
390 +
391 + // 4) Determine user_identifier
392 + $user_identifier = $agent_name
393 + ? $agent_name
394 + : MxChat_User::mxchat_get_user_identifier();
395 +
396 + // 5) Determine displayed_name
397 + $user_email = MxChat_User::mxchat_get_user_email();
398 + $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
399 +
400 + // 6) Check for a saved email in wp_options
401 + $email_option_key = "mxchat_email_{$session_id}";
402 + $saved_email = get_option($email_option_key);
403 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
404 +
405 + // Check for a saved name in wp_options
406 + $name_option_key = "mxchat_name_{$session_id}";
407 + $saved_name = get_option($name_option_key);
408 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for name_option_key: {$name_option_key}, found: {$saved_name}");
409 +
410 + // If found, update DB user_email and user_name
411 + if ($saved_email || $saved_name) {
412 + $update_data = [];
413 + if ($saved_email) {
414 + $update_data['user_email'] = $saved_email;
415 + }
416 + if ($saved_name) {
417 + $update_data['user_name'] = $saved_name;
418 + }
419 +
420 + if (!empty($update_data)) {
421 + $update_res = $wpdb->update(
422 + $table_name,
423 + $update_data,
424 + ['session_id' => $session_id],
425 + array_fill(0, count($update_data), '%s'),
426 + ['%s']
427 + );
428 + //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email/user_name update for session_id {$session_id}. update_res: {$update_res}");
429 + }
430 + }
431 +
432 + // 7) Save to session history in wp_options
433 + $history_key = "mxchat_history_{$session_id}";
434 + $history = get_option($history_key, []);
435 + $history[] = [
436 + 'id' => $message_id,
437 + 'role' => $role,
438 + 'content' => $message,
439 + 'timestamp' => round(microtime(true) * 1000),
440 + 'agent_name' => $displayed_name,
441 + ];
442 + update_option($history_key, $history, 'no');
443 + //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
444 +
445 + // 8) Save the message to DB (INSERT)
446 + $insert_data = [
447 + 'user_id' => $user_id,
448 + 'user_identifier'=> $user_identifier,
449 + 'user_email' => $saved_email ?: $user_email,
450 + 'user_name' => $saved_name ?: '', // Add name to insert data
451 + 'session_id' => $session_id,
452 + 'role' => $role,
453 + 'message' => $message,
454 + 'timestamp' => current_time('mysql', 1),
455 + ];
456 +
457 + // IMPROVED: Handle originating page data
458 + $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
459 +
460 + if ($columns_exist) {
461 + if ($is_new_session && $role === 'user') {
462 + // For the first user message, set originating page data
463 +
464 + // First check if we have it from the parameter
465 + if ($originating_page && !empty($originating_page['url'])) {
466 + $insert_data['originating_page_url'] = $originating_page['url'];
467 + $insert_data['originating_page_title'] = $originating_page['title'] ?? '';
468 +
469 + //error_log("[DEBUG] Setting originating page from parameter: " . $originating_page['url']);
470 + }
471 + // Otherwise check if it's stored in the instance property
472 + else if (isset($this->pending_originating_page) && !empty($this->pending_originating_page['url'])) {
473 + $insert_data['originating_page_url'] = $this->pending_originating_page['url'];
474 + $insert_data['originating_page_title'] = $this->pending_originating_page['title'] ?? '';
475 +
476 + //error_log("[DEBUG] Setting originating page from pending_originating_page: " . $this->pending_originating_page['url']);
477 +
478 + // Clear after using
479 + unset($this->pending_originating_page);
480 + }
481 + // Fallback to HTTP_REFERER if nothing else is available
482 + else if (isset($_SERVER['HTTP_REFERER'])) {
483 + $referer_url = esc_url_raw($_SERVER['HTTP_REFERER']);
484 + $insert_data['originating_page_url'] = $referer_url;
485 +
486 + // Generate title from URL
487 + $parsed_url = parse_url($referer_url);
488 + $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
489 +
490 + if (empty($path) || $path === 'index.php' || $path === 'index.html') {
491 + $insert_data['originating_page_title'] = 'Homepage';
492 + } else {
493 + $title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
494 + $insert_data['originating_page_title'] = ucwords(trim($title));
495 + }
496 +
497 + //error_log("[DEBUG] Setting originating page from HTTP_REFERER: " . $referer_url);
498 + }
499 +
500 + // Store for this session so all messages have the same originating page
501 + if (!empty($insert_data['originating_page_url'])) {
502 + update_option("mxchat_originating_page_{$session_id}", [
503 + 'url' => $insert_data['originating_page_url'],
504 + 'title' => $insert_data['originating_page_title']
505 + ], 'no');
506 + }
507 + } else {
508 + // For subsequent messages in the session, use the stored originating page
509 + $stored_originating = get_option("mxchat_originating_page_{$session_id}");
510 + if ($stored_originating && !empty($stored_originating['url'])) {
511 + $insert_data['originating_page_url'] = $stored_originating['url'];
512 + $insert_data['originating_page_title'] = $stored_originating['title'] ?? '';
513 + }
514 + }
515 + }
516 +
517 + $wpdb->insert($table_name, $insert_data);
518 + //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
519 +
520 + // 9) Send notification email if this is the first user message in a new session
521 + if ($wpdb->insert_id && $is_new_session && $role === 'user') {
522 + $this->send_new_chat_notification($session_id, array(
523 + 'identifier' => $user_identifier,
524 + 'email' => $saved_email ?: $user_email,
525 + 'ip' => $_SERVER['REMOTE_ADDR']
526 + ));
527 + }
528 +
529 + //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
530 + return $message_id;
531 +}
532 +
533 +private function send_new_chat_notification($session_id, $user_info = array()) {
534 + $options = get_option('mxchat_transcripts_options');
535 +
536 + // Check if notifications are enabled
537 + if (empty($options['mxchat_enable_notifications'])) {
538 + return false;
539 + }
540 +
541 + // Get notification email
542 + $to = !empty($options['mxchat_notification_email']) ?
543 + $options['mxchat_notification_email'] :
544 + get_option('admin_email');
545 +
546 + if (!is_email($to)) {
547 + return false;
548 + }
549 +
550 + // Prepare email content
551 + $subject = sprintf('[%s] New Chat Session Started', get_bloginfo('name'));
552 +
553 + $user_identifier = isset($user_info['identifier']) ? $user_info['identifier'] : 'Guest';
554 + $user_email = isset($user_info['email']) ? $user_info['email'] : 'Not provided';
555 + $user_ip = isset($user_info['ip']) ? $user_info['ip'] : $_SERVER['REMOTE_ADDR'];
556 +
557 + $message = sprintf(
558 + "A new chat session has started on your website.\n\n" .
559 + "Session ID: %s\n" .
560 + "User: %s\n" .
561 + "Email: %s\n" .
562 + "IP Address: %s\n" .
563 + "Time: %s\n\n" .
564 + "View transcripts: %s",
565 + $session_id,
566 + $user_identifier,
567 + $user_email,
568 + $user_ip,
569 + current_time('mysql'),
570 + admin_url('admin.php?page=mxchat-transcripts')
571 + );
572 +
573 + // Send email
574 + return wp_mail($to, $subject, $message);
575 +}
576 +
577 +public function mxchat_handle_save_email_and_response() {
578 + //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
579 + //error_log('DEBUG: POST data: ' . print_r($_POST, true));
580 +
581 + // Validate nonce
582 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
583 + //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
584 + wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
585 + wp_die();
586 + }
587 +
588 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
589 + $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
590 + $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
591 +
592 + //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}, name: {$name}");
593 +
594 + if (empty($session_id) || empty($email)) {
595 + //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
596 + wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
597 + wp_die();
598 + }
599 +
600 + // Validate name if provided (check if name field is enabled and name is required)
601 + $options = get_option('mxchat_options', []);
602 + $name_field_enabled = isset($options['enable_name_field']) &&
603 + ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
604 +
605 + if ($name_field_enabled && (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 100)) {
606 + //error_log("[ERROR] Invalid name: {$name} (enabled: {$name_field_enabled})");
607 + wp_send_json_error(['message' => esc_html__('Name must be between 2 and 100 characters.', 'mxchat')]);
608 + wp_die();
609 + }
610 +
611 + // 1) Always store email in wp_options
612 + $email_option_key = "mxchat_email_{$session_id}";
613 + update_option($email_option_key, $email);
614 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$email_option_key} => {$email}");
615 +
616 + // Store name in wp_options if provided
617 + if (!empty($name)) {
618 + $name_option_key = "mxchat_name_{$session_id}";
619 + update_option($name_option_key, $name);
620 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$name_option_key} => {$name}");
621 + }
622 +
623 + // 2) (Optional) Also store in DB if a row already exists
624 + global $wpdb;
625 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
626 +
627 + // Make sure we have a valid placeholder in prepare
628 + $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
629 + $session_count = $wpdb->get_var($sql);
630 +
631 + //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
632 +
633 + if ($session_count) {
634 + // Update both user_email and user_name if row(s) exist
635 + if (!empty($name)) {
636 + $update_sql = $wpdb->prepare(
637 + "UPDATE {$table_name} SET user_email = %s, user_name = %s WHERE session_id = %s",
638 + $email,
639 + $name,
640 + $session_id
641 + );
642 + } else {
643 + $update_sql = $wpdb->prepare(
644 + "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
645 + $email,
646 + $session_id
647 + );
648 + }
649 + $wpdb->query($update_sql);
650 + //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
651 + } else {
652 + //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email/name is only in wp_options.");
653 + }
654 +
655 + // Provide success response (same as original)
656 + $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
657 + //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
658 + wp_send_json_success(['message' => $bot_message]);
659 + wp_die();
660 +}
661 +
662 +public function mxchat_check_email_provided() {
663 + //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
664 +
665 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
666 + //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
667 + wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
668 + }
669 +
670 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
671 + if (empty($session_id)) {
672 + //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
673 + wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
674 + }
675 +
676 + // Check if the user is logged in
677 + if (is_user_logged_in()) {
678 + $current_user = wp_get_current_user();
679 + //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
680 +
681 + // Get user's display name for logged in users
682 + $user_name = !empty($current_user->display_name) ? $current_user->display_name :
683 + (!empty($current_user->first_name) ? $current_user->first_name : '');
684 +
685 + $response_data = ['logged_in' => true, 'email' => $current_user->user_email];
686 + if (!empty($user_name)) {
687 + $response_data['name'] = $user_name;
688 + }
689 +
690 + wp_send_json_success($response_data);
691 + }
692 +
693 + // Check if name field is required
694 + $options = get_option('mxchat_options', []);
695 + $name_field_enabled = isset($options['enable_name_field']) &&
696 + ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
697 +
698 + $email_option_key = "mxchat_email_{$session_id}";
699 + $stored_email = get_option($email_option_key, '');
700 +
701 + // Check for stored name
702 + $name_option_key = "mxchat_name_{$session_id}";
703 + $stored_name = get_option($name_option_key, '');
704 +
705 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking email option: {$email_option_key}, found: {$stored_email}");
706 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking name option: {$name_option_key}, found: {$stored_name}, required: " . ($name_field_enabled ? 'yes' : 'no'));
707 +
708 + // Check if we have email and name (if name is required)
709 + $has_required_info = !empty($stored_email);
710 +
711 + if ($name_field_enabled) {
712 + $has_required_info = $has_required_info && !empty($stored_name);
713 + }
714 +
715 + if ($has_required_info) {
716 + //error_log("[DEBUG] mxchat_check_email_provided -> Required info found, returning success");
717 +
718 + $response_data = ['email' => $stored_email];
719 + if (!empty($stored_name)) {
720 + $response_data['name'] = $stored_name;
721 + }
722 +
723 + wp_send_json_success($response_data);
724 + } else {
725 + //error_log("[DEBUG] mxchat_check_email_provided -> Required info missing, returning error");
726 + wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
727 + }
728 +}
729 +
730 +/**
731 + * Send error response in appropriate format based on streaming mode
732 + * ADDED: Helper method to consistently handle errors in both streaming and non-streaming modes
733 + *
734 + * @param string $error_message The error message to display
735 + * @param string $error_code Optional error code for debugging
736 + */
737 +private function send_error_response($error_message, $error_code = 'api_error') {
738 + if ($this->is_streaming) {
739 + echo "data: " . json_encode([
740 + 'error' => true,
741 + 'error_message' => $error_message,
742 + 'error_code' => $error_code,
743 + 'text' => $error_message,
744 + 'message' => $error_message
745 + ]) . "\n\n";
746 + echo "data: [DONE]\n\n";
747 + flush();
748 + } else {
749 + wp_send_json_error([
750 + 'error_message' => $error_message,
751 + 'error_code' => $error_code
752 + ]);
753 + }
754 + wp_die();
755 +}
756 +
757 +public function mxchat_handle_chat_request() {
758 + global $wpdb;
759 +
760 + // Debug: Log incoming bot_id
761 + $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
762 + error_log("=== MXCHAT DEBUG: Starting chat request ===");
763 + error_log("MXCHAT DEBUG: Bot ID received: " . $bot_id);
764 +
765 + // Get bot-specific options
766 + $bot_options = $this->get_bot_options($bot_id);
767 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
768 +
769 + // Check if this is a streaming request
770 + $is_streaming = isset($_POST['action']) && $_POST['action'] === 'mxchat_stream_chat' &&
771 + isset($current_options['enable_streaming_toggle']) && $current_options['enable_streaming_toggle'] === 'on';
772 +
773 + // ADDED: Store streaming state in class property for use in private methods
774 + $this->is_streaming = $is_streaming;
775 +
776 + // Set streaming headers if needed
777 + if ($is_streaming) {
778 + // Disable output buffering
779 + while (ob_get_level()) {
780 + ob_end_flush(); // Changed from ob_end_clean()
781 + }
782 +
783 + // Set headers for SSE
784 + header('Content-Type: text/event-stream');
785 + header('Cache-Control: no-cache');
786 + header('Connection: keep-alive');
787 + header('X-Accel-Buffering: no');
788 +
789 + // Add these new lines:
790 + ob_implicit_flush(true);
791 + flush();
792 + }
793 +
794 + // Check if MX Chat Moderation is active
795 + if (class_exists('MX_Chat_Moderation')) {
796 + // Get user email and IP
797 + $user_email = '';
798 + $user_ip = $_SERVER['REMOTE_ADDR'];
799 +
800 + // If user is logged in, get their email
801 + if (is_user_logged_in()) {
802 + $current_user = wp_get_current_user();
803 + $user_email = $current_user->user_email;
804 + }
805 +
806 + // Create ban handler instance
807 + $ban_handler = new MX_Chat_Ban_Handler();
808 +
809 + // Check if user is banned by IP
810 + if ($ban_handler->check_ban($user_ip, 'ip')) {
811 + wp_send_json([
812 + 'success' => false,
813 + 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
814 + 'status' => 'banned'
815 + ]);
816 + wp_die();
817 + }
818 +
819 + // If user is logged in, also check email
820 + if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
821 + wp_send_json([
822 + 'success' => false,
823 + 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
824 + 'status' => 'banned'
825 + ]);
826 + wp_die();
827 + }
828 + }
829 +
830 + $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
831 + $this->productCardHtml = '';
832 +
833 + // Get the actual WordPress user ID if logged in
834 + $is_logged_in = is_user_logged_in();
835 + if ($is_logged_in) {
836 + $user_id = get_current_user_id(); // This will get the actual WordPress user ID
837 + } else {
838 + // For logged-out users, use your existing identifier method
839 + $user_id = $this->mxchat_get_user_identifier();
840 + }
841 +
842 + // Get and sanitize the user identifier
843 + $user_id = sanitize_key($user_id);
844 +
845 + // Check rate limit using new settings structure
846 + $rate_limit_result = $this->check_rate_limit();
847 +
848 + if ($rate_limit_result !== true) {
849 + wp_send_json([
850 + 'success' => false,
851 + 'message' => $rate_limit_result['message'],
852 + 'status' => 'rate_limit_exceeded'
853 + ]);
854 + wp_die();
855 + }
856 +
857 + // Rest of your existing code...
858 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
859 +
860 + if (empty($session_id)) {
861 + wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
862 + wp_die();
863 + }
864 +
865 + // SECURITY FIX: Verify session ownership before processing chat request
866 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
867 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
868 +
869 + if ($session_owner && $session_owner !== $current_user_identifier) {
870 + wp_send_json_error(esc_html__('Unauthorized access.', 'mxchat'));
871 + wp_die();
872 + }
873 +
874 + // Validate and sanitize the incoming message
875 + if (empty($_POST['message'])) {
876 + wp_send_json_error(esc_html__('No message received.', 'mxchat'));
877 + wp_die();
878 + }
879 +
880 +
881 + // Track originating page for first message in session
882 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
883 +
884 + // Check if originating page columns exist
885 + $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
886 +
887 + if ($columns_exist) {
888 + // Check if this session already has messages
889 + $message_count = $wpdb->get_var($wpdb->prepare(
890 + "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
891 + $session_id
892 + ));
893 +
894 + // If this is the first message in the session
895 + if ($message_count == 0) {
896 + // Get originating page from JavaScript (preferred) or HTTP_REFERER (fallback)
897 + $originating_url = '';
898 + $originating_title = '';
899 +
900 + // Try to get from POST data first (sent by JavaScript)
901 + if (isset($_POST['current_page_url'])) {
902 + $originating_url = esc_url_raw($_POST['current_page_url']);
903 + $originating_title = isset($_POST['current_page_title'])
904 + ? sanitize_text_field($_POST['current_page_title'])
905 + : '';
906 + }
907 + // Fallback to HTTP_REFERER if not provided by JavaScript
908 + else if (isset($_SERVER['HTTP_REFERER'])) {
909 + $originating_url = esc_url_raw($_SERVER['HTTP_REFERER']);
910 + }
911 +
912 + // Generate title if we have URL but no title
913 + if ($originating_url && empty($originating_title)) {
914 + $parsed_url = parse_url($originating_url);
915 + $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
916 +
917 + if (empty($path) || $path === 'index.php' || $path === 'index.html') {
918 + $originating_title = 'Homepage';
919 + } else {
920 + // Clean up the path to make a readable title
921 + $originating_title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
922 + $originating_title = ucwords(trim($originating_title));
923 + }
924 + }
925 +
926 + // Store for later use when saving the message
927 + $this->pending_originating_page = [
928 + 'url' => $originating_url,
929 + 'title' => $originating_title
930 + ];
931 + }
932 + }
933 +
934 +
935 +
936 + // Get page context if provided
937 + $page_context = null;
938 + if (isset($_POST['page_context']) && !empty($_POST['page_context'])) {
939 + $page_context_raw = stripslashes($_POST['page_context']);
940 + $page_context = json_decode($page_context_raw, true);
941 +
942 + // Validate page context structure
943 + if (is_array($page_context) &&
944 + isset($page_context['url']) &&
945 + isset($page_context['title']) &&
946 + isset($page_context['content'])) {
947 +
948 + // Sanitize page context
949 + $page_context['url'] = esc_url_raw($page_context['url']);
950 + $page_context['title'] = sanitize_text_field($page_context['title']);
951 + $page_context['content'] = wp_kses_post($page_context['content']);
952 + } else {
953 + $page_context = null;
954 + }
955 + }
956 +
957 + // Modify the message sanitization to preserve PHP tags in code blocks
958 + $allowed_tags = [
959 + 'pre' => [],
960 + 'code' => ['class' => true],
961 + 'span' => ['class' => true],
962 + 'div' => ['class' => true],
963 + ];
964 +
965 + // First preserve code blocks
966 + $message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
967 + return htmlspecialchars_decode($matches[0]);
968 + }, $_POST['message']);
969 +
970 + // Then apply sanitization
971 + $message = wp_kses($message, $allowed_tags);
972 +
973 + // Preserve code blocks from markdown conversion
974 + $message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
975 + $message = apply_filters('mxchat_filter_message', $message, 'prompt', $session_id);
976 +
977 + // ===== SIMPLIFIED TESTING PANEL INITIALIZATION =====
978 + // Always initialize testing data for admins (no toggle needed)
979 + $testing_data = null;
980 + if (current_user_can('administrator')) {
981 + // For vision messages, use the original user message for the query display
982 + $query_for_testing = $message;
983 + if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
984 + $query_for_testing = sanitize_textarea_field($_POST['original_user_message']);
985 + }
986 +
987 + $testing_data = [
988 + 'query' => $query_for_testing,
989 + 'timestamp' => time(),
990 + 'top_matches' => [],
991 + 'action_matches' => [], // Initialize action matches array
992 + 'page_context' => $page_context, // Include page context in testing data
993 + 'is_vision' => isset($_POST['vision_processed']) && $_POST['vision_processed'],
994 + 'bot_id' => $bot_id // Include bot ID in testing data
995 + ];
996 +
997 + // Get similarity threshold from bot options or default options
998 + $similarity_threshold = isset($current_options['similarity_threshold'])
999 + ? ((int) $current_options['similarity_threshold']) / 100
1000 + : 0.35;
1001 +
1002 + $testing_data['similarity_threshold'] = $similarity_threshold;
1003 +
1004 + // Determine knowledge base type using bot-specific config
1005 + $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
1006 + $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
1007 + $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
1008 + }
1009 + // ===== END SIMPLIFIED TESTING INITIALIZATION =====
1010 +
1011 + // Add debug before and after:
1012 + //error_log('MxChat Core: About to call mxchat_pre_process_message filter with message: ' . $message);
1013 + $pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
1014 + //error_log('MxChat Core: Filter returned: ' . (is_array($pre_processed_result) ? 'array' : $pre_processed_result));
1015 +
1016 +
1017 + // If the pre-processing returned a result (not the original message), use it directly
1018 + if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
1019 + // Save the AI response
1020 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
1021 +
1022 + // Save HTML content if provided
1023 + if (!empty($pre_processed_result['html'])) {
1024 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
1025 + }
1026 +
1027 + // Add testing data if admin
1028 + $response_data = [
1029 + 'text' => $pre_processed_result['text'],
1030 + 'html' => $pre_processed_result['html'] ?? '',
1031 + 'session_id' => $session_id
1032 + ];
1033 +
1034 + if ($testing_data !== null) {
1035 + $response_data['testing_data'] = $testing_data;
1036 + }
1037 +
1038 + wp_send_json($response_data);
1039 + wp_die();
1040 + }
1041 +
1042 + // Save the user's message - handle vision processed messages differently
1043 + if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1044 + // For vision messages, save the original user message with image indicator
1045 + $original_message = sanitize_textarea_field($_POST['original_user_message']);
1046 + if (isset($_POST['vision_images_count']) && $_POST['vision_images_count'] > 0) {
1047 + $image_count = intval($_POST['vision_images_count']);
1048 + $original_message .= " [{$image_count} image(s)]";
1049 + }
1050 + $this->mxchat_save_chat_message($session_id, 'user', $original_message);
1051 + } else {
1052 + // Regular message - save as normal
1053 + $this->mxchat_save_chat_message($session_id, 'user', $message);
1054 + }
1055 +
1056 +
1057 + if (is_email($message)) {
1058 + // Add the email to Loops
1059 + $this->add_email_to_loops($message);
1060 +
1061 + // Get the user's success message instruction using current_options
1062 + $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1063 +
1064 + // Set instruction for AI using the user's success message
1065 + $this->current_action_instruction = $user_success_message;
1066 +
1067 + // Clear the email capture transient since we got the email
1068 + delete_transient('mxchat_email_capture_' . $user_id);
1069 + }
1070 +
1071 + // Check if we're in an email capture flow but user hasn't provided email yet
1072 + elseif (get_transient('mxchat_email_capture_' . $user_id)) {
1073 + // Check if the message contains an email (not the whole message being an email)
1074 + if (preg_match('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $message, $matches)) {
1075 + $extracted_email = $matches[0];
1076 +
1077 + // Add the extracted email to Loops
1078 + $this->add_email_to_loops($extracted_email);
1079 +
1080 + // Get the user's success message instruction using current_options
1081 + $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1082 +
1083 + // Set instruction for AI using the user's success message
1084 + $this->current_action_instruction = $user_success_message;
1085 +
1086 + // Clear the email capture transient since we got the email
1087 + delete_transient('mxchat_email_capture_' . $user_id);
1088 + }
1089 + // If no email found but we're in capture mode, remind them
1090 + else {
1091 + // Get the original instruction to remind them using current_options
1092 + $original_instruction = $current_options['triggered_phrase_response'] ?? __("Please provide your email address.", 'mxchat');
1093 + $this->current_action_instruction = $original_instruction;
1094 + }
1095 + }
1096 +
1097 + $intent_info = '';
1098 +
1099 + // Check chat mode
1100 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1101 +
1102 + // Handle agent mode
1103 + // Handle agent mode
1104 + if ($chat_mode === 'agent') {
1105 + // First, check for switch intent before doing anything else
1106 + $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1107 +
1108 + // Capture action analysis for testing panel after intent check
1109 + if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1110 + $testing_data['action_matches'] = $this->last_action_analysis;
1111 + }
1112 +
1113 + // Around line 506, in the agent mode handling section:
1114 + if ($intent_matched && !empty($this->fallbackResponse['text'])) {
1115 + // Update chat mode first
1116 + update_option("mxchat_mode_{$session_id}", 'ai');
1117 +
1118 + // Clear any existing PDF context to start fresh
1119 + $this->clear_pdf_transients($session_id);
1120 +
1121 + // Prepare clean switch response with explicit chat_mode
1122 + $response_data = [
1123 + 'text' => $this->fallbackResponse['text'],
1124 + 'html' => $this->fallbackResponse['html'] ?? '',
1125 + 'session_id' => $session_id,
1126 + 'chat_mode' => 'ai' // EXPLICITLY SET THIS
1127 + ];
1128 +
1129 + if ($testing_data !== null) {
1130 + $response_data['testing_data'] = $testing_data;
1131 + }
1132 +
1133 + // Save the mode switch message
1134 + $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
1135 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1136 +
1137 + // Send response and exit
1138 + wp_send_json($response_data);
1139 + wp_die();
1140 + } elseif (!$intent_matched) {
1141 + // No intent matched, handle live agent message
1142 + try {
1143 + $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
1144 +
1145 + $agent_response = [
1146 + 'status' => 'waiting_for_agent',
1147 + 'message' => esc_html__('Message sent to live agent.', 'mxchat')
1148 + ];
1149 +
1150 + if ($testing_data !== null) {
1151 + $agent_response['testing_data'] = $testing_data;
1152 + }
1153 +
1154 + wp_send_json_success($agent_response);
1155 + } catch (\Exception $e) {
1156 + wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
1157 + }
1158 + wp_die();
1159 + }
1160 + }
1161 +
1162 + // Step 1: Check for new PDF URL in the message
1163 + if (!isset($_POST['vision_processed']) && preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1164 + $new_pdf_url = $matches[0];
1165 +
1166 + // Check if this is likely a PDF-related request
1167 + $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
1168 + $is_pdf_request = false;
1169 +
1170 + foreach ($pdf_keywords as $keyword) {
1171 + if (stripos($message, $keyword) !== false) {
1172 + $is_pdf_request = true;
1173 + break;
1174 + }
1175 + }
1176 +
1177 + // If it looks like a PDF request or we're waiting for a PDF URL
1178 + if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1179 + // Validate HTTPS
1180 + if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
1181 + // Extract filename from URL
1182 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1183 +
1184 + // Clear previous PDF transients
1185 + $this->clear_pdf_transients($session_id);
1186 +
1187 + // Process new PDF using current_options
1188 + $max_pages = $current_options['pdf_max_pages'] ?? 69;
1189 + $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
1190 +
1191 + if ($embeddings === 'too_many_pages') {
1192 + $error_text = sprintf(
1193 + $current_options['pdf_intent_error_text'] ??
1194 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1195 + $max_pages
1196 + );
1197 + $this->fallbackResponse['text'] = $error_text;
1198 + } elseif ($embeddings) {
1199 + // Store new PDF information
1200 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1201 +
1202 + // If the filename is generic, create a more descriptive one
1203 + if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
1204 + strpos($pdf_filename, '.php') !== false) {
1205 + $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
1206 + }
1207 +
1208 + set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
1209 + set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
1210 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
1211 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
1212 +
1213 + $success_text = $current_options['pdf_intent_success_text'] ??
1214 + esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
1215 +
1216 + $pdf_response = [
1217 + 'success' => true,
1218 + 'message' => $success_text,
1219 + 'data' => [
1220 + 'filename' => $pdf_filename
1221 + ]
1222 + ];
1223 +
1224 + if ($testing_data !== null) {
1225 + $pdf_response['testing_data'] = $testing_data;
1226 + }
1227 +
1228 + wp_send_json($pdf_response);
1229 + wp_die();
1230 + } else {
1231 + $error_text = $current_options['pdf_intent_error_text'] ??
1232 + esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1233 + $this->fallbackResponse['text'] = $error_text;
1234 + }
1235 +
1236 + $pdf_error_response = [
1237 + 'success' => false,
1238 + 'message' => $this->fallbackResponse['text']
1239 + ];
1240 +
1241 + if ($testing_data !== null) {
1242 + $pdf_error_response['testing_data'] = $testing_data;
1243 + }
1244 +
1245 + wp_send_json($pdf_error_response);
1246 + wp_die();
1247 + }
1248 + }
1249 + }
1250 +
1251 +
1252 + // Step 2: Detect intent and handle intent-based responses
1253 + $intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1254 +
1255 + // Capture action analysis for testing panel after intent check
1256 + if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1257 + $testing_data['action_matches'] = $this->last_action_analysis;
1258 + }
1259 +
1260 + // Step 3: Handle the intent result appropriately
1261 + if ($intent_result !== false) {
1262 + // Intent was matched - ALWAYS send as JSON response, never streaming
1263 +
1264 + if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
1265 + // Intent returned a direct response array
1266 + $response_data = [
1267 + 'text' => $intent_result['text'] ?? '',
1268 + 'html' => $intent_result['html'] ?? '',
1269 + 'session_id' => $session_id
1270 + ];
1271 +
1272 + // IMPORTANT: Include chat_mode if present (for WhatsApp, Slack, etc.)
1273 + if (isset($intent_result['chat_mode'])) {
1274 + $response_data['chat_mode'] = $intent_result['chat_mode'];
1275 + }
1276 +
1277 + if ($testing_data !== null) {
1278 + $response_data['testing_data'] = $testing_data;
1279 + }
1280 +
1281 + // Clear streaming headers if they were set
1282 + if ($is_streaming) {
1283 + header_remove('Content-Type');
1284 + header_remove('Cache-Control');
1285 + header_remove('Connection');
1286 + header_remove('X-Accel-Buffering');
1287 + header('Content-Type: application/json');
1288 + }
1289 +
1290 + wp_send_json($response_data);
1291 + wp_die();
1292 + } else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
1293 + // Intent returned true and set fallbackResponse
1294 +
1295 + // SAVE TO TRANSCRIPT FIRST
1296 + if (!empty($this->fallbackResponse['text'])) {
1297 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1298 + }
1299 + if (!empty($this->fallbackResponse['html'])) {
1300 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1301 + }
1302 +
1303 + $response_data = [
1304 + 'text' => $this->fallbackResponse['text'] ?? '',
1305 + 'html' => $this->fallbackResponse['html'] ?? '',
1306 + 'session_id' => $session_id
1307 + ];
1308 +
1309 + if (isset($this->fallbackResponse['chat_mode'])) {
1310 + $response_data['chat_mode'] = $this->fallbackResponse['chat_mode'];
1311 + }
1312 +
1313 + if ($testing_data !== null) {
1314 + $response_data['testing_data'] = $testing_data;
1315 + }
1316 +
1317 + // Clear streaming headers if they were set
1318 + if ($is_streaming) {
1319 + header_remove('Content-Type');
1320 + header_remove('Cache-Control');
1321 + header_remove('Connection');
1322 + header_remove('X-Accel-Buffering');
1323 + header('Content-Type: application/json');
1324 + }
1325 +
1326 + wp_send_json($response_data);
1327 + wp_die();
1328 + }
1329 + }
1330 +
1331 + // If we get here, no intent matched OR the intent didn't provide a usable response
1332 +
1333 + // Step 4: Generate AI response
1334 + $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
1335 + $this->mxchat_increment_chat_count();
1336 +
1337 + // Generate embedding for the user's query - USE BOT-SPECIFIC API KEY
1338 + $api_key = $current_options['api_key'] ?? $this->options['api_key'];
1339 + $user_message_embedding = $this->mxchat_generate_embedding($message, $api_key);
1340 +
1341 + // Check if the embedding generation returned an error
1342 + if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
1343 + $error_message = $user_message_embedding['error'];
1344 + $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
1345 +
1346 + // FIXED: Send error in appropriate format based on streaming mode
1347 + if ($is_streaming) {
1348 + echo "data: " . json_encode([
1349 + 'error' => true,
1350 + 'error_message' => $error_message,
1351 + 'error_code' => $error_code,
1352 + 'text' => $error_message,
1353 + 'message' => $error_message
1354 + ]) . "\n\n";
1355 + echo "data: [DONE]\n\n";
1356 + flush();
1357 + } else {
1358 + wp_send_json_error([
1359 + 'error_message' => $error_message,
1360 + 'error_code' => $error_code
1361 + ]);
1362 + }
1363 + wp_die();
1364 + }
1365 +
1366 + // Check if the embedding is valid
1367 + if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
1368 + $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
1369 +
1370 + // FIXED: Send error in appropriate format based on streaming mode
1371 + if ($is_streaming) {
1372 + echo "data: " . json_encode([
1373 + 'error' => true,
1374 + 'error_message' => $error_message,
1375 + 'error_code' => 'invalid_embedding',
1376 + 'text' => $error_message,
1377 + 'message' => $error_message
1378 + ]) . "\n\n";
1379 + echo "data: [DONE]\n\n";
1380 + flush();
1381 + } else {
1382 + wp_send_json_error([
1383 + 'error_message' => $error_message,
1384 + 'error_code' => 'invalid_embedding'
1385 + ]);
1386 + }
1387 + wp_die();
1388 + }
1389 +
1390 + // Build context with both knowledge base and PDF content if available
1391 + $context_content = "User asked: '{$message}'\n\n";
1392 +
1393 + // Add action instruction if present (add this right after the above line)
1394 + if (!empty($this->current_action_instruction)) {
1395 + $context_content .= "===== SPECIAL INSTRUCTION =====\n";
1396 + $context_content .= "IMPORTANT: " . $this->current_action_instruction . "\n";
1397 + $context_content .= "Respond naturally and conversationally while following this instruction.\n";
1398 + $context_content .= "===== END SPECIAL INSTRUCTION =====\n\n";
1399 +
1400 + // Clear the instruction after using it
1401 + $this->current_action_instruction = null;
1402 + }
1403 +
1404 +
1405 + // Add page context if available and contextual awareness is enabled using current_options
1406 + if ($page_context && isset($current_options['contextual_awareness_toggle']) && $current_options['contextual_awareness_toggle'] === 'on') {
1407 + $context_content .= "===== CURRENT PAGE CONTEXT =====\n";
1408 + $context_content .= "Page URL: " . $page_context['url'] . "\n";
1409 + $context_content .= "Page Title: " . $page_context['title'] . "\n";
1410 + $context_content .= "Page Content: " . $page_context['content'] . "\n";
1411 + $context_content .= "===== END CURRENT PAGE CONTEXT =====\n\n";
1412 + }
1413 +
1414 + // Get relevant content from knowledge base - PASS BOT_ID
1415 + $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding, $bot_id);
1416 +
1417 + // NEW: Also extract URLs from system instructions
1418 + $system_instructions = $this->get_system_instructions($bot_id);
1419 + if (!empty($system_instructions)) {
1420 + preg_match_all(
1421 + '#\bhttps?://[^\s<>"\']+#i',
1422 + $system_instructions,
1423 + $system_instruction_urls
1424 + );
1425 +
1426 + if (!empty($system_instruction_urls[0])) {
1427 + // Merge with existing valid URLs
1428 + $this->current_valid_urls = array_merge(
1429 + $this->current_valid_urls,
1430 + $system_instruction_urls[0]
1431 + );
1432 + // Remove duplicates
1433 + $this->current_valid_urls = array_unique($this->current_valid_urls);
1434 +
1435 + error_log("Added " . count($system_instruction_urls[0]) . " URLs from system instructions");
1436 + }
1437 + }
1438 +
1439 +// ===== CAPTURE REAL SIMILARITY DATA FOR ADMINS =====
1440 +if ($testing_data !== null && $this->last_similarity_analysis !== null) {
1441 + // Update testing data with the REAL similarity analysis
1442 + $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
1443 + $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
1444 + $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
1445 +}
1446 +// ===== END SIMILARITY DATA CAPTURE =====
1447 +
1448 +// NEW: Add valid URLs to testing data for admin panel display (AFTER similarity data)
1449 +if ($testing_data !== null && !empty($this->current_valid_urls)) {
1450 + $testing_data['approved_urls'] = array_values($this->current_valid_urls);
1451 + error_log("Added " . count($this->current_valid_urls) . " approved URLs to testing data");
1452 +}
1453 +
1454 + if (!empty($relevant_content)) {
1455 + $context_content .= "===== OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n" . $relevant_content . "\n===== END OF OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n\n";
1456 + } else {
1457 + $context_content .= "===== NO RELEVANT CONTENT FOUND IN KNOWLEDGE DATABASE =====\n";
1458 + }
1459 +
1460 + // NEW: Add approved URLs list to context for AI
1461 + if (!empty($this->current_valid_urls)) {
1462 + $context_content .= "===== APPROVED URLS FOR CITATIONS =====\n";
1463 + $context_content .= "You may ONLY use these exact URLs in your response:\n";
1464 + foreach ($this->current_valid_urls as $url) {
1465 + $context_content .= "- " . $url . "\n";
1466 + }
1467 + $context_content .= "\nCRITICAL: Do NOT create, modify, extend, or invent any other URLs. ";
1468 + $context_content .= "===== END APPROVED URLS =====\n\n";
1469 + }
1470 +
1471 + // Check for and include PDF content
1472 + $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
1473 + $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
1474 + $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
1475 + if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
1476 + $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
1477 + if (!empty($relevant_pdf_pages)) {
1478 + $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
1479 + foreach ($relevant_pdf_pages as $page_data) {
1480 + $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
1481 + }
1482 + $context_content .= "\n";
1483 + }
1484 + }
1485 +
1486 + // Check for and include Word content
1487 + $word_url = get_transient('mxchat_word_url_' . $session_id);
1488 + $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
1489 + $word_filename = get_transient('mxchat_word_filename_' . $session_id);
1490 + if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
1491 + $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
1492 + if (!empty($relevant_word_chunks)) {
1493 + $context_content .= "Relevant content from Word document '{$word_filename}':\n";
1494 + foreach ($relevant_word_chunks as $chunk_data) {
1495 + $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
1496 + }
1497 + $context_content .= "\n";
1498 + }
1499 + }
1500 +
1501 + $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
1502 +
1503 + // Extract model from current options for bot-specific model support
1504 + $selected_model = isset($current_options['model']) ? $current_options['model'] : 'gpt-4o';
1505 +
1506 + $response = $this->mxchat_generate_response(
1507 + $context_content,
1508 + $current_options['api_key'] ?? $this->options['api_key'],
1509 + $current_options['xai_api_key'] ?? $this->options['xai_api_key'],
1510 + $current_options['claude_api_key'] ?? $this->options['claude_api_key'],
1511 + $current_options['deepseek_api_key'] ?? $this->options['deepseek_api_key'],
1512 + $current_options['gemini_api_key'] ?? $this->options['gemini_api_key'],
1513 + $current_options['openrouter_api_key'] ?? $this->options['openrouter_api_key'],
1514 + $conversation_history,
1515 + $is_streaming,
1516 + $session_id,
1517 + $testing_data,
1518 + $selected_model
1519 + );
1520 +
1521 + // Handle streaming vs non-streaming responses
1522 + if ($is_streaming) {
1523 + // Check if streaming actually happened or if it fell back to regular response
1524 + if ($response === true) {
1525 + wp_die();
1526 + }
1527 + // If we get here, streaming fell back to regular response, continue
1528 + // But if there's an error, we need to send it as SSE format since headers are already set
1529 + if (is_array($response) && isset($response['error'])) {
1530 + $error_message = $response['error'];
1531 + $error_code = $response['error_code'] ?? 'api_error';
1532 + // Send error in SSE format that the client JS can handle
1533 + echo "data: " . json_encode([
1534 + 'error' => true,
1535 + 'error_message' => $error_message,
1536 + 'error_code' => $error_code,
1537 + 'text' => $error_message, // Also include as text for fallback handling
1538 + 'message' => $error_message
1539 + ]) . "\n\n";
1540 + echo "data: [DONE]\n\n";
1541 + flush();
1542 + wp_die();
1543 + }
1544 + }
1545 +
1546 + // Check if the response is an error array (non-streaming mode)
1547 + if (is_array($response) && isset($response['error'])) {
1548 + wp_send_json_error([
1549 + 'error_message' => $response['error'],
1550 + 'error_code' => $response['error_code'] ?? 'api_error'
1551 + ]);
1552 + wp_die();
1553 + }
1554 +
1555 + // DEBUG: Check what we have
1556 + error_log("=== BEFORE URL VALIDATION ===");
1557 + error_log("current_valid_urls is empty? " . (empty($this->current_valid_urls) ? 'YES' : 'NO'));
1558 + error_log("current_valid_urls count: " . count($this->current_valid_urls));
1559 + error_log("current_valid_urls content: " . print_r($this->current_valid_urls, true));
1560 +
1561 + // If we get here, the response is valid text - now validate URLs
1562 + if (!empty($this->current_valid_urls)) {
1563 + error_log("CALLING validate_and_clean_urls");
1564 + $response = $this->validate_and_clean_urls($response, $this->current_valid_urls);
1565 + } else {
1566 + error_log("SKIPPING validation - current_valid_urls is empty");
1567 + }
1568 + // ===== END URL VALIDATION =====
1569 +
1570 + // Save the cleaned response
1571 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
1572 +
1573 + // Step 5: Save additional content if available
1574 + if (!empty($this->productCardHtml)) {
1575 + $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
1576 + }
1577 +
1578 + if (!empty($this->fallbackResponse['html'])) {
1579 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1580 + }
1581 +
1582 + // Step 6: Return the response
1583 + $response_data = [
1584 + 'text' => $response,
1585 + 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
1586 + 'session_id' => $session_id
1587 + ];
1588 +
1589 + // Always add testing data for admins (no toggle needed)
1590 + if ($testing_data !== null) {
1591 + $response_data['testing_data'] = $testing_data;
1592 + }
1593 +
1594 + wp_send_json($response_data);
1595 + wp_die();
1596 +}
1597 +
1598 +/**
1599 + * Get bot-specific options for multi-bot functionality
1600 + * Falls back to default options if bot_id is 'default' or multi-bot add-on is not active
1601 + */
1602 +// Also debug the bot options retrieval
1603 +private function get_bot_options($bot_id = 'default') {
1604 + error_log("MXCHAT DEBUG: get_bot_options called for bot: " . $bot_id);
1605 +
1606 + if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
1607 + error_log("MXCHAT DEBUG: Using default options (no multi-bot or bot is 'default')");
1608 + return array();
1609 + }
1610 +
1611 + $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
1612 +
1613 + if (!empty($bot_options)) {
1614 + error_log("MXCHAT DEBUG: Got bot-specific options from filter");
1615 + if (isset($bot_options['similarity_threshold'])) {
1616 + error_log(" - similarity_threshold: " . $bot_options['similarity_threshold']);
1617 + }
1618 + }
1619 +
1620 + return is_array($bot_options) ? $bot_options : array();
1621 +}
1622 +
1623 +/**
1624 + * Get bot-specific Pinecone configuration
1625 + * Used in the knowledge retrieval functions
1626 + */
1627 +// Also add debugging to your get_bot_pinecone_config function
1628 +private function get_bot_pinecone_config($bot_id = 'default') {
1629 + error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
1630 +
1631 + // If default bot or multi-bot add-on not active, use default Pinecone config
1632 + if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
1633 + error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
1634 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
1635 + $config = array(
1636 + 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
1637 + 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
1638 + 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
1639 + 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
1640 + );
1641 + error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
1642 + return $config;
1643 + }
1644 +
1645 + error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
1646 +
1647 + // Hook for multi-bot add-on to provide bot-specific Pinecone config
1648 + $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
1649 +
1650 + if (!empty($bot_pinecone_config)) {
1651 + error_log("MXCHAT DEBUG: Got bot-specific config from filter");
1652 + error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
1653 + error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
1654 + error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
1655 + } else {
1656 + error_log("MXCHAT DEBUG: Filter returned empty config!");
1657 + }
1658 +
1659 + return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
1660 +}
1661 +
1662 +
1663 +// Updated function to check intents and invoke the callback function
1664 +private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
1665 + global $wpdb;
1666 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1667 +
1668 + // Get the current bot_id
1669 + $current_bot_id = $this->get_current_bot_id($session_id);
1670 +
1671 + // Generate the user embedding
1672 + $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1673 +
1674 + // Check if embedding generation returned an error
1675 + if (is_array($user_embedding) && isset($user_embedding['error'])) {
1676 + $error_message = $user_embedding['error'];
1677 + $error_code = $user_embedding['error_code'] ?? 'embedding_error';
1678 +
1679 + // FIXED: Send error in appropriate format based on streaming mode
1680 + if ($this->is_streaming) {
1681 + echo "data: " . json_encode([
1682 + 'error' => true,
1683 + 'error_message' => $error_message,
1684 + 'error_code' => $error_code,
1685 + 'text' => $error_message,
1686 + 'message' => $error_message
1687 + ]) . "\n\n";
1688 + echo "data: [DONE]\n\n";
1689 + flush();
1690 + } else {
1691 + wp_send_json_error([
1692 + 'error_message' => $error_message,
1693 + 'error_code' => $error_code
1694 + ]);
1695 + }
1696 + wp_die();
1697 + }
1698 +
1699 + // Check if embedding is valid
1700 + if (!is_array($user_embedding) || empty($user_embedding)) {
1701 + $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
1702 +
1703 + // FIXED: Send error in appropriate format based on streaming mode
1704 + if ($this->is_streaming) {
1705 + echo "data: " . json_encode([
1706 + 'error' => true,
1707 + 'error_message' => $error_message,
1708 + 'error_code' => 'invalid_embedding',
1709 + 'text' => $error_message,
1710 + 'message' => $error_message
1711 + ]) . "\n\n";
1712 + echo "data: [DONE]\n\n";
1713 + flush();
1714 + } else {
1715 + wp_send_json_error([
1716 + 'error_message' => $error_message,
1717 + 'error_code' => 'invalid_embedding'
1718 + ]);
1719 + }
1720 + wp_die();
1721 + }
1722 +
1723 + // Fetch intents from the database
1724 + $table_name = $wpdb->prefix . 'mxchat_intents';
1725 + if ($chat_mode === 'agent') {
1726 + $query = $wpdb->prepare(
1727 + "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
1728 + 'mxchat_handle_switch_to_chatbot_intent'
1729 + );
1730 + $intents = $wpdb->get_results($query);
1731 + } else {
1732 + $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
1733 + }
1734 +
1735 + if (empty($intents)) {
1736 + return false;
1737 + }
1738 +
1739 + $highest_similarity = -INF;
1740 + $matched_intent = null;
1741 +
1742 + // Array to store action analysis for testing panel
1743 + $action_analysis = [];
1744 +
1745 + foreach ($intents as $intent) {
1746 + // Additional check for enabled state
1747 + $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
1748 + if (!$is_enabled) {
1749 + continue;
1750 + }
1751 +
1752 + // Check if this action is enabled for the current bot
1753 + if (!$this->is_action_enabled_for_bot($intent, $current_bot_id)) {
1754 + continue;
1755 + }
1756 +
1757 + $intent_embedding_serialized = $intent->embedding_vector;
1758 + $intent_embedding = $intent_embedding_serialized
1759 + ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1760 + : null;
1761 +
1762 + if (!is_array($intent_embedding)) {
1763 + continue;
1764 + }
1765 +
1766 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1767 + $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1768 +
1769 + // Store action analysis data for testing panel
1770 + $action_analysis[] = [
1771 + 'intent_label' => $intent->intent_label,
1772 + 'callback_function' => $intent->callback_function,
1773 + 'similarity' => round($similarity, 4),
1774 + 'similarity_percentage' => round($similarity * 100, 2),
1775 + 'threshold' => $intent_threshold,
1776 + 'threshold_percentage' => round($intent_threshold * 100, 2),
1777 + 'above_threshold' => $similarity >= $intent_threshold,
1778 + 'triggered' => false // Will be updated below if this intent is triggered
1779 + ];
1780 +
1781 + if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1782 + $highest_similarity = $similarity;
1783 + $matched_intent = $intent;
1784 + }
1785 + }
1786 +
1787 + // Mark the triggered action if any
1788 + if ($matched_intent) {
1789 + foreach ($action_analysis as &$action) {
1790 + if ($action['intent_label'] === $matched_intent->intent_label) {
1791 + $action['triggered'] = true;
1792 + break;
1793 + }
1794 + }
1795 + }
1796 +
1797 + // Sort actions by similarity (highest first) and store for testing panel
1798 + usort($action_analysis, function($a, $b) {
1799 + return $b['similarity'] <=> $a['similarity'];
1800 + });
1801 +
1802 + // Store action analysis for testing panel capture
1803 + $this->last_action_analysis = $action_analysis;
1804 +
1805 + // Around line 715 in your mxchat_check_intent_and_invoke_callback function
1806 + if ($matched_intent) {
1807 + // If the callback is a method on this instance (core callback), call it directly
1808 + if (method_exists($this, $matched_intent->callback_function)) {
1809 + $callback_result = call_user_func(
1810 + [$this, $matched_intent->callback_function],
1811 + $message,
1812 + $user_id,
1813 + $session_id,
1814 + $matched_intent,
1815 + $user_context ?? null
1816 + );
1817 + } else {
1818 + // Otherwise, use apply_filters for add-on callbacks
1819 + $callback_result = apply_filters(
1820 + $matched_intent->callback_function,
1821 + false,
1822 + $message,
1823 + $user_id,
1824 + $session_id,
1825 + $matched_intent
1826 + );
1827 + }
1828 +
1829 + // Handle the callback result properly
1830 + if ($callback_result !== false) {
1831 + // If callback returned an array with chat_mode, use it directly
1832 + if (is_array($callback_result) && isset($callback_result['chat_mode'])) {
1833 + $this->fallbackResponse = $callback_result;
1834 + return $callback_result; // Return the full array
1835 + } else {
1836 + $this->fallbackResponse = $callback_result;
1837 + return true;
1838 + }
1839 + }
1840 + }
1841 +
1842 + return false;
1843 +}
1844 +
1845 +/**
1846 + * Check if an action is enabled for a specific bot
1847 + */
1848 +private function is_action_enabled_for_bot($intent, $bot_id) {
1849 + // If enabled_bots column doesn't exist or is null, assume it's enabled for all bots (backward compatibility)
1850 + if (!isset($intent->enabled_bots) || empty($intent->enabled_bots)) {
1851 + return true;
1852 + }
1853 +
1854 + $enabled_bots = json_decode($intent->enabled_bots, true);
1855 +
1856 + // If JSON decode fails or returns empty array, assume enabled for all (backward compatibility)
1857 + if (!is_array($enabled_bots) || empty($enabled_bots)) {
1858 + return true;
1859 + }
1860 +
1861 + // Check if the current bot is in the enabled bots list
1862 + return in_array($bot_id, $enabled_bots);
1863 +}
1864 +
1865 +// Helper function to clear PDF and Word document related transients
1866 +private function clear_pdf_transients($session_id) {
1867 + // PDF transients
1868 + delete_transient('mxchat_pdf_url_' . $session_id);
1869 + delete_transient('mxchat_pdf_embeddings_' . $session_id);
1870 + delete_transient('mxchat_include_pdf_in_context_' . $session_id);
1871 + delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
1872 +
1873 + // Word document transients
1874 + delete_transient('mxchat_word_url_' . $session_id);
1875 + delete_transient('mxchat_word_filename_' . $session_id);
1876 + delete_transient('mxchat_word_embeddings_' . $session_id);
1877 + delete_transient('mxchat_include_word_in_context_' . $session_id);
1878 + delete_transient('mxchat_waiting_for_word_' . $session_id);
1879 +}
1880 +
1881 +
1882 +
1883 +//verified good
1884 +public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1885 + // Get the user's original instruction/message
1886 + $user_instruction = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Please provide your email address.", 'mxchat'));
1887 +
1888 + // Set instruction for AI - just pass along what the user wanted to say
1889 + $this->current_action_instruction = $user_instruction;
1890 +
1891 + // Set the transient to track email capture flow
1892 + set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1893 +
1894 + // Return false to let the AI generate the response
1895 + return false;
1896 +}
1897 +
1898 +public function mxchat_generate_image($message, $user_id, $session_id) {
1899 + //error_log("Starting image generation for message: " . $message);
1900 +
1901 + // Prepare a prompt for DALL-E
1902 + $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1903 +
1904 + // Use the existing OpenAI API key
1905 + $openai_api_key = sanitize_text_field($this->options['api_key']);
1906 +
1907 + // Call DALL-E to generate an image
1908 + $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1909 +
1910 + // Check if the response contains an image URL
1911 + if (isset($image_response['imageUrl'])) {
1912 + $image_url = esc_url_raw($image_response['imageUrl']);
1913 +
1914 + // Construct the HTML with a CSS class instead of inline styles
1915 + $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1916 + $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1917 +
1918 + // Save the bot message with both text and HTML
1919 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1920 + $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
1921 +
1922 + // Set the fallback response for the chat handler
1923 + $this->fallbackResponse = [
1924 + 'text' => $response_text,
1925 + 'html' => $response_html,
1926 + 'images' => [$image_url]
1927 + ];
1928 +
1929 + // For debugging/verification - Use json_encode to verify what's being set
1930 + //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
1931 +
1932 + // Return the response directly instead of relying on the property
1933 + return $this->fallbackResponse;
1934 + } else {
1935 + $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1936 +
1937 + // Save the error message
1938 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1939 +
1940 + // Set the fallback response for the chat handler
1941 + $this->fallbackResponse = [
1942 + 'text' => $response_text,
1943 + 'html' => '',
1944 + 'images' => []
1945 + ];
1946 +
1947 + //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1948 + //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
1949 +
1950 + // Return the response directly instead of relying on the property
1951 + return $this->fallbackResponse;
1952 + }
1953 +}
1954 +private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1955 + $api_url = 'https://api.openai.com/v1/images/generations';
1956 + $body = json_encode([
1957 + 'prompt' => sanitize_text_field($prompt),
1958 + 'n' => 1,
1959 + 'size' => '1024x1024',
1960 + 'model' => sanitize_text_field($model),
1961 + ]);
1962 +
1963 + $args = [
1964 + 'body' => $body,
1965 + 'headers' => [
1966 + 'Content-Type' => 'application/json',
1967 + 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1968 + ],
1969 + 'method' => 'POST',
1970 + 'timeout' => absint($timeout),
1971 + ];
1972 +
1973 + $response = wp_remote_post($api_url, $args);
1974 +
1975 + if (is_wp_error($response)) {
1976 + //error_log("DALL-E request failed: " . $response->get_error_message());
1977 + return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1978 + }
1979 +
1980 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
1981 +
1982 + if (isset($response_body['data'][0]['url'])) {
1983 + return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1984 + } else {
1985 + //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1986 + return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1987 + }
1988 +}
1989 +
1990 +/**
1991 + * Handle web search requests.
1992 + *
1993 + * Sends the refined search query to the Brave Search API and uses the
1994 + * results to generate a conversational response with the AI model.
1995 + *
1996 + * @since 1.0.0
1997 + * @param string $message The user's search query.
1998 + * @param string $user_id The user identifier.
1999 + * @param string $session_id The current session ID.
2000 + * @return array Response array containing text with embedded HTML links
2001 + */
2002 +public function mxchat_handle_search_request($message, $user_id, $session_id) {
2003 + // Step 1: Interpret and refine the search query
2004 + $refined_search_query = $this->mxchat_interpret_search_query($message);
2005 + if (empty($refined_search_query)) {
2006 + return array(
2007 + 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
2008 + 'html' => ''
2009 + );
2010 + }
2011 +
2012 + // Retrieve and validate API settings
2013 + $options = get_option('mxchat_options');
2014 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
2015 + $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
2016 +
2017 + if (empty($api_key)) {
2018 + return array(
2019 + 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
2020 + 'html' => ''
2021 + );
2022 + }
2023 +
2024 + // Build the API request URL
2025 + $api_url = add_query_arg(
2026 + array(
2027 + 'q' => rawurlencode($refined_search_query),
2028 + 'count' => $results_count,
2029 + 'text_decorations' => 'true',
2030 + 'rich_data' => 'true',
2031 + ),
2032 + 'https://api.search.brave.com/res/v1/web/search'
2033 + );
2034 +
2035 + // Attempt to retrieve cached results first
2036 + $transient_key = 'mxchat_search_' . md5($refined_search_query);
2037 + $results = get_transient($transient_key);
2038 +
2039 + if (false === $results) {
2040 + // SECURITY FIX: Changed to wp_safe_remote_get
2041 + $response = wp_safe_remote_get(
2042 + $api_url,
2043 + array(
2044 + 'headers' => array(
2045 + 'Accept' => 'application/json',
2046 + 'Accept-Encoding' => 'gzip',
2047 + 'X-Subscription-Token'=> $api_key,
2048 + ),
2049 + 'timeout' => 10,
2050 + )
2051 + );
2052 +
2053 + if (is_wp_error($response)) {
2054 + return array(
2055 + 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
2056 + 'html' => ''
2057 + );
2058 + }
2059 +
2060 + $results = json_decode(wp_remote_retrieve_body($response), true);
2061 +
2062 + if (json_last_error() !== JSON_ERROR_NONE) {
2063 + return array(
2064 + 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
2065 + 'html' => ''
2066 + );
2067 + }
2068 +
2069 + // Cache results for one hour
2070 + set_transient($transient_key, $results, HOUR_IN_SECONDS);
2071 + }
2072 +
2073 + // Process results
2074 + if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
2075 + // Create a more straightforward summary with HTML links
2076 + $search_results_text = '';
2077 +
2078 + // Add a simple intro
2079 + $search_results_text .= sprintf(
2080 + esc_html__("Here's what I found about '%s':", 'mxchat'),
2081 + esc_html($refined_search_query)
2082 + );
2083 +
2084 + // Add the top results with HTML links
2085 + foreach (array_slice($results['web']['results'], 0, 5) as $result) {
2086 + $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
2087 + $url = isset($result['url']) ? esc_url($result['url']) : '';
2088 + $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
2089 +
2090 + // Add a line break after the intro
2091 + $search_results_text .= '<br><br>';
2092 +
2093 + // Add title as a link
2094 + $search_results_text .= sprintf(
2095 + '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
2096 + $url,
2097 + $title
2098 + );
2099 +
2100 + // Add a condensed description
2101 + $search_results_text .= sprintf("%s", $description);
2102 + }
2103 +
2104 + // Save to chat history
2105 + $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
2106 +
2107 + // Return the formatted text with embedded HTML links
2108 + return array(
2109 + 'text' => $search_results_text,
2110 + 'html' => ''
2111 + );
2112 + } else {
2113 + return array(
2114 + 'text' => sprintf(
2115 + esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
2116 + esc_html($refined_search_query)
2117 + ),
2118 + 'html' => ''
2119 + );
2120 + }
2121 +}
2122 +
2123 +//very good
2124 +/**
2125 + * Handle image search requests from the chatbot
2126 + *
2127 + * @param string $message The user's search query
2128 + * @param int $user_id The user's ID
2129 + * @param string $session_id The chat session ID
2130 + * @return array Response array with text and HTML content
2131 + */
2132 +public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
2133 + // Step 1: Interpret the search query using the user's selected AI model
2134 + $refined_search_query = $this->mxchat_interpret_search_query($message);
2135 +
2136 + // If no query was interpreted, return a fallback message
2137 + if (empty($refined_search_query)) {
2138 + return array(
2139 + 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
2140 + 'html' => "",
2141 + );
2142 + }
2143 +
2144 + // Brave API URL
2145 + $api_url = 'https://api.search.brave.com/res/v1/images/search';
2146 +
2147 + // Retrieve Brave API settings
2148 + $options = get_option('mxchat_options');
2149 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
2150 +
2151 + if (empty($api_key)) {
2152 + return array(
2153 + 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
2154 + 'html' => "",
2155 + );
2156 + }
2157 +
2158 + $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
2159 + $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
2160 +
2161 + // Append query parameters based on settings
2162 + $api_url = add_query_arg([
2163 + 'q' => rawurlencode($refined_search_query),
2164 + 'count' => $image_count,
2165 + 'safesearch' => $safe_search,
2166 + ], $api_url);
2167 +
2168 + // Implement caching
2169 + $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
2170 + $body = get_transient($transient_key);
2171 +
2172 + if (false === $body) {
2173 + $args = [
2174 + 'headers' => [
2175 + 'Accept' => 'application/json',
2176 + 'Accept-Encoding' => 'gzip',
2177 + 'X-Subscription-Token' => $api_key,
2178 + ],
2179 + 'timeout' => 10,
2180 + ];
2181 +
2182 + // SECURITY FIX: Changed to wp_safe_remote_get
2183 + $response = wp_safe_remote_get($api_url, $args);
2184 +
2185 + if (is_wp_error($response)) {
2186 + return array(
2187 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
2188 + 'html' => "",
2189 + );
2190 + }
2191 +
2192 + $body = json_decode(wp_remote_retrieve_body($response), true);
2193 + set_transient($transient_key, $body, HOUR_IN_SECONDS);
2194 + }
2195 +
2196 + // Process the API response
2197 + if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
2198 + $html_output = '<div class="mxchat-image-gallery">';
2199 +
2200 + // Get the configured image count (1-6)
2201 + $display_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
2202 + $display_count = min($display_count, count($body['results'])); // Make sure we don't exceed available images
2203 +
2204 + // Use only the requested number of images
2205 + for ($i = 0; $i < $display_count; $i++) {
2206 + $image = $body['results'][$i];
2207 + $image_url = isset($image['url']) ? esc_url($image['url']) : '';
2208 + $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
2209 + $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
2210 +
2211 + if ($image_url && $thumbnail_url) {
2212 + $html_output .= '<div class="mxchat-image-item">';
2213 + $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
2214 + $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
2215 + $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
2216 + $html_output .= '</a></div>';
2217 + }
2218 + }
2219 +
2220 + $html_output .= '</div>';
2221 +
2222 + // Create response text
2223 + $response_text = sprintf(__("Here are some images of %s:", 'mxchat'), $refined_search_query);
2224 +
2225 + // Save both response text and HTML to chat history
2226 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2227 + $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
2228 +
2229 + // Return the combined response
2230 + return array(
2231 + 'text' => $response_text,
2232 + 'html' => $html_output,
2233 + );
2234 + } else {
2235 + $response_text = __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat');
2236 +
2237 + // Save the error message to chat history
2238 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2239 +
2240 + return array(
2241 + 'text' => $response_text,
2242 + 'html' => "",
2243 + );
2244 + }
2245 +}
2246 +
2247 +/**
2248 + * Interpret the search query using the user's selected AI model
2249 + *
2250 + * @param string $user_query The original query from the user
2251 + * @return string The refined search query
2252 + */
2253 +public function mxchat_interpret_search_query($user_query) {
2254 + $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');
2255 +
2256 + // Get options and determine the selected model
2257 + $options = $this->options ?? get_option('mxchat_options');
2258 + $selected_model = isset($options['model']) ? $options['model'] : 'gpt-4o';
2259 +
2260 + // Extract model prefix to determine the provider
2261 + $model_parts = explode('-', $selected_model);
2262 + $provider = strtolower($model_parts[0]);
2263 +
2264 + // Determine which API key to use based on the provider
2265 + switch ($provider) {
2266 + case 'gemini':
2267 + $api_key = isset($options['gemini_api_key']) ? sanitize_text_field($options['gemini_api_key']) : '';
2268 + if (empty($api_key)) {
2269 + return sanitize_text_field($user_query); // Default to original query if API key missing
2270 + }
2271 + return $this->interpret_query_with_gemini($user_query, $system_prompt, $api_key, $selected_model);
2272 +
2273 + case 'claude':
2274 + $api_key = isset($options['claude_api_key']) ? sanitize_text_field($options['claude_api_key']) : '';
2275 + if (empty($api_key)) {
2276 + return sanitize_text_field($user_query);
2277 + }
2278 + return $this->interpret_query_with_claude($user_query, $system_prompt, $api_key, $selected_model);
2279 +
2280 + case 'grok':
2281 + $api_key = isset($options['xai_api_key']) ? sanitize_text_field($options['xai_api_key']) : '';
2282 + if (empty($api_key)) {
2283 + return sanitize_text_field($user_query);
2284 + }
2285 + return $this->interpret_query_with_xai($user_query, $system_prompt, $api_key, $selected_model);
2286 +
2287 + case 'deepseek':
2288 + $api_key = isset($options['deepseek_api_key']) ? sanitize_text_field($options['deepseek_api_key']) : '';
2289 + if (empty($api_key)) {
2290 + return sanitize_text_field($user_query);
2291 + }
2292 + return $this->interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $selected_model);
2293 +
2294 + case 'gpt':
2295 + default:
2296 + // Default to OpenAI for custom models or unrecognized prefixes
2297 + $api_key = isset($options['api_key']) ? sanitize_text_field($options['api_key']) : '';
2298 + if (empty($api_key)) {
2299 + return sanitize_text_field($user_query);
2300 + }
2301 + return $this->interpret_query_with_openai($user_query, $system_prompt, $api_key, $selected_model);
2302 + }
2303 +}
2304 +
2305 +/**
2306 + * Interpret query using OpenAI models
2307 + */
2308 +private function interpret_query_with_openai($user_query, $system_prompt, $api_key, $model = 'gpt-4o') {
2309 + $url = 'https://api.openai.com/v1/chat/completions';
2310 + $args = [
2311 + 'headers' => [
2312 + 'Authorization' => 'Bearer ' . $api_key,
2313 + 'Content-Type' => 'application/json',
2314 + ],
2315 + 'body' => wp_json_encode([
2316 + 'model' => $model,
2317 + 'messages' => [
2318 + ['role' => 'system', 'content' => $system_prompt],
2319 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2320 + ],
2321 + 'temperature' => 0.2,
2322 + 'max_tokens' => 20,
2323 + ]),
2324 + 'method' => 'POST',
2325 + 'timeout' => 15,
2326 + ];
2327 +
2328 + $response = wp_remote_post($url, $args);
2329 + if (is_wp_error($response)) {
2330 + return sanitize_text_field($user_query);
2331 + }
2332 +
2333 + $body = json_decode(wp_remote_retrieve_body($response), true);
2334 + return isset($body['choices'][0]['message']['content'])
2335 + ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
2336 + : sanitize_text_field($user_query);
2337 +}
2338 +
2339 +/**
2340 + * Interpret query using Claude models
2341 + */
2342 +private function interpret_query_with_claude($user_query, $system_prompt, $api_key, $model) {
2343 + $url = 'https://api.anthropic.com/v1/messages';
2344 +
2345 + $args = [
2346 + 'headers' => [
2347 + 'Content-Type' => 'application/json',
2348 + 'x-api-key' => $api_key,
2349 + 'anthropic-version' => '2023-06-01',
2350 + ],
2351 + 'body' => wp_json_encode([
2352 + 'model' => $model,
2353 + 'system' => $system_prompt,
2354 + 'messages' => [
2355 + ['role' => 'user', 'content' => sanitize_text_field($user_query)]
2356 + ],
2357 + 'max_tokens' => 20,
2358 + 'temperature' => 0.2,
2359 + ]),
2360 + 'method' => 'POST',
2361 + 'timeout' => 15,
2362 + ];
2363 +
2364 + $response = wp_remote_post($url, $args);
2365 + if (is_wp_error($response)) {
2366 + return sanitize_text_field($user_query);
2367 + }
2368 +
2369 + $body = json_decode(wp_remote_retrieve_body($response), true);
2370 + if (!empty($body['content'][0]['text'])) {
2371 + return sanitize_text_field(trim($body['content'][0]['text']));
2372 + }
2373 +
2374 + return sanitize_text_field($user_query);
2375 +}
2376 +
2377 +/**
2378 + * Interpret query using Gemini models
2379 + */
2380 +private function interpret_query_with_gemini($user_query, $system_prompt, $api_key, $model) {
2381 + // Strip "gemini-" prefix for the API
2382 + $model_version = str_replace('gemini-', '', $model);
2383 +
2384 + $url = "https://generativelanguage.googleapis.com/v1/models/$model_version:generateContent?key=" . urlencode($api_key);
2385 +
2386 + $args = [
2387 + 'headers' => [
2388 + 'Content-Type' => 'application/json',
2389 + ],
2390 + 'body' => wp_json_encode([
2391 + 'contents' => [
2392 + [
2393 + 'role' => 'user',
2394 + 'parts' => [
2395 + ['text' => $system_prompt . "\n\nQuery: " . sanitize_text_field($user_query)]
2396 + ]
2397 + ]
2398 + ],
2399 + 'generationConfig' => [
2400 + 'temperature' => 0.2,
2401 + 'maxOutputTokens' => 20,
2402 + ],
2403 + ]),
2404 + 'method' => 'POST',
2405 + 'timeout' => 15,
2406 + ];
2407 +
2408 + $response = wp_remote_post($url, $args);
2409 + if (is_wp_error($response)) {
2410 + return sanitize_text_field($user_query);
2411 + }
2412 +
2413 + $body = json_decode(wp_remote_retrieve_body($response), true);
2414 + if (!empty($body['candidates'][0]['content']['parts'][0]['text'])) {
2415 + return sanitize_text_field(trim($body['candidates'][0]['content']['parts'][0]['text']));
2416 + }
2417 +
2418 + return sanitize_text_field($user_query);
2419 +}
2420 +
2421 +/**
2422 + * Interpret query using X.AI (Grok) models
2423 + */
2424 +private function interpret_query_with_xai($user_query, $system_prompt, $api_key, $model) {
2425 + $url = 'https://api.xai.com/v1/chat/completions';
2426 +
2427 + $args = [
2428 + 'headers' => [
2429 + 'Content-Type' => 'application/json',
2430 + 'Authorization' => 'Bearer ' . $api_key,
2431 + ],
2432 + 'body' => wp_json_encode([
2433 + 'model' => $model,
2434 + 'messages' => [
2435 + ['role' => 'system', 'content' => $system_prompt],
2436 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2437 + ],
2438 + 'temperature' => 0.2,
2439 + 'max_tokens' => 20,
2440 + ]),
2441 + 'method' => 'POST',
2442 + 'timeout' => 15,
2443 + ];
2444 +
2445 + $response = wp_remote_post($url, $args);
2446 + if (is_wp_error($response)) {
2447 + return sanitize_text_field($user_query);
2448 + }
2449 +
2450 + $body = json_decode(wp_remote_retrieve_body($response), true);
2451 + if (isset($body['choices'][0]['message']['content'])) {
2452 + return sanitize_text_field(trim($body['choices'][0]['message']['content']));
2453 + }
2454 +
2455 + return sanitize_text_field($user_query);
2456 +}
2457 +
2458 +/**
2459 + * Interpret query using DeepSeek models
2460 + */
2461 +private function interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $model) {
2462 + $url = 'https://api.deepseek.com/v1/chat/completions';
2463 +
2464 + $args = [
2465 + 'headers' => [
2466 + 'Content-Type' => 'application/json',
2467 + 'Authorization' => 'Bearer ' . $api_key,
2468 + ],
2469 + 'body' => wp_json_encode([
2470 + 'model' => $model,
2471 + 'messages' => [
2472 + ['role' => 'system', 'content' => $system_prompt],
2473 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2474 + ],
2475 + 'temperature' => 0.2,
2476 + 'max_tokens' => 20,
2477 + ]),
2478 + 'method' => 'POST',
2479 + 'timeout' => 15,
2480 + ];
2481 +
2482 + $response = wp_remote_post($url, $args);
2483 + if (is_wp_error($response)) {
2484 + return sanitize_text_field($user_query);
2485 + }
2486 +
2487 + $body = json_decode(wp_remote_retrieve_body($response), true);
2488 + if (isset($body['choices'][0]['message']['content'])) {
2489 + return sanitize_text_field(trim($body['choices'][0]['message']['content']));
2490 + }
2491 +
2492 + return sanitize_text_field($user_query);
2493 +}
2494 +
2495 +//very good
2496 +private function add_email_to_loops($email) {
2497 + // Sanitize the email
2498 + $email = sanitize_email($email);
2499 +
2500 + // Retrieve and sanitize options
2501 + $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
2502 + $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
2503 +
2504 + // Check for missing API key or mailing list ID
2505 + if (empty($api_key) || empty($mailing_list_id)) {
2506 + //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
2507 + return;
2508 + }
2509 +
2510 + $data = array(
2511 + 'email' => $email,
2512 + 'subscribed' => true,
2513 + 'source' => __('MxChat AI Chatbot', 'mxchat'),
2514 + 'mailingLists' => array($mailing_list_id => true),
2515 + );
2516 +
2517 + $url = 'https://app.loops.so/api/v1/contacts/create';
2518 + $args = array(
2519 + 'body' => wp_json_encode($data),
2520 + 'headers' => array(
2521 + 'Authorization' => 'Bearer ' . $api_key,
2522 + 'Content-Type' => 'application/json',
2523 + ),
2524 + 'method' => 'POST',
2525 + 'timeout' => 45,
2526 + );
2527 +
2528 + $response = wp_remote_post($url, $args);
2529 +
2530 + // Handle errors in the API request
2531 + if (is_wp_error($response)) {
2532 + //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
2533 + return;
2534 + }
2535 +
2536 + // Check for non-200 HTTP responses
2537 + $response_code = wp_remote_retrieve_response_code($response);
2538 + if ($response_code != 200) {
2539 + $response_body = wp_remote_retrieve_body($response);
2540 + //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
2541 + }
2542 +}
2543 +
2544 +public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
2545 + // Get the maximum number of pages allowed from admin settings
2546 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2547 +
2548 + // Retrieve options for dynamic texts
2549 + $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
2550 + $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
2551 + $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
2552 +
2553 + // Check for explicit request for new PDF
2554 + $new_pdf_requested = stripos($message, 'new') !== false ||
2555 + stripos($message, 'another') !== false ||
2556 + stripos($message, 'different') !== false;
2557 +
2558 + // If user mentions adding/reading a PDF, set waiting flag
2559 + if (stripos($message, 'pdf') !== false ||
2560 + stripos($message, 'document') !== false ||
2561 + stripos($message, 'read') !== false) {
2562 + set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
2563 + $this->fallbackResponse['text'] = $trigger_text;
2564 + return;
2565 + }
2566 +
2567 + // If we're waiting for a URL or user requested new PDF
2568 + if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
2569 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
2570 + // Process URL... (rest of your existing URL processing code)
2571 + } else {
2572 + $this->fallbackResponse['text'] = $trigger_text;
2573 + }
2574 + return;
2575 + }
2576 +
2577 + // Default to proceeding with conversation if no specific PDF action is needed
2578 + $this->fallbackResponse['text'] = '';
2579 +}
2580 +
2581 +
2582 +/**
2583 + * Enhanced fetch_and_split_pdf_pages with SSRF protection
2584 + */
2585 +private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
2586 + // CLEAR DEBUG LOGGING
2587 + //error_log("=== MXCHAT PDF PROCESSING START ===");
2588 + //error_log("PDF Source: " . $pdf_source);
2589 + //error_log("Max Pages: " . $max_pages);
2590 + //error_log("Session ID: " . ($this->session_id ?? 'not set'));
2591 +
2592 + // Check if Advanced Claude Toolbar is available and enabled
2593 + $claude_available = function_exists('mxchatACT_is_advanced_claude_enabled');
2594 + $claude_enabled = $claude_available ? mxchatACT_is_advanced_claude_enabled() : false;
2595 +
2596 + //error_log("Claude Function Available: " . ($claude_available ? 'YES' : 'NO'));
2597 + //error_log("Claude Enabled: " . ($claude_enabled ? 'YES' : 'NO'));
2598 +
2599 + if ($claude_available && $claude_enabled) {
2600 + //error_log("🚀 ATTEMPTING CLAUDE PROCESSING...");
2601 +
2602 + // Attempt Claude processing first
2603 + $claude_result = apply_filters('mxchat_process_pdf_advanced', false, $pdf_source, $max_pages, $this->session_id);
2604 +
2605 + if ($claude_result !== false && is_array($claude_result) && !empty($claude_result)) {
2606 + //error_log("✅ CLAUDE PROCESSING SUCCESSFUL!");
2607 + //error_log("Claude returned " . count($claude_result) . " processed pages");
2608 +
2609 + // Log first page details for verification
2610 + if (isset($claude_result[0])) {
2611 + $first_page = $claude_result[0];
2612 + //error_log("First page enhanced: " . (isset($first_page['enhanced']) && $first_page['enhanced'] ? 'YES' : 'NO'));
2613 + //error_log("Processing method: " . ($first_page['processing_method'] ?? 'not set'));
2614 + //error_log("First page text preview: " . substr($first_page['text'] ?? '', 0, 100) . "...");
2615 + }
2616 +
2617 + //error_log("=== MXCHAT PDF PROCESSING END (CLAUDE) ===");
2618 + return $claude_result;
2619 + } else {
2620 + //error_log("❌ CLAUDE PROCESSING FAILED or returned invalid result");
2621 + //error_log("Claude result type: " . gettype($claude_result));
2622 + if (is_array($claude_result)) {
2623 + //error_log("Claude result count: " . count($claude_result));
2624 + }
2625 + }
2626 + }
2627 +
2628 + // Fallback to basic processing
2629 + //error_log("🔄 FALLING BACK TO BASIC PDF PROCESSING...");
2630 +
2631 + $upload_dir = wp_upload_dir();
2632 + $temp_file = null;
2633 +
2634 + try {
2635 + // Your existing basic processing code here...
2636 + // (I'll include the key parts with debug logging)
2637 +
2638 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
2639 + //error_log("Downloading PDF from URL...");
2640 +
2641 + // SECURITY FIX: Validate URL before processing
2642 + if (!$this->mxchat_is_safe_pdf_url($pdf_source)) {
2643 + //error_log("❌ SECURITY: Blocked unsafe PDF URL");
2644 + return false;
2645 + }
2646 +
2647 + $temp_file = wp_tempnam($pdf_source);
2648 +
2649 + // SECURITY FIX: Changed from wp_remote_get to wp_safe_remote_get
2650 + $response = wp_safe_remote_get($pdf_source, [
2651 + 'timeout' => 60,
2652 + 'headers' => ['User-Agent' => 'MxChat PDF Processor']
2653 + ]);
2654 +
2655 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2656 + $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code($response);
2657 + //error_log("❌ BASIC PROCESSING: Failed to download PDF: " . $error_message);
2658 + return false;
2659 + }
2660 +
2661 + file_put_contents($temp_file, wp_remote_retrieve_body($response));
2662 + //error_log("✅ PDF downloaded successfully");
2663 + } else {
2664 + $temp_file = $pdf_source;
2665 + //error_log("Using local PDF file: " . $temp_file);
2666 + }
2667 +
2668 + // Parse PDF
2669 + //error_log("Parsing PDF with basic parser...");
2670 + $parser = new \Smalot\PdfParser\Parser();
2671 + $pdf = $parser->parseFile($temp_file);
2672 + $pages = $pdf->getPages();
2673 +
2674 + //error_log("PDF contains " . count($pages) . " pages");
2675 +
2676 + if (count($pages) > $max_pages) {
2677 + //error_log("❌ BASIC PROCESSING: Too many pages (" . count($pages) . " > " . $max_pages . ")");
2678 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
2679 + unlink($temp_file);
2680 + }
2681 + return 'too_many_pages';
2682 + }
2683 +
2684 + $embeddings = [];
2685 + $processed_pages = 0;
2686 +
2687 + foreach ($pages as $page_number => $page) {
2688 + $text = $page->getText();
2689 +
2690 + if (empty(trim($text))) {
2691 + //error_log("Skipping empty page: " . ($page_number + 1));
2692 + continue;
2693 + }
2694 +
2695 + $text = $this->mxchat_clean_text($text);
2696 +
2697 + $embedding = $this->mxchat_generate_embedding(
2698 + __("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
2699 + $this->options['api_key']
2700 + );
2701 +
2702 + if ($embedding) {
2703 + $embeddings[] = [
2704 + 'page_number' => $page_number + 1,
2705 + 'embedding' => $embedding,
2706 + 'text' => $text,
2707 + 'enhanced' => false, // CLEARLY MARK AS BASIC
2708 + 'processing_method' => 'basic_pdf_parser'
2709 + ];
2710 + $processed_pages++;
2711 + }
2712 + }
2713 +
2714 + //error_log("✅ BASIC PROCESSING COMPLETE: " . $processed_pages . " pages processed");
2715 +
2716 + // Cleanup
2717 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2718 + unlink($temp_file);
2719 + }
2720 +
2721 + //error_log("=== MXCHAT PDF PROCESSING END (BASIC) ===");
2722 + return $embeddings;
2723 +
2724 + } catch (\Exception $e) {
2725 + //error_log("❌ BASIC PROCESSING ERROR: " . $e->getMessage());
2726 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2727 + unlink($temp_file);
2728 + }
2729 + //error_log("=== MXCHAT PDF PROCESSING END (ERROR) ===");
2730 + return false;
2731 + }
2732 +}
2733 +
2734 +
2735 +/**
2736 + * Validate PDF URL for security
2737 + * Prevents SSRF attacks by blocking dangerous URLs
2738 + */
2739 +
2740 +private function mxchat_is_safe_pdf_url($url) {
2741 + // Use WordPress core function for comprehensive validation
2742 + // This blocks localhost, private IPs, and reserved IP ranges
2743 + $validated_url = wp_http_validate_url($url);
2744 +
2745 + if ($validated_url === false) {
2746 + return false;
2747 + }
2748 +
2749 + // Additional check: only allow HTTP/HTTPS schemes
2750 + $parsed = parse_url($url);
2751 + if (!isset($parsed['scheme']) || !in_array($parsed['scheme'], ['http', 'https'], true)) {
2752 + return false;
2753 + }
2754 +
2755 + return true;
2756 +}
2757 +
2758 +
2759 +private function mxchat_clean_text($text) {
2760 + // Remove excessive whitespace
2761 + $text = preg_replace('/\s+/', ' ', $text);
2762 +
2763 + // Remove control characters except newlines and tabs
2764 + $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);
2765 +
2766 + // Normalize line endings
2767 + $text = str_replace(["\r\n", "\r"], "\n", $text);
2768 +
2769 + // Trim whitespace
2770 + $text = trim($text);
2771 +
2772 + return $text;
2773 +}
2774 +
2775 +private function find_relevant_pdf_pages($query_embedding, $embeddings) {
2776 + //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
2777 +
2778 + $most_relevant = null;
2779 + $highest_similarity = -INF;
2780 +
2781 + foreach ($embeddings as $page_data) {
2782 + $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
2783 +
2784 + if ($similarity > $highest_similarity) {
2785 + $highest_similarity = $similarity;
2786 + $most_relevant = $page_data['page_number'];
2787 + }
2788 + }
2789 +
2790 + if (!is_null($most_relevant)) {
2791 + $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
2792 + return array_filter($embeddings, function ($page) use ($page_numbers) {
2793 + return in_array($page['page_number'], $page_numbers);
2794 + });
2795 + }
2796 +
2797 + return [];
2798 +}
2799 +
2800 +
2801 +public function handle_pdf_upload() {
2802 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2803 +
2804 + if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
2805 + wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
2806 + return;
2807 + }
2808 +
2809 + // SECURITY FIX: Check if PDF uploads are enabled in settings
2810 + $options = get_option('mxchat_options', array());
2811 + $show_pdf_button = isset($options['show_pdf_upload_button']) ? $options['show_pdf_upload_button'] : 'on';
2812 +
2813 + if ($show_pdf_button !== 'on') {
2814 + wp_send_json_error(esc_html__('PDF uploads are currently disabled.', 'mxchat'));
2815 + return;
2816 + }
2817 +
2818 + $file = $_FILES['pdf_file'];
2819 + $session_id = sanitize_text_field($_POST['session_id']);
2820 + $original_filename = sanitize_text_field($file['name']);
2821 +
2822 + // SECURITY FIX: Verify session ownership before allowing upload
2823 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
2824 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
2825 +
2826 + if ($session_owner && $session_owner !== $current_user_identifier) {
2827 + wp_send_json_error(esc_html__('Unauthorized access.', 'mxchat'));
2828 + return;
2829 + }
2830 +
2831 + $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
2832 + if ($file_type['type'] !== 'application/pdf') {
2833 + wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
2834 + return;
2835 + }
2836 +
2837 + $upload_dir = wp_upload_dir();
2838 +
2839 + // SECURITY FIX: Generate random filename without exposing session_id
2840 + $random_string = wp_generate_password(20, false, false); // 20 char alphanumeric string
2841 + $pdf_filename = 'mxchat_' . $random_string . '_' . time() . '.pdf';
2842 + $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
2843 +
2844 + if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
2845 + wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
2846 + return;
2847 + }
2848 +
2849 + $this->clear_pdf_transients($session_id);
2850 +
2851 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2852 + $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
2853 +
2854 + if ($embeddings === 'too_many_pages') {
2855 + unlink($pdf_path);
2856 + $error_message = sprintf(
2857 + $this->options['pdf_intent_error_text'] ??
2858 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
2859 + $max_pages
2860 + );
2861 + wp_send_json_error($error_message);
2862 + return;
2863 + }
2864 +
2865 + if ($embeddings === false || empty($embeddings)) {
2866 + unlink($pdf_path);
2867 + $error_message = $this->options['pdf_intent_error_text'] ??
2868 + esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
2869 + wp_send_json_error($error_message);
2870 + return;
2871 + }
2872 +
2873 + if (!empty($embeddings)) {
2874 + // Store the mapping between session and the random filename
2875 + set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
2876 + set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
2877 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
2878 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
2879 +
2880 + $success_message = $this->options['pdf_intent_success_text'] ??
2881 + esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
2882 +
2883 + wp_send_json_success([
2884 + 'message' => $success_message,
2885 + 'filename' => $original_filename
2886 + ]);
2887 + return;
2888 + }
2889 +
2890 + unlink($pdf_path);
2891 + $error_message = $this->options['pdf_intent_error_text'] ??
2892 + esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
2893 + wp_send_json_error($error_message);
2894 + return;
2895 +}
2896 +public function handle_pdf_remove() {
2897 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2898 +
2899 + if (empty($_POST['session_id'])) {
2900 + wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
2901 + wp_die();
2902 + }
2903 +
2904 + $session_id = sanitize_text_field($_POST['session_id']);
2905 + $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
2906 +
2907 + if ($pdf_path && file_exists($pdf_path)) {
2908 + unlink($pdf_path);
2909 + }
2910 +
2911 + $this->clear_pdf_transients($session_id);
2912 +
2913 + wp_send_json_success([
2914 + 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2915 + ]);
2916 + wp_die();
2917 +}
2918 +
2919 +
2920 +function mxchat_fetch_new_messages() {
2921 + $session_id = sanitize_text_field($_POST['session_id']);
2922 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2923 + $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2924 + $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2925 +
2926 + if (empty($session_id)) {
2927 + //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2928 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2929 + wp_die();
2930 + }
2931 +
2932 + $history = get_option("mxchat_history_{$session_id}", []);
2933 +
2934 + error_log("MxChat WhatsApp DEBUG: Fetch new messages for session {$session_id}");
2935 + error_log("MxChat WhatsApp DEBUG: last_seen_id = " . var_export($last_seen_id, true));
2936 + error_log("MxChat WhatsApp DEBUG: History count = " . count($history));
2937 + error_log("MxChat WhatsApp DEBUG: Full history = " . print_r($history, true));
2938 +
2939 + $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2940 + error_log("MxChat WhatsApp DEBUG: Checking message - ID: " . ($message['id'] ?? 'NO_ID') . ", Role: " . ($message['role'] ?? 'NO_ROLE'));
2941 +
2942 + // If persistence is enabled, show all new messages
2943 + if ($persistence_enabled) {
2944 + $has_id = !empty($message['id']);
2945 + $is_agent = $message['role'] === 'agent';
2946 +
2947 + // If last_seen_id is empty, 'NaN', or invalid, show all agent messages
2948 + if (empty($last_seen_id) || $last_seen_id === 'NaN' || $last_seen_id === 'undefined') {
2949 + $is_newer = true;
2950 + } else {
2951 + $is_newer = strcmp($message['id'] ?? '', $last_seen_id) > 0;
2952 + }
2953 +
2954 + error_log("MxChat WhatsApp DEBUG: has_id={$has_id}, is_newer={$is_newer}, is_agent={$is_agent}");
2955 +
2956 + return $has_id && $is_newer && $is_agent;
2957 + }
2958 +
2959 + // If persistence is disabled, only show messages after initial timestamp
2960 + return !empty($message['id']) &&
2961 + $message['role'] === 'agent' &&
2962 + $message['timestamp'] > $initial_timestamp;
2963 + });
2964 +
2965 + error_log("MxChat WhatsApp DEBUG: Filtered messages count = " . count($new_messages));
2966 +
2967 + wp_send_json_success([
2968 + 'new_messages' => array_values($new_messages)
2969 + ]);
2970 + wp_die();
2971 +}
2972 +public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2973 + // First check if live agents are available
2974 + $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2975 + if ($live_agent_available !== 'on') {
2976 + $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2977 + $this->fallbackResponse = [
2978 + 'text' => $away_message,
2979 + 'html' => '',
2980 + 'images' => [],
2981 + 'chat_mode' => 'ai'
2982 + ];
2983 + wp_send_json([
2984 + 'text' => $away_message,
2985 + 'html' => '',
2986 + 'chat_mode' => 'ai',
2987 + 'session_id' => $session_id
2988 + ]);
2989 + wp_die();
2990 + }
2991 +
2992 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
2993 +
2994 + if (empty($slack_bot_token)) {
2995 + return false;
2996 + }
2997 +
2998 + // Check if channel already exists for this session
2999 + $channel_id = get_option("mxchat_channel_{$session_id}", '');
3000 +
3001 + if (empty($channel_id)) {
3002 + // Create new channel with session ID as name
3003 + $channel_name = $this->generate_channel_name($session_id);
3004 +
3005 + //error_log("Attempting to create channel: $channel_name");
3006 +
3007 + $response = wp_remote_post('https://slack.com/api/conversations.create', [
3008 + 'headers' => [
3009 + 'Content-Type' => 'application/json',
3010 + 'Authorization' => 'Bearer ' . $slack_bot_token
3011 + ],
3012 + 'body' => json_encode([
3013 + 'name' => $channel_name,
3014 + 'is_private' => false // Public channel - anyone in workspace can join
3015 + ])
3016 + ]);
3017 +
3018 + if (!is_wp_error($response)) {
3019 + $response_body = wp_remote_retrieve_body($response);
3020 + $response_data = json_decode($response_body, true);
3021 +
3022 + //error_log("Channel creation response: " . $response_body);
3023 +
3024 + if (isset($response_data['ok']) && $response_data['ok']) {
3025 + $channel_id = $response_data['channel']['id'];
3026 + $actual_channel_name = $response_data['channel']['name'] ?? 'unknown';
3027 + //error_log("Channel created successfully: ID=$channel_id, Name=$actual_channel_name");
3028 + update_option("mxchat_channel_{$session_id}", $channel_id);
3029 +
3030 + // Auto-invite agents to the channel
3031 + $agent_user_ids = $this->options['live_agent_user_ids'] ?? '';
3032 +
3033 + if (!empty($agent_user_ids)) {
3034 + // Parse user IDs (one per line)
3035 + $user_ids = array_filter(array_map('trim', explode("\n", $agent_user_ids)));
3036 +
3037 + foreach ($user_ids as $user_id_to_invite) {
3038 + //error_log("Inviting user to channel: $user_id_to_invite");
3039 +
3040 + $invite_response = wp_remote_post('https://slack.com/api/conversations.invite', [
3041 + 'headers' => [
3042 + 'Content-Type' => 'application/json',
3043 + 'Authorization' => 'Bearer ' . $slack_bot_token
3044 + ],
3045 + 'body' => json_encode([
3046 + 'channel' => $channel_id,
3047 + 'users' => $user_id_to_invite
3048 + ])
3049 + ]);
3050 +
3051 + if (!is_wp_error($invite_response)) {
3052 + $invite_body = wp_remote_retrieve_body($invite_response);
3053 + $invite_data = json_decode($invite_body, true);
3054 + //error_log("Invite response for $user_id_to_invite: " . $invite_body);
3055 +
3056 + if (isset($invite_data['ok']) && $invite_data['ok']) {
3057 + //error_log("Successfully invited user $user_id_to_invite to channel");
3058 + } else {
3059 + //error_log("Failed to invite user $user_id_to_invite: " . ($invite_data['error'] ?? 'Unknown error'));
3060 + }
3061 + } else {
3062 + //error_log("WP Error inviting user $user_id_to_invite: " . $invite_response->get_error_message());
3063 + }
3064 + }
3065 + } else {
3066 + //error_log("No agent user IDs configured for auto-invite");
3067 + }
3068 + } else {
3069 + //error_log("Channel creation failed: " . ($response_data['error'] ?? 'Unknown error'));
3070 + }
3071 + } else {
3072 + //error_log("WP Error creating channel: " . $response->get_error_message());
3073 + }
3074 +
3075 + if (empty($channel_id)) {
3076 + return false; // Failed to create channel
3077 + }
3078 + }
3079 +
3080 + // Get recent chat history
3081 + $history = get_option("mxchat_history_{$session_id}", []);
3082 + $recent_history = array_slice($history, -5);
3083 +
3084 + // Format conversation context
3085 + $conversation_context = "";
3086 + if (!empty($recent_history)) {
3087 + $conversation_context = "*Recent Conversation:*\n";
3088 + foreach ($recent_history as $hist_message) {
3089 + $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
3090 + $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
3091 + }
3092 + $conversation_context .= "\n";
3093 + }
3094 +
3095 + update_option("mxchat_mode_{$session_id}", 'agent');
3096 +
3097 + // Send message to channel
3098 + $channel_message = "🔔 *New Live Agent Request*\n\n";
3099 + $channel_message .= "*Session ID:* `{$session_id}`\n";
3100 + $channel_message .= "*User ID:* `{$user_id}`\n\n";
3101 +
3102 + if (!empty($conversation_context)) {
3103 + $channel_message .= $conversation_context;
3104 + }
3105 +
3106 + $channel_message .= "*Current Message:*\n{$message}\n\n";
3107 + $channel_message .= "_Reply directly in this channel - all messages will go to the user_";
3108 +
3109 + wp_remote_post('https://slack.com/api/chat.postMessage', [
3110 + 'headers' => [
3111 + 'Content-Type' => 'application/json',
3112 + 'Authorization' => 'Bearer ' . $slack_bot_token
3113 + ],
3114 + 'body' => json_encode([
3115 + 'channel' => $channel_id,
3116 + 'text' => $channel_message,
3117 + 'mrkdwn' => true
3118 + ])
3119 + ]);
3120 +
3121 + $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
3122 + $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
3123 +
3124 + $this->fallbackResponse = [
3125 + 'text' => $success_message,
3126 + 'html' => '',
3127 + 'images' => [],
3128 + 'chat_mode' => 'agent'
3129 + ];
3130 +
3131 + wp_send_json([
3132 + 'success' => true,
3133 + 'text' => $success_message,
3134 + 'html' => '',
3135 + 'chat_mode' => 'agent',
3136 + 'session_id' => $session_id,
3137 + 'fallbackResponse' => $this->fallbackResponse
3138 + ]);
3139 + wp_die();
3140 +}
3141 +
3142 +private function generate_channel_name($session_id) {
3143 + $email = null;
3144 + $name = null;
3145 +
3146 + // 1. First priority: Check if user is logged in and get their info
3147 + if (is_user_logged_in()) {
3148 + $current_user = wp_get_current_user();
3149 + if (!empty($current_user->user_email)) {
3150 + $email = $current_user->user_email;
3151 + //error_log("[DEBUG] Using logged-in user email for channel: {$email}");
3152 + }
3153 + if (!empty($current_user->display_name)) {
3154 + $name = $current_user->display_name;
3155 + //error_log("[DEBUG] Using logged-in user name for channel: {$name}");
3156 + }
3157 + }
3158 +
3159 + // 2. Second priority: Check for saved email/name from "require email to chat" option
3160 + if (empty($email)) {
3161 + $email_option_key = "mxchat_email_{$session_id}";
3162 + $saved_email = get_option($email_option_key);
3163 + if (!empty($saved_email)) {
3164 + $email = $saved_email;
3165 + //error_log("[DEBUG] Using saved email from session for channel: {$email}");
3166 + }
3167 + }
3168 +
3169 + if (empty($name)) {
3170 + $name_option_key = "mxchat_name_{$session_id}";
3171 + $saved_name = get_option($name_option_key);
3172 + if (!empty($saved_name)) {
3173 + $name = $saved_name;
3174 + //error_log("[DEBUG] Using saved name from session for channel: {$name}");
3175 + }
3176 + }
3177 +
3178 + // 3. Third priority: Check existing chat transcript for email/name
3179 + if (empty($email) || empty($name)) {
3180 + global $wpdb;
3181 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3182 + $existing_data = $wpdb->get_row($wpdb->prepare(
3183 + "SELECT user_email, user_name FROM $table_name WHERE session_id = %s AND (user_email IS NOT NULL OR user_name IS NOT NULL) LIMIT 1",
3184 + $session_id
3185 + ));
3186 +
3187 + if ($existing_data) {
3188 + if (empty($email) && !empty($existing_data->user_email)) {
3189 + $email = $existing_data->user_email;
3190 + //error_log("[DEBUG] Using email from chat transcript for channel: {$email}");
3191 + }
3192 + if (empty($name) && !empty($existing_data->user_name)) {
3193 + $name = $existing_data->user_name;
3194 + //error_log("[DEBUG] Using name from chat transcript for channel: {$name}");
3195 + }
3196 + }
3197 + }
3198 +
3199 + // 4. Generate channel name based on priority: Name > Email > Session ID
3200 + $channel_name = '';
3201 +
3202 + if (!empty($name)) {
3203 + // Convert name to valid Slack channel name
3204 + $base_name = strtolower(trim($name));
3205 + // Replace spaces and invalid characters
3206 + $base_name = preg_replace('/[^a-z0-9\s]/', '', $base_name);
3207 + $base_name = preg_replace('/\s+/', '-', $base_name);
3208 + $base_name = trim($base_name, '-');
3209 +
3210 + // Get last 4 characters of session ID for uniqueness
3211 + $session_suffix = substr($session_id, -4);
3212 + $channel_name = 'chat-' . $base_name . '-' . strtolower($session_suffix);
3213 +
3214 + // Slack channel names have a 21 character limit
3215 + if (strlen($channel_name) > 21) {
3216 + // Calculate available space for name (21 - 'chat-' - '-' - session_suffix)
3217 + $available_space = 21 - 5 - 1 - strlen($session_suffix); // 'chat-' = 5, '-' = 1
3218 + $truncated_name = substr($base_name, 0, $available_space);
3219 + $truncated_name = rtrim($truncated_name, '-'); // Remove trailing hyphen
3220 + $channel_name = 'chat-' . $truncated_name . '-' . strtolower($session_suffix);
3221 + }
3222 +
3223 + //error_log("[DEBUG] Using name for channel: {$channel_name} (from name: {$name})");
3224 +
3225 + } elseif (!empty($email)) {
3226 + // Convert email to valid Slack channel name (your existing logic)
3227 + $channel_name = 'chat-' . strtolower(str_replace(['@', '.', '+', '_'], ['-at-', '-', '-plus-', '-'], $email));
3228 + // Remove any remaining invalid characters
3229 + $channel_name = preg_replace('/[^a-z0-9\-]/', '', $channel_name);
3230 + // Ensure it doesn't end with a hyphen
3231 + $channel_name = rtrim($channel_name, '-');
3232 + // Slack channel names have a 21 character limit, so truncate if needed
3233 + if (strlen($channel_name) > 21) {
3234 + $channel_name = substr($channel_name, 0, 21);
3235 + $channel_name = rtrim($channel_name, '-'); // Remove trailing hyphen if truncation created one
3236 + }
3237 +
3238 + //error_log("[DEBUG] Using email for channel: {$channel_name} (from email: {$email})");
3239 +
3240 + } else {
3241 + // Fallback to session ID if no name or email found
3242 + $channel_name = 'chat-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $session_id));
3243 + //error_log("[DEBUG] No name or email found, using session ID for channel: {$channel_name}");
3244 + }
3245 +
3246 + // Final validation - ensure channel name meets Slack requirements
3247 + if (strlen($channel_name) > 21) {
3248 + $channel_name = substr($channel_name, 0, 21);
3249 + $channel_name = rtrim($channel_name, '-');
3250 + }
3251 +
3252 + //error_log("[DEBUG] Generated channel name: {$channel_name}");
3253 + return $channel_name;
3254 +}
3255 +public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
3256 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
3257 + $channel_id = get_option("mxchat_channel_{$session_id}", '');
3258 +
3259 + if (empty($slack_bot_token) || empty($channel_id)) {
3260 + return false;
3261 + }
3262 +
3263 + $user_message = "💬 *User:* {$message}";
3264 +
3265 + $response = wp_remote_post('https://slack.com/api/chat.postMessage', [
3266 + 'headers' => [
3267 + 'Content-Type' => 'application/json',
3268 + 'Authorization' => 'Bearer ' . $slack_bot_token
3269 + ],
3270 + 'body' => json_encode([
3271 + 'channel' => $channel_id,
3272 + 'text' => $user_message,
3273 + 'mrkdwn' => true
3274 + ])
3275 + ]);
3276 +
3277 + return !is_wp_error($response);
3278 +}
3279 +public function handle_slack_interaction(WP_REST_Request $request) {
3280 + //error_log('Received Slack interaction');
3281 +
3282 + $payload = json_decode($request->get_param('payload'), true);
3283 + //error_log('Payload: ' . print_r($payload, true));
3284 +
3285 + // Handle button click
3286 + if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
3287 + $session_id = $payload['actions'][0]['value'];
3288 + $trigger_id = $payload['trigger_id'];
3289 +
3290 + // Get Bot Token from settings
3291 + $slack_token = $this->options['live_agent_bot_token'] ?? '';
3292 +
3293 + if (empty($slack_token)) {
3294 + //error_log('Slack Bot Token not configured');
3295 + return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
3296 + }
3297 + $response = wp_remote_post('https://slack.com/api/views.open', [
3298 + 'headers' => [
3299 + 'Content-Type' => 'application/json',
3300 + 'Authorization' => 'Bearer ' . $slack_token
3301 + ],
3302 + 'body' => json_encode([
3303 + 'trigger_id' => $trigger_id,
3304 + 'view' => [
3305 + 'type' => 'modal',
3306 + 'callback_id' => 'reply_modal',
3307 + 'title' => [
3308 + 'type' => 'plain_text',
3309 + 'text' => __('Reply to User', 'mxchat')
3310 + ],
3311 + 'submit' => [
3312 + 'type' => 'plain_text',
3313 + 'text' => __('Send', 'mxchat')
3314 + ],
3315 + 'close' => [
3316 + 'type' => 'plain_text',
3317 + 'text' => __('Cancel', 'mxchat')
3318 + ],
3319 + 'blocks' => [
3320 + [
3321 + 'type' => 'input',
3322 + 'block_id' => 'reply_block',
3323 + 'label' => [
3324 + 'type' => 'plain_text',
3325 + 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
3326 + ],
3327 + 'element' => [
3328 + 'type' => 'plain_text_input',
3329 + 'action_id' => 'message',
3330 + 'multiline' => true,
3331 + 'placeholder' => [
3332 + 'type' => 'plain_text',
3333 + 'text' => __('Type your message here...', 'mxchat')
3334 + ]
3335 + ]
3336 + ]
3337 + ],
3338 + 'private_metadata' => $session_id
3339 + ]
3340 + ])
3341 + ]);
3342 +
3343 + //error_log('Views.open response: ' . print_r($response, true));
3344 +
3345 + // Return immediate acknowledgment
3346 + return new WP_REST_Response(['ok' => true]);
3347 + }
3348 +
3349 + // Handle modal submission
3350 +// Handle modal submission
3351 +if ($payload['type'] === 'view_submission') {
3352 + $session_id = $payload['view']['private_metadata'];
3353 + $message = $payload['view']['state']['values']['reply_block']['message']['value'];
3354 +
3355 + // Save the message (keep the message_id but don't include in response)
3356 + $this->mxchat_save_chat_message($session_id, 'agent', $message);
3357 +
3358 + // Keep the original response format for Slack
3359 + return new WP_REST_Response([
3360 + 'response_action' => 'clear'
3361 + ]);
3362 +}
3363 +
3364 + // Default acknowledgment
3365 + return new WP_REST_Response(['ok' => true]);
3366 +}
3367 +public function mxchat_handle_agent_response(WP_REST_Request $request) {
3368 + //error_log('Received agent response request');
3369 + //error_log('Request data: ' . print_r($request->get_params(), true));
3370 + // //error_log('Raw body: ' . file_get_contents('php://input'));
3371 +
3372 + // Get the data from Slack's slash command format
3373 + $command_text = $request->get_param('text');
3374 + // //error_log('Command text: ' . $command_text);
3375 +
3376 + if (empty($command_text)) {
3377 + //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
3378 + return new WP_REST_Response([
3379 + 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
3380 + ], 400);
3381 + }
3382 +
3383 + // Split the command text into session_id and message
3384 + $parts = explode(' ', $command_text, 2);
3385 + if (count($parts) !== 2) {
3386 + //error_log('Agent response error: Invalid command format');
3387 + return new WP_REST_Response([
3388 + 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
3389 + ], 400);
3390 + }
3391 +
3392 + $session_id = sanitize_text_field($parts[0]);
3393 + $message = sanitize_text_field($parts[1]);
3394 +
3395 + //error_log("Processing agent response - Session ID: $session_id, Message: $message");
3396 +
3397 + // Save the message
3398 + $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
3399 +
3400 + if (!$message_id) {
3401 + // //error_log('Failed to save agent message');
3402 + return new WP_REST_Response([
3403 + 'error' => esc_html__('Failed to save message', 'mxchat')
3404 + ], 500);
3405 + }
3406 +
3407 + // Return success response in Slack's expected format
3408 + return new WP_REST_Response([
3409 + 'response_type' => 'in_channel',
3410 + 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
3411 + ], 200);
3412 +}
3413 +public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
3414 + // Update mode to AI
3415 + update_option("mxchat_mode_{$session_id}", 'ai');
3416 +
3417 + // Clear any existing PDF context to start fresh
3418 + $this->clear_pdf_transients($session_id);
3419 +
3420 + // Set the response with explicit chat_mode
3421 + $this->fallbackResponse = [
3422 + 'text' => esc_html__('You are now chatting with the AI chatbot.', 'mxchat'),
3423 + 'html' => '',
3424 + 'images' => [],
3425 + 'chat_mode' => 'ai' // Ensure this is set
3426 + ];
3427 +
3428 + // Return the complete response array instead of just true
3429 + return $this->fallbackResponse;
3430 +}
3431 +
3432 +public function handle_slack_messages(WP_REST_Request $request) {
3433 + // Log the incoming request for debugging
3434 + //error_log('Slack events request received: ' . $request->get_body());
3435 +
3436 + $body = $request->get_body();
3437 + $data = json_decode($body, true);
3438 +
3439 + // Handle Slack URL verification
3440 + if (isset($data['type']) && $data['type'] === 'url_verification') {
3441 + //error_log('Slack URL verification challenge: ' . $data['challenge']);
3442 + return new WP_REST_Response($data['challenge'], 200, ['Content-Type' => 'text/plain']);
3443 + }
3444 +
3445 + // IMPORTANT: Handle Slack's event deduplication
3446 + if (isset($data['event_id'])) {
3447 + $event_id = $data['event_id'];
3448 + $processed_events = get_transient('mxchat_slack_events') ?: [];
3449 +
3450 + // Check if we've already processed this event
3451 + if (in_array($event_id, $processed_events)) {
3452 + //error_log("Duplicate event detected: $event_id");
3453 + return new WP_REST_Response(['ok' => true]);
3454 + }
3455 +
3456 + // Add this event to processed list
3457 + $processed_events[] = $event_id;
3458 + // Keep only last 100 events to prevent memory issues
3459 + if (count($processed_events) > 100) {
3460 + $processed_events = array_slice($processed_events, -100);
3461 + }
3462 + // Store for 1 hour
3463 + set_transient('mxchat_slack_events', $processed_events, HOUR_IN_SECONDS);
3464 + }
3465 +
3466 + // Handle message events
3467 + if (isset($data['event']) && $data['event']['type'] === 'message') {
3468 + $event = $data['event'];
3469 +
3470 + // Skip bot messages and messages with subtypes (like bot_message)
3471 + if (isset($event['bot_id']) || isset($event['subtype'])) {
3472 + return new WP_REST_Response(['ok' => true]);
3473 + }
3474 +
3475 + // Additional check: Skip if this is a threaded reply to our confirmation
3476 + if (isset($event['thread_ts']) && $event['thread_ts'] !== $event['ts']) {
3477 + return new WP_REST_Response(['ok' => true]);
3478 + }
3479 +
3480 + $channel_id = $event['channel'];
3481 + $message_text = $event['text'] ?? '';
3482 + $message_ts = $event['ts'] ?? '';
3483 +
3484 + // Find session ID by looking for matching channel
3485 + global $wpdb;
3486 + $session_option = $wpdb->get_var(
3487 + $wpdb->prepare(
3488 + "SELECT option_name FROM {$wpdb->options}
3489 + WHERE option_name LIKE 'mxchat_channel_%'
3490 + AND option_value = %s",
3491 + $channel_id
3492 + )
3493 + );
3494 +
3495 + if ($session_option) {
3496 + $session_id = str_replace('mxchat_channel_', '', $session_option);
3497 +
3498 + // Create a unique key for this specific message
3499 + $message_key = md5($session_id . $message_ts . $message_text);
3500 + $processed_messages = get_transient('mxchat_processed_messages_' . $session_id) ?: [];
3501 +
3502 + // Check if we've already processed this exact message
3503 + if (in_array($message_key, $processed_messages)) {
3504 + //error_log("Duplicate message detected for session $session_id");
3505 + return new WP_REST_Response(['ok' => true]);
3506 + }
3507 +
3508 + // Add to processed messages
3509 + $processed_messages[] = $message_key;
3510 + // Keep only last 50 messages per session
3511 + if (count($processed_messages) > 50) {
3512 + $processed_messages = array_slice($processed_messages, -50);
3513 + }
3514 + set_transient('mxchat_processed_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
3515 +
3516 + // Save the agent message
3517 + $this->mxchat_save_chat_message($session_id, 'agent', $message_text);
3518 +
3519 + // Send confirmation back to Slack (only once)
3520 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
3521 + if (!empty($slack_bot_token)) {
3522 + // Use a transient to prevent duplicate confirmations
3523 + $confirm_key = 'mxchat_confirm_' . $message_key;
3524 + if (!get_transient($confirm_key)) {
3525 + wp_remote_post('https://slack.com/api/chat.postMessage', [
3526 + 'headers' => [
3527 + 'Content-Type' => 'application/json',
3528 + 'Authorization' => 'Bearer ' . $slack_bot_token
3529 + ],
3530 + 'body' => json_encode([
3531 + 'channel' => $channel_id,
3532 + 'text' => "✅ _Message sent to user_",
3533 + 'thread_ts' => $event['ts'] // Reply in thread
3534 + ])
3535 + ]);
3536 + // Set transient to prevent duplicate confirmations
3537 + set_transient($confirm_key, true, 300); // 5 minutes
3538 + }
3539 + }
3540 + }
3541 + }
3542 +
3543 + return new WP_REST_Response(['ok' => true]);
3544 +}
3545 +
3546 +// For the word upload handler
3547 +public function mxchat_handle_word_upload() {
3548 + // Delegate to word handler
3549 + $this->word_handler->mxchat_handle_word_upload();
3550 +}
3551 +
3552 +// For the word removal handler
3553 +public function mxchat_handle_word_remove() {
3554 + // Delegate to word handler
3555 + $this->word_handler->mxchat_handle_word_remove();
3556 +}
3557 +
3558 +// For the word status check
3559 +public function mxchat_check_word_status() {
3560 + // Delegate to word handler
3561 + $this->word_handler->mxchat_check_word_status();
3562 +}
3563 +
3564 +
3565 +private function mxchat_get_user_identifier() {
3566 + return MxChat_User::mxchat_get_user_identifier();
3567 +}
3568 +
3569 +private function mxchat_generate_embedding($text, $api_key) {
3570 + try {
3571 + // Get options and selected model
3572 + $options = get_option('mxchat_options');
3573 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
3574 +
3575 + // Determine endpoint and API key based on model
3576 + if (strpos($selected_model, 'voyage') === 0) {
3577 + $endpoint = 'https://api.voyageai.com/v1/embeddings';
3578 + $api_key = $options['voyage_api_key'] ?? '';
3579 +
3580 + // Check if Voyage API key is missing
3581 + if (empty($api_key)) {
3582 + //error_log('Voyage API key is missing');
3583 + return [
3584 + 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
3585 + 'error_code' => 'missing_voyage_api_key'
3586 + ];
3587 + }
3588 + } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
3589 + $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
3590 + $api_key = $options['gemini_api_key'] ?? '';
3591 +
3592 + // Check if Gemini API key is missing
3593 + if (empty($api_key)) {
3594 + //error_log('Gemini API key is missing');
3595 + return [
3596 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
3597 + 'error_code' => 'missing_gemini_api_key'
3598 + ];
3599 + }
3600 + } else {
3601 + $endpoint = 'https://api.openai.com/v1/embeddings';
3602 + // Use the passed API key for OpenAI
3603 +
3604 + // Check if OpenAI API key is missing
3605 + if (empty($api_key)) {
3606 + //error_log('OpenAI API key is missing');
3607 + return [
3608 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3609 + 'error_code' => 'missing_openai_api_key'
3610 + ];
3611 + }
3612 + }
3613 +
3614 + // Check if text is empty
3615 + if (empty($text)) {
3616 + //error_log('Empty text provided for embedding generation');
3617 + return [
3618 + 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
3619 + 'error_code' => 'empty_embedding_text'
3620 + ];
3621 + }
3622 +
3623 + // Prepare request body based on provider
3624 + if (strpos($selected_model, 'gemini-embedding') === 0) {
3625 + // Gemini API format
3626 + $request_body = [
3627 + 'model' => 'models/' . $selected_model,
3628 + 'content' => [
3629 + 'parts' => [
3630 + ['text' => $text]
3631 + ]
3632 + ],
3633 + 'outputDimensionality' => 1536
3634 + ];
3635 +
3636 + // Prepare headers for Gemini (API key as query parameter)
3637 + $endpoint .= '?key=' . $api_key;
3638 + $headers = [
3639 + 'Content-Type' => 'application/json'
3640 + ];
3641 + } else {
3642 + // OpenAI/Voyage API format
3643 + $request_body = [
3644 + 'input' => $text,
3645 + 'model' => $selected_model
3646 + ];
3647 +
3648 + // Add output_dimension for voyage-3-large
3649 + if ($selected_model === 'voyage-3-large') {
3650 + $request_body['output_dimension'] = 2048;
3651 + }
3652 +
3653 + // Prepare headers for OpenAI/Voyage
3654 + $headers = [
3655 + 'Content-Type' => 'application/json',
3656 + 'Authorization' => 'Bearer ' . $api_key
3657 + ];
3658 + }
3659 +
3660 + // Prepare request arguments
3661 + $args = [
3662 + 'body' => wp_json_encode($request_body),
3663 + 'headers' => $headers,
3664 + 'timeout' => 60,
3665 + 'redirection' => 5,
3666 + 'blocking' => true,
3667 + 'httpversion' => '1.0',
3668 + 'sslverify' => true,
3669 + ];
3670 +
3671 + // Make the request
3672 + $response = wp_remote_post($endpoint, $args);
3673 +
3674 + // Handle WordPress errors
3675 + if (is_wp_error($response)) {
3676 + $error_message = $response->get_error_message();
3677 + //error_log('Embedding Generation Error: ' . $error_message);
3678 + return [
3679 + 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($error_message),
3680 + 'error_code' => 'embedding_connection_error'
3681 + ];
3682 + }
3683 +
3684 + // Check HTTP status code
3685 + $status_code = wp_remote_retrieve_response_code($response);
3686 + if ($status_code !== 200) {
3687 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3688 +
3689 + $error_message = isset($response_body['error']['message'])
3690 + ? $response_body['error']['message']
3691 + : 'HTTP Error ' . $status_code;
3692 +
3693 + $error_type = isset($response_body['error']['type'])
3694 + ? $response_body['error']['type']
3695 + : 'unknown';
3696 +
3697 + //error_log('Embedding API HTTP Error: ' . $status_code . ' - ' . $error_message);
3698 +
3699 + // Handle specific error types
3700 + switch ($error_type) {
3701 + case 'invalid_request_error':
3702 + if (strpos($error_message, 'API key') !== false) {
3703 + return [
3704 + 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
3705 + 'error_code' => 'embedding_invalid_api_key'
3706 + ];
3707 + }
3708 + break;
3709 +
3710 + case 'authentication_error':
3711 + return [
3712 + 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
3713 + 'error_code' => 'embedding_auth_error'
3714 + ];
3715 +
3716 + case 'rate_limit_exceeded':
3717 + return [
3718 + 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
3719 + 'error_code' => 'embedding_rate_limit'
3720 + ];
3721 +
3722 + case 'quota_exceeded':
3723 + return [
3724 + 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
3725 + 'error_code' => 'embedding_quota_exceeded'
3726 + ];
3727 + }
3728 +
3729 + // Generic error fallback
3730 + return [
3731 + 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($error_message),
3732 + 'error_code' => 'embedding_api_error',
3733 + 'status_code' => $status_code
3734 + ];
3735 + }
3736 +
3737 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3738 +
3739 + // Handle different response formats based on provider
3740 + if (strpos($selected_model, 'gemini-embedding') === 0) {
3741 + // Gemini API response format
3742 + if (isset($response_body['embedding']['values']) && is_array($response_body['embedding']['values'])) {
3743 + return $response_body['embedding']['values'];
3744 + } else {
3745 + //error_log('Invalid Gemini embedding response: ' . wp_json_encode($response_body));
3746 + return [
3747 + 'error' => esc_html__('Received invalid embedding data from the Gemini API.', 'mxchat'),
3748 + 'error_code' => 'invalid_gemini_embedding_response'
3749 + ];
3750 + }
3751 + } else {
3752 + // OpenAI/Voyage API response format
3753 + if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
3754 + return $response_body['data'][0]['embedding'];
3755 + } else {
3756 + //error_log('Invalid embedding response: ' . wp_json_encode($response_body));
3757 + return [
3758 + 'error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'),
3759 + 'error_code' => 'invalid_embedding_response'
3760 + ];
3761 + }
3762 + }
3763 + } catch (Exception $e) {
3764 + //error_log('Embedding Exception: ' . $e->getMessage());
3765 + return [
3766 + 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
3767 + 'error_code' => 'embedding_exception'
3768 + ];
3769 + }
3770 +}
3771 +
3772 +
3773 +private function mxchat_find_relevant_content($user_embedding, $bot_id = 'default') {
3774 + error_log("MXCHAT DEBUG: find_relevant_content called with bot_id: " . $bot_id);
3775 +
3776 + // Get bot-specific Pinecone configuration
3777 + $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
3778 +
3779 + // Debug: Log the Pinecone configuration
3780 + error_log("MXCHAT DEBUG: Pinecone config for bot '$bot_id':");
3781 + error_log(" - use_pinecone: " . ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false'));
3782 + error_log(" - api_key: " . (empty($bot_pinecone_config['api_key']) ? 'EMPTY' : 'SET (hidden)'));
3783 + error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'NOT SET'));
3784 + error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'NOT SET'));
3785 +
3786 + // Determine whether to use Pinecone based on bot configuration
3787 + $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
3788 +
3789 + error_log("MXCHAT DEBUG: Using " . ($use_pinecone ? "Pinecone" : "WordPress Database") . " for knowledge retrieval");
3790 +
3791 + if ($use_pinecone) {
3792 + return $this->find_relevant_content_pinecone($user_embedding, $bot_id, $bot_pinecone_config);
3793 + } else {
3794 + return $this->find_relevant_content_wordpress($user_embedding, $bot_id);
3795 + }
3796 +}
3797 +
3798 +private function find_relevant_content_wordpress($user_embedding, $bot_id = 'default') {
3799 + global $wpdb;
3800 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3801 + $cache_key = 'mxchat_system_prompt_embeddings_' . $bot_id;
3802 + $batch_size = 500;
3803 +
3804 + // Initialize similarity analysis storage
3805 + $this->last_similarity_analysis = [
3806 + 'knowledge_base_type' => 'WordPress Database',
3807 + 'bot_id' => $bot_id,
3808 + 'top_matches' => [],
3809 + 'threshold_used' => 0,
3810 + 'total_checked' => 0
3811 + ];
3812 +
3813 + // NEW: Initialize valid URLs array
3814 + $valid_urls = [];
3815 +
3816 + // Get bot-specific options for similarity threshold
3817 + $bot_options = $this->get_bot_options($bot_id);
3818 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
3819 +
3820 + // Retrieve embeddings from cache or database
3821 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
3822 + if ($embeddings === false) {
3823 + // Cache miss - load embeddings from database WITH CONTENT and ROLE RESTRICTION for testing
3824 + $embeddings = [];
3825 + $offset = 0;
3826 +
3827 + do {
3828 + // Add bot_id filter if not default and if bot_metadata column exists
3829 + $bot_filter = '';
3830 + if ($bot_id !== 'default') {
3831 + // Check if bot_metadata column exists
3832 + $column_exists = $wpdb->get_var("SHOW COLUMNS FROM {$system_prompt_table} LIKE 'bot_metadata'");
3833 + if ($column_exists) {
3834 + $bot_filter = $wpdb->prepare(" AND (bot_metadata = %s OR bot_metadata IS NULL OR bot_metadata = '')", $bot_id);
3835 + }
3836 + }
3837 +
3838 + $query = $wpdb->prepare(
3839 + "SELECT id, embedding_vector, article_content, source_url, role_restriction
3840 + FROM {$system_prompt_table}
3841 + WHERE 1=1 {$bot_filter}
3842 + LIMIT %d OFFSET %d",
3843 + $batch_size,
3844 + $offset
3845 + );
3846 +
3847 + $batch = $wpdb->get_results($query);
3848 + if (empty($batch)) {
3849 + break;
3850 + }
3851 +
3852 + $embeddings = array_merge($embeddings, $batch);
3853 + $offset += $batch_size;
3854 + unset($batch);
3855 + } while (true);
3856 +
3857 + if (empty($embeddings)) {
3858 + // Store empty array for valid URLs since no content found
3859 + $this->current_valid_urls = [];
3860 + return '';
3861 + }
3862 +
3863 + // Cache embeddings for future use (but note: this now includes content and role restrictions)
3864 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
3865 + }
3866 +
3867 + // Get knowledge manager instance for role checking
3868 + $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3869 +
3870 + // Get base similarity threshold from bot options or default options
3871 + $similarity_threshold = isset($current_options['similarity_threshold'])
3872 + ? ((int) $current_options['similarity_threshold']) / 100
3873 + : 0.35;
3874 +
3875 + $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
3876 +
3877 + // Calculate similarities and build results array
3878 + $all_similarities = [];
3879 + $relevant_results = [];
3880 +
3881 + foreach ($embeddings as $embedding) {
3882 + $database_embedding = $embedding->embedding_vector
3883 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
3884 + : null;
3885 +
3886 + if (is_array($database_embedding) && is_array($user_embedding)) {
3887 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
3888 +
3889 + // Check role access
3890 + $role_restriction = $embedding->role_restriction ?? 'public';
3891 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
3892 +
3893 + // Store ALL similarities for testing (top 10)
3894 + $source_display = '';
3895 + if (!empty($embedding->source_url) && $embedding->source_url !== '#') {
3896 + $source_display = $embedding->source_url;
3897 + } else {
3898 + $content_preview = strip_tags($embedding->article_content ?? '');
3899 + $content_preview = preg_replace('/\s+/', ' ', $content_preview);
3900 + $source_display = substr(trim($content_preview), 0, 50) . '...';
3901 + }
3902 +
3903 + $all_similarities[] = [
3904 + 'document_id' => $embedding->id,
3905 + 'similarity' => $similarity,
3906 + 'similarity_percentage' => round($similarity * 100, 2),
3907 + 'above_threshold' => $similarity >= $similarity_threshold,
3908 + 'source_display' => $source_display,
3909 + 'content_preview' => substr(strip_tags($embedding->article_content ?? ''), 0, 100) . '...',
3910 + 'used_for_context' => false, // Initialize as false, we'll update this later
3911 + 'role_restriction' => $role_restriction,
3912 + 'has_access' => $has_access,
3913 + 'filtered_out' => !$has_access
3914 + ];
3915 +
3916 + // Only consider results above threshold AND with access for actual content retrieval
3917 + if ($similarity >= $similarity_threshold && $has_access) {
3918 + $relevant_results[] = [
3919 + 'id' => $embedding->id,
3920 + 'similarity' => $similarity
3921 + ];
3922 + }
3923 + }
3924 +
3925 + unset($database_embedding);
3926 + }
3927 +
3928 + // Sort ALL similarities for testing display (highest first)
3929 + usort($all_similarities, function ($a, $b) {
3930 + return $b['similarity'] <=> $a['similarity'];
3931 + });
3932 +
3933 + // Sort relevant results by similarity (highest first)
3934 + usort($relevant_results, function ($a, $b) {
3935 + return $b['similarity'] <=> $a['similarity'];
3936 + });
3937 +
3938 + // Get top 5 results for actual content (standard approach)
3939 + $top_results = array_slice($relevant_results, 0, 3);
3940 +
3941 + // NOW mark which documents are actually used for context
3942 + $used_document_ids = [];
3943 + foreach ($top_results as $result) {
3944 + $used_document_ids[] = $result['id'];
3945 + }
3946 +
3947 + // Update the all_similarities array to mark which were actually used
3948 + foreach ($all_similarities as &$similarity_item) {
3949 + $similarity_item['used_for_context'] = in_array($similarity_item['document_id'], $used_document_ids);
3950 + }
3951 +
3952 + // Store top 10 for testing panel (now with correct used_for_context flags and role info)
3953 + $this->last_similarity_analysis['top_matches'] = array_slice($all_similarities, 0, 10);
3954 + $this->last_similarity_analysis['total_checked'] = count($embeddings);
3955 +
3956 + // Initialize final content
3957 + $content = '';
3958 +
3959 + // Track document IDs to avoid duplicates
3960 + $added_document_ids = [];
3961 +
3962 + // Fetch and format content for each selected result
3963 + foreach ($top_results as $index => $result) {
3964 + if (in_array($result['id'], $added_document_ids)) {
3965 + continue;
3966 + }
3967 +
3968 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
3969 + $added_document_ids[] = $result['id'];
3970 +
3971 + // NEW: Extract source_url from database for this result
3972 + $source_url = $wpdb->get_var($wpdb->prepare(
3973 + "SELECT source_url FROM {$system_prompt_table} WHERE id = %d",
3974 + $result['id']
3975 + ));
3976 +
3977 + // NEW: Add source_url to valid URLs list if it exists and is not empty/placeholder
3978 + if (!empty($source_url) && $source_url !== '#') {
3979 + $valid_urls[] = $source_url;
3980 + }
3981 +
3982 + // NEW: Extract any URLs from the article content itself
3983 + preg_match_all(
3984 + '#\bhttps?://[^\s<>"\']+#i',
3985 + $chunk_content,
3986 + $content_urls
3987 + );
3988 + if (!empty($content_urls[0])) {
3989 + $valid_urls = array_merge($valid_urls, $content_urls[0]);
3990 + }
3991 +
3992 + $content .= "## Reference " . ($index + 1) . " ##\n";
3993 + $content .= $chunk_content . "\n\n";
3994 +
3995 + // PDF surrounding pages logic (unchanged)
3996 + if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
3997 + $surrounding_content = $wpdb->get_results($wpdb->prepare(
3998 + "SELECT id, article_content, role_restriction FROM {$system_prompt_table}
3999 + WHERE id IN (
4000 + (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
4001 + (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
4002 + )",
4003 + $result['id'],
4004 + $result['id']
4005 + ));
4006 +
4007 + // Check role access for surrounding content too
4008 + if (!empty($surrounding_content[0])) {
4009 + $surrounding_role = $surrounding_content[0]->role_restriction ?? 'public';
4010 + if ($knowledge_manager->mxchat_user_has_content_access($surrounding_role)) {
4011 + // NEW: Extract URLs from surrounding content too
4012 + preg_match_all(
4013 + '#\bhttps?://[^\s<>"\']+#i',
4014 + $surrounding_content[0]->article_content,
4015 + $surrounding_urls
4016 + );
4017 + if (!empty($surrounding_urls[0])) {
4018 + $valid_urls = array_merge($valid_urls, $surrounding_urls[0]);
4019 + }
4020 +
4021 + $content .= "## Related Content ##\n";
4022 + $content .= $surrounding_content[0]->article_content . "\n\n";
4023 + $added_document_ids[] = $surrounding_content[0]->id;
4024 + }
4025 + }
4026 +
4027 + if (!empty($surrounding_content[1])) {
4028 + $surrounding_role = $surrounding_content[1]->role_restriction ?? 'public';
4029 + if ($knowledge_manager->mxchat_user_has_content_access($surrounding_role)) {
4030 + // NEW: Extract URLs from surrounding content too
4031 + preg_match_all(
4032 + '#\bhttps?://[^\s<>"\']+#i',
4033 + $surrounding_content[1]->article_content,
4034 + $surrounding_urls
4035 + );
4036 + if (!empty($surrounding_urls[0])) {
4037 + $valid_urls = array_merge($valid_urls, $surrounding_urls[0]);
4038 + }
4039 +
4040 + $content .= "## Related Content ##\n";
4041 + $content .= $surrounding_content[1]->article_content . "\n\n";
4042 + $added_document_ids[] = $surrounding_content[1]->id;
4043 + }
4044 + }
4045 + }
4046 + }
4047 +
4048 + // NEW: Store unique valid URLs for validation
4049 + $this->current_valid_urls = array_unique($valid_urls);
4050 +
4051 + // Add response guidelines
4052 + if (empty($top_results)) {
4053 + $content = "No reference information was found for this query.\n\n";
4054 + } else {
4055 + $content .= "\n## Response Guidelines ##\n" .
4056 + "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
4057 + "Be conversational and friendly, but never mention your knowledge base or training data. " .
4058 + "If you don't have specific information or are uncertain about any details, it's always " .
4059 + "better to honestly say you don't know rather than making up or guessing at answers. " .
4060 + "When information is incomplete, let them know you are unsure.\n\n" .
4061 + "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
4062 + "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
4063 + }
4064 +
4065 + return trim($content);
4066 +}
4067 +
4068 +private function find_relevant_content_pinecone($user_embedding, $bot_id = 'default', $bot_config = null) {
4069 + global $wpdb;
4070 +
4071 + error_log("MXCHAT DEBUG: find_relevant_content_pinecone called");
4072 + error_log(" - bot_id: " . $bot_id);
4073 + error_log(" - user_embedding is array: " . (is_array($user_embedding) ? 'yes' : 'no'));
4074 + error_log(" - user_embedding count: " . (is_array($user_embedding) ? count($user_embedding) : 'N/A'));
4075 +
4076 + // Use bot-specific config or fall back to default
4077 + if ($bot_config === null) {
4078 + $bot_config = $this->get_bot_pinecone_config($bot_id);
4079 + }
4080 +
4081 + $api_key = $bot_config['api_key'] ?? '';
4082 + $host = $bot_config['host'] ?? '';
4083 + $namespace = $bot_config['namespace'] ?? '';
4084 +
4085 + error_log("MXCHAT DEBUG: Pinecone query parameters:");
4086 + error_log(" - API Key: " . (empty($api_key) ? 'EMPTY - ERROR!' : 'Present (length: ' . strlen($api_key) . ')'));
4087 + error_log(" - Host: " . (empty($host) ? 'EMPTY - ERROR!' : $host));
4088 + error_log(" - Namespace: " . (empty($namespace) ? 'EMPTY (will use default)' : $namespace));
4089 +
4090 + // Initialize similarity analysis storage
4091 + $this->last_similarity_analysis = [
4092 + 'knowledge_base_type' => 'Pinecone',
4093 + 'bot_id' => $bot_id,
4094 + 'namespace' => $namespace,
4095 + 'top_matches' => [],
4096 + 'threshold_used' => 0,
4097 + 'total_checked' => 0
4098 + ];
4099 +
4100 + // NEW: Initialize valid URLs array
4101 + $valid_urls = [];
4102 +
4103 + if (empty($host) || empty($api_key)) {
4104 + error_log("MXCHAT DEBUG ERROR: Missing Pinecone host or API key!");
4105 + error_log(" - Host empty: " . (empty($host) ? 'YES' : 'NO'));
4106 + error_log(" - API key empty: " . (empty($api_key) ? 'YES' : 'NO'));
4107 + // Store empty array for valid URLs since we can't proceed
4108 + $this->current_valid_urls = [];
4109 + return '';
4110 + }
4111 +
4112 + // Get knowledge manager instance for role checking
4113 + $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
4114 +
4115 + // Get the similarity threshold from the bot options or main options
4116 + $bot_options = $this->get_bot_options($bot_id);
4117 + $current_options = !empty($bot_options) ? $bot_options : get_option('mxchat_options', []);
4118 +
4119 + $similarity_threshold = isset($current_options['similarity_threshold'])
4120 + ? ((int) $current_options['similarity_threshold']) / 100
4121 + : 0.35;
4122 +
4123 + $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
4124 +
4125 + // Prepare the query request for Pinecone
4126 + $api_endpoint = "https://{$host}/query";
4127 +
4128 + $request_body = array(
4129 + 'vector' => $user_embedding,
4130 + 'topK' => 20, // Request more to get good testing data
4131 + 'includeMetadata' => true,
4132 + 'includeValues' => true
4133 + );
4134 +
4135 + // Add namespace if specified for this bot
4136 + if (!empty($namespace)) {
4137 + $request_body['namespace'] = $namespace;
4138 + }
4139 +
4140 + error_log("MXCHAT DEBUG: About to call Pinecone API");
4141 + error_log(" - Endpoint: " . $api_endpoint);
4142 + error_log(" - Namespace in request: " . (!empty($namespace) ? $namespace : 'NOT SET'));
4143 +
4144 + $response = wp_remote_post($api_endpoint, array(
4145 + 'headers' => array(
4146 + 'Api-Key' => $api_key,
4147 + 'accept' => 'application/json',
4148 + 'content-type' => 'application/json'
4149 + ),
4150 + 'body' => wp_json_encode($request_body),
4151 + 'timeout' => 30
4152 + ));
4153 +
4154 + if (is_wp_error($response)) {
4155 + error_log("MXCHAT DEBUG ERROR: WP Error in Pinecone request: " . $response->get_error_message());
4156 + // Store empty array for valid URLs
4157 + $this->current_valid_urls = [];
4158 + return '';
4159 + }
4160 +
4161 + $response_code = wp_remote_retrieve_response_code($response);
4162 + error_log("MXCHAT DEBUG: Pinecone response code: " . $response_code);
4163 +
4164 + if ($response_code !== 200) {
4165 + $response_body = wp_remote_retrieve_body($response);
4166 + error_log("MXCHAT DEBUG ERROR: Pinecone API error response: " . substr($response_body, 0, 500));
4167 + // Store empty array for valid URLs
4168 + $this->current_valid_urls = [];
4169 + return '';
4170 + }
4171 +
4172 + // ADD DETAILED DEBUG SECTION HERE
4173 + $response_body = wp_remote_retrieve_body($response);
4174 + error_log("MXCHAT DEBUG: Raw Pinecone response length: " . strlen($response_body));
4175 +
4176 + $results = json_decode($response_body, true);
4177 +
4178 + if (json_last_error() !== JSON_ERROR_NONE) {
4179 + error_log("MXCHAT DEBUG ERROR: JSON decode error: " . json_last_error_msg());
4180 + error_log("MXCHAT DEBUG: First 500 chars of response: " . substr($response_body, 0, 500));
4181 + // Store empty array for valid URLs
4182 + $this->current_valid_urls = [];
4183 + return '';
4184 + }
4185 +
4186 + error_log("MXCHAT DEBUG: Pinecone response structure:");
4187 + error_log(" - Has 'matches' key: " . (isset($results['matches']) ? 'yes' : 'no'));
4188 + error_log(" - Has 'namespace' key: " . (isset($results['namespace']) ? 'yes (' . $results['namespace'] . ')' : 'no'));
4189 +
4190 + if (empty($results['matches'])) {
4191 + error_log("MXCHAT DEBUG: No matches found in Pinecone response");
4192 + error_log("MXCHAT DEBUG: Response keys: " . implode(', ', array_keys($results)));
4193 + // Store empty array for valid URLs
4194 + $this->current_valid_urls = [];
4195 + return '';
4196 + }
4197 +
4198 + error_log("MXCHAT DEBUG: Found " . count($results['matches']) . " matches in Pinecone");
4199 +
4200 + // Log first match details for debugging
4201 + if (!empty($results['matches'][0])) {
4202 + $first_match = $results['matches'][0];
4203 + error_log("MXCHAT DEBUG: First match details:");
4204 + error_log(" - Score: " . ($first_match['score'] ?? 'no score'));
4205 + error_log(" - Has metadata: " . (isset($first_match['metadata']) ? 'yes' : 'no'));
4206 + if (isset($first_match['metadata'])) {
4207 + error_log(" - Metadata keys: " . implode(', ', array_keys($first_match['metadata'])));
4208 + }
4209 + }
4210 +
4211 + // Initialize the final content
4212 + $content = '';
4213 + $matches_used = 0;
4214 + $matches_used_for_context = [];
4215 +
4216 + // Process each match for actual content generation (lazy role checking)
4217 + foreach ($results['matches'] as $index => $match) {
4218 + // Skip if similarity is below threshold
4219 + if ($match['score'] < $similarity_threshold) {
4220 + continue;
4221 + }
4222 +
4223 + // Limit to top 3 matches above threshold
4224 + if ($matches_used >= 3) {
4225 + break;
4226 + }
4227 +
4228 + if (!empty($match['metadata']['text'])) {
4229 + // LAZY ROLE CHECK: Only check role for content we're actually considering
4230 + $match_id = $match['id'] ?? '';
4231 + $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
4232 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
4233 +
4234 + // Skip if user doesn't have access
4235 + if (!$has_access) {
4236 + continue;
4237 + }
4238 +
4239 + // User has access - add to content
4240 + $content .= "## Reference " . ($matches_used + 1) . " ##\n";
4241 + $content .= $match['metadata']['text'] . "\n\n";
4242 +
4243 + // NEW: Extract source_url from metadata if it exists
4244 + if (!empty($match['metadata']['source_url']) && $match['metadata']['source_url'] !== '#') {
4245 + $valid_urls[] = $match['metadata']['source_url'];
4246 + $content .= "URL: " . $match['metadata']['source_url'] . "\n\n";
4247 + }
4248 +
4249 + // NEW: Extract any URLs from the text content itself
4250 + preg_match_all(
4251 + '#\bhttps?://[^\s<>"\']+#i',
4252 + $match['metadata']['text'],
4253 + $content_urls
4254 + );
4255 + if (!empty($content_urls[0])) {
4256 + $valid_urls = array_merge($valid_urls, $content_urls[0]);
4257 + }
4258 +
4259 + $matches_used_for_context[] = $match['id'] ?? $index;
4260 + $matches_used++;
4261 + }
4262 + }
4263 +
4264 + // Process ALL matches for testing data (top 10) - with role checking for testing display
4265 + $all_matches = [];
4266 + foreach ($results['matches'] as $index => $match) {
4267 + if ($index >= 10) break; // Limit to top 10 for testing
4268 +
4269 + $match_id = $match['id'] ?? '';
4270 +
4271 + // Check role access for testing display (use cache if available)
4272 + $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
4273 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
4274 +
4275 + $source_display = '';
4276 + if (!empty($match['metadata']['source_url'])) {
4277 + $source_display = $match['metadata']['source_url'];
4278 + } else {
4279 + $content_preview = strip_tags($match['metadata']['text'] ?? '');
4280 + $content_preview = preg_replace('/\s+/', ' ', $content_preview);
4281 + $source_display = substr(trim($content_preview), 0, 50) . '...';
4282 + }
4283 +
4284 + $match_id_for_display = $match['id'] ?? $index;
4285 +
4286 + $all_matches[] = [
4287 + 'document_id' => $match_id_for_display,
4288 + 'similarity' => $match['score'],
4289 + 'similarity_percentage' => round($match['score'] * 100, 2),
4290 + 'above_threshold' => $match['score'] >= $similarity_threshold,
4291 + 'source_display' => $source_display,
4292 + 'content_preview' => substr(strip_tags($match['metadata']['text'] ?? ''), 0, 100) . '...',
4293 + 'used_for_context' => in_array($match_id_for_display, $matches_used_for_context),
4294 + 'role_restriction' => $role_restriction,
4295 + 'has_access' => $has_access,
4296 + 'filtered_out' => !$has_access
4297 + ];
4298 + }
4299 +
4300 + // Store for testing panel
4301 + $this->last_similarity_analysis['top_matches'] = $all_matches;
4302 + $this->last_similarity_analysis['total_checked'] = count($results['matches']);
4303 +
4304 + // NEW: Store unique valid URLs for validation
4305 + $this->current_valid_urls = array_unique($valid_urls);
4306 +
4307 + // Add response guidelines
4308 + if ($matches_used === 0) {
4309 + $content = "No reference information was found for this query.\n\n";
4310 + } else {
4311 + $content .= "\n## Response Guidelines ##\n" .
4312 + "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
4313 + "Be conversational and friendly, but never mention your knowledge base or training data. " .
4314 + "If you don't have specific information or are uncertain about any details, it's always " .
4315 + "better to honestly say you don't know rather than making up or guessing at answers. " .
4316 + "When information is incomplete, let them know you are unsure.\n\n" .
4317 + "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
4318 + "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
4319 + }
4320 +
4321 + return trim($content);
4322 +}
4323 +
4324 +/**
4325 + * Get role restriction for a single vector (with caching)
4326 + */
4327 +private function get_single_vector_role($vector_id, $metadata = array()) {
4328 + global $wpdb;
4329 +
4330 + if (empty($vector_id)) {
4331 + return 'public';
4332 + }
4333 +
4334 + // Check cache first
4335 + $cache_key = 'mxchat_vector_role_' . $vector_id;
4336 + $cached_role = wp_cache_get($cache_key, 'mxchat_vector_roles');
4337 +
4338 + if ($cached_role !== false) {
4339 + return $cached_role;
4340 + }
4341 +
4342 + $role_restriction = 'public';
4343 +
4344 + // First try Pinecone metadata
4345 + if (!empty($metadata['role_restriction'])) {
4346 + $role_restriction = $metadata['role_restriction'];
4347 + } else {
4348 + // Check WordPress table for user-modified roles
4349 + $roles_table = $wpdb->prefix . 'mxchat_pinecone_roles';
4350 + $stored_role = $wpdb->get_var($wpdb->prepare(
4351 + "SELECT role_restriction FROM {$roles_table} WHERE vector_id = %s",
4352 + $vector_id
4353 + ));
4354 +
4355 + if ($stored_role) {
4356 + $role_restriction = $stored_role;
4357 + }
4358 + }
4359 +
4360 + // Cache individual role for 1 hour
4361 + wp_cache_set($cache_key, $role_restriction, 'mxchat_vector_roles', 3600);
4362 +
4363 + return $role_restriction;
4364 +}
4365 +
4366 +private function mxchat_find_relevant_products($user_embedding) {
4367 + //error_log('MXChat Vector Search: Starting product search...');
4368 +
4369 + // Retrieve the add-on settings from the database
4370 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
4371 +
4372 + // Determine whether Pinecone is enabled
4373 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
4374 +
4375 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
4376 +
4377 + if ($use_pinecone === 1) {
4378 + //error_log('MXChat Vector Search: Using Pinecone database for products');
4379 + return $this->find_relevant_products_pinecone($user_embedding);
4380 + } else {
4381 + //error_log('MXChat Vector Search: Using WordPress database for products');
4382 + return $this->find_relevant_products_wordpress($user_embedding);
4383 + }
4384 +}
4385 +private function find_relevant_products_wordpress($user_embedding) {
4386 + global $wpdb;
4387 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
4388 + $cache_key = 'mxchat_system_prompt_embeddings';
4389 + $batch_size = 500;
4390 +
4391 + // Original WordPress database search logic
4392 + // [Previous implementation remains the same]
4393 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
4394 + if ($embeddings === false) {
4395 + $embeddings = [];
4396 + $offset = 0;
4397 +
4398 + do {
4399 + $query = $wpdb->prepare(
4400 + "SELECT id, embedding_vector
4401 + FROM {$system_prompt_table}
4402 + LIMIT %d OFFSET %d",
4403 + $batch_size,
4404 + $offset
4405 + );
4406 +
4407 + $batch = $wpdb->get_results($query);
4408 + if (empty($batch)) {
4409 + break;
4410 + }
4411 +
4412 + $embeddings = array_merge($embeddings, $batch);
4413 + $offset += $batch_size;
4414 +
4415 + unset($batch);
4416 +
4417 + } while (true);
4418 +
4419 + if (empty($embeddings)) {
4420 + return '';
4421 + }
4422 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
4423 + }
4424 +
4425 + $relevant_results = [];
4426 + foreach ($embeddings as $embedding) {
4427 + $database_embedding = $embedding->embedding_vector
4428 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
4429 + : null;
4430 + if (is_array($database_embedding) && is_array($user_embedding)) {
4431 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
4432 + $relevant_results[] = [
4433 + 'id' => $embedding->id,
4434 + 'similarity' => $similarity
4435 + ];
4436 + }
4437 + unset($database_embedding);
4438 + }
4439 +
4440 + // Use fixed threshold for products
4441 + $similarity_threshold = 0.85;
4442 +
4443 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
4444 + return $result['similarity'] >= $similarity_threshold;
4445 + });
4446 + usort($relevant_results, function ($a, $b) {
4447 + return $b['similarity'] <=> $a['similarity'];
4448 + });
4449 +
4450 + $top_results = array_slice($relevant_results, 0, 3);
4451 + $content = '';
4452 +
4453 + foreach ($top_results as $result) {
4454 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
4455 + $content .= $chunk_content . "\n\n";
4456 + }
4457 +
4458 + return trim($content);
4459 +}
4460 +
4461 +
4462 +private function find_relevant_products_pinecone($user_embedding) {
4463 + //error_log('Starting Pinecone product search...');
4464 +
4465 + $options = get_option('mxchat_pinecone_addon_options', array());
4466 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
4467 + $host = $options['mxchat_pinecone_host'] ?? '';
4468 +
4469 + if (empty($host) || empty($api_key)) {
4470 + //error_log('Pinecone credentials not properly configured for product search');
4471 + return '';
4472 + }
4473 +
4474 + $similarity_threshold = 0.85;
4475 + $api_endpoint = "https://{$host}/query";
4476 +
4477 + $request_body = array(
4478 + 'vector' => $user_embedding,
4479 + 'topK' => 5,
4480 + 'includeMetadata' => true,
4481 + 'includeValues' => true,
4482 + 'filter' => array(
4483 + 'type' => 'product'
4484 + )
4485 + );
4486 +
4487 + //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
4488 +
4489 + $response = wp_remote_post($api_endpoint, array(
4490 + 'headers' => array(
4491 + 'Api-Key' => $api_key,
4492 + 'accept' => 'application/json',
4493 + 'content-type' => 'application/json'
4494 + ),
4495 + 'body' => wp_json_encode($request_body),
4496 + 'timeout' => 30
4497 + ));
4498 +
4499 + if (is_wp_error($response)) {
4500 + //error_log('Pinecone product query error: ' . $response->get_error_message());
4501 + return '';
4502 + }
4503 +
4504 + $response_code = wp_remote_retrieve_response_code($response);
4505 + //error_log('Pinecone response code: ' . $response_code);
4506 +
4507 + if ($response_code !== 200) {
4508 + //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
4509 + return '';
4510 + }
4511 +
4512 + $results = json_decode(wp_remote_retrieve_body($response), true);
4513 + //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
4514 +
4515 + if (empty($results['matches'])) {
4516 + //error_log('No matches found in Pinecone response');
4517 + return '';
4518 + }
4519 +
4520 + $content = '';
4521 + foreach ($results['matches'] as $match) {
4522 + if ($match['score'] < $similarity_threshold) {
4523 + //error_log("Match below threshold: " . $match['score']);
4524 + continue;
4525 + }
4526 +
4527 + if (!empty($match['metadata']['text'])) {
4528 + $content .= $match['metadata']['text'];
4529 + if (!empty($match['metadata']['source_url'])) {
4530 + $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
4531 + }
4532 + $content .= "\n\n";
4533 + }
4534 + }
4535 +
4536 + return trim($content);
4537 +}
4538 +
4539 +
4540 +private function fetch_content_with_product_links($most_relevant_id) {
4541 + global $wpdb;
4542 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
4543 +
4544 + // Fetch the article content and associated product URL
4545 + $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
4546 + $result = $wpdb->get_row($query);
4547 +
4548 + if ($result) {
4549 + // Append the product link to the content if available
4550 + $content = $result->article_content;
4551 + if (!empty($result->source_url)) {
4552 + $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
4553 + }
4554 + return $content;
4555 + }
4556 +
4557 + return null;
4558 +}
4559 +
4560 +/**
4561 + * Get system instructions for a specific bot or default
4562 + * Checks for multi-bot add-on and uses bot-specific instructions if available
4563 + */
4564 +private function get_system_instructions($bot_id = 'default') {
4565 + // Check if multi-bot add-on is active
4566 + if (class_exists('MxChat_Multi_Bot_Core_Manager') && $bot_id !== 'default') {
4567 + // Get bot-specific options from multi-bot add-on
4568 + $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
4569 +
4570 + // If bot has custom system instructions, use those
4571 + if (!empty($bot_options['system_prompt_instructions'])) {
4572 + return $bot_options['system_prompt_instructions'];
4573 + }
4574 + }
4575 +
4576 + // Fall back to default system instructions
4577 + return isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
4578 +}
4579 +/**
4580 + * Get the current bot ID from session or request context
4581 + */
4582 +private function get_current_bot_id($session_id = '') {
4583 + // First, check if bot_id is passed in the current request
4584 + if (isset($_POST['bot_id']) && !empty($_POST['bot_id'])) {
4585 + return sanitize_key($_POST['bot_id']);
4586 + }
4587 +
4588 + // If not in POST, try to get it from session data
4589 + if (!empty($session_id)) {
4590 + $bot_id = get_option("mxchat_session_bot_{$session_id}", '');
4591 + if (!empty($bot_id)) {
4592 + return $bot_id;
4593 + }
4594 + }
4595 +
4596 + // Fall back to default
4597 + return 'default';
4598 +}
4599 +private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $gemini_api_key, $openrouter_api_key, $conversation_history, $streaming = false, $session_id = '', $testing_data = null, $selected_model = 'gpt-4o') {
4600 + try {
4601 + if (!$relevant_content) {
4602 + $error_response = [
4603 + 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
4604 + 'error_code' => 'no_relevant_content'
4605 + ];
4606 +
4607 + if ($testing_data !== null) {
4608 + $error_response['testing_data'] = $testing_data;
4609 + }
4610 +
4611 + return $error_response;
4612 + }
4613 +
4614 + if (!is_array($conversation_history)) {
4615 + $conversation_history = array();
4616 + }
4617 +
4618 + // Check if this is an OpenRouter model
4619 + if ($selected_model === 'openrouter') {
4620 + // Get the actual OpenRouter model from options
4621 + $openrouter_selected_model = $this->options['openrouter_selected_model'] ?? '';
4622 +
4623 + if (empty($openrouter_selected_model)) {
4624 + $error_response = [
4625 + 'error' => esc_html__('No OpenRouter model selected. Please select a model in settings.', 'mxchat'),
4626 + 'error_code' => 'no_openrouter_model_selected'
4627 + ];
4628 + if ($testing_data !== null) {
4629 + $error_response['testing_data'] = $testing_data;
4630 + }
4631 + return $error_response;
4632 + }
4633 +
4634 + if (empty($openrouter_api_key)) {
4635 + $error_response = [
4636 + 'error' => esc_html__('OpenRouter API key is not configured', 'mxchat'),
4637 + 'error_code' => 'missing_openrouter_api_key'
4638 + ];
4639 + if ($testing_data !== null) {
4640 + $error_response['testing_data'] = $testing_data;
4641 + }
4642 + return $error_response;
4643 + }
4644 +
4645 + if ($streaming) {
4646 + return $this->mxchat_generate_response_openrouter_stream(
4647 + $openrouter_selected_model,
4648 + $openrouter_api_key,
4649 + $conversation_history,
4650 + $relevant_content,
4651 + $session_id,
4652 + $testing_data
4653 + );
4654 + } else {
4655 + $response = $this->mxchat_generate_response_openrouter(
4656 + $openrouter_selected_model,
4657 + $openrouter_api_key,
4658 + $conversation_history,
4659 + $relevant_content
4660 + );
4661 + }
4662 +
4663 + if (is_array($response) && isset($response['error'])) {
4664 + if ($testing_data !== null) {
4665 + $response['testing_data'] = $testing_data;
4666 + }
4667 + return $response;
4668 + }
4669 +
4670 + return $response;
4671 + }
4672 +
4673 + // Extract model prefix to determine the provider
4674 + $model_parts = explode('-', $selected_model);
4675 + $provider = strtolower($model_parts[0]);
4676 +
4677 + // Handle model selection based on provider prefix
4678 + switch ($provider) {
4679 + case 'gemini':
4680 + if (empty($gemini_api_key)) {
4681 + $error_response = [
4682 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
4683 + 'error_code' => 'missing_gemini_api_key'
4684 + ];
4685 + if ($testing_data !== null) {
4686 + $error_response['testing_data'] = $testing_data;
4687 + }
4688 + return $error_response;
4689 + }
4690 + $response = $this->mxchat_generate_response_gemini(
4691 + $selected_model,
4692 + $gemini_api_key,
4693 + $conversation_history,
4694 + $relevant_content
4695 + );
4696 + break;
4697 +
4698 + case 'claude':
4699 + if (empty($claude_api_key)) {
4700 + $error_response = [
4701 + 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
4702 + 'error_code' => 'missing_claude_api_key'
4703 + ];
4704 + if ($testing_data !== null) {
4705 + $error_response['testing_data'] = $testing_data;
4706 + }
4707 + return $error_response;
4708 + }
4709 + if ($streaming) {
4710 + return $this->mxchat_generate_response_claude_stream(
4711 + $selected_model,
4712 + $claude_api_key,
4713 + $conversation_history,
4714 + $relevant_content,
4715 + $session_id,
4716 + $testing_data
4717 + );
4718 + } else {
4719 + $response = $this->mxchat_generate_response_claude(
4720 + $selected_model,
4721 + $claude_api_key,
4722 + $conversation_history,
4723 + $relevant_content
4724 + );
4725 + }
4726 + break;
4727 +
4728 + case 'grok':
4729 + if (empty($xai_api_key)) {
4730 + $error_response = [
4731 + 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
4732 + 'error_code' => 'missing_xai_api_key'
4733 + ];
4734 + if ($testing_data !== null) {
4735 + $error_response['testing_data'] = $testing_data;
4736 + }
4737 + return $error_response;
4738 + }
4739 + if ($streaming) {
4740 + return $this->mxchat_generate_response_xai_stream(
4741 + $selected_model,
4742 + $xai_api_key,
4743 + $conversation_history,
4744 + $relevant_content,
4745 + $session_id,
4746 + $testing_data
4747 + );
4748 + } else {
4749 + $response = $this->mxchat_generate_response_xai(
4750 + $selected_model,
4751 + $xai_api_key,
4752 + $conversation_history,
4753 + $relevant_content
4754 + );
4755 + }
4756 + break;
4757 +
4758 + case 'deepseek':
4759 + if (empty($deepseek_api_key)) {
4760 + $error_response = [
4761 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
4762 + 'error_code' => 'missing_deepseek_api_key'
4763 + ];
4764 + if ($testing_data !== null) {
4765 + $error_response['testing_data'] = $testing_data;
4766 + }
4767 + return $error_response;
4768 + }
4769 + if ($streaming) {
4770 + return $this->mxchat_generate_response_deepseek_stream(
4771 + $selected_model,
4772 + $deepseek_api_key,
4773 + $conversation_history,
4774 + $relevant_content,
4775 + $session_id,
4776 + $testing_data
4777 + );
4778 + } else {
4779 + $response = $this->mxchat_generate_response_deepseek(
4780 + $selected_model,
4781 + $deepseek_api_key,
4782 + $conversation_history,
4783 + $relevant_content
4784 + );
4785 + }
4786 + break;
4787 +
4788 + case 'gpt':
4789 + case 'o1':
4790 + if (empty($api_key)) {
4791 + $error_response = [
4792 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
4793 + 'error_code' => 'missing_openai_api_key'
4794 + ];
4795 + if ($testing_data !== null) {
4796 + $error_response['testing_data'] = $testing_data;
4797 + }
4798 + return $error_response;
4799 + }
4800 + if ($streaming) {
4801 + return $this->mxchat_generate_response_openai_stream(
4802 + $selected_model,
4803 + $api_key,
4804 + $conversation_history,
4805 + $relevant_content,
4806 + $session_id,
4807 + $testing_data
4808 + );
4809 + } else {
4810 + $response = $this->mxchat_generate_response_openai(
4811 + $selected_model,
4812 + $api_key,
4813 + $conversation_history,
4814 + $relevant_content
4815 + );
4816 + }
4817 + break;
4818 +
4819 + default:
4820 + if (empty($api_key)) {
4821 + $error_response = [
4822 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
4823 + 'error_code' => 'missing_openai_api_key'
4824 + ];
4825 + if ($testing_data !== null) {
4826 + $error_response['testing_data'] = $testing_data;
4827 + }
4828 + return $error_response;
4829 + }
4830 + if ($streaming) {
4831 + return $this->mxchat_generate_response_openai_stream(
4832 + $selected_model,
4833 + $api_key,
4834 + $conversation_history,
4835 + $relevant_content,
4836 + $session_id,
4837 + $testing_data
4838 + );
4839 + } else {
4840 + $response = $this->mxchat_generate_response_openai(
4841 + $selected_model,
4842 + $api_key,
4843 + $conversation_history,
4844 + $relevant_content
4845 + );
4846 + }
4847 + break;
4848 + }
4849 +
4850 + if (is_array($response) && isset($response['error'])) {
4851 + if ($testing_data !== null) {
4852 + $response['testing_data'] = $testing_data;
4853 + }
4854 + return $response;
4855 + }
4856 +
4857 + return $response;
4858 +
4859 + } catch (Exception $e) {
4860 + $error_response = [
4861 + 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
4862 + 'error_code' => 'system_exception',
4863 + 'exception_details' => $e->getMessage()
4864 + ];
4865 +
4866 + if ($testing_data !== null) {
4867 + $error_response['testing_data'] = $testing_data;
4868 + }
4869 +
4870 + return $error_response;
4871 + }
4872 +}
4873 +private function mxchat_generate_response_openrouter_stream($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
4874 + try {
4875 + $bot_id = $this->get_current_bot_id($session_id);
4876 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
4877 +
4878 + if (!is_array($conversation_history)) {
4879 + $conversation_history = array();
4880 + }
4881 +
4882 + $formatted_conversation = array();
4883 +
4884 + $formatted_conversation[] = array(
4885 + 'role' => 'system',
4886 + 'content' => $system_prompt_instructions . " " . $relevant_content
4887 + );
4888 +
4889 + foreach ($conversation_history as $message) {
4890 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
4891 + $role = $message['role'];
4892 + if ($role === 'bot' || $role === 'agent') {
4893 + $role = 'assistant';
4894 + }
4895 + if (!in_array($role, ['system', 'assistant', 'user'])) {
4896 + $role = 'user';
4897 + }
4898 + $formatted_conversation[] = array(
4899 + 'role' => $role,
4900 + 'content' => $message['content']
4901 + );
4902 + }
4903 + }
4904 +
4905 + if (headers_sent() || !function_exists('curl_init')) {
4906 + $regular_response = $this->mxchat_generate_response_openrouter(
4907 + $selected_model,
4908 + $openrouter_api_key,
4909 + $conversation_history,
4910 + $relevant_content
4911 + );
4912 +
4913 + $response_data = [
4914 + 'text' => $regular_response,
4915 + 'html' => '',
4916 + 'session_id' => $session_id
4917 + ];
4918 +
4919 + if ($testing_data !== null) {
4920 + $response_data['testing_data'] = $testing_data;
4921 + }
4922 +
4923 + header('Content-Type: application/json');
4924 + echo json_encode($response_data);
4925 + return true;
4926 + }
4927 +
4928 + $body = json_encode([
4929 + 'model' => $selected_model,
4930 + 'messages' => $formatted_conversation,
4931 + 'temperature' => 1,
4932 + 'stream' => true
4933 + ]);
4934 +
4935 + $ch = curl_init();
4936 + curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
4937 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
4938 + curl_setopt($ch, CURLOPT_POST, true);
4939 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
4940 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
4941 + 'Content-Type: application/json',
4942 + 'Authorization: Bearer ' . $openrouter_api_key,
4943 + 'HTTP-Referer: ' . home_url(),
4944 + 'X-Title: ' . get_bloginfo('name')
4945 + ));
4946 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
4947 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
4948 +
4949 + $full_response = '';
4950 + $stream_started = false;
4951 + $buffer = '';
4952 +
4953 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
4954 + if (!$stream_started && $testing_data !== null) {
4955 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
4956 + flush();
4957 + $stream_started = true;
4958 + }
4959 +
4960 + $buffer .= $data;
4961 + $lines = explode("\n", $buffer);
4962 + $buffer = array_pop($lines);
4963 +
4964 + foreach ($lines as $line) {
4965 + if (trim($line) === '') {
4966 + continue;
4967 + }
4968 +
4969 + if (strpos($line, 'data: ') !== 0) {
4970 + continue;
4971 + }
4972 +
4973 + $json_str = substr($line, 6);
4974 +
4975 + if (trim($json_str) === '[DONE]') {
4976 + echo "data: [DONE]\n\n";
4977 + flush();
4978 + continue;
4979 + }
4980 +
4981 + $json = json_decode(trim($json_str), true);
4982 + if ($json && isset($json['choices'][0]['delta']['content'])) {
4983 + $content = $json['choices'][0]['delta']['content'];
4984 + $full_response .= $content;
4985 +
4986 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
4987 + flush();
4988 + }
4989 + }
4990 +
4991 + return strlen($data);
4992 + });
4993 +
4994 + $response = curl_exec($ch);
4995 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
4996 +
4997 + if (curl_errno($ch) || $http_code !== 200) {
4998 + curl_close($ch);
4999 +
5000 + $regular_response = $this->mxchat_generate_response_openrouter(
5001 + $selected_model,
5002 + $openrouter_api_key,
5003 + $conversation_history,
5004 + $relevant_content
5005 + );
5006 +
5007 + $response_data = [
5008 + 'text' => $regular_response,
5009 + 'html' => '',
5010 + 'session_id' => $session_id
5011 + ];
5012 +
5013 + if ($testing_data !== null) {
5014 + $response_data['testing_data'] = $testing_data;
5015 + }
5016 +
5017 + header('Content-Type: application/json');
5018 + echo json_encode($response_data);
5019 + return true;
5020 + }
5021 +
5022 + curl_close($ch);
5023 +
5024 + if (!empty($full_response) && !empty($session_id)) {
5025 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
5026 + }
5027 +
5028 + return true;
5029 +
5030 + } catch (Exception $e) {
5031 + $regular_response = $this->mxchat_generate_response_openrouter(
5032 + $selected_model,
5033 + $openrouter_api_key,
5034 + $conversation_history,
5035 + $relevant_content
5036 + );
5037 +
5038 + $response_data = [
5039 + 'text' => $regular_response,
5040 + 'html' => '',
5041 + 'session_id' => $session_id
5042 + ];
5043 +
5044 + if ($testing_data !== null) {
5045 + $response_data['testing_data'] = $testing_data;
5046 + }
5047 +
5048 + header('Content-Type: application/json');
5049 + echo json_encode($response_data);
5050 + return true;
5051 + }
5052 +}
5053 +private function mxchat_generate_response_openai_stream($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5054 + try {
5055 + $bot_id = $this->get_current_bot_id($session_id);
5056 +
5057 + // Get system prompt instructions using centralized function
5058 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5059 +
5060 + // Ensure conversation_history is an array
5061 + if (!is_array($conversation_history)) {
5062 + $conversation_history = array();
5063 + }
5064 +
5065 + // Format conversation history for OpenAI
5066 + $formatted_conversation = array();
5067 +
5068 + $formatted_conversation[] = array(
5069 + 'role' => 'system',
5070 + 'content' => $system_prompt_instructions . " " . $relevant_content
5071 + );
5072 +
5073 + foreach ($conversation_history as $message) {
5074 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5075 + $role = $message['role'];
5076 + if ($role === 'bot' || $role === 'agent') {
5077 + $role = 'assistant';
5078 + }
5079 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
5080 + $role = 'user';
5081 + }
5082 + $formatted_conversation[] = array(
5083 + 'role' => $role,
5084 + 'content' => $message['content']
5085 + );
5086 + }
5087 + }
5088 +
5089 + // Check if we can actually stream
5090 + if (headers_sent() || !function_exists('curl_init')) {
5091 + // Fallback to regular response with testing data
5092 + $regular_response = $this->mxchat_generate_response_openai(
5093 + $selected_model,
5094 + $api_key,
5095 + $conversation_history,
5096 + $relevant_content
5097 + );
5098 +
5099 + $response_data = [
5100 + 'text' => $regular_response,
5101 + 'html' => '',
5102 + 'session_id' => $session_id
5103 + ];
5104 +
5105 + if ($testing_data !== null) {
5106 + $response_data['testing_data'] = $testing_data;
5107 + }
5108 +
5109 + header('Content-Type: application/json');
5110 + echo json_encode($response_data);
5111 + return true;
5112 + }
5113 +
5114 + // Check if this is a GPT-5 model (supports reasoning_effort parameter)
5115 + $is_gpt5_model = (
5116 + strpos($selected_model, 'gpt-5') === 0 ||
5117 + $selected_model === 'gpt-5.1-2025-11-13' ||
5118 + $selected_model === 'gpt-5' ||
5119 + $selected_model === 'gpt-5-mini' ||
5120 + $selected_model === 'gpt-5-nano'
5121 + );
5122 +
5123 + // Build request body with optimal settings for fast streaming
5124 + $request_body = [
5125 + 'model' => $selected_model,
5126 + 'messages' => $formatted_conversation,
5127 + 'temperature' => 1,
5128 + 'stream' => true
5129 + ];
5130 +
5131 + // Add reasoning_effort only for GPT-5 models
5132 + if ($is_gpt5_model) {
5133 + // GPT-5.1 uses 'low' instead of 'minimal'
5134 + if ($selected_model === 'gpt-5.1-2025-11-13') {
5135 + $request_body['reasoning_effort'] = 'low';
5136 + } else {
5137 + $request_body['reasoning_effort'] = 'minimal'; // For other GPT-5 models
5138 + }
5139 + }
5140 +
5141 + $body = json_encode($request_body);
5142 +
5143 + // Use cURL for streaming support
5144 + $ch = curl_init();
5145 + curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
5146 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5147 + curl_setopt($ch, CURLOPT_POST, true);
5148 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5149 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5150 + 'Content-Type: application/json',
5151 + 'Authorization: Bearer ' . $api_key
5152 + ));
5153 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5154 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5155 +
5156 + $full_response = ''; // Accumulate full response for saving
5157 + $stream_started = false;
5158 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5159 +
5160 + // Buffer control for real-time streaming
5161 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5162 + // Send testing data as the first event if available
5163 + if (!$stream_started && $testing_data !== null) {
5164 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5165 + flush();
5166 + $stream_started = true;
5167 + }
5168 +
5169 + // CRITICAL FIX: Append new data to buffer
5170 + $buffer .= $data;
5171 +
5172 + // Process complete lines only
5173 + $lines = explode("\n", $buffer);
5174 +
5175 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5176 + // The last element might be incomplete, so keep it in buffer
5177 + $buffer = array_pop($lines);
5178 +
5179 + foreach ($lines as $line) {
5180 + // Skip empty lines
5181 + if (trim($line) === '') {
5182 + continue;
5183 + }
5184 +
5185 + // Only process lines that start with "data: "
5186 + if (strpos($line, 'data: ') !== 0) {
5187 + continue;
5188 + }
5189 +
5190 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5191 +
5192 + if (trim($json_str) === '[DONE]') {
5193 + echo "data: [DONE]\n\n";
5194 + flush();
5195 + continue;
5196 + }
5197 +
5198 + // Try to decode JSON
5199 + $json = json_decode(trim($json_str), true);
5200 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5201 + $content = $json['choices'][0]['delta']['content'];
5202 + $full_response .= $content; // Accumulate the full response
5203 +
5204 + // Send as SSE format
5205 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5206 + flush();
5207 + }
5208 + }
5209 +
5210 + return strlen($data);
5211 + });
5212 +
5213 + $response = curl_exec($ch);
5214 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5215 +
5216 + if (curl_errno($ch) || $http_code !== 200) {
5217 + $curl_error = curl_error($ch);
5218 + curl_close($ch);
5219 +
5220 + // Fallback to regular response
5221 + $regular_response = $this->mxchat_generate_response_openai(
5222 + $selected_model,
5223 + $api_key,
5224 + $conversation_history,
5225 + $relevant_content
5226 + );
5227 +
5228 + // FIXED: Check if regular response returned an error
5229 + if (is_array($regular_response) && isset($regular_response['error'])) {
5230 + // Send error in SSE format since we're in streaming mode
5231 + echo "data: " . json_encode([
5232 + 'error' => true,
5233 + 'error_message' => $regular_response['error'],
5234 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5235 + 'text' => $regular_response['error'],
5236 + 'message' => $regular_response['error']
5237 + ]) . "\n\n";
5238 + echo "data: [DONE]\n\n";
5239 + flush();
5240 + return true;
5241 + }
5242 +
5243 + $response_data = [
5244 + 'text' => $regular_response,
5245 + 'html' => '',
5246 + 'session_id' => $session_id
5247 + ];
5248 +
5249 + if ($testing_data !== null) {
5250 + $response_data['testing_data'] = $testing_data;
5251 + }
5252 +
5253 + header('Content-Type: application/json');
5254 + echo json_encode($response_data);
5255 + return true;
5256 + }
5257 +
5258 + curl_close($ch);
5259 +
5260 + // Save the complete response to maintain chat persistence
5261 + if (!empty($full_response) && !empty($session_id)) {
5262 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
5263 + }
5264 +
5265 + return true; // Indicate streaming completed successfully
5266 +
5267 + } catch (Exception $e) {
5268 + // Fallback to regular response
5269 + $regular_response = $this->mxchat_generate_response_openai(
5270 + $selected_model,
5271 + $api_key,
5272 + $conversation_history,
5273 + $relevant_content
5274 + );
5275 +
5276 + // FIXED: Check if regular response returned an error
5277 + if (is_array($regular_response) && isset($regular_response['error'])) {
5278 + // Send error in SSE format since we're in streaming mode
5279 + echo "data: " . json_encode([
5280 + 'error' => true,
5281 + 'error_message' => $regular_response['error'],
5282 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5283 + 'text' => $regular_response['error'],
5284 + 'message' => $regular_response['error']
5285 + ]) . "\n\n";
5286 + echo "data: [DONE]\n\n";
5287 + flush();
5288 + return true;
5289 + }
5290 +
5291 + $response_data = [
5292 + 'text' => $regular_response,
5293 + 'html' => '',
5294 + 'session_id' => $session_id
5295 + ];
5296 +
5297 + if ($testing_data !== null) {
5298 + $response_data['testing_data'] = $testing_data;
5299 + }
5300 +
5301 + header('Content-Type: application/json');
5302 + echo json_encode($response_data);
5303 + return true;
5304 + }
5305 +}
5306 +private function mxchat_generate_response_claude_stream($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5307 + try {
5308 + // Get bot ID from session or request
5309 + $bot_id = $this->get_current_bot_id($session_id);
5310 +
5311 + // Get system prompt instructions using centralized function
5312 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5313 + // Ensure conversation_history is an array
5314 + if (!is_array($conversation_history)) {
5315 + $conversation_history = array();
5316 + }
5317 +
5318 + // Clean and validate conversation history
5319 + foreach ($conversation_history as &$message) {
5320 + // Convert bot and agent roles to assistant
5321 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
5322 + $message['role'] = 'assistant';
5323 + }
5324 +
5325 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
5326 + if (!in_array($message['role'], ['assistant', 'user'])) {
5327 + $message['role'] = 'user';
5328 + }
5329 +
5330 + // Ensure content field exists
5331 + if (!isset($message['content']) || empty($message['content'])) {
5332 + $message['content'] = '';
5333 + }
5334 +
5335 + // Remove any unsupported fields
5336 + $message = array_intersect_key($message, array_flip(['role', 'content']));
5337 + }
5338 +
5339 + // Add relevant content as the latest user message
5340 + $conversation_history[] = [
5341 + 'role' => 'user',
5342 + 'content' => $relevant_content
5343 + ];
5344 +
5345 + // Prepare the request body with stream: true
5346 + $body = json_encode([
5347 + 'model' => $selected_model,
5348 + 'messages' => $conversation_history,
5349 + 'max_tokens' => 1000,
5350 + 'temperature' => 0.8,
5351 + 'system' => $system_prompt_instructions,
5352 + 'stream' => true
5353 + ]);
5354 +
5355 + // Check if we can actually stream (headers not sent, etc.)
5356 + if (headers_sent() || !function_exists('curl_init')) {
5357 + // Fallback to regular response with testing data
5358 + //error_log("MxChat: Streaming not possible, falling back to regular response");
5359 + $regular_response = $this->mxchat_generate_response_claude(
5360 + $selected_model,
5361 + $claude_api_key,
5362 + array_slice($conversation_history, 0, -1), // Remove the added content
5363 + $relevant_content
5364 + );
5365 +
5366 + // Return as JSON with testing data
5367 + $response_data = [
5368 + 'text' => $regular_response,
5369 + 'html' => '',
5370 + 'session_id' => $session_id
5371 + ];
5372 +
5373 + if ($testing_data !== null) {
5374 + $response_data['testing_data'] = $testing_data;
5375 + //error_log("MxChat Testing: Added testing data to Claude fallback response");
5376 + }
5377 +
5378 + // Clear any streaming headers and send JSON
5379 + if (headers_sent() === false) {
5380 + header('Content-Type: application/json');
5381 + }
5382 + echo json_encode($response_data);
5383 + return true; // Indicate we handled the response
5384 + }
5385 +
5386 + // Use cURL for streaming support
5387 + $ch = curl_init();
5388 + curl_setopt($ch, CURLOPT_URL, 'https://api.anthropic.com/v1/messages');
5389 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5390 + curl_setopt($ch, CURLOPT_POST, true);
5391 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5392 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5393 + 'Content-Type: application/json',
5394 + 'x-api-key: ' . $claude_api_key,
5395 + 'anthropic-version: 2023-06-01'
5396 + ));
5397 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5398 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5399 +
5400 + $full_response = ''; // Accumulate full response for saving
5401 + $stream_started = false;
5402 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5403 +
5404 + // Buffer control for real-time streaming
5405 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5406 + // Send testing data as the first event if available
5407 + if (!$stream_started && $testing_data !== null) {
5408 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5409 + flush();
5410 + $stream_started = true;
5411 + //error_log("MxChat Testing: Sent testing data in Claude stream");
5412 + }
5413 +
5414 + // CRITICAL FIX: Append new data to buffer
5415 + $buffer .= $data;
5416 +
5417 + // Process complete lines only
5418 + $lines = explode("\n", $buffer);
5419 +
5420 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5421 + // The last element might be incomplete, so keep it in buffer
5422 + $buffer = array_pop($lines);
5423 +
5424 + foreach ($lines as $line) {
5425 + if (trim($line) === '') {
5426 + continue;
5427 + }
5428 +
5429 + // Claude uses event: and data: format
5430 + if (strpos($line, 'event: ') === 0) {
5431 + // Store the event type for the next data line
5432 + continue;
5433 + }
5434 +
5435 + if (strpos($line, 'data: ') === 0) {
5436 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5437 +
5438 + $json = json_decode(trim($json_str), true);
5439 + if (json_last_error() !== JSON_ERROR_NONE) {
5440 + continue;
5441 + }
5442 +
5443 + // Handle different event types
5444 + if (isset($json['type'])) {
5445 + switch ($json['type']) {
5446 + case 'content_block_delta':
5447 + if (isset($json['delta']['text'])) {
5448 + $content = $json['delta']['text'];
5449 + $full_response .= $content; // Accumulate
5450 + // Send as SSE format compatible with your frontend
5451 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5452 + flush();
5453 + }
5454 + break;
5455 +
5456 + case 'message_stop':
5457 + echo "data: [DONE]\n\n";
5458 + flush();
5459 + break;
5460 +
5461 + case 'error':
5462 + echo "data: " . json_encode(['error' => $json['error']['message'] ?? 'Unknown error']) . "\n\n";
5463 + flush();
5464 + break;
5465 + }
5466 + }
5467 + }
5468 + }
5469 +
5470 + return strlen($data);
5471 + });
5472 +
5473 + $response = curl_exec($ch);
5474 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5475 +
5476 + if (curl_errno($ch)) {
5477 + curl_close($ch);
5478 + throw new Exception('cURL Error: ' . curl_error($ch));
5479 + }
5480 +
5481 + curl_close($ch);
5482 +
5483 + if ($http_code !== 200) {
5484 + // Fallback to regular response
5485 + //error_log("MxChat: Claude streaming failed with HTTP $http_code, falling back");
5486 + $regular_response = $this->mxchat_generate_response_claude(
5487 + $selected_model,
5488 + $claude_api_key,
5489 + array_slice($conversation_history, 0, -1), // Remove the added content
5490 + $relevant_content
5491 + );
5492 +
5493 + // FIXED: Check if regular response returned an error
5494 + if (is_array($regular_response) && isset($regular_response['error'])) {
5495 + // Send error in SSE format since we're in streaming mode
5496 + echo "data: " . json_encode([
5497 + 'error' => true,
5498 + 'error_message' => $regular_response['error'],
5499 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5500 + 'text' => $regular_response['error'],
5501 + 'message' => $regular_response['error']
5502 + ]) . "\n\n";
5503 + echo "data: [DONE]\n\n";
5504 + flush();
5505 + return true;
5506 + }
5507 +
5508 + $response_data = [
5509 + 'text' => $regular_response,
5510 + 'html' => '',
5511 + 'session_id' => $session_id
5512 + ];
5513 +
5514 + if ($testing_data !== null) {
5515 + $response_data['testing_data'] = $testing_data;
5516 + //error_log("MxChat Testing: Added testing data to Claude error fallback");
5517 + }
5518 +
5519 + header('Content-Type: application/json');
5520 + echo json_encode($response_data);
5521 + return true;
5522 + }
5523 +
5524 + // Save the complete response to maintain chat persistence
5525 + if (!empty($full_response) && !empty($session_id)) {
5526 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
5527 + }
5528 +
5529 + return true; // Indicate streaming completed successfully
5530 +
5531 + } catch (Exception $e) {
5532 + //error_log("MxChat Claude streaming exception: " . $e->getMessage());
5533 +
5534 + // Fallback to regular response on exception
5535 + $regular_response = $this->mxchat_generate_response_claude(
5536 + $selected_model,
5537 + $claude_api_key,
5538 + $conversation_history,
5539 + $relevant_content
5540 + );
5541 +
5542 + // FIXED: Check if regular response returned an error
5543 + if (is_array($regular_response) && isset($regular_response['error'])) {
5544 + // Send error in SSE format since we're in streaming mode
5545 + echo "data: " . json_encode([
5546 + 'error' => true,
5547 + 'error_message' => $regular_response['error'],
5548 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5549 + 'text' => $regular_response['error'],
5550 + 'message' => $regular_response['error']
5551 + ]) . "\n\n";
5552 + echo "data: [DONE]\n\n";
5553 + flush();
5554 + return true;
5555 + }
5556 +
5557 + $response_data = [
5558 + 'text' => $regular_response,
5559 + 'html' => '',
5560 + 'session_id' => $session_id
5561 + ];
5562 +
5563 + if ($testing_data !== null) {
5564 + $response_data['testing_data'] = $testing_data;
5565 + //error_log("MxChat Testing: Added testing data to Claude exception fallback");
5566 + }
5567 +
5568 + header('Content-Type: application/json');
5569 + echo json_encode($response_data);
5570 + return true;
5571 + }
5572 +}
5573 +private function mxchat_generate_response_xai_stream($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5574 + try {
5575 + // Get bot ID from session or request
5576 + $bot_id = $this->get_current_bot_id($session_id);
5577 +
5578 + // Get system prompt instructions using centralized function
5579 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5580 +
5581 + // Ensure conversation_history is an array
5582 + if (!is_array($conversation_history)) {
5583 + $conversation_history = array();
5584 + }
5585 +
5586 + // Format conversation history for X.AI (same as OpenAI format)
5587 + $formatted_conversation = array();
5588 +
5589 + $formatted_conversation[] = array(
5590 + 'role' => 'system',
5591 + 'content' => $system_prompt_instructions . " " . $relevant_content
5592 + );
5593 +
5594 + foreach ($conversation_history as $message) {
5595 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5596 + $role = $message['role'];
5597 + if ($role === 'bot' || $role === 'agent') {
5598 + $role = 'assistant';
5599 + }
5600 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
5601 + $role = 'user';
5602 + }
5603 + $formatted_conversation[] = array(
5604 + 'role' => $role,
5605 + 'content' => $message['content']
5606 + );
5607 + }
5608 + }
5609 +
5610 + // Check if we can actually stream
5611 + if (headers_sent() || !function_exists('curl_init')) {
5612 + // Fallback to regular response with testing data
5613 + //error_log("MxChat: X.AI streaming not possible, falling back to regular response");
5614 + $regular_response = $this->mxchat_generate_response_xai(
5615 + $selected_model,
5616 + $xai_api_key,
5617 + $conversation_history,
5618 + $relevant_content
5619 + );
5620 +
5621 + $response_data = [
5622 + 'text' => $regular_response,
5623 + 'html' => '',
5624 + 'session_id' => $session_id
5625 + ];
5626 +
5627 + if ($testing_data !== null) {
5628 + $response_data['testing_data'] = $testing_data;
5629 + //error_log("MxChat Testing: Added testing data to X.AI fallback response");
5630 + }
5631 +
5632 + header('Content-Type: application/json');
5633 + echo json_encode($response_data);
5634 + return true;
5635 + }
5636 +
5637 + // Prepare the request body with stream: true
5638 + $body = json_encode([
5639 + 'model' => $selected_model,
5640 + 'messages' => $formatted_conversation,
5641 + 'temperature' => 0.8,
5642 + 'stream' => true
5643 + ]);
5644 +
5645 + // Use cURL for streaming support
5646 + $ch = curl_init();
5647 + curl_setopt($ch, CURLOPT_URL, 'https://api.x.ai/v1/chat/completions');
5648 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5649 + curl_setopt($ch, CURLOPT_POST, true);
5650 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5651 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5652 + 'Content-Type: application/json',
5653 + 'Authorization: Bearer ' . $xai_api_key
5654 + ));
5655 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5656 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5657 +
5658 + $full_response = ''; // Accumulate full response for saving
5659 + $stream_started = false;
5660 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5661 +
5662 + // Buffer control for real-time streaming
5663 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5664 + // Send testing data as the first event if available
5665 + if (!$stream_started && $testing_data !== null) {
5666 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5667 + flush();
5668 + $stream_started = true;
5669 + //error_log("MxChat Testing: Sent testing data in X.AI stream");
5670 + }
5671 +
5672 + // CRITICAL FIX: Append new data to buffer
5673 + $buffer .= $data;
5674 +
5675 + // Process complete lines only
5676 + $lines = explode("\n", $buffer);
5677 +
5678 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5679 + // The last element might be incomplete, so keep it in buffer
5680 + $buffer = array_pop($lines);
5681 +
5682 + foreach ($lines as $line) {
5683 + // Skip empty lines
5684 + if (trim($line) === '') {
5685 + continue;
5686 + }
5687 +
5688 + // Only process lines that start with "data: "
5689 + if (strpos($line, 'data: ') !== 0) {
5690 + continue;
5691 + }
5692 +
5693 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5694 +
5695 + if (trim($json_str) === '[DONE]') {
5696 + echo "data: [DONE]\n\n";
5697 + flush();
5698 + continue;
5699 + }
5700 +
5701 + // Try to decode JSON
5702 + $json = json_decode(trim($json_str), true);
5703 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5704 + $content = $json['choices'][0]['delta']['content'];
5705 + $full_response .= $content; // Accumulate
5706 + // Send as SSE format
5707 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5708 + flush();
5709 + }
5710 + }
5711 +
5712 + return strlen($data);
5713 + });
5714 +
5715 + $response = curl_exec($ch);
5716 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5717 +
5718 + if (curl_errno($ch) || $http_code !== 200) {
5719 + curl_close($ch);
5720 +
5721 + // Fallback to regular response
5722 + //error_log("MxChat: X.AI streaming failed, falling back");
5723 + $regular_response = $this->mxchat_generate_response_xai(
5724 + $selected_model,
5725 + $xai_api_key,
5726 + $conversation_history,
5727 + $relevant_content
5728 + );
5729 +
5730 + $response_data = [
5731 + 'text' => $regular_response,
5732 + 'html' => '',
5733 + 'session_id' => $session_id
5734 + ];
5735 +
5736 + if ($testing_data !== null) {
5737 + $response_data['testing_data'] = $testing_data;
5738 + //error_log("MxChat Testing: Added testing data to X.AI error fallback");
5739 + }
5740 +
5741 + header('Content-Type: application/json');
5742 + echo json_encode($response_data);
5743 + return true;
5744 + }
5745 +
5746 + curl_close($ch);
5747 +
5748 + // Save the complete response to maintain chat persistence
5749 + if (!empty($full_response) && !empty($session_id)) {
5750 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
5751 + }
5752 +
5753 + return true; // Indicate streaming completed successfully
5754 +
5755 + } catch (Exception $e) {
5756 + //error_log("MxChat X.AI streaming exception: " . $e->getMessage());
5757 +
5758 + // Fallback to regular response
5759 + $regular_response = $this->mxchat_generate_response_xai(
5760 + $selected_model,
5761 + $xai_api_key,
5762 + $conversation_history,
5763 + $relevant_content
5764 + );
5765 +
5766 + $response_data = [
5767 + 'text' => $regular_response,
5768 + 'html' => '',
5769 + 'session_id' => $session_id
5770 + ];
5771 +
5772 + if ($testing_data !== null) {
5773 + $response_data['testing_data'] = $testing_data;
5774 + //error_log("MxChat Testing: Added testing data to X.AI exception fallback");
5775 + }
5776 +
5777 + header('Content-Type: application/json');
5778 + echo json_encode($response_data);
5779 + return true;
5780 + }
5781 +}
5782 +private function mxchat_generate_response_deepseek_stream($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5783 + try {
5784 + // Get bot ID from session or request
5785 + $bot_id = $this->get_current_bot_id($session_id);
5786 +
5787 + // Get system prompt instructions using centralized function
5788 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5789 +
5790 + // Ensure conversation_history is an array
5791 + if (!is_array($conversation_history)) {
5792 + $conversation_history = array();
5793 + }
5794 +
5795 + // Format conversation history for DeepSeek
5796 + $formatted_conversation = array();
5797 +
5798 + $formatted_conversation[] = array(
5799 + 'role' => 'system',
5800 + 'content' => $system_prompt_instructions . " " . $relevant_content
5801 + );
5802 +
5803 + foreach ($conversation_history as $message) {
5804 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5805 + $role = $message['role'];
5806 + if ($role === 'bot' || $role === 'agent') {
5807 + $role = 'assistant';
5808 + }
5809 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
5810 + $role = 'user';
5811 + }
5812 + $formatted_conversation[] = array(
5813 + 'role' => $role,
5814 + 'content' => $message['content']
5815 + );
5816 + }
5817 + }
5818 +
5819 + // Check if we can actually stream
5820 + if (headers_sent() || !function_exists('curl_init')) {
5821 + // Fallback to regular response with testing data
5822 + //error_log("MxChat: DeepSeek streaming not possible, falling back to regular response");
5823 + $regular_response = $this->mxchat_generate_response_deepseek(
5824 + $selected_model,
5825 + $deepseek_api_key,
5826 + $conversation_history,
5827 + $relevant_content
5828 + );
5829 +
5830 + $response_data = [
5831 + 'text' => $regular_response,
5832 + 'html' => '',
5833 + 'session_id' => $session_id
5834 + ];
5835 +
5836 + if ($testing_data !== null) {
5837 + $response_data['testing_data'] = $testing_data;
5838 + //error_log("MxChat Testing: Added testing data to DeepSeek fallback response");
5839 + }
5840 +
5841 + header('Content-Type: application/json');
5842 + echo json_encode($response_data);
5843 + return true;
5844 + }
5845 +
5846 + // Prepare the request body with stream: true
5847 + $body = json_encode([
5848 + 'model' => $selected_model,
5849 + 'messages' => $formatted_conversation,
5850 + 'temperature' => 0.8,
5851 + 'stream' => true
5852 + ]);
5853 +
5854 + // Use cURL for streaming support
5855 + $ch = curl_init();
5856 + curl_setopt($ch, CURLOPT_URL, 'https://api.deepseek.com/v1/chat/completions');
5857 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5858 + curl_setopt($ch, CURLOPT_POST, true);
5859 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5860 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5861 + 'Content-Type: application/json',
5862 + 'Authorization: Bearer ' . $deepseek_api_key
5863 + ));
5864 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5865 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5866 +
5867 + $full_response = ''; // Accumulate full response for saving
5868 + $stream_started = false;
5869 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5870 +
5871 + // Buffer control for real-time streaming
5872 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5873 + // Send testing data as the first event if available
5874 + if (!$stream_started && $testing_data !== null) {
5875 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5876 + flush();
5877 + $stream_started = true;
5878 + //error_log("MxChat Testing: Sent testing data in DeepSeek stream");
5879 + }
5880 +
5881 + // CRITICAL FIX: Append new data to buffer
5882 + $buffer .= $data;
5883 +
5884 + // Process complete lines only
5885 + $lines = explode("\n", $buffer);
5886 +
5887 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5888 + // The last element might be incomplete, so keep it in buffer
5889 + $buffer = array_pop($lines);
5890 +
5891 + foreach ($lines as $line) {
5892 + // Skip empty lines
5893 + if (trim($line) === '') {
5894 + continue;
5895 + }
5896 +
5897 + // Only process lines that start with "data: "
5898 + if (strpos($line, 'data: ') !== 0) {
5899 + continue;
5900 + }
5901 +
5902 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5903 +
5904 + if (trim($json_str) === '[DONE]') {
5905 + echo "data: [DONE]\n\n";
5906 + flush();
5907 + continue;
5908 + }
5909 +
5910 + // Try to decode JSON
5911 + $json = json_decode(trim($json_str), true);
5912 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5913 + $content = $json['choices'][0]['delta']['content'];
5914 + $full_response .= $content; // Accumulate the full response
5915 +
5916 + // Send as SSE format
5917 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5918 + flush();
5919 + }
5920 + }
5921 +
5922 + return strlen($data);
5923 + });
5924 +
5925 + $response = curl_exec($ch);
5926 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5927 +
5928 + if (curl_errno($ch) || $http_code !== 200) {
5929 + $curl_error = curl_error($ch);
5930 + curl_close($ch);
5931 +
5932 + // Log the specific error for debugging
5933 + //error_log("MxChat: DeepSeek streaming failed - HTTP: $http_code, cURL: $curl_error");
5934 +
5935 + // Fallback to regular response
5936 + $regular_response = $this->mxchat_generate_response_deepseek(
5937 + $selected_model,
5938 + $deepseek_api_key,
5939 + $conversation_history,
5940 + $relevant_content
5941 + );
5942 +
5943 + // Handle error response from regular function
5944 + if (is_array($regular_response) && isset($regular_response['error'])) {
5945 + if ($testing_data !== null) {
5946 + $regular_response['testing_data'] = $testing_data;
5947 + }
5948 + header('Content-Type: application/json');
5949 + echo json_encode($regular_response);
5950 + return true;
5951 + }
5952 +
5953 + $response_data = [
5954 + 'text' => $regular_response,
5955 + 'html' => '',
5956 + 'session_id' => $session_id
5957 + ];
5958 +
5959 + if ($testing_data !== null) {
5960 + $response_data['testing_data'] = $testing_data;
5961 + //error_log("MxChat Testing: Added testing data to DeepSeek error fallback");
5962 + }
5963 +
5964 + header('Content-Type: application/json');
5965 + echo json_encode($response_data);
5966 + return true;
5967 + }
5968 +
5969 + curl_close($ch);
5970 +
5971 + // Save the complete response to maintain chat persistence
5972 + if (!empty($full_response) && !empty($session_id)) {
5973 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
5974 + }
5975 +
5976 + return true; // Indicate streaming completed successfully
5977 +
5978 + } catch (Exception $e) {
5979 + //error_log("MxChat DeepSeek streaming exception: " . $e->getMessage());
5980 +
5981 + // Fallback to regular response
5982 + $regular_response = $this->mxchat_generate_response_deepseek(
5983 + $selected_model,
5984 + $deepseek_api_key,
5985 + $conversation_history,
5986 + $relevant_content
5987 + );
5988 +
5989 + // Handle error response from regular function
5990 + if (is_array($regular_response) && isset($regular_response['error'])) {
5991 + if ($testing_data !== null) {
5992 + $regular_response['testing_data'] = $testing_data;
5993 + }
5994 + header('Content-Type: application/json');
5995 + echo json_encode($regular_response);
5996 + return true;
5997 + }
5998 +
5999 + $response_data = [
6000 + 'text' => $regular_response,
6001 + 'html' => '',
6002 + 'session_id' => $session_id
6003 + ];
6004 +
6005 + if ($testing_data !== null) {
6006 + $response_data['testing_data'] = $testing_data;
6007 + //error_log("MxChat Testing: Added testing data to DeepSeek exception fallback");
6008 + }
6009 +
6010 + header('Content-Type: application/json');
6011 + echo json_encode($response_data);
6012 + return true;
6013 + }
6014 +}
6015 +
6016 +
6017 +private function mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content) {
6018 + try {
6019 + if (!is_array($conversation_history)) {
6020 + $conversation_history = array();
6021 + }
6022 +
6023 + $bot_id = $this->get_current_bot_id('');
6024 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6025 +
6026 + $formatted_conversation = array();
6027 +
6028 + $formatted_conversation[] = array(
6029 + 'role' => 'system',
6030 + 'content' => $system_prompt_instructions . " " . $relevant_content
6031 + );
6032 +
6033 + foreach ($conversation_history as $message) {
6034 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6035 + $role = $message['role'];
6036 +
6037 + if ($role === 'bot' || $role === 'agent') {
6038 + $role = 'assistant';
6039 + }
6040 + if (!in_array($role, ['system', 'assistant', 'user'])) {
6041 + $role = 'user';
6042 + }
6043 +
6044 + $formatted_conversation[] = array(
6045 + 'role' => $role,
6046 + 'content' => $message['content']
6047 + );
6048 + }
6049 + }
6050 +
6051 + $body = json_encode([
6052 + 'model' => $selected_model,
6053 + 'messages' => $formatted_conversation,
6054 + 'temperature' => 1,
6055 + ]);
6056 +
6057 + $args = [
6058 + 'body' => $body,
6059 + 'headers' => [
6060 + 'Content-Type' => 'application/json',
6061 + 'Authorization' => 'Bearer ' . $openrouter_api_key,
6062 + 'HTTP-Referer' => home_url(),
6063 + 'X-Title' => get_bloginfo('name'),
6064 + ],
6065 + 'timeout' => 60,
6066 + 'redirection' => 5,
6067 + 'blocking' => true,
6068 + 'httpversion' => '1.0',
6069 + 'sslverify' => true,
6070 + ];
6071 +
6072 + $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', $args);
6073 +
6074 + if (is_wp_error($response)) {
6075 + $error_message = $response->get_error_message();
6076 + return [
6077 + 'error' => esc_html__('Connection error when contacting OpenRouter: ', 'mxchat') . esc_html($error_message),
6078 + 'error_code' => 'openrouter_connection_error',
6079 + 'provider' => 'openrouter'
6080 + ];
6081 + }
6082 +
6083 + $status_code = wp_remote_retrieve_response_code($response);
6084 + if ($status_code !== 200) {
6085 + $response_body = wp_remote_retrieve_body($response);
6086 + $decoded_response = json_decode($response_body, true);
6087 +
6088 + $error_message = isset($decoded_response['error']['message'])
6089 + ? $decoded_response['error']['message']
6090 + : 'HTTP Error ' . $status_code;
6091 +
6092 + return [
6093 + 'error' => esc_html__('OpenRouter API error: ', 'mxchat') . esc_html($error_message),
6094 + 'error_code' => 'openrouter_api_error',
6095 + 'provider' => 'openrouter',
6096 + 'status_code' => $status_code
6097 + ];
6098 + }
6099 +
6100 + $response_body = wp_remote_retrieve_body($response);
6101 + $decoded_response = json_decode($response_body, true);
6102 +
6103 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6104 + return trim($decoded_response['choices'][0]['message']['content']);
6105 + } else {
6106 + return [
6107 + 'error' => esc_html__('Unexpected response format from OpenRouter.', 'mxchat'),
6108 + 'error_code' => 'openrouter_response_format_error',
6109 + 'provider' => 'openrouter'
6110 + ];
6111 + }
6112 + } catch (Exception $e) {
6113 + return [
6114 + 'error' => esc_html__('System error when processing OpenRouter request: ', 'mxchat') . esc_html($e->getMessage()),
6115 + 'error_code' => 'openrouter_exception',
6116 + 'provider' => 'openrouter'
6117 + ];
6118 + }
6119 +}
6120 +private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
6121 +
6122 + // Get bot ID from session or request
6123 + $bot_id = $this->get_current_bot_id($session_id);
6124 +
6125 + // Get system prompt instructions using centralized function
6126 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6127 +
6128 + // Clean and validate conversation history
6129 + foreach ($conversation_history as &$message) {
6130 + // Convert bot and agent roles to assistant
6131 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
6132 + $message['role'] = 'assistant';
6133 + }
6134 +
6135 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
6136 + if (!in_array($message['role'], ['assistant', 'user'])) {
6137 + $message['role'] = 'user';
6138 + }
6139 +
6140 + // Ensure content field exists
6141 + if (!isset($message['content']) || empty($message['content'])) {
6142 + $message['content'] = '';
6143 + }
6144 +
6145 + // Remove any unsupported fields
6146 + $message = array_intersect_key($message, array_flip(['role', 'content']));
6147 + }
6148 +
6149 + // Add relevant content as the latest user message
6150 + $conversation_history[] = [
6151 + 'role' => 'user',
6152 + 'content' => $relevant_content
6153 + ];
6154 +
6155 + // Build request body
6156 + $body = json_encode([
6157 + 'model' => $selected_model,
6158 + 'max_tokens' => 1000,
6159 + 'temperature' => 0.8,
6160 + 'messages' => $conversation_history,
6161 + 'system' => $system_prompt_instructions
6162 + ]);
6163 +
6164 + // Set up API request
6165 + $args = [
6166 + 'body' => $body,
6167 + 'headers' => [
6168 + 'Content-Type' => 'application/json',
6169 + 'x-api-key' => $claude_api_key,
6170 + 'anthropic-version' => '2023-06-01'
6171 + ],
6172 + 'timeout' => 60,
6173 + 'redirection' => 5,
6174 + 'blocking' => true,
6175 + 'httpversion' => '1.0',
6176 + 'sslverify' => true,
6177 + ];
6178 +
6179 + // Make API request
6180 + $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
6181 +
6182 + // Check for WordPress errors
6183 + if (is_wp_error($response)) {
6184 + //error_log("Claude API request error: " . $response->get_error_message());
6185 + return "Sorry, there was an error connecting to the API.";
6186 + }
6187 +
6188 + // Check HTTP response code
6189 + $http_code = wp_remote_retrieve_response_code($response);
6190 + if ($http_code !== 200) {
6191 + $error_body = wp_remote_retrieve_body($response);
6192 + //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
6193 +
6194 + // Try to extract error message from response
6195 + $error_data = json_decode($error_body, true);
6196 + $error_message = isset($error_data['error']['message']) ?
6197 + $error_data['error']['message'] :
6198 + "HTTP error " . $http_code;
6199 +
6200 + return "Sorry, the API returned an error: " . $error_message;
6201 + }
6202 +
6203 + // Parse response
6204 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
6205 +
6206 + // Check for JSON decode errors
6207 + if (json_last_error() !== JSON_ERROR_NONE) {
6208 + //error_log("Claude API JSON decode error: " . json_last_error_msg());
6209 + return "Sorry, there was an error processing the API response.";
6210 + }
6211 +
6212 + // Extract and validate response content
6213 + if (isset($response_body['content']) &&
6214 + is_array($response_body['content']) &&
6215 + !empty($response_body['content']) &&
6216 + isset($response_body['content'][0]['text'])) {
6217 + return trim($response_body['content'][0]['text']);
6218 + }
6219 +
6220 + // Log unexpected response format
6221 + //error_log("Claude API unexpected response format: " . print_r($response_body, true));
6222 + return "Sorry, I received an unexpected response format from the API.";
6223 +}
6224 +private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
6225 + try {
6226 + // Ensure conversation_history is an array
6227 + if (!is_array($conversation_history)) {
6228 + $conversation_history = array();
6229 + }
6230 +
6231 + // Get bot ID from session or request
6232 + $bot_id = $this->get_current_bot_id('');
6233 +
6234 + // Get system prompt instructions using centralized function
6235 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6236 +
6237 + // Create a new array for the formatted conversation
6238 + $formatted_conversation = array();
6239 +
6240 + // Add system message first
6241 + $formatted_conversation[] = array(
6242 + 'role' => 'system',
6243 + 'content' => $system_prompt_instructions . " " . $relevant_content
6244 + );
6245 +
6246 + // Add the rest of the conversation history
6247 + foreach ($conversation_history as $message) {
6248 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6249 + $role = $message['role'];
6250 +
6251 + // Convert roles to supported format
6252 + if ($role === 'bot' || $role === 'agent') {
6253 + $role = 'assistant';
6254 + }
6255 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
6256 + $role = 'user';
6257 + }
6258 +
6259 + $formatted_conversation[] = array(
6260 + 'role' => $role,
6261 + 'content' => $message['content']
6262 + );
6263 + }
6264 + }
6265 +
6266 + // Check if this is a GPT-5 model (supports reasoning_effort parameter)
6267 + $is_gpt5_model = (
6268 + strpos($selected_model, 'gpt-5') === 0 ||
6269 + $selected_model === 'gpt-5.1-2025-11-13' ||
6270 + $selected_model === 'gpt-5' ||
6271 + $selected_model === 'gpt-5-mini' ||
6272 + $selected_model === 'gpt-5-nano'
6273 + );
6274 +
6275 + // Build request body with optimal settings for fast responses
6276 + $request_body = [
6277 + 'model' => $selected_model,
6278 + 'messages' => $formatted_conversation,
6279 + 'temperature' => 1,
6280 + 'stream' => false
6281 + ];
6282 +
6283 + // Add reasoning_effort only for GPT-5 models
6284 + if ($is_gpt5_model) {
6285 + // GPT-5.1 uses 'low' instead of 'minimal'
6286 + if ($selected_model === 'gpt-5.1-2025-11-13') {
6287 + $request_body['reasoning_effort'] = 'low';
6288 + } else {
6289 + $request_body['reasoning_effort'] = 'minimal'; // For other GPT-5 models
6290 + }
6291 + }
6292 +
6293 + $body = json_encode($request_body);
6294 +
6295 + $args = [
6296 + 'body' => $body,
6297 + 'headers' => [
6298 + 'Content-Type' => 'application/json',
6299 + 'Authorization' => 'Bearer ' . $api_key,
6300 + ],
6301 + 'timeout' => 60,
6302 + 'redirection' => 5,
6303 + 'blocking' => true,
6304 + 'httpversion' => '1.0',
6305 + 'sslverify' => true,
6306 + ];
6307 +
6308 + $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
6309 +
6310 + if (is_wp_error($response)) {
6311 + $error_message = $response->get_error_message();
6312 + return [
6313 + 'error' => esc_html__('Connection error when contacting OpenAI: ', 'mxchat') . esc_html($error_message),
6314 + 'error_code' => 'openai_connection_error',
6315 + 'provider' => 'openai'
6316 + ];
6317 + }
6318 +
6319 + $status_code = wp_remote_retrieve_response_code($response);
6320 + if ($status_code !== 200) {
6321 + $response_body = wp_remote_retrieve_body($response);
6322 + $decoded_response = json_decode($response_body, true);
6323 +
6324 + $error_message = isset($decoded_response['error']['message'])
6325 + ? $decoded_response['error']['message']
6326 + : 'HTTP Error ' . $status_code;
6327 +
6328 + $error_type = isset($decoded_response['error']['type'])
6329 + ? $decoded_response['error']['type']
6330 + : 'unknown';
6331 +
6332 + // Handle specific error types
6333 + switch ($error_type) {
6334 + case 'invalid_request_error':
6335 + if (strpos($error_message, 'API key') !== false) {
6336 + return [
6337 + 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
6338 + 'error_code' => 'openai_invalid_api_key',
6339 + 'provider' => 'openai'
6340 + ];
6341 + }
6342 + break;
6343 +
6344 + case 'authentication_error':
6345 + return [
6346 + 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
6347 + 'error_code' => 'openai_auth_error',
6348 + 'provider' => 'openai'
6349 + ];
6350 +
6351 + case 'rate_limit_exceeded':
6352 + return [
6353 + 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
6354 + 'error_code' => 'openai_rate_limit',
6355 + 'provider' => 'openai'
6356 + ];
6357 +
6358 + case 'quota_exceeded':
6359 + return [
6360 + 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
6361 + 'error_code' => 'openai_quota_exceeded',
6362 + 'provider' => 'openai'
6363 + ];
6364 + }
6365 +
6366 + // Generic error fallback
6367 + return [
6368 + 'error' => esc_html__('OpenAI API error: ', 'mxchat') . esc_html($error_message),
6369 + 'error_code' => 'openai_api_error',
6370 + 'provider' => 'openai',
6371 + 'status_code' => $status_code
6372 + ];
6373 + }
6374 +
6375 + $response_body = wp_remote_retrieve_body($response);
6376 + $decoded_response = json_decode($response_body, true);
6377 +
6378 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6379 + return trim($decoded_response['choices'][0]['message']['content']);
6380 + } else {
6381 + return [
6382 + 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
6383 + 'error_code' => 'openai_response_format_error',
6384 + 'provider' => 'openai'
6385 + ];
6386 + }
6387 + } catch (Exception $e) {
6388 + return [
6389 + 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
6390 + 'error_code' => 'openai_exception',
6391 + 'provider' => 'openai'
6392 + ];
6393 + }
6394 +}
6395 +
6396 +private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
6397 + try {
6398 + // Get bot ID from session or request
6399 + $bot_id = $this->get_current_bot_id($session_id);
6400 +
6401 + // Get system prompt instructions using centralized function
6402 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6403 +
6404 + // Add system prompt to relevant content
6405 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
6406 +
6407 + // Prepend system instructions to the conversation history
6408 + array_unshift($conversation_history, [
6409 + 'role' => 'system',
6410 + 'content' => "Here are your instructions: " . $content_with_instructions
6411 + ]);
6412 +
6413 + // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
6414 + foreach ($conversation_history as &$message) {
6415 + if ($message['role'] === 'bot') {
6416 + $message['role'] = 'assistant';
6417 + } elseif ($message['role'] === 'agent') {
6418 + // Tag the message as coming from a live agent
6419 + $message['role'] = 'assistant';
6420 + if (!isset($message['metadata'])) {
6421 + $message['metadata'] = ['source' => 'live_agent'];
6422 + }
6423 + }
6424 +
6425 + // Ensure all roles are valid
6426 + if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
6427 + $message['role'] = 'user'; // Default to 'user'
6428 + }
6429 + }
6430 +
6431 + // Build the request body
6432 + $body = json_encode([
6433 + 'model' => $selected_model,
6434 + 'messages' => $conversation_history,
6435 + 'temperature' => 0.8,
6436 + 'stream' => false
6437 + ]);
6438 +
6439 + // Set up the API request
6440 + $args = [
6441 + 'body' => $body,
6442 + 'headers' => [
6443 + 'Content-Type' => 'application/json',
6444 + 'Authorization' => 'Bearer ' . $xai_api_key,
6445 + ],
6446 + 'timeout' => 60,
6447 + 'redirection' => 5,
6448 + 'blocking' => true,
6449 + 'httpversion' => '1.0',
6450 + 'sslverify' => true,
6451 + ];
6452 +
6453 + // Make the API request
6454 + $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
6455 +
6456 + // Process the response
6457 + if (is_wp_error($response)) {
6458 + $error_message = $response->get_error_message();
6459 + //error_log('X.AI API Error: ' . $error_message);
6460 + return [
6461 + 'error' => esc_html__('Connection error when contacting X.AI: ', 'mxchat') . esc_html($error_message),
6462 + 'error_code' => 'xai_connection_error',
6463 + 'provider' => 'xai'
6464 + ];
6465 + }
6466 +
6467 + $status_code = wp_remote_retrieve_response_code($response);
6468 + if ($status_code !== 200) {
6469 + $response_body = wp_remote_retrieve_body($response);
6470 + $decoded_response = json_decode($response_body, true);
6471 +
6472 + // Log the full response for debugging
6473 + //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
6474 +
6475 + // Extract error message from X.AI's specific format
6476 + $error_message = '';
6477 +
6478 + // Check for direct error string (as seen in your logs)
6479 + if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
6480 + $error_message = $decoded_response['error'];
6481 + }
6482 + // Check for nested error object (OpenAI style)
6483 + elseif (isset($decoded_response['error']['message'])) {
6484 + $error_message = $decoded_response['error']['message'];
6485 + }
6486 + // Check for top-level message
6487 + elseif (isset($decoded_response['message'])) {
6488 + $error_message = $decoded_response['message'];
6489 + }
6490 + // Fallback
6491 + else {
6492 + $error_message = 'HTTP Error ' . $status_code;
6493 + }
6494 +
6495 + //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
6496 +
6497 + // Check for API key errors using string matching
6498 + if (stripos($error_message, 'api key') !== false ||
6499 + stripos($error_message, 'incorrect api key') !== false ||
6500 + stripos($error_message, 'invalid api key') !== false) {
6501 + return [
6502 + 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
6503 + 'error_code' => 'xai_invalid_api_key',
6504 + 'provider' => 'xai'
6505 + ];
6506 + }
6507 +
6508 + // Authentication errors
6509 + if ($status_code === 401 || $status_code === 403 ||
6510 + stripos($error_message, 'auth') !== false) {
6511 + return [
6512 + 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat'),
6513 + 'error_code' => 'xai_auth_error',
6514 + 'provider' => 'xai'
6515 + ];
6516 + }
6517 +
6518 + // Model errors
6519 + if (stripos($error_message, 'model') !== false) {
6520 + return [
6521 + 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat'),
6522 + 'error_code' => 'xai_invalid_model',
6523 + 'provider' => 'xai'
6524 + ];
6525 + }
6526 +
6527 + // Rate limit errors
6528 + if ($status_code === 429 ||
6529 + stripos($error_message, 'rate') !== false ||
6530 + stripos($error_message, 'limit') !== false) {
6531 + return [
6532 + 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
6533 + 'error_code' => 'xai_rate_limit',
6534 + 'provider' => 'xai'
6535 + ];
6536 + }
6537 +
6538 + // Quota errors
6539 + if (stripos($error_message, 'quota') !== false ||
6540 + stripos($error_message, 'billing') !== false) {
6541 + return [
6542 + 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
6543 + 'error_code' => 'xai_quota_exceeded',
6544 + 'provider' => 'xai'
6545 + ];
6546 + }
6547 +
6548 + // Server errors
6549 + if ($status_code >= 500) {
6550 + return [
6551 + 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
6552 + 'error_code' => 'xai_service_unavailable',
6553 + 'provider' => 'xai'
6554 + ];
6555 + }
6556 +
6557 + // Generic error fallback with the actual error message
6558 + return [
6559 + 'error' => esc_html__('X.AI API error: ', 'mxchat') . esc_html($error_message),
6560 + 'error_code' => 'xai_api_error',
6561 + 'provider' => 'xai',
6562 + 'status_code' => $status_code
6563 + ];
6564 + }
6565 +
6566 + $response_body = wp_remote_retrieve_body($response);
6567 + $decoded_response = json_decode($response_body, true);
6568 +
6569 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6570 + return trim($decoded_response['choices'][0]['message']['content']);
6571 + } else {
6572 + //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
6573 + return [
6574 + 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
6575 + 'error_code' => 'xai_response_format_error',
6576 + 'provider' => 'xai'
6577 + ];
6578 + }
6579 +} catch (Exception $e) {
6580 + //error_log('X.AI Exception: ' . $e->getMessage());
6581 + return [
6582 + 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
6583 + 'error_code' => 'xai_exception',
6584 + 'provider' => 'xai'
6585 + ];
6586 +}
6587 +
6588 +
6589 +}
6590 +private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
6591 + try {
6592 + // Ensure conversation_history is an array
6593 + if (!is_array($conversation_history)) {
6594 + $conversation_history = array();
6595 + }
6596 +
6597 + // Get bot ID from session or request
6598 + $bot_id = $this->get_current_bot_id($session_id);
6599 +
6600 + // Get system prompt instructions using centralized function
6601 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6602 +
6603 + // Create a new array for the formatted conversation
6604 + $formatted_conversation = array();
6605 +
6606 + // Add system message first
6607 + $formatted_conversation[] = array(
6608 + 'role' => 'system',
6609 + 'content' => $system_prompt_instructions . " " . $relevant_content
6610 + );
6611 +
6612 + // Add the rest of the conversation history
6613 + foreach ($conversation_history as $message) {
6614 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6615 + $role = $message['role'];
6616 +
6617 + // Convert roles to supported format
6618 + if ($role === 'bot' || $role === 'agent') {
6619 + $role = 'assistant';
6620 + }
6621 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
6622 + $role = 'user';
6623 + }
6624 +
6625 + $formatted_conversation[] = array(
6626 + 'role' => $role,
6627 + 'content' => $message['content']
6628 + );
6629 + }
6630 + }
6631 +
6632 + $body = json_encode([
6633 + 'model' => $selected_model,
6634 + 'messages' => $formatted_conversation,
6635 + 'temperature' => 0.8,
6636 + 'stream' => false
6637 + ]);
6638 +
6639 + $args = [
6640 + 'body' => $body,
6641 + 'headers' => [
6642 + 'Content-Type' => 'application/json',
6643 + 'Authorization' => 'Bearer ' . $deepseek_api_key,
6644 + ],
6645 + 'timeout' => 60,
6646 + 'redirection' => 5,
6647 + 'blocking' => true,
6648 + 'httpversion' => '1.0',
6649 + 'sslverify' => true,
6650 + ];
6651 +
6652 + $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
6653 +
6654 + if (is_wp_error($response)) {
6655 + $error_message = $response->get_error_message();
6656 + //error_log('DeepSeek API Error: ' . $error_message);
6657 + return [
6658 + 'error' => esc_html__('Connection error when contacting DeepSeek: ', 'mxchat') . esc_html($error_message),
6659 + 'error_code' => 'deepseek_connection_error',
6660 + 'provider' => 'deepseek'
6661 + ];
6662 + }
6663 +
6664 + $status_code = wp_remote_retrieve_response_code($response);
6665 + if ($status_code !== 200) {
6666 + $response_body = wp_remote_retrieve_body($response);
6667 + $decoded_response = json_decode($response_body, true);
6668 +
6669 + $error_message = isset($decoded_response['error']['message'])
6670 + ? $decoded_response['error']['message']
6671 + : 'HTTP Error ' . $status_code;
6672 +
6673 + $error_type = isset($decoded_response['error']['type'])
6674 + ? $decoded_response['error']['type']
6675 + : 'unknown';
6676 +
6677 + //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
6678 +
6679 + // Handle specific error types
6680 + switch ($status_code) {
6681 + case 401:
6682 + return [
6683 + 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
6684 + 'error_code' => 'deepseek_auth_error',
6685 + 'provider' => 'deepseek'
6686 + ];
6687 +
6688 + case 400:
6689 + if (strpos($error_message, 'API key') !== false) {
6690 + return [
6691 + 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
6692 + 'error_code' => 'deepseek_invalid_api_key',
6693 + 'provider' => 'deepseek'
6694 + ];
6695 + }
6696 + break;
6697 +
6698 + case 429:
6699 + if (strpos($error_message, 'quota') !== false) {
6700 + return [
6701 + 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
6702 + 'error_code' => 'deepseek_quota_exceeded',
6703 + 'provider' => 'deepseek'
6704 + ];
6705 + } else {
6706 + return [
6707 + 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
6708 + 'error_code' => 'deepseek_rate_limit',
6709 + 'provider' => 'deepseek'
6710 + ];
6711 + }
6712 +
6713 + case 500:
6714 + case 502:
6715 + case 503:
6716 + case 504:
6717 + return [
6718 + 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
6719 + 'error_code' => 'deepseek_service_unavailable',
6720 + 'provider' => 'deepseek'
6721 + ];
6722 + }
6723 +
6724 + // Generic error fallback
6725 + return [
6726 + 'error' => esc_html__('DeepSeek API error: ', 'mxchat') . esc_html($error_message),
6727 + 'error_code' => 'deepseek_api_error',
6728 + 'provider' => 'deepseek',
6729 + 'status_code' => $status_code
6730 + ];
6731 + }
6732 +
6733 + $response_body = wp_remote_retrieve_body($response);
6734 + $decoded_response = json_decode($response_body, true);
6735 +
6736 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6737 + return trim($decoded_response['choices'][0]['message']['content']);
6738 + } else {
6739 + //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
6740 + return [
6741 + 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
6742 + 'error_code' => 'deepseek_response_format_error',
6743 + 'provider' => 'deepseek'
6744 + ];
6745 + }
6746 + } catch (Exception $e) {
6747 + //error_log('DeepSeek Exception: ' . $e->getMessage());
6748 + return [
6749 + 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
6750 + 'error_code' => 'deepseek_exception',
6751 + 'provider' => 'deepseek'
6752 + ];
6753 + }
6754 +}
6755 +private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content) {
6756 + // Get bot ID from session or request
6757 + $bot_id = $this->get_current_bot_id($session_id);
6758 +
6759 + // Get system prompt instructions using centralized function
6760 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6761 +
6762 + // Add system prompt to relevant content
6763 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
6764 +
6765 + // Format messages for Gemini API
6766 + $formatted_messages = [];
6767 +
6768 + // Add system message as the first user message with role prefix
6769 + // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
6770 + $formatted_messages[] = [
6771 + 'role' => 'user',
6772 + 'parts' => [
6773 + ['text' => "[System Instructions] " . $content_with_instructions]
6774 + ]
6775 + ];
6776 +
6777 + // Add model response to acknowledge system instructions
6778 + $formatted_messages[] = [
6779 + 'role' => 'model',
6780 + 'parts' => [
6781 + ['text' => "I understand and will follow these instructions."]
6782 + ]
6783 + ];
6784 +
6785 + // Process the rest of the conversation history
6786 + $current_role = null;
6787 + $current_parts = [];
6788 +
6789 + foreach ($conversation_history as $message) {
6790 + // Skip the first system message as we already handled it
6791 + if ($message['role'] === 'system') {
6792 + continue;
6793 + }
6794 +
6795 + // Map roles to Gemini format
6796 + $gemini_role = '';
6797 + if ($message['role'] === 'user') {
6798 + $gemini_role = 'user';
6799 + } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
6800 + $gemini_role = 'model';
6801 + } else {
6802 + // Skip unsupported roles
6803 + continue;
6804 + }
6805 +
6806 + // If we have a new role, add the previous message
6807 + if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
6808 + $formatted_messages[] = [
6809 + 'role' => $current_role,
6810 + 'parts' => $current_parts
6811 + ];
6812 + $current_parts = [];
6813 + }
6814 +
6815 + // Set current role and add text to parts
6816 + $current_role = $gemini_role;
6817 + $current_parts[] = ['text' => $message['content']];
6818 + }
6819 +
6820 + // Add the last message if there's content
6821 + if ($current_role !== null && !empty($current_parts)) {
6822 + $formatted_messages[] = [
6823 + 'role' => $current_role,
6824 + 'parts' => $current_parts
6825 + ];
6826 + }
6827 +
6828 + // Build the request body
6829 + $body = json_encode([
6830 + 'contents' => $formatted_messages,
6831 + 'generationConfig' => [
6832 + 'temperature' => 0.7,
6833 + 'topP' => 0.95,
6834 + 'topK' => 40,
6835 + 'maxOutputTokens' => 8192,
6836 + ],
6837 + 'safetySettings' => [
6838 + [
6839 + 'category' => 'HARM_CATEGORY_HARASSMENT',
6840 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
6841 + ],
6842 + [
6843 + 'category' => 'HARM_CATEGORY_HATE_SPEECH',
6844 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
6845 + ],
6846 + [
6847 + 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
6848 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
6849 + ],
6850 + [
6851 + 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
6852 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
6853 + ]
6854 + ]
6855 + ]);
6856 +
6857 + // Prepare the API endpoint
6858 + $api_endpoint = 'https://generativelanguage.googleapis.com/v1/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
6859 +
6860 + // Set up the API request
6861 + $args = [
6862 + 'body' => $body,
6863 + 'headers' => [
6864 + 'Content-Type' => 'application/json',
6865 + ],
6866 + 'timeout' => 60,
6867 + 'redirection' => 5,
6868 + 'blocking' => true,
6869 + 'httpversion' => '1.0',
6870 + 'sslverify' => true,
6871 + ];
6872 +
6873 + // Make the API request
6874 + $response = wp_remote_post($api_endpoint, $args);
6875 +
6876 + // Process the response
6877 + if (is_wp_error($response)) {
6878 + return "Sorry, there was an error processing your request: " . $response->get_error_message();
6879 + }
6880 +
6881 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
6882 +
6883 + // Handle potential errors in the response
6884 + if (isset($response_body['error'])) {
6885 + //error_log('Gemini API Error: ' . json_encode($response_body['error']));
6886 + return "Sorry, there was an error with the Gemini API: " .
6887 + (isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error');
6888 + }
6889 +
6890 + // Extract the response text
6891 + if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
6892 + return trim($response_body['candidates'][0]['content']['parts'][0]['text']);
6893 + } else {
6894 + //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
6895 + return "Sorry, I couldn't process that request. The response format was unexpected.";
6896 + }
6897 +}
6898 +
6899 +
6900 +public function test_streaming_request() {
6901 + $options = get_option('mxchat_options', []);
6902 + $model = $options['model'] ?? 'gpt-4o';
6903 +
6904 + // Detect provider from model prefix
6905 + $provider = strtolower(explode('-', $model)[0]);
6906 +
6907 + $sample_prompt = 'Hello! Can you stream this response back to me?';
6908 + $messages = [['role' => 'user', 'content' => $sample_prompt]];
6909 + $headers = [];
6910 + $body = [];
6911 + $url = '';
6912 + $api_key = '';
6913 +
6914 + switch ($provider) {
6915 + case 'gpt':
6916 + case 'o1':
6917 + $api_key = $options['api_key'] ?? '';
6918 + if (empty($api_key)) return '❌ Missing API key for OpenAI';
6919 + $url = 'https://api.openai.com/v1/chat/completions';
6920 + $headers = [
6921 + 'Content-Type: application/json',
6922 + 'Authorization: Bearer ' . $api_key
6923 + ];
6924 + $body = [
6925 + 'model' => $model,
6926 + 'messages' => $messages,
6927 + 'stream' => true
6928 + ];
6929 + break;
6930 +
6931 + case 'claude':
6932 + $api_key = $options['claude_api_key'] ?? '';
6933 + if (empty($api_key)) return '❌ Missing API key for Claude';
6934 + $url = 'https://api.anthropic.com/v1/messages';
6935 + $headers = [
6936 + 'Content-Type: application/json',
6937 + 'x-api-key: ' . $api_key,
6938 + 'anthropic-version: 2023-06-01'
6939 + ];
6940 + $body = [
6941 + 'model' => $model,
6942 + 'messages' => $messages,
6943 + 'max_tokens' => 100,
6944 + 'stream' => true
6945 + ];
6946 + break;
6947 +
6948 + case 'grok':
6949 + $api_key = $options['xai_api_key'] ?? '';
6950 + if (empty($api_key)) return '❌ Missing API key for X.AI';
6951 + $url = 'https://api.x.ai/v1/chat/completions';
6952 + $headers = [
6953 + 'Content-Type: application/json',
6954 + 'Authorization: Bearer ' . $api_key
6955 + ];
6956 + $body = [
6957 + 'model' => $model,
6958 + 'messages' => $messages,
6959 + 'stream' => true
6960 + ];
6961 + break;
6962 +
6963 + case 'deepseek':
6964 + if (empty($deepseek_api_key)) {
6965 + $error_response = [
6966 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
6967 + 'error_code' => 'missing_deepseek_api_key'
6968 + ];
6969 + if ($testing_data !== null) {
6970 + $error_response['testing_data'] = $testing_data;
6971 + }
6972 + return $error_response;
6973 + }
6974 + if ($streaming) {
6975 + return $this->mxchat_generate_response_deepseek_stream(
6976 + $selected_model,
6977 + $deepseek_api_key,
6978 + $conversation_history,
6979 + $relevant_content,
6980 + $session_id,
6981 + $testing_data // Pass testing data
6982 + );
6983 + } else {
6984 + $response = $this->mxchat_generate_response_deepseek(
6985 + $selected_model,
6986 + $deepseek_api_key,
6987 + $conversation_history,
6988 + $relevant_content
6989 + );
6990 + }
6991 + break;
6992 +
6993 + case 'gemini':
6994 + $api_key = $options['gemini_api_key'] ?? '';
6995 + if (empty($api_key)) return '❌ Missing API key for Gemini';
6996 + $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':streamGenerateContent?key=' . $api_key;
6997 + $headers = ['Content-Type: application/json'];
6998 + $body = [
6999 + 'contents' => [['role' => 'user', 'parts' => [['text' => $sample_prompt]]]],
7000 + 'generationConfig' => ['temperature' => 0.7]
7001 + ];
7002 + break;
7003 +
7004 + default:
7005 + return '❌ Unsupported provider: ' . $provider;
7006 + }
7007 +
7008 + // Do the actual streaming test
7009 + $ch = curl_init($url);
7010 + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
7011 + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
7012 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
7013 + curl_setopt($ch, CURLOPT_TIMEOUT, 15);
7014 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
7015 +
7016 + $response = curl_exec($ch);
7017 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
7018 + $error = curl_error($ch);
7019 + curl_close($ch);
7020 +
7021 + if ($error) return "❌ cURL error: $error";
7022 + if ($http_code !== 200) {
7023 + $error_message = json_decode($response, true)['error']['message'] ?? 'Unknown';
7024 + return "❌ HTTP $http_code: $error_message";
7025 + }
7026 +
7027 + return true;
7028 +}
7029 +
7030 +public function mxchat_dismiss_pre_chat_message() {
7031 + // Get and sanitize the user identifier
7032 + $user_id = $this->mxchat_get_user_identifier();
7033 + $user_id = sanitize_key($user_id);
7034 +
7035 + // Set a transient to track that the user has dismissed the pre-chat message
7036 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
7037 + set_transient($transient_key, true, DAY_IN_SECONDS);
7038 +
7039 + wp_send_json_success();
7040 +}
7041 +
7042 +public function mxchat_check_pre_chat_message_status() {
7043 + // Get and sanitize the user identifier
7044 + $user_id = $this->mxchat_get_user_identifier();
7045 + $user_id = sanitize_key($user_id);
7046 +
7047 + // Check if the transient exists (i.e., if the message was dismissed)
7048 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
7049 + $dismissed = get_transient($transient_key);
7050 +
7051 + // Log the result to see if it's being set correctly
7052 + //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
7053 +
7054 + if ($dismissed) {
7055 + wp_send_json_success(['dismissed' => true]);
7056 + } else {
7057 + wp_send_json_success(['dismissed' => false]);
7058 + }
7059 +
7060 + wp_die();
7061 +}
7062 +
7063 +private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
7064 + if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
7065 + return 0;
7066 + }
7067 +
7068 + $dotProduct = array_sum(array_map(function ($a, $b) {
7069 + return $a * $b;
7070 + }, $vectorA, $vectorB));
7071 + $normA = sqrt(array_sum(array_map(function ($a) {
7072 + return $a * $a;
7073 + }, $vectorA)));
7074 + $normB = sqrt(array_sum(array_map(function ($b) {
7075 + return $b * $b;
7076 + }, $vectorB)));
7077 +
7078 + if ($normA == 0 || $normB == 0) {
7079 + return 0;
7080 + }
7081 +
7082 + return $dotProduct / ($normA * $normB);
7083 + }
7084 +
7085 +
7086 +public function mxchat_enqueue_scripts_styles() {
7087 + // Enqueue the script
7088 + wp_enqueue_script(
7089 + 'mxchat-chat-js',
7090 + plugin_dir_url(__FILE__) . '../js/chat-script.js',
7091 + array('jquery'),
7092 + MXCHAT_VERSION,
7093 + true
7094 + );
7095 + // Enqueue the CSS
7096 + wp_enqueue_style(
7097 + 'mxchat-chat-css',
7098 + plugin_dir_url(__FILE__) . '../css/chat-style.css',
7099 + array(),
7100 + MXCHAT_VERSION
7101 + );
7102 + // Fetch options from the database
7103 + $this->options = get_option('mxchat_options');
7104 + $prompts_options = get_option('mxchat_prompts_options', array());
7105 +
7106 + // Prepare settings for JavaScript
7107 + $style_settings = array(
7108 + 'ajax_url' => admin_url('admin-ajax.php'),
7109 + 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
7110 + 'model' => isset($this->options['model']) ? $this->options['model'] : 'gpt-4o',
7111 + 'enable_streaming_toggle' => isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on',
7112 + 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
7113 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
7114 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
7115 + 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
7116 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
7117 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
7118 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
7119 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
7120 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
7121 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
7122 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
7123 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
7124 + 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
7125 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
7126 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
7127 + 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
7128 + 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
7129 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
7130 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
7131 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
7132 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
7133 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
7134 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
7135 + 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
7136 + 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off', // FIXED
7137 + 'initial_email_state' => null, // Also fixed this undefined variable
7138 + 'skip_email_check' => true,
7139 + 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
7140 + );
7141 + // Pass the settings to the script
7142 + wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
7143 +}
7144 +
7145 +
7146 +/**
7147 + * Setup the cron jobs for rate limits with guard against multiple calls
7148 + */
7149 +public function setup_rate_limit_cron_jobs() {
7150 + // Add a guard to prevent multiple rapid calls
7151 + $last_setup = get_transient('mxchat_cron_setup_guard');
7152 + if ($last_setup && (time() - $last_setup) < 60) {
7153 + // Don't run again if we ran less than 60 seconds ago
7154 + return;
7155 + }
7156 +
7157 + // Set the guard
7158 + set_transient('mxchat_cron_setup_guard', time(), 300); // 5 minutes
7159 +
7160 + try {
7161 + // First, check if WordPress cron is disabled
7162 + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
7163 + //error_log('MxChat: WordPress cron is disabled (DISABLE_WP_CRON = true), using fallback system');
7164 + $this->setup_fallback_rate_limit_system();
7165 + return;
7166 + }
7167 +
7168 + // Check if cron is already scheduled - if so, don't mess with it
7169 + if (wp_next_scheduled('mxchat_reset_rate_limits')) {
7170 + //error_log('MxChat: Rate limit cron already scheduled, skipping setup');
7171 + return;
7172 + }
7173 +
7174 + // Clear any orphaned hooks (but don't loop indefinitely)
7175 + $hooks_to_clear = [
7176 + 'mxchat_reset_rate_limits',
7177 + 'mxchat_reset_hourly_rate_limits',
7178 + 'mxchat_reset_daily_rate_limits',
7179 + 'mxchat_reset_weekly_rate_limits',
7180 + 'mxchat_reset_monthly_rate_limits'
7181 + ];
7182 +
7183 + foreach ($hooks_to_clear as $hook) {
7184 + // Only clear a maximum of 3 instances to prevent infinite loops
7185 + $cleared = 0;
7186 + while (wp_next_scheduled($hook) && $cleared < 3) {
7187 + wp_clear_scheduled_hook($hook);
7188 + $cleared++;
7189 + }
7190 + }
7191 +
7192 + // Small delay after clearing
7193 + usleep(100000); // 0.1 seconds
7194 +
7195 + // Try to schedule the event
7196 + $initial_time = time() + 300; // Start in 5 minutes
7197 + $result = wp_schedule_event($initial_time, 'hourly', 'mxchat_reset_rate_limits');
7198 +
7199 + if ($result === false) {
7200 + //error_log('MxChat: Failed to schedule cron, using fallback system');
7201 + $this->setup_fallback_rate_limit_system();
7202 + } else {
7203 + //error_log('MxChat: Successfully scheduled rate limit reset cron');
7204 + }
7205 +
7206 + } catch (Exception $e) {
7207 + //error_log('MxChat: Cron setup exception: ' . $e->getMessage());
7208 + $this->setup_fallback_rate_limit_system();
7209 + }
7210 +}
7211 +
7212 +/**
7213 + * Try alternative cron scheduling methods
7214 + */
7215 +private function try_alternative_cron_scheduling($initial_time) {
7216 + try {
7217 + // Method 1: Try with current time instead of future time
7218 + $result1 = wp_schedule_event(time(), 'hourly', 'mxchat_reset_rate_limits');
7219 + if ($result1 !== false) {
7220 + //error_log('MxChat: Alternative method 1 (current time) succeeded');
7221 + return true;
7222 + }
7223 +
7224 + // Method 2: Try with a different interval
7225 + $result2 = wp_schedule_event($initial_time, 'daily', 'mxchat_reset_rate_limits');
7226 + if ($result2 !== false) {
7227 + //error_log('MxChat: Alternative method 2 (daily interval) succeeded');
7228 + return true;
7229 + }
7230 +
7231 + // Method 3: Try wp_schedule_single_event first, then recurring
7232 + $result3 = wp_schedule_single_event($initial_time, 'mxchat_reset_rate_limits');
7233 + if ($result3 !== false) {
7234 + //error_log('MxChat: Alternative method 3 (single event) succeeded');
7235 + // Schedule the next one manually in the handler
7236 + return true;
7237 + }
7238 +
7239 + return false;
7240 +
7241 + } catch (Exception $e) {
7242 + //error_log('MxChat: Alternative cron scheduling exception: ' . $e->getMessage());
7243 + return false;
7244 + }
7245 +}
7246 +
7247 +/**
7248 + * Enhanced fallback rate limit system
7249 + */
7250 +private function setup_fallback_rate_limit_system() {
7251 + // Set a flag to use database-based rate limit cleanup
7252 + update_option('mxchat_use_fallback_rate_limits', true);
7253 +
7254 + // Schedule a one-time check to happen on the next plugin load
7255 + update_option('mxchat_next_rate_limit_check', time() + 3600);
7256 +
7257 + // Also set up a more frequent fallback check (every 4 hours)
7258 + update_option('mxchat_fallback_check_interval', 4 * 3600);
7259 +
7260 + //error_log('MxChat: Fallback rate limit system activated');
7261 +}
7262 +
7263 +/**
7264 + * Enhanced fallback check method
7265 + */
7266 +public function check_fallback_rate_limits() {
7267 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
7268 +
7269 + if (!$use_fallback) {
7270 + return; // Regular cron is working
7271 + }
7272 +
7273 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
7274 + $check_interval = get_option('mxchat_fallback_check_interval', 3600);
7275 +
7276 + if (time() >= $next_check) {
7277 + //error_log('MxChat: Running fallback rate limit cleanup');
7278 + $this->mxchat_reset_rate_limits();
7279 +
7280 + // Schedule next check
7281 + update_option('mxchat_next_rate_limit_check', time() + $check_interval);
7282 + }
7283 +}
7284 +/**
7285 + * Enhanced rate limit check that includes fallback cleanup and bot-specific rate limits
7286 + */
7287 +public function check_rate_limit() {
7288 + // Check if we need to run fallback cleanup
7289 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
7290 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
7291 +
7292 + if ($use_fallback && time() >= $next_check) {
7293 + $this->mxchat_reset_rate_limits();
7294 + update_option('mxchat_next_rate_limit_check', time() + 3600); // Next hour
7295 + }
7296 +
7297 + // Get bot ID from current request context
7298 + $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
7299 +
7300 + // Get bot-specific options (includes rate limits if overridden)
7301 + $bot_options = $this->get_bot_options($bot_id);
7302 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
7303 +
7304 + // Use bot-specific rate limits if available, otherwise fall back to default
7305 + $rate_limits_source = isset($current_options['rate_limits']) ? $current_options['rate_limits'] : get_option('mxchat_options', [])['rate_limits'] ?? [];
7306 +
7307 + // Determine user role or if logged out
7308 + if (is_user_logged_in()) {
7309 + $user = wp_get_current_user();
7310 + $user_id = $user->ID;
7311 +
7312 + // Get the user's primary role using reset() to safely get the first element
7313 + $user_roles = $user->roles;
7314 +
7315 + // Safely get the first role regardless of array key structure
7316 + if (!empty($user_roles) && is_array($user_roles)) {
7317 + $role = reset($user_roles); // This safely gets the first element regardless of key
7318 + } else {
7319 + $role = 'subscriber'; // Default to subscriber if no role found
7320 + }
7321 + } else {
7322 + $role = 'logged_out';
7323 + // Use IP address for non-logged-in users
7324 + $user_id = $this->get_client_ip();
7325 + }
7326 +
7327 + // Check if rate limits are configured for this role
7328 + if (!isset($rate_limits_source[$role])) {
7329 + return true; // No limit set for this role
7330 + }
7331 +
7332 + $limit = $rate_limits_source[$role]['limit'];
7333 +
7334 + // If unlimited, return true immediately
7335 + if ($limit === 'unlimited') {
7336 + return true;
7337 + }
7338 +
7339 + // Get the option name for this user/role with safer naming (include bot_id for bot-specific limits)
7340 + $safe_role = preg_replace('/[^a-zA-Z0-9_]/', '_', $role);
7341 + $safe_user_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $user_id);
7342 + $safe_bot_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id);
7343 +
7344 + // Include bot_id in option name so each bot has separate rate limits
7345 + $option_name = 'mxchat_chat_limit_' . $safe_bot_id . '_' . $safe_role . '_' . $safe_user_id;
7346 +
7347 + // Get the counter data
7348 + $limit_data = get_option($option_name, ['count' => 0, 'timestamp' => time()]);
7349 +
7350 + // If first request or counter reset needed, set the initial timestamp
7351 + if ($limit_data['count'] === 0) {
7352 + $limit_data['timestamp'] = time();
7353 + update_option($option_name, $limit_data);
7354 + }
7355 +
7356 + // Get the timeframe
7357 + $timeframe = isset($rate_limits_source[$role]['timeframe']) ?
7358 + $rate_limits_source[$role]['timeframe'] : 'daily';
7359 +
7360 + // Check if the counter needs to be reset based on timeframe
7361 + $current_time = time();
7362 + $timestamp = $limit_data['timestamp'];
7363 + $should_reset = false;
7364 +
7365 + switch ($timeframe) {
7366 + case 'hourly':
7367 + $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
7368 + break;
7369 + case 'daily':
7370 + $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
7371 + break;
7372 + case 'weekly':
7373 + $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
7374 + break;
7375 + case 'monthly':
7376 + $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
7377 + break;
7378 + }
7379 +
7380 + // Reset the counter if the timeframe has passed
7381 + if ($should_reset) {
7382 + $limit_data = ['count' => 0, 'timestamp' => $current_time];
7383 + update_option($option_name, $limit_data);
7384 + }
7385 +
7386 + // Check if user has exceeded their limit
7387 + if ($limit_data['count'] >= intval($limit)) {
7388 + // Get the custom message for this role
7389 + $message = !empty($rate_limits_source[$role]['message'])
7390 + ? $rate_limits_source[$role]['message']
7391 + : __('Rate limit exceeded. Please try again later.', 'mxchat');
7392 +
7393 + // Add timeframe information to the message if placeholders exist
7394 + $timeframe_label = '';
7395 + switch ($timeframe) {
7396 + case 'hourly':
7397 + $timeframe_label = __('hour', 'mxchat');
7398 + break;
7399 + case 'daily':
7400 + $timeframe_label = __('day', 'mxchat');
7401 + break;
7402 + case 'weekly':
7403 + $timeframe_label = __('week', 'mxchat');
7404 + break;
7405 + case 'monthly':
7406 + $timeframe_label = __('month', 'mxchat');
7407 + break;
7408 + }
7409 +
7410 + // Replace placeholders in the message
7411 + $message = str_replace(
7412 + ['{limit}', '{count}', '{remaining}', '{timeframe}'],
7413 + [intval($limit), $limit_data['count'], max(0, intval($limit) - $limit_data['count']), $timeframe_label],
7414 + $message
7415 + );
7416 +
7417 + // Process HTML links in the message
7418 + $message = $this->process_rate_limit_message_html($message);
7419 +
7420 + // Return error with the processed message
7421 + return [
7422 + 'error' => true,
7423 + 'message' => $message
7424 + ];
7425 + }
7426 +
7427 + // Increment the counter
7428 + $limit_data['count']++;
7429 + update_option($option_name, $limit_data);
7430 +
7431 + return true;
7432 +}
7433 +
7434 +/**
7435 + * Enhanced rate limit reset with better error handling
7436 + */
7437 +public function mxchat_reset_rate_limits() {
7438 + try {
7439 + global $wpdb;
7440 + $all_options = get_option('mxchat_options', []);
7441 + $current_time = time();
7442 +
7443 + // Get rate limit options with a safer query and limit
7444 + $option_names = $wpdb->get_col(
7445 + $wpdb->prepare(
7446 + "SELECT option_name FROM {$wpdb->options}
7447 + WHERE option_name LIKE %s
7448 + LIMIT 1000",
7449 + 'mxchat_chat_limit_%'
7450 + )
7451 + );
7452 +
7453 + if (empty($option_names)) {
7454 + return;
7455 + }
7456 +
7457 + $processed_count = 0;
7458 + $max_processing_time = 30; // Maximum 30 seconds
7459 + $start_time = time();
7460 +
7461 + foreach ($option_names as $option_name) {
7462 + // Check processing time limit
7463 + if ((time() - $start_time) > $max_processing_time) {
7464 + //error_log('MxChat: Rate limit reset timeout after processing ' . $processed_count . ' entries');
7465 + break;
7466 + }
7467 +
7468 + // Parse the option name more safely
7469 + if (!preg_match('/^mxchat_chat_limit_(.+)_(.+)$/', $option_name, $matches)) {
7470 + continue;
7471 + }
7472 +
7473 + $role_and_user = $matches[1] . '_' . $matches[2];
7474 + $parts = explode('_', $role_and_user);
7475 +
7476 + if (count($parts) < 2) {
7477 + continue;
7478 + }
7479 +
7480 + // Extract role (everything except the last part which is user ID)
7481 + $user_id_part = array_pop($parts);
7482 + $role = implode('_', $parts);
7483 +
7484 + // Skip if role doesn't exist in our settings
7485 + if (!isset($all_options['rate_limits'][$role])) {
7486 + // Clean up orphaned entries
7487 + delete_option($option_name);
7488 + continue;
7489 + }
7490 +
7491 + $timeframe = $all_options['rate_limits'][$role]['timeframe'] ?? 'daily';
7492 + $limit_data = get_option($option_name);
7493 +
7494 + if (!$limit_data || !is_array($limit_data) || !isset($limit_data['timestamp'])) {
7495 + // Clean up invalid entries
7496 + delete_option($option_name);
7497 + continue;
7498 + }
7499 +
7500 + $timestamp = $limit_data['timestamp'];
7501 + $should_reset = false;
7502 +
7503 + // Determine if we should reset based on the timeframe
7504 + switch ($timeframe) {
7505 + case 'hourly':
7506 + $should_reset = ($current_time - $timestamp) >= 3600;
7507 + break;
7508 + case 'daily':
7509 + $should_reset = ($current_time - $timestamp) >= 86400;
7510 + break;
7511 + case 'weekly':
7512 + $should_reset = ($current_time - $timestamp) >= 604800;
7513 + break;
7514 + case 'monthly':
7515 + $should_reset = ($current_time - $timestamp) >= 2592000;
7516 + break;
7517 + }
7518 +
7519 + // Reset the counter if the timeframe has passed
7520 + if ($should_reset) {
7521 + delete_option($option_name);
7522 + wp_cache_delete($option_name, 'options');
7523 + $processed_count++;
7524 + }
7525 + }
7526 +
7527 + // Clean up any orphaned cache entries
7528 + wp_cache_delete('mxchat_all_chat_limits', 'options');
7529 +
7530 + //error_log("MxChat: Rate limit reset completed. Processed {$processed_count} entries.");
7531 +
7532 + } catch (Exception $e) {
7533 + //error_log('MxChat: Rate limit reset error: ' . $e->getMessage());
7534 + }
7535 +}
7536 +
7537 +
7538 +/**
7539 + * Process HTML links in rate limit messages
7540 + *
7541 + * @param string $message The rate limit message
7542 + * @return string The processed message with safe HTML links
7543 + */
7544 +private function process_rate_limit_message_html($message) {
7545 + // Return original message if empty
7546 + if (empty($message)) {
7547 + return $message;
7548 + }
7549 +
7550 + // First, convert markdown links to HTML
7551 + $message = $this->convert_markdown_links($message);
7552 +
7553 + // Then, auto-convert any remaining plain URLs to links
7554 + $message = $this->auto_link_urls($message);
7555 +
7556 + // Allow basic HTML tags for links and formatting
7557 + $allowed_tags = [
7558 + 'a' => [
7559 + 'href' => true,
7560 + 'target' => true,
7561 + 'rel' => true,
7562 + 'title' => true,
7563 + 'class' => true
7564 + ],
7565 + 'strong' => [],
7566 + 'em' => [],
7567 + 'br' => [],
7568 + 'b' => [],
7569 + 'i' => [],
7570 + 'span' => ['class' => true]
7571 + ];
7572 +
7573 + // Sanitize but allow the specified HTML tags
7574 + $processed_message = wp_kses($message, $allowed_tags);
7575 +
7576 + // If wp_kses stripped everything, return the original message as plain text
7577 + if (empty($processed_message) && !empty($message)) {
7578 + // Strip all HTML and return plain text as fallback
7579 + return wp_strip_all_tags($message);
7580 + }
7581 +
7582 + return $processed_message;
7583 +}
7584 +
7585 +/**
7586 + * Convert markdown links to HTML
7587 + *
7588 + * @param string $text The text to process
7589 + * @return string The text with markdown links converted to HTML
7590 + */
7591 +private function convert_markdown_links($text) {
7592 + // Return original text if empty
7593 + if (empty($text)) {
7594 + return $text;
7595 + }
7596 +
7597 + // Pattern to match markdown links: [text](url)
7598 + $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
7599 +
7600 + $processed_text = preg_replace_callback($pattern, function($matches) {
7601 + $link_text = $matches[1];
7602 + $url = $matches[2];
7603 +
7604 + // Clean up any trailing punctuation from the URL
7605 + $url = rtrim($url, '.,;:!?');
7606 +
7607 + // Sanitize the link text and URL
7608 + $safe_text = esc_html($link_text);
7609 + $safe_url = esc_url($url);
7610 +
7611 + // Create the HTML link
7612 + return '<a href="' . $safe_url . '" target="_blank" rel="noopener noreferrer">' . $safe_text . '</a>';
7613 + }, $text);
7614 +
7615 + // If preg_replace_callback failed, return original text
7616 + if ($processed_text === null) {
7617 + return $text;
7618 + }
7619 +
7620 + return $processed_text;
7621 +}
7622 +
7623 +/**
7624 + * Auto-convert plain URLs to clickable links
7625 + *
7626 + * @param string $text The text to process
7627 + * @return string The text with URLs converted to links
7628 + */
7629 +private function auto_link_urls($text) {
7630 + // Return original text if empty
7631 + if (empty($text)) {
7632 + return $text;
7633 + }
7634 +
7635 + // Simple pattern that avoids complex lookbehinds
7636 + // This will match URLs that are not already inside href attributes or markdown links
7637 + $pattern = '/(?<!href=["\'])(?<!\]\()https?:\/\/[^\s<>"\')\]]+/i';
7638 +
7639 + $processed_text = preg_replace_callback($pattern, function($matches) {
7640 + $url = $matches[0];
7641 + // Clean up any trailing punctuation that might have been captured
7642 + $url = rtrim($url, '.,;:!?');
7643 +
7644 + // Add target="_blank" and rel="noopener noreferrer" for security
7645 + return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>';
7646 + }, $text);
7647 +
7648 + // If preg_replace_callback failed, return original text
7649 + if ($processed_text === null) {
7650 + return $text;
7651 + }
7652 +
7653 + return $processed_text;
7654 +}
7655 +
7656 +
7657 +// Helper function to get client IP address
7658 +private function get_client_ip() {
7659 + // Check for shared internet/ISP IP
7660 + if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
7661 + return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
7662 + }
7663 +
7664 + // Check for IPs passing through proxies
7665 + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
7666 + // Use the first value in the comma-separated list
7667 + $forwarded_for = explode(',', sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']));
7668 + return trim($forwarded_for[0]);
7669 + }
7670 +
7671 + if (!empty($_SERVER['REMOTE_ADDR'])) {
7672 + return sanitize_text_field($_SERVER['REMOTE_ADDR']);
7673 + }
7674 +
7675 + // Fallback
7676 + return 'unknown';
7677 +}
7678 +
7679 +/**
7680 + * AJAX handler to get system information for testing panel
7681 + */
7682 +/**
7683 + * AJAX handler to get system information for testing panel
7684 + */
7685 +public function mxchat_get_system_info() {
7686 + // Verify nonce for security
7687 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
7688 + wp_send_json_error(['message' => 'Invalid nonce']);
7689 + return;
7690 + }
7691 +
7692 + // Only allow admin users
7693 + if (!current_user_can('administrator')) {
7694 + wp_send_json_error(['message' => 'Unauthorized']);
7695 + return;
7696 + }
7697 +
7698 + // Get system prompt from options
7699 + $system_prompt = isset($this->options['system_prompt_instructions'])
7700 + ? $this->options['system_prompt_instructions']
7701 + : 'No system prompt configured';
7702 +
7703 + // Get selected model
7704 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
7705 +
7706 + // Check if OpenRouter is being used
7707 + $is_openrouter = ($selected_model === 'openrouter');
7708 + $openrouter_model = '';
7709 +
7710 + if ($is_openrouter) {
7711 + // Get the actual OpenRouter model that's selected
7712 + $openrouter_model = isset($this->options['openrouter_selected_model'])
7713 + ? $this->options['openrouter_selected_model']
7714 + : 'No OpenRouter model selected';
7715 +
7716 + // Update selected_model display to show both
7717 + $selected_model = 'OpenRouter: ' . $openrouter_model;
7718 + }
7719 +
7720 + // Get API key status (just check if they exist, don't expose the keys)
7721 + $api_status = [];
7722 + $api_status['openai'] = !empty($this->options['api_key']);
7723 + $api_status['claude'] = !empty($this->options['claude_api_key']);
7724 + $api_status['gemini'] = !empty($this->options['gemini_api_key']);
7725 + $api_status['xai'] = !empty($this->options['xai_api_key']);
7726 + $api_status['deepseek'] = !empty($this->options['deepseek_api_key']);
7727 + $api_status['openrouter'] = !empty($this->options['openrouter_api_key']);
7728 +
7729 + wp_send_json_success([
7730 + 'system_prompt' => $system_prompt,
7731 + 'selected_model' => $selected_model,
7732 + 'is_openrouter' => $is_openrouter,
7733 + 'openrouter_model' => $openrouter_model,
7734 + 'api_status' => $api_status
7735 + ]);
7736 +}
7737 +
7738 +/**
7739 + * AJAX handler to get similarity threshold
7740 + */
7741 +public function mxchat_get_similarity_threshold() {
7742 + // Verify nonce for security
7743 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
7744 + wp_send_json_error(['message' => 'Invalid nonce']);
7745 + return;
7746 + }
7747 +
7748 + // Only allow admin users
7749 + if (!current_user_can('administrator')) {
7750 + wp_send_json_error(['message' => 'Unauthorized']);
7751 + return;
7752 + }
7753 +
7754 + // Get similarity threshold from main options (default 35%)
7755 + $similarity_threshold = isset($this->options['similarity_threshold'])
7756 + ? ((int) $this->options['similarity_threshold']) / 100
7757 + : 0.35;
7758 +
7759 + wp_send_json_success([
7760 + 'threshold' => $similarity_threshold,
7761 + 'threshold_percentage' => ($similarity_threshold * 100) . '%'
7762 + ]);
7763 +}
7764 +
7765 +/**
7766 + * AJAX handler to get knowledge base status
7767 + */
7768 +public function mxchat_get_kb_status() {
7769 + // Verify nonce for security
7770 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
7771 + wp_send_json_error(['message' => 'Invalid nonce']);
7772 + return;
7773 + }
7774 +
7775 + // Only allow admin users
7776 + if (!current_user_can('administrator')) {
7777 + wp_send_json_error(['message' => 'Unauthorized']);
7778 + return;
7779 + }
7780 +
7781 + // Check Pinecone vs WordPress
7782 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
7783 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
7784 +
7785 + $kb_info = [
7786 + 'type' => $use_pinecone ? 'Pinecone' : 'WordPress Database',
7787 + 'status' => 'Active'
7788 + ];
7789 +
7790 + // Get document count
7791 + if ($use_pinecone) {
7792 + $kb_info['documents'] = 'Connected to Pinecone';
7793 + $kb_info['api_configured'] = !empty($addon_options['mxchat_pinecone_api_key']);
7794 + } else {
7795 + // Count documents in WordPress database
7796 + global $wpdb;
7797 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
7798 + $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
7799 + $kb_info['documents'] = $count ? $count . ' documents' : 'No documents';
7800 + }
7801 +
7802 + wp_send_json_success($kb_info);
7803 +}
7804 +
7805 +/**
7806 + * AJAX handler to start a completely fresh session (NEW - replaces old clear session)
7807 + */
7808 +public function mxchat_start_fresh_session() {
7809 + // Verify nonce for security
7810 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
7811 + wp_send_json_error(['message' => 'Invalid nonce']);
7812 + return;
7813 + }
7814 +
7815 + // Only allow admin users
7816 + if (!current_user_can('administrator')) {
7817 + wp_send_json_error(['message' => 'Unauthorized']);
7818 + return;
7819 + }
7820 +
7821 + $old_session_id = isset($_POST['old_session_id']) ? sanitize_text_field($_POST['old_session_id']) : '';
7822 + $new_session_id = isset($_POST['new_session_id']) ? sanitize_text_field($_POST['new_session_id']) : '';
7823 +
7824 + if (empty($old_session_id)) {
7825 + wp_send_json_error(['message' => 'Old session ID required']);
7826 + return;
7827 + }
7828 +
7829 + // If no new session ID provided, generate one
7830 + if (empty($new_session_id)) {
7831 + $new_session_id = 'mxchat_chat_' . substr(md5(uniqid()), 0, 9);
7832 + }
7833 +
7834 + // Clear ALL data associated with the old session
7835 + $this->clear_complete_session_data($old_session_id);
7836 +
7837 + // Initialize the new session
7838 + $this->initialize_fresh_session($new_session_id);
7839 +
7840 + wp_send_json_success([
7841 + 'message' => 'Fresh session started successfully',
7842 + 'new_session_id' => $new_session_id,
7843 + 'old_session_id' => $old_session_id
7844 + ]);
7845 +}
7846 +
7847 +/**
7848 + * Clear ALL data associated with a session (ENHANCED)
7849 + */
7850 +private function clear_complete_session_data($session_id) {
7851 + // Clear chat history
7852 + delete_option("mxchat_history_{$session_id}");
7853 +
7854 + // Clear chat mode
7855 + delete_option("mxchat_mode_{$session_id}");
7856 +
7857 + // Clear any PDF/Word transients
7858 + $this->clear_pdf_transients($session_id);
7859 + if (method_exists($this, 'clear_word_transients')) {
7860 + $this->clear_word_transients($session_id);
7861 + }
7862 +
7863 + // Clear agent-related data
7864 + delete_option("mxchat_channel_{$session_id}");
7865 + delete_option("mxchat_agent_name_{$session_id}");
7866 + delete_option("mxchat_email_{$session_id}");
7867 +
7868 + // Clear any recommendation flow state
7869 + delete_option("mxchat_sr_flow_state_{$session_id}");
7870 +
7871 + // Clear any cached embeddings or context
7872 + delete_transient("mxchat_context_{$session_id}");
7873 + delete_transient("mxchat_last_query_{$session_id}");
7874 +
7875 + // Clear any testing data
7876 + delete_transient("mxchat_testing_data_{$session_id}");
7877 +
7878 + // Clear any rate limiting data for this session
7879 + delete_transient("mxchat_rate_limit_{$session_id}");
7880 +
7881 + // Clear any other session-specific transients
7882 + delete_transient("mxchat_waiting_for_pdf_url_{$session_id}");
7883 + delete_transient("mxchat_include_pdf_in_context_{$session_id}");
7884 + delete_transient("mxchat_include_word_in_context_{$session_id}");
7885 +
7886 + //error_log("MxChat: Cleared all data for session: {$session_id}");
7887 +}
7888 +
7889 +/**
7890 + * Initialize a fresh session with default data
7891 + */
7892 +private function initialize_fresh_session($session_id) {
7893 + // Set default chat mode
7894 + update_option("mxchat_mode_{$session_id}", 'ai');
7895 +
7896 + //error_log("MxChat: Initialized fresh session: {$session_id}");
7897 +}
7898 +
7899 +/**
7900 + * Helper method to clear Word document transients (if you have Word support)
7901 + */
7902 +private function clear_word_transients($session_id) {
7903 + delete_transient('mxchat_word_url_' . $session_id);
7904 + delete_transient('mxchat_word_filename_' . $session_id);
7905 + delete_transient('mxchat_word_embeddings_' . $session_id);
7906 + delete_transient('mxchat_include_word_in_context_' . $session_id);
7907 +}
7908 +
7909 +/**
7910 + * Simplified testing data capture method (CLEANED UP)
7911 + */
7912 +private function capture_testing_data($user_embedding, $message, $session_id) {
7913 + // Only capture for admin users
7914 + if (!current_user_can('administrator')) {
7915 + return null;
7916 + }
7917 +
7918 + $testing_data = [
7919 + 'query' => $message,
7920 + 'timestamp' => time(),
7921 + 'top_matches' => [],
7922 + 'action_matches' => [] // Add action matches
7923 + ];
7924 +
7925 + // Get similarity threshold
7926 + $similarity_threshold = isset($this->options['similarity_threshold'])
7927 + ? ((int) $this->options['similarity_threshold']) / 100
7928 + : 0.35;
7929 +
7930 + $testing_data['similarity_threshold'] = $similarity_threshold;
7931 +
7932 + // Use the real similarity analysis if available
7933 + if ($this->last_similarity_analysis !== null) {
7934 + $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
7935 + $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
7936 + $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
7937 + } else {
7938 + // Fallback: determine knowledge base type
7939 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
7940 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
7941 +
7942 + $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
7943 + }
7944 +
7945 + // Include action analysis if available
7946 + if (isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
7947 + $testing_data['action_matches'] = $this->last_action_analysis;
7948 +
7949 + // Clear it after capturing to avoid stale data
7950 + $this->last_action_analysis = null;
7951 + }
7952 +
7953 + return $testing_data;
7954 +}
7955 +
7956 +
7957 +/**
7958 + * Track URL clicks from chatbot responses
7959 + */
7960 +public function mxchat_track_url_click() {
7961 + // Verify nonce for security
7962 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
7963 + wp_send_json_error(['message' => 'Invalid nonce']);
7964 + wp_die();
7965 + }
7966 +
7967 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
7968 + $clicked_url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
7969 + $message_context = isset($_POST['message_context']) ? sanitize_textarea_field($_POST['message_context']) : '';
7970 +
7971 + if (empty($session_id) || empty($clicked_url)) {
7972 + wp_send_json_error(['message' => 'Missing required data']);
7973 + wp_die();
7974 + }
7975 +
7976 + global $wpdb;
7977 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
7978 +
7979 + // Insert click tracking record
7980 + $wpdb->insert(
7981 + $table_name,
7982 + [
7983 + 'session_id' => $session_id,
7984 + 'clicked_url' => $clicked_url,
7985 + 'message_context' => $message_context,
7986 + 'click_timestamp' => current_time('mysql', 1),
7987 + 'user_ip' => $_SERVER['REMOTE_ADDR'],
7988 + 'user_agent' => $_SERVER['HTTP_USER_AGENT']
7989 + ]
7990 + );
7991 +
7992 + wp_send_json_success(['message' => 'Click tracked']);
7993 + wp_die();
7994 +}
7995 +
7996 +/**
7997 + * Get URL click analytics for a session
7998 + */
7999 +public function mxchat_get_url_clicks($session_id) {
8000 + global $wpdb;
8001 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
8002 +
8003 + $clicks = $wpdb->get_results($wpdb->prepare(
8004 + "SELECT * FROM $table_name WHERE session_id = %s ORDER BY click_timestamp ASC",
8005 + $session_id
8006 + ));
8007 +
8008 + return $clicks;
8009 +}
8010 +/**
8011 + * Track the originating page where chat was started
8012 + */
8013 +public function mxchat_track_originating_page() {
8014 + // Verify nonce
8015 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
8016 + wp_send_json_error(['message' => 'Invalid nonce']);
8017 + wp_die();
8018 + }
8019 +
8020 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
8021 + $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
8022 + $page_title = isset($_POST['page_title']) ? sanitize_text_field($_POST['page_title']) : '';
8023 +
8024 + if (empty($session_id)) {
8025 + wp_send_json_error(['message' => 'Missing session ID']);
8026 + wp_die();
8027 + }
8028 +
8029 + global $wpdb;
8030 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
8031 +
8032 + // Check if we've already tracked for this session
8033 + $existing = $wpdb->get_var($wpdb->prepare(
8034 + "SELECT COUNT(*) FROM $table_name
8035 + WHERE session_id = %s
8036 + AND originating_page_url IS NOT NULL",
8037 + $session_id
8038 + ));
8039 +
8040 + if ($existing > 0) {
8041 + wp_send_json_success(['message' => 'Already tracked']);
8042 + wp_die();
8043 + }
8044 +
8045 + // Update the first message in this session with originating page info
8046 + $wpdb->query($wpdb->prepare(
8047 + "UPDATE $table_name
8048 + SET originating_page_url = %s,
8049 + originating_page_title = %s
8050 + WHERE session_id = %s
8051 + ORDER BY timestamp ASC
8052 + LIMIT 1",
8053 + $page_url,
8054 + $page_title,
8055 + $session_id
8056 + ));
8057 +
8058 + wp_send_json_success(['message' => 'Originating page tracked']);
8059 + wp_die();
8060 +}
8061 +
8062 +/**
8063 + * Validate and clean URLs from AI response
8064 + * Removes any URLs that aren't in the knowledge base
8065 + *
8066 + * @param string $response_text The AI-generated response
8067 + * @param array $valid_urls Array of URLs from the knowledge base
8068 + * @return string Cleaned response with invalid URLs removed/flagged
8069 + */
8070 +private function validate_and_clean_urls($response_text, $valid_urls) {
8071 + // DEBUG: Log what we're working with
8072 + error_log("=== MxChat URL Validation Debug ===");
8073 + error_log("Valid URLs count: " . count($valid_urls));
8074 + error_log("Valid URLs: " . print_r($valid_urls, true));
8075 + error_log("Response text length: " . strlen($response_text));
8076 + error_log("Response text preview: " . substr($response_text, 0, 500));
8077 +
8078 + // If no valid URLs provided or empty response, return as-is
8079 + if (empty($valid_urls) || empty($response_text)) {
8080 + error_log("Validation skipped - empty valid_urls or response");
8081 + return $response_text;
8082 + }
8083 +
8084 + // Extract all URLs from the AI response
8085 + // This regex matches http:// and https:// URLs
8086 + preg_match_all(
8087 + '#\bhttps?://[^\s<>"\')\]]+#i',
8088 + $response_text,
8089 + $matches
8090 + );
8091 +
8092 + // If no URLs found in response, return as-is
8093 + if (empty($matches[0])) {
8094 + error_log("No URLs found in response");
8095 + return $response_text;
8096 + }
8097 +
8098 + $found_urls = $matches[0];
8099 + $cleaned_response = $response_text;
8100 + $removed_count = 0;
8101 +
8102 + // Normalize valid URLs for comparison (remove trailing slashes, fragments, etc.)
8103 + $normalized_valid_urls = array_map(function($url) {
8104 + // Remove trailing slash
8105 + $url = rtrim($url, '/');
8106 + // Remove URL fragments (#section)
8107 + $url = preg_replace('/#.*$/', '', $url);
8108 + // Remove trailing punctuation that might have been captured
8109 + $url = rtrim($url, '.,;:!?');
8110 + return $url;
8111 + }, $valid_urls);
8112 +
8113 + error_log("Normalized valid URLs: " . print_r($normalized_valid_urls, true));
8114 +
8115 + foreach ($found_urls as $found_url) {
8116 + // Clean up the found URL (remove trailing punctuation that might have been captured)
8117 + $clean_found_url = rtrim($found_url, '.,;:!?)');
8118 +
8119 + // DEBUG: Log each URL being checked
8120 + error_log("Checking found URL: " . $found_url);
8121 +
8122 + // Normalize for comparison
8123 + $normalized_found = rtrim($clean_found_url, '/');
8124 + $normalized_found = preg_replace('/#.*$/', '', $normalized_found);
8125 +
8126 + error_log("Normalized found URL: " . $normalized_found);
8127 +
8128 + // Check if this URL exists in our valid URLs list
8129 + $is_valid = false;
8130 +
8131 + error_log("Starting validation checks for: " . $normalized_found);
8132 +
8133 + // First, try exact match
8134 + if (in_array($normalized_found, $normalized_valid_urls)) {
8135 + $is_valid = true;
8136 + error_log("EXACT MATCH FOUND");
8137 + } else {
8138 + error_log("No exact match, checking variations...");
8139 + // If no exact match, check if it's a variation (with query params, etc.)
8140 + foreach ($normalized_valid_urls as $valid_url) {
8141 + error_log(" Comparing against valid URL: " . $valid_url);
8142 +
8143 + // Check if the found URL starts with a valid URL (handles query params)
8144 + if (strpos($normalized_found, $valid_url) === 0) {
8145 + // Check what comes after the valid URL
8146 + $remainder = substr($normalized_found, strlen($valid_url));
8147 +
8148 + // Only valid if:
8149 + // 1. Exact match (remainder is empty)
8150 + // 2. Query params (starts with ?)
8151 + // 3. Fragment (starts with #)
8152 + if (empty($remainder) || $remainder[0] === '?' || $remainder[0] === '#') {
8153 + $is_valid = true;
8154 + error_log(" MATCH: Found URL is valid variation of base URL");
8155 + break;
8156 + } else {
8157 + error_log(" NOT A MATCH: Found URL extends path beyond valid URL (remainder: " . $remainder . ")");
8158 + }
8159 + }
8160 + // Also check the reverse (in case valid URL has query params)
8161 + if (strpos($valid_url, $normalized_found) === 0) {
8162 + $is_valid = true;
8163 + error_log(" MATCH: Valid URL starts with found URL");
8164 + break;
8165 + }
8166 + }
8167 +
8168 + if (!$is_valid) {
8169 + error_log("NO MATCH FOUND - URL should be removed");
8170 + }
8171 + }
8172 +
8173 + // If URL is not valid, remove it from the response
8174 + if (!$is_valid) {
8175 + // Log the removal for debugging
8176 + error_log("MxChat: Removed hallucinated URL: " . $found_url);
8177 + error_log("MxChat: Valid URLs were: " . implode(', ', array_slice($normalized_valid_urls, 0, 5)));
8178 +
8179 + $removed_count++;
8180 +
8181 + // Check if URL is part of a markdown link: [text](url)
8182 + $markdown_pattern = '/\[([^\]]+)\]\(' . preg_quote($found_url, '/') . '\)/';
8183 + if (preg_match($markdown_pattern, $cleaned_response)) {
8184 + error_log("Found markdown link, removing but keeping text");
8185 + // Remove the markdown link but keep the text
8186 + $cleaned_response = preg_replace($markdown_pattern, '$1', $cleaned_response);
8187 + }
8188 + // Check if URL is part of an HTML link: <a href="url">text</a>
8189 + else if (preg_match('/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>(.*?)<\/a>/i', $cleaned_response, $link_match)) {
8190 + error_log("Found HTML link, removing but keeping text");
8191 + // Remove the HTML link but keep the text
8192 + $link_text = $link_match[1];
8193 + $cleaned_response = preg_replace(
8194 + '/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>.*?<\/a>/i',
8195 + $link_text,
8196 + $cleaned_response
8197 + );
8198 + }
8199 + // Otherwise just remove the bare URL
8200 + else {
8201 + error_log("Removing bare URL");
8202 + $cleaned_response = str_replace($found_url, '', $cleaned_response);
8203 + }
8204 + }
8205 + }
8206 +
8207 + // Log summary if any URLs were removed
8208 + if ($removed_count > 0) {
8209 + error_log("MxChat: URL Validation Summary - Removed {$removed_count} hallucinated URL(s)");
8210 + } else {
8211 + error_log("MxChat: URL Validation Summary - No URLs removed, all were valid");
8212 + }
8213 +
8214 + // Clean up any double spaces or awkward punctuation left behind
8215 + $cleaned_response = preg_replace('/\s+/', ' ', $cleaned_response);
8216 + $cleaned_response = preg_replace('/\s+([.,;:!?])/', '$1', $cleaned_response);
8217 +
8218 + error_log("Final cleaned response: " . $cleaned_response);
8219 +
8220 + return trim($cleaned_response);
8221 +}
8222 +
8223 +/**
8224 + * AJAX handler to get current chat mode for a session
8225 + */
8226 +public function mxchat_get_current_chat_mode() {
8227 + // Verify nonce for security
8228 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
8229 + wp_send_json_error(['message' => 'Invalid nonce']);
8230 + wp_die();
8231 + }
8232 +
8233 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
8234 +
8235 + if (empty($session_id)) {
8236 + wp_send_json_error(['message' => 'Session ID missing']);
8237 + wp_die();
8238 + }
8239 +
8240 + // Get the current chat mode for this session
8241 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
8242 +
8243 + wp_send_json_success([
8244 + 'chat_mode' => $chat_mode
8245 + ]);
8246 + wp_die();
8247 +}
8248 +
8249 +
8250 +
8251 +}
8252 +?>