PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.6.1
MxChat – AI Chatbot & Content Generation for WordPress v1.6.1
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | includes/class-mxchat-admin.php +3682 -8317 3.2.61.6.1 View file →
@@ -6,31 +6,13 @@
6 6 class MxChat_Admin {
7 7 private $options;
8 8 private $chat_count;
9 9 private $is_activated;
10 - private $knowledge_manager;
11 10
12 - /**
13 - * Get whether the license is activated
14 - * @return bool
15 - */
16 - public function is_activated() {
17 - return $this->is_activated;
18 - }
19 -
20 - /**
21 - * Get plugin options
22 - * @return array
23 - */
24 - public function get_options() {
25 - return $this->options;
26 - }
27 -
28 - public function __construct($knowledge_manager = null) {
11 + public function __construct() {
29 12 $this->options = get_option('mxchat_options');
30 13 $this->chat_count = get_option('mxchat_chat_count', 0);
31 14 $this->is_activated = $this->is_license_active();
32 - $this->knowledge_manager = $knowledge_manager;
33 15
34 16 // Initialize default options if they are not set
35 17 if (!$this->options) {
36 18 $this->initialize_default_options();
@@ -37,323 +19,107 @@
37 19 }
38 20
39 21 // Add admin menu and initialize settings
40 22 add_action('admin_menu', array($this, 'mxchat_add_plugin_page'));
41 - // Pro & Extensions registers at priority 30 so it always lands last in
42 - // the sidebar — below API Access (priority 20) and below any other
43 - // submenu that hooks at default priority 10.
44 - add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30);
45 23 add_action('admin_init', array($this, 'mxchat_page_init'));
46 - add_action('admin_init', array($this, 'mxchat_prompts_page_init'));
24 + add_action('admin_init', array($this, 'mxchat_prompts_page_init')); // Add this line
47 25 add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets'));
48 26 add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history'));
27 + add_action('admin_post_mxchat_submit_content', array($this, 'mxchat_handle_content_submission'));
49 28 add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt'));
50 29 add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
51 30 add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history'));
52 - add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation'));
31 + add_action('admin_post_mxchat_submit_sitemap', array($this, 'mxchat_handle_sitemap_submission'));
53 32 add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body'));
54 33 add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets'));
55 34 add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets'));
35 + add_action('wp_ajax_mxchat_activate_license', array($this, 'mxchat_handle_activate_license'));
56 36 add_action('admin_notices', array($this, 'mxchat_display_admin_notice'));
37 + // Add the AJAX handler for logged-in users
38 + add_action('wp_ajax_mxchat_save_inline_prompt', array($this, 'mxchat_save_inline_prompt'));
57 39 add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts'));
40 +
41 + // Define admin_post actions for form submission handling
58 42 add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent'));
59 43 add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent'));
60 - add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent'));
61 - add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts'));
44 + add_action('admin_post_mxchat_update_intent_threshold', array($this, 'mxchat_handle_update_intent_threshold'));
45 + add_action('admin_post_mxchat_stop_processing', array($this, 'mxchat_stop_processing'));
46 + add_action('admin_post_mxchat_edit_intent', array($this, 'handle_edit_intent'));
62 47
63 - // Leads tab (inside Transcripts)
64 - add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads'));
65 - add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads'));
66 - add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads'));
48 + add_action('save_post', array($this, 'handle_post_update'), 10, 3);
49 + add_action('post_updated', array($this, 'handle_post_update'), 10, 3);
50 +add_action('wp_ajax_mxchat_save_setting', array($this, 'mxchat_save_setting_callback'));
67 51
68 - add_action('admin_init', array($this, 'mxchat_transcripts_page_init'));
69 - add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice'));
70 - add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice'));
71 - add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts'));
72 52
73 - add_action('admin_init', array($this, 'register_pinecone_settings'));
74 - add_action('admin_init', array($this, 'register_openai_vectorstore_settings'));
75 -
76 - add_action('admin_notices', array($this, 'display_admin_notices'));
77 -
78 - add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']);
79 - add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback
80 - add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection'));
81 -
82 - add_action('wp_ajax_mxchat_save_selected_bot', array($this, 'mxchat_save_selected_bot'));
83 - add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models'));
84 - add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context'));
85 -
86 - // Actions page AJAX handlers
87 - add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list'));
88 - add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status'));
89 - add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions'));
90 - add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax'));
91 - add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax'));
92 - add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax'));
93 - add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax'));
94 - add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax'));
95 - add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax'));
96 - add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax'));
97 -
98 - // Slack test connection
99 - add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection'));
100 -
101 - // Translation handlers
102 - add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages'));
103 - add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation'));
104 -
105 - // 3.2.3: Embedding model switch protection
106 - add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax'));
107 - add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax'));
108 - add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice'));
109 53 }
110 54
111 - /**
112 - * 3.2.3: Preflight check before allowing the embedding model dropdown to
113 - * switch. Pure option comparison — no counts, no DB queries beyond the
114 - * cached options. The dialog is shown whenever the user has previously
115 - * embedded with a different model than the one they're switching to.
116 - */
117 - public function mxchat_check_embedding_switch_ajax() {
118 - check_ajax_referer('mxchat_admin_nonce', 'security');
119 - if (!current_user_can('manage_options')) {
120 - wp_send_json_error(__('Unauthorized', 'mxchat'));
121 - }
122 -
123 - $new_model = isset($_POST['new_model']) ? sanitize_text_field(wp_unslash($_POST['new_model'])) : '';
124 - $active_model = MxChat_Utils::get_active_embedding_model();
125 -
126 - $is_mismatch = !empty($active_model) && !empty($new_model) && $active_model !== $new_model;
127 -
128 - $active_dims = MxChat_Utils::embedding_model_dimensions($active_model);
129 - $new_dims = MxChat_Utils::embedding_model_dimensions($new_model);
130 -
131 - wp_send_json_success(array(
132 - 'is_mismatch' => $is_mismatch,
133 - 'active_model' => $active_model,
134 - 'active_label' => MxChat_Utils::embedding_model_label($active_model),
135 - 'new_model' => $new_model,
136 - 'new_label' => MxChat_Utils::embedding_model_label($new_model),
137 - 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims),
138 - 'active_dims' => $active_dims,
139 - 'new_dims' => $new_dims,
140 - ));
55 + // Method to check if the license is active
56 + private function is_license_active() {
57 + $license_status = get_option('mxchat_license_status', 'inactive');
58 + return $license_status === 'active';
141 59 }
142 60
143 - /**
144 - * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected
145 - * pair so the banner reappears on the next switch event.
146 - */
147 - public function mxchat_dismiss_embedding_mismatch_ajax() {
148 - check_ajax_referer('mxchat_admin_nonce', 'security');
149 - if (!current_user_can('manage_options')) {
150 - wp_send_json_error(__('Unauthorized', 'mxchat'));
151 - }
152 -
153 - $options = get_option('mxchat_options', array());
154 - $selected = $options['embedding_model'] ?? '';
155 - $active = MxChat_Utils::get_active_embedding_model();
156 - update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false);
157 - wp_send_json_success();
158 - }
159 -
160 - /**
161 - * 3.2.3: Persistent admin banner shown whenever the active embedding model
162 - * (last used to actually embed something) differs from the currently
163 - * selected model. Pure option comparison — no DB queries on every page
164 - * load. The banner auto-clears once both match again, i.e. after a delete
165 - * + re-embed cycle.
166 - */
167 - public function mxchat_embedding_mismatch_notice() {
168 - if (!current_user_can('manage_options')) {
169 - return;
170 - }
171 -
172 - $options = get_option('mxchat_options', array());
173 - $selected = $options['embedding_model'] ?? '';
174 - $active = MxChat_Utils::get_active_embedding_model();
175 -
176 - if (empty($active) || empty($selected) || $active === $selected) {
177 - return;
178 - }
179 -
180 - $dismissed = get_option('mxchat_dismissed_embedding_mismatch', '');
181 - if ($dismissed === $active . '|' . $selected) {
182 - return;
183 - }
184 -
185 - $active_label = MxChat_Utils::embedding_model_label($active);
186 - $selected_label = MxChat_Utils::embedding_model_label($selected);
187 - $active_dims = MxChat_Utils::embedding_model_dimensions($active);
188 - $selected_dims = MxChat_Utils::embedding_model_dimensions($selected);
189 - $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims);
190 -
191 - $kb_url = admin_url('admin.php?page=mxchat-prompts');
192 - $actions_url = admin_url('admin.php?page=mxchat-actions');
193 -
194 - ?>
195 - <div class="notice notice-error is-dismissible mxchat-embedding-mismatch-notice"
196 - data-active="<?php echo esc_attr($active); ?>"
197 - data-selected="<?php echo esc_attr($selected); ?>">
198 - <p><strong><?php esc_html_e('MxChat: Embedding model mismatch detected', 'mxchat'); ?></strong></p>
199 - <p>
200 - <?php
201 - printf(
202 - /* translators: 1: previously-used model name, 2: currently-selected model name */
203 - esc_html__('Your knowledge base and actions were embedded with %1$s, but %2$s is now selected. Similarity matching will return inaccurate or empty results until you delete all existing embeddings and re-embed your content with the new model.', 'mxchat'),
204 - '<code>' . esc_html($active_label) . '</code>',
205 - '<code>' . esc_html($selected_label) . '</code>'
206 - );
207 - ?>
208 - </p>
209 - <?php if ($dims_differ) : ?>
210 - <p>
211 - <strong><?php esc_html_e('Dimension mismatch:', 'mxchat'); ?></strong>
212 - <?php
213 - printf(
214 - /* translators: 1: old dim count, 2: new dim count */
215 - esc_html__('Existing vectors are %1$d-dimensional but the new model produces %2$d-dimensional vectors. If you use Pinecone, your index will reject queries entirely until re-embedded.', 'mxchat'),
216 - (int) $active_dims,
217 - (int) $selected_dims
218 - );
219 - ?>
220 - </p>
221 - <?php endif; ?>
222 - <p>
223 - <?php esc_html_e('To fix this:', 'mxchat'); ?>
224 - <a href="<?php echo esc_url($kb_url); ?>"><?php esc_html_e('Delete all knowledge base entries', 'mxchat'); ?></a> ·
225 - <a href="<?php echo esc_url($actions_url); ?>"><?php esc_html_e('Delete all actions', 'mxchat'); ?></a> ·
226 - <?php esc_html_e('then re-import / re-add them with the new model selected.', 'mxchat'); ?>
227 - </p>
228 - </div>
229 - <script>
230 - (function($){
231 - $(document).on('click', '.mxchat-embedding-mismatch-notice .notice-dismiss', function(){
232 - $.post(ajaxurl, {
233 - action: 'mxchat_dismiss_embedding_mismatch',
234 - security: '<?php echo esc_js(wp_create_nonce('mxchat_admin_nonce')); ?>'
235 - });
236 - });
237 - })(jQuery);
238 - </script>
239 - <?php
240 - }
241 -
242 -private function is_license_active() {
243 - $license_status = get_option('mxchat_license_status', 'inactive');
244 - return ($license_status === 'active');
245 -}
246 -
61 + // Initialize default options
247 62 private function initialize_default_options() {
248 63 $default_options = array(
249 64 'api_key' => '',
250 65 'xai_api_key' => '',
251 66 'claude_api_key' => '',
252 - 'deepseek_api_key' => '',
253 - 'voyage_api_key' => '',
254 - 'gemini_api_key' => '',
255 - 'enable_streaming_toggle' => 'off',
256 - 'enable_web_search' => 'off',
257 - 'embedding_model' => 'text-embedding-ada-002',
258 - 'system_prompt_instructions' => 'You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
259 -
260 - # Response Style - CRITICALLY IMPORTANT
261 - - MAXIMUM LENGTH: 1-3 short sentences per response
262 - - Ultra-concise: Get straight to the answer with no filler
263 - - No introductions like "Sure!" or "I\'d be happy to help"
264 - - No phrases like "based on my knowledge" or "according to information"
265 - - No explanatory text before giving the answer
266 - - No summaries or repetition
267 - - Hyperlink all URLs
268 - - Respond in user\'s language
269 - - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
270 -
271 - # Knowledge Base Requirements - PREVENT HALLUCINATIONS
272 - - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
273 - - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
274 - - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
275 - - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
276 - - Better to admit insufficient information than provide inaccurate answers',
277 - 'model' => esc_html__('gpt-5.1-chat-latest', 'mxchat'),
278 - 'rate_limit_logged_out' => esc_html__('100', 'mxchat'),
279 - 'role_rate_limits' => array(),
280 - 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
67 + 'system_prompt_instructions' => '[EXAMPLE INSTRUCTIONS] You are an AI Chatbot assistant for this website. The primary subject you should focus on is [insert proper subject here]. Your main goal is to assist visitors with questions related to this specific topic. Here are some key things to keep in mind:
68 + - Your name is [Chatbot Name].
69 + - Stay focused on topics related to [insert proper subject here]. If a visitor asks about an unrelated topic, politely redirect the conversation to how you can assist them with this subject.
70 + - Do not make up links to pages. Only use specific links you see in your knowledgebase.
71 + - Keep your responses short, concise, and to the point. Provide clear and direct answers suitable for a chatbot interaction.
72 + - Provide answers based on the knowledge available to you. If you do not have an answer to a specific question, let the visitor know that you don’t have the information.',
73 + 'model' => 'gpt-4o',
74 + 'rate_limit_logged_in' => '100',
75 + 'rate_limit_logged_out' => '100',
76 + 'rate_limit_message' => 'Rate limit exceeded. Please try again later.',
281 77 'enable_email_block' => '',
282 - 'email_blocker_header_content' => __("<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>", 'mxchat'),
283 - 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'),
284 - 'enable_name_field' => 'off', // NEW
285 - 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW
286 - 'top_bar_title' => esc_html__('MxChat', 'mxchat'),
287 - 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'),
288 - 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'),
289 - 'input_copy' => esc_html__('How can I assist?', 'mxchat'),
290 - 'append_to_body' => esc_html__('off', 'mxchat'),
291 - 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude'
292 - 'post_type_visibility_list' => array(), // Array of post type slugs
293 - 'contextual_awareness_toggle' => 'off',
294 - 'citation_links_toggle' => 'on',
295 - 'satisfaction_rating_enabled' => 'off',
296 - 'satisfaction_rating_idle_seconds' => 60,
297 - 'satisfaction_rating_question' => '',
298 - 'satisfaction_rating_thanks' => '',
299 - 'satisfaction_rating_placeholder' => '',
300 - 'satisfaction_rating_saved' => '',
301 - 'close_button_color' => esc_html__('#fff', 'mxchat'),
302 - 'chatbot_bg_color' => esc_html__('#fff', 'mxchat'),
303 - 'user_message_bg_color' => esc_html__('#fff', 'mxchat'),
304 - 'user_message_font_color' => esc_html__('#212121', 'mxchat'),
305 - 'bot_message_bg_color' => esc_html__('#212121', 'mxchat'),
306 - 'bot_message_font_color' => esc_html__('#fff', 'mxchat'),
307 - 'top_bar_bg_color' => esc_html__('#212121', 'mxchat'),
308 - 'send_button_font_color' => esc_html__('#212121', 'mxchat'),
309 - 'chat_input_font_color' => esc_html__('#212121', 'mxchat'),
310 - 'chatbot_background_color' => esc_html__('#212121', 'mxchat'),
311 - 'icon_color' => esc_html__('#fff', 'mxchat'),
312 - 'enable_woocommerce_integration' => esc_html__('0', 'mxchat'),
313 - 'link_target_toggle' => esc_html__('off', 'mxchat'),
314 - 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'),
78 + 'email_blocker_header_content' => "<h2>Welcome to Our Chat!</h2>\n<p>Let's get started. Enter your email to begin chatting with us.</p>",
79 + 'email_blocker_button_text' => 'Start Chat',
80 + 'top_bar_title' => 'MxChat',
81 + 'intro_message' => 'Hello! How can I assist you today?',
82 + 'input_copy' => 'How can I assist?',
83 + 'append_to_body' => 'off',
84 + 'close_button_color' => '#fff',
85 + 'chatbot_bg_color' => '#fff',
86 + 'user_message_bg_color' => '#fff',
87 + 'user_message_font_color' => '#212121',
88 + 'bot_message_bg_color' => '#212121',
89 + 'bot_message_font_color' => '#fff',
90 + 'top_bar_bg_color' => '#212121',
91 + 'send_button_font_color' => '#212121',
92 + 'chat_input_font_color' => '#212121',
93 + 'chatbot_background_color' => '#212121',
94 + 'icon_color' => '#fff',
95 + 'enable_woocommerce_integration' => '0',
96 + 'link_target_toggle' => 'off',
97 + 'pre_chat_message' => 'Hey there! Ask me anything!',
315 98
316 99 // New fields for Loops Integration
317 100 'loops_api_key' => '',
318 101 'loops_mailing_list' => '',
319 - 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
320 - 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
102 + 'triggered_phrase_response' => 'Would you like to join our mailing list? Please provide your email below.',
103 + 'email_capture_response' => 'Thank you for providing your email! You\'ve been added to our list.',
321 104 'popular_question_1' => '',
322 105 'popular_question_2' => '',
323 106 'popular_question_3' => '',
324 - 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
325 - 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'),
326 - 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
107 + 'pdf_intent_trigger_text' => "Please provide the URL to the PDF you'd like to discuss.",
108 + 'pdf_intent_success_text' => "I've processed the PDF. What questions do you have about it?",
109 + 'pdf_intent_error_text' => "Sorry, I couldn't process the PDF. Please ensure it's a valid file.",
327 110 'pdf_max_pages' => 69,
328 - 'show_pdf_upload_button' => 'on',
329 - 'show_word_upload_button' => 'on',
330 111
331 - // Live Agent Integration (Slack)
112 + // Live Agent Integration
332 113 'live_agent_webhook_url' => '',
333 114 'live_agent_secret_key' => '',
334 115 'live_agent_bot_token' => '',
335 - 'live_agent_message_bg_color' => esc_html__('#ffffff', 'mxchat'),
336 - 'live_agent_message_font_color' => esc_html__('#333333', 'mxchat'),
337 -
338 - // Telegram Integration
339 - 'telegram_status' => 'off',
340 - 'telegram_bot_token' => '',
341 - 'telegram_group_id' => '',
342 - 'telegram_webhook_secret' => '',
343 - 'telegram_notification_message' => __("I've notified a support agent. Please allow a moment for them to respond. If you'd like to continue with AI, just type \"Switch to AI\" at any time.", 'mxchat'),
344 - 'telegram_away_message' => __("I just checked, and it looks like our support team isn't personally available at the moment. If you'd like, you can leave your email address, and they'll get back to you as soon as possible. In the meantime, you can keep chatting with me — just let me know how I can help!", 'mxchat'),
345 -
346 - 'chat_toolbar_toggle' => esc_html__('off', 'mxchat'),
347 - 'mode_indicator_bg_color' => esc_html__('#767676', 'mxchat'),
348 - 'mode_indicator_font_color' => esc_html__('#ffffff', 'mxchat'),
349 - 'toolbar_icon_color' => esc_html__('#212121', 'mxchat'),
350 -
351 - // Optimization settings
352 - 'script_loading_strategy' => 'default',
353 -
354 - // Debug settings
355 - 'debug_mode' => 'off',
116 + 'live_agent_message_bg_color' => '#ffffff',
117 + 'live_agent_message_font_color' => '#333333',
118 + 'chat_toolbar_toggle' => 'off',
119 + 'mode_indicator_bg_color' => '#767676',
120 + 'mode_indicator_font_color' => '#ffffff',
121 + 'toolbar_icon_color' => '#212121',
356 122 );
357 123
358 124
359 125 // Merge existing options with defaults
@@ -364,629 +130,160 @@
364 130 if ($existing_options !== $merged_options) {
365 131 update_option('mxchat_options', $merged_options);
366 132 }
367 133
368 - // Add default limits for each role
369 - $roles = wp_roles()->get_names();
370 - foreach ($roles as $role_id => $role_name) {
371 - $default_options['role_rate_limits'][$role_id] = esc_html__('100', 'mxchat');
372 - }
373 -
374 - return $default_options;
375 -
376 134 // Update the $this->options property
377 135 $this->options = $merged_options;
378 136 }
379 137
380 -public function mxchat_add_plugin_page() {
381 - // Main menu page
382 - add_menu_page(
383 - esc_html__('MxChat Settings', 'mxchat'),
384 - esc_html__('MxChat', 'mxchat'),
385 - 'manage_options',
386 - 'mxchat-max',
387 - array($this, 'mxchat_create_admin_page'),
388 - 'dashicons-testimonial',
389 - 6
390 - );
391 138
392 - // Rename the first submenu item from "MxChat" to "Settings"
393 - add_submenu_page(
394 - 'mxchat-max',
395 - esc_html__('MxChat Settings', 'mxchat'),
396 - esc_html__('Settings', 'mxchat'),
397 - 'manage_options',
398 - 'mxchat-max',
399 - array($this, 'mxchat_create_admin_page')
400 - );
401 139
402 - // Submenu page for Knowledge
403 - add_submenu_page(
404 - 'mxchat-max',
405 - esc_html__('Prompts', 'mxchat'),
406 - esc_html__('Knowledge', 'mxchat'),
407 - 'manage_options',
408 - 'mxchat-prompts',
409 - array($this, 'mxchat_create_prompts_page')
410 - );
140 + public function mxchat_add_plugin_page() {
141 + // Main menu page
142 + add_menu_page(
143 + 'MxChat Settings',
144 + 'MxChat',
145 + 'manage_options',
146 + 'mxchat-max',
147 + array($this, 'mxchat_create_admin_page'),
148 + 'dashicons-testimonial',
149 + 6
150 + );
411 151
412 - add_submenu_page(
413 - 'mxchat-max',
414 - esc_html__('Chat Transcripts', 'mxchat'),
415 - esc_html__('Transcripts', 'mxchat'),
416 - 'manage_options',
417 - 'mxchat-transcripts',
418 - array($this, 'mxchat_create_transcripts_page')
419 - );
152 + // Submenu page for Knowledge
153 + add_submenu_page(
154 + 'mxchat-max',
155 + 'Prompts',
156 + 'Knowledge',
157 + 'manage_options',
158 + 'mxchat-prompts',
159 + array($this, 'mxchat_create_prompts_page')
160 + );
420 161
421 - add_submenu_page(
422 - 'mxchat-max',
423 - esc_html__('MxChat Actions', 'mxchat'),
424 - esc_html__('Actions', 'mxchat'),
425 - 'manage_options',
426 - 'mxchat-actions',
427 - array($this, 'mxchat_actions_page_html')
428 - );
162 + // Submenu page for Chat Transcripts
163 + add_submenu_page(
164 + 'mxchat-max', // Corrected parent slug to match the main menu
165 + 'Chat Transcripts',
166 + 'Transcripts',
167 + 'manage_options',
168 + 'mxchat-transcripts',
169 + array($this, 'mxchat_create_transcripts_page') // Prefixed function name with mxchat_
170 + );
429 171
430 - // Content Generator page
172 + // Submenu page for Intents
431 173 add_submenu_page(
432 - 'mxchat-max',
433 - esc_html__('Content', 'mxchat'),
434 - esc_html__('Content', 'mxchat'),
435 - 'manage_options',
436 - 'mxchat-content',
437 - array($this, 'mxchat_create_content_page')
174 + 'mxchat-max', // Parent slug
175 + 'MxChat Intents', // Page title
176 + 'Intents', // Menu title
177 + 'manage_options', // Capability
178 + 'mxchat-intents', // Menu slug
179 + array($this, 'mxchat_intents_page_html') // Callback function
438 180 );
439 181
440 -}
182 + // Submenu page for Activation Key
183 + add_submenu_page(
184 + 'mxchat-max',
185 + 'Pro Upgrade',
186 + 'Pro Upgrade',
187 + 'manage_options',
188 + 'mxchat-activation',
189 + array($this, 'mxchat_create_activation_page')
190 + );
441 191
442 -/**
443 - * Register the Pro & Extensions submenu on a later admin_menu priority so it
444 - * always renders as the bottom-most item in the MxChat sidebar — below
445 - * configuration pages like API Access (priority 20).
446 - */
447 -public function mxchat_add_pro_extensions_page() {
448 - add_submenu_page(
449 - 'mxchat-max',
450 - esc_html__('Pro & Extensions', 'mxchat'),
451 - esc_html__('Pro & Extensions', 'mxchat'),
452 - 'manage_options',
453 - 'mxchat-activation',
454 - array($this, 'mxchat_create_activation_page')
455 - );
456 -}
457 192
458 -public function mxchat_create_addons_page() {
459 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
460 - $addons_page = new MxChat_Addons();
461 - $addons_page->render_page();
462 193 }
463 194
464 -/**
465 - * Render the Content Generator admin page
466 - */
467 -public function mxchat_create_content_page() {
468 - require_once plugin_dir_path(__FILE__) . 'admin-content-page.php';
469 - mxchat_render_content_page($this);
470 -}
195 +public function mxchat_save_setting_callback() {
196 + check_ajax_referer('mxchat_save_setting_nonce');
471 197
472 -/**
473 - * Test actual streaming functionality in the WordPress environment
474 - */
475 -public function mxchat_handle_test_streaming_actual() {
476 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
198 + if (!current_user_can('manage_options')) {
199 + wp_send_json_error(['message' => 'Unauthorized']);
200 + }
477 201
478 - // Check if headers have already been sent
479 - if (headers_sent()) {
480 - wp_send_json_error(['message' => 'Headers already sent - streaming not possible']);
481 - return;
482 - }
202 + $name = isset($_POST['name']) ? $_POST['name'] : '';
203 + // Strip slashes from the value before saving
204 + $value = isset($_POST['value']) ? stripslashes($_POST['value']) : '';
483 205
484 - // Check for required functions
485 - if (!function_exists('curl_init')) {
486 - wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']);
487 - return;
488 - }
206 + if (empty($name)) {
207 + wp_send_json_error(['message' => 'Invalid field name']);
208 + }
489 209
490 - // Get user's selected model and API key
491 - $options = get_option('mxchat_options', []);
492 - $selected_model = $options['model'] ?? 'gpt-5.1-chat-latest';
210 + // Load the full options array
211 + $options = get_option('mxchat_options', []);
493 212
494 - // Get the provider from the model
495 - $model_parts = explode('-', $selected_model);
496 - $provider = strtolower($model_parts[0]);
213 + // Handle special cases
214 + switch ($name) {
215 + case 'additional_popular_questions':
216 + $questions = json_decode($value, true); // No need for stripslashes here
217 + if (is_array($questions)) {
218 + $options[$name] = $questions;
219 + // Also update old option for backwards compatibility
220 + update_option('additional_popular_questions', $questions);
221 + }
222 + break;
497 223
498 - // Get the appropriate API key
499 - $api_key = '';
500 - switch ($provider) {
501 - case 'gpt':
502 - case 'o1':
503 - $api_key = $options['api_key'] ?? '';
504 - break;
505 - case 'claude':
506 - $api_key = $options['claude_api_key'] ?? '';
507 - break;
508 - case 'grok':
509 - $api_key = $options['xai_api_key'] ?? '';
510 - break;
511 - case 'deepseek':
512 - $api_key = $options['deepseek_api_key'] ?? '';
513 - break;
514 - case 'gemini':
515 - $api_key = $options['gemini_api_key'] ?? '';
516 - break;
517 - default:
518 - // Default to OpenAI for unknown models
519 - $api_key = $options['api_key'] ?? '';
520 - $provider = 'gpt';
521 - break;
522 - }
224 + case 'close_button_color':
225 + case 'user_message_bg_color':
226 + case 'user_message_font_color':
227 + case 'bot_message_bg_color':
228 + case 'bot_message_font_color':
229 + case 'top_bar_bg_color':
230 + case 'send_button_font_color':
231 + case 'chatbot_background_color':
232 + case 'icon_color':
233 + case 'chat_input_font_color':
234 + case 'live_agent_message_bg_color':
235 + case 'live_agent_message_font_color':
236 + case 'mode_indicator_bg_color':
523 237
524 - if (empty($api_key)) {
525 - wp_send_json_error(['message' => "API key not configured for {$provider} provider"]);
526 - return;
527 - }
238 + case 'mode_indicator_font_color':
239 + case 'toolbar_icon_color':
240 + // Store color values directly
241 + $options[$name] = $value;
242 + break;
243 +case 'live_agent_status':
244 + // Set the new value
245 + $options[$name] = ($value === 'on') ? 'on' : 'off';
246 + break;
528 247
529 - // Test streaming with the selected model and provider
530 - try {
531 - $this->perform_streaming_test($provider, $selected_model, $api_key);
532 - } catch (Exception $e) {
533 - wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]);
534 - }
535 -}
248 + case 'enable_woocommerce_integration':
249 + // Handle values that used to be 1/0
250 + $options[$name] = ($value === 'on' || $value === '1') ? 'on' : 'off';
251 + break;
536 252
537 -/**
538 - * Perform the actual streaming test
539 - */
540 -private function perform_streaming_test($provider, $model, $api_key) {
541 - // Set streaming headers
542 - header('Content-Type: text/event-stream');
543 - header('Cache-Control: no-cache');
544 - header('X-Accel-Buffering: no'); // Disable nginx buffering
545 -
546 - // Prepare test message
547 - $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing.";
548 -
549 - // Configure API request based on provider
550 - $url = '';
551 - $headers = [];
552 - $body = [];
553 -
554 - switch ($provider) {
555 - case 'gpt':
556 - case 'o1':
557 - $url = 'https://api.openai.com/v1/chat/completions';
558 - $headers = [
559 - 'Content-Type: application/json',
560 - 'Authorization: Bearer ' . $api_key
561 - ];
562 - $body = [
563 - 'model' => $model,
564 - 'messages' => [['role' => 'user', 'content' => $test_message]],
565 - 'max_tokens' => 50,
566 - 'temperature' => 0.3,
567 - 'stream' => true
568 - ];
569 - break;
570 -
571 - case 'claude':
572 - $url = 'https://api.anthropic.com/v1/messages';
573 - $headers = [
574 - 'Content-Type: application/json',
575 - 'x-api-key: ' . $api_key,
576 - 'anthropic-version: 2023-06-01'
577 - ];
578 - $body = [
579 - 'model' => $model,
580 - 'messages' => [['role' => 'user', 'content' => $test_message]],
581 - 'max_tokens' => 50,
582 - 'temperature' => 0.3,
583 - 'stream' => true
584 - ];
585 - break;
586 -
587 - case 'grok':
588 - $url = 'https://api.x.ai/v1/chat/completions';
589 - $headers = [
590 - 'Content-Type: application/json',
591 - 'Authorization: Bearer ' . $api_key
592 - ];
593 - $body = [
594 - 'model' => $model,
595 - 'messages' => [['role' => 'user', 'content' => $test_message]],
596 - 'max_tokens' => 50,
597 - 'temperature' => 0.3,
598 - 'stream' => true
599 - ];
600 - break;
601 -
602 - case 'deepseek':
603 - $url = 'https://api.deepseek.com/v1/chat/completions';
604 - $headers = [
605 - 'Content-Type: application/json',
606 - 'Authorization: Bearer ' . $api_key
607 - ];
608 - $body = [
609 - 'model' => $model,
610 - 'messages' => [['role' => 'user', 'content' => $test_message]],
611 - 'max_tokens' => 50,
612 - 'temperature' => 0.3,
613 - 'stream' => true
614 - ];
615 - break;
616 -
617 - default:
618 - echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n";
619 - flush();
620 - return;
621 - }
622 -
623 - // Initialize cURL
624 - $ch = curl_init();
625 - curl_setopt($ch, CURLOPT_URL, $url);
626 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
627 - curl_setopt($ch, CURLOPT_POST, true);
628 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
629 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
630 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
631 - curl_setopt($ch, CURLOPT_TIMEOUT, 30);
632 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) {
633 - return $this->process_streaming_test_data($data, $provider);
634 - });
635 -
636 - // Send initial test message
637 - echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n";
638 - flush();
639 -
640 - $result = curl_exec($ch);
641 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
642 - $curl_error = curl_error($ch);
643 - curl_close($ch);
644 -
645 - if ($curl_error) {
646 - echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n";
647 - flush();
648 - return;
649 - }
650 -
651 - if ($http_code !== 200) {
652 - echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n";
653 - flush();
654 - return;
655 - }
656 -
657 - // Send completion signal
658 - echo "data: [DONE]\n\n";
659 - flush();
660 -}
661 -
662 -/**
663 - * Process streaming data for the test
664 - */
665 -private function process_streaming_test_data($data, $provider) {
666 - static $chunk_count = 0;
667 -
668 - $lines = explode("\n", $data);
669 -
670 - foreach ($lines as $line) {
671 - if (trim($line) === '') {
672 - continue;
673 - }
674 -
675 - // Handle different provider formats
676 - if ($provider === 'claude') {
677 - // Claude uses event: and data: format
678 - if (strpos($line, 'data: ') === 0) {
679 - $json_str = substr($line, 6);
680 - $json = json_decode($json_str, true);
681 -
682 - if (isset($json['type']) && $json['type'] === 'content_block_delta') {
683 - if (isset($json['delta']['text'])) {
684 - $chunk_count++;
685 - echo "data: " . json_encode([
686 - 'content' => $json['delta']['text'],
687 - 'test_chunk' => $chunk_count
688 - ]) . "\n\n";
689 - flush();
690 - }
691 - }
692 - }
693 - } else {
694 - // OpenAI, X.AI, DeepSeek format
695 - if (strpos($line, 'data: ') === 0) {
696 - $json_str = substr($line, 6);
697 -
698 - if ($json_str === '[DONE]') {
699 - // Don't echo [DONE] here, let the main function handle it
700 - continue;
701 - }
702 -
703 - $json = json_decode($json_str, true);
704 - if (isset($json['choices'][0]['delta']['content'])) {
705 - $chunk_count++;
706 - echo "data: " . json_encode([
707 - 'content' => $json['choices'][0]['delta']['content'],
708 - 'test_chunk' => $chunk_count
709 - ]) . "\n\n";
710 - flush();
711 - }
712 - }
713 - }
714 - }
715 -
716 - return strlen($data);
717 -}
718 -
719 -/**
720 - * Updated version of your existing test method (keep this as a fallback)
721 - */
722 -public function mxchat_handle_test_streaming() {
723 - check_ajax_referer('mxchat_test_streaming_nonce', 'nonce');
724 -
725 - // Use the actual streaming test instead
726 - $this->mxchat_handle_test_streaming_actual();
727 -}
728 -
729 -
730 -public function register_pinecone_settings() {
731 - register_setting(
732 - 'mxchat_pinecone_addon_options',
733 - 'mxchat_pinecone_addon_options',
734 - array(
735 - 'type' => 'array',
736 - 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'),
737 - 'default' => array(
738 - 'mxchat_use_pinecone' => '0',
739 - 'mxchat_pinecone_api_key' => '',
740 - 'mxchat_pinecone_host' => '',
741 - 'mxchat_pinecone_index' => '',
742 - 'mxchat_pinecone_environment' => ''
743 - )
744 - )
745 - );
746 -}
747 -
748 -public function sanitize_pinecone_settings($input) {
749 - $sanitized = array();
750 -
751 - $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0';
752 - $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
753 - $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
754 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
755 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
756 -
757 - // Remove https:// from host if present
758 - $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']);
759 -
760 - return $sanitized;
761 -}
762 -
763 -public function register_openai_vectorstore_settings() {
764 - register_setting(
765 - 'mxchat_openai_vectorstore_options',
766 - 'mxchat_openai_vectorstore_options',
767 - array(
768 - 'type' => 'array',
769 - 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'),
770 - 'default' => array(
771 - 'mxchat_use_openai_vectorstore' => '0',
772 - 'mxchat_vectorstore_ids' => '',
773 - 'mxchat_vectorstore_max_results' => 5
774 - )
775 - )
776 - );
777 -}
778 -
779 -public function sanitize_openai_vectorstore_settings($input) {
780 - $sanitized = array();
781 -
782 - $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0';
783 - $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? '');
784 - $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5);
785 -
786 - // Ensure max results is within reasonable range
787 - if ($sanitized['mxchat_vectorstore_max_results'] < 1) {
788 - $sanitized['mxchat_vectorstore_max_results'] = 1;
789 - }
790 - if ($sanitized['mxchat_vectorstore_max_results'] > 20) {
791 - $sanitized['mxchat_vectorstore_max_results'] = 20;
792 - }
793 -
794 - return $sanitized;
795 -}
796 -
797 -/**
798 - * AJAX handler to test OpenAI Vector Store connection
799 - */
800 -public function mxchat_test_vectorstore_connection() {
801 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
802 -
803 - if (!current_user_can('manage_options')) {
804 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
805 - return;
806 - }
807 -
808 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
809 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
810 - $mxchat_options = get_option('mxchat_options', array());
811 - $api_key = $mxchat_options['api_key'] ?? '';
812 -
813 - if (empty($api_key)) {
814 - wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat')));
815 - return;
816 - }
817 -
818 - if (empty($vectorstore_ids)) {
819 - wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat')));
820 - return;
821 - }
822 -
823 - // Get the first Vector Store ID for testing
824 - $ids_array = array_map('trim', explode(',', $vectorstore_ids));
825 - $test_id = $ids_array[0];
826 -
827 - // Test by retrieving the Vector Store info
828 - $response = wp_remote_get(
829 - 'https://api.openai.com/v1/vector_stores/' . $test_id,
830 - array(
831 - 'headers' => array(
832 - 'Authorization' => 'Bearer ' . $api_key,
833 - 'Content-Type' => 'application/json',
834 - 'OpenAI-Beta' => 'assistants=v2'
835 - ),
836 - 'timeout' => 30
837 - )
838 - );
839 -
840 - if (is_wp_error($response)) {
841 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message()));
842 - return;
843 - }
844 -
845 - $status_code = wp_remote_retrieve_response_code($response);
846 - $body = json_decode(wp_remote_retrieve_body($response), true);
847 -
848 - if ($status_code === 200 && isset($body['id'])) {
849 - $file_count = $body['file_counts']['completed'] ?? 0;
850 - $name = $body['name'] ?? $test_id;
851 - wp_send_json_success(array(
852 - 'message' => sprintf(
853 - __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'),
854 - esc_html($name),
855 - $file_count
856 - )
857 - ));
858 - } elseif ($status_code === 404) {
859 - wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat')));
860 - } elseif ($status_code === 401) {
861 - wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat')));
253 + default:
254 + // Handle toggles
255 + if (strpos($name, 'toggle') !== false || in_array($name, [
256 + 'chat_persistence_toggle',
257 + 'privacy_toggle',
258 + 'complianz_toggle',
259 + 'chat_toolbar_toggle' // Removed live_agent_status from here
260 + ])) {
261 + $options[$name] = ($value === 'on') ? 'on' : 'off';
862 262 } else {
863 - $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat');
864 - wp_send_json_error(array('message' => $error_message));
263 + // Store all other values directly
264 + $options[$name] = $value;
865 265 }
866 -}
266 + break;
267 + }
867 268
868 -/**
869 - * AJAX handler to test Slack connection and validate scopes
870 - */
871 -public function mxchat_test_slack_connection() {
872 - check_ajax_referer('mxchat_admin_nonce', 'nonce');
269 + // Save all updates
270 + $updated = update_option('mxchat_options', $options);
873 271
874 - if (!current_user_can('manage_options')) {
875 - wp_send_json_error(array('message' => __('Permission denied.', 'mxchat')));
876 - return;
877 - }
272 + // Handle backwards compatibility for certain fields
273 + $legacy_fields = ['brave_api_key', 'brave_image_count', 'brave_safe_search', 'brave_news_count',
274 + 'brave_country', 'brave_language', 'similarity_threshold'];
878 275
879 - $bot_token = $this->options['live_agent_bot_token'] ?? '';
276 + if (in_array($name, $legacy_fields)) {
277 + // Also update the individual option for backwards compatibility
278 + update_option($name, $value);
279 + }
880 280
881 - if (empty($bot_token)) {
882 - wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat')));
883 - return;
884 - }
885 -
886 - // Test 1: Validate bot token with auth.test
887 - $auth_response = wp_remote_post('https://slack.com/api/auth.test', array(
888 - 'headers' => array(
889 - 'Authorization' => 'Bearer ' . $bot_token,
890 - 'Content-Type' => 'application/json'
891 - ),
892 - 'timeout' => 15
893 - ));
894 -
895 - if (is_wp_error($auth_response)) {
896 - wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message()));
897 - return;
898 - }
899 -
900 - $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true);
901 -
902 - if (!isset($auth_body['ok']) || !$auth_body['ok']) {
903 - $error = $auth_body['error'] ?? 'unknown_error';
904 - $error_messages = array(
905 - 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'),
906 - 'not_authed' => __('No authentication token provided.', 'mxchat'),
907 - 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'),
908 - 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'),
909 - );
910 - $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error);
911 - wp_send_json_error(array('message' => $message));
912 - return;
913 - }
914 -
915 - $team_name = $auth_body['team'] ?? 'Unknown Workspace';
916 - $bot_name = $auth_body['user'] ?? 'Unknown Bot';
917 -
918 - // Test 2: Check if we can list channels (tests channels:read scope)
919 - $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array(
920 - 'headers' => array(
921 - 'Authorization' => 'Bearer ' . $bot_token,
922 - 'Content-Type' => 'application/json'
923 - ),
924 - 'body' => json_encode(array('limit' => 1)),
925 - 'timeout' => 15
926 - ));
927 -
928 - $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true);
929 - $can_read_channels = isset($channels_body['ok']) && $channels_body['ok'];
930 -
931 - // Test 3: Check if we can create channels (tests channels:manage scope)
932 - // We'll just check the error message without actually creating
933 - $create_response = wp_remote_post('https://slack.com/api/conversations.create', array(
934 - 'headers' => array(
935 - 'Authorization' => 'Bearer ' . $bot_token,
936 - 'Content-Type' => 'application/json'
937 - ),
938 - 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)),
939 - 'timeout' => 15
940 - ));
941 -
942 - $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
943 -
944 - // If channel was created, delete it immediately
945 - if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) {
946 - wp_remote_post('https://slack.com/api/conversations.archive', array(
947 - 'headers' => array(
948 - 'Authorization' => 'Bearer ' . $bot_token,
949 - 'Content-Type' => 'application/json'
950 - ),
951 - 'body' => json_encode(array('channel' => $create_body['channel']['id'])),
952 - 'timeout' => 15
953 - ));
954 - $can_create_channels = true;
955 - } else {
956 - $create_error = $create_body['error'] ?? '';
957 - // name_taken means we have permission but channel exists
958 - $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok']));
959 -
960 - // Check for missing scope errors
961 - if ($create_error === 'missing_scope') {
962 - $can_create_channels = false;
963 - }
964 - }
965 -
966 - // Build result message
967 - $results = array();
968 - $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name));
969 - $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name));
970 - $results[] = '';
971 - $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat');
972 - $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat');
973 -
974 - $missing_scopes = array();
975 - if (!$can_read_channels) $missing_scopes[] = 'channels:read';
976 - if (!$can_create_channels) $missing_scopes[] = 'channels:manage';
977 -
978 - if (!empty($missing_scopes)) {
979 - wp_send_json_error(array(
980 - 'message' => implode("\n", $results),
981 - 'missing_scopes' => $missing_scopes,
982 - 'partial' => true
983 - ));
984 - } else {
985 - wp_send_json_success(array(
986 - 'message' => implode("\n", $results)
987 - ));
988 - }
281 + if ($updated) {
282 + wp_send_json_success(['message' => 'Setting saved']);
283 + } else {
284 + wp_send_json_error(['message' => 'Update failed or no changes']);
285 + }
989 286 }
990 287
991 288 public function mxchat_display_admin_notice() {
992 289 // Success notice
@@ -993,9 +290,9 @@
993 290 if ($message = get_transient('mxchat_admin_notice_success')) {
994 291 ?>
995 292 <div class="notice notice-success is-dismissible">
996 293 <p><?php echo esc_html($message); ?></p>
997 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
294 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
998 295 </div>
999 296 <?php
1000 297 delete_transient('mxchat_admin_notice_success'); // Clear the transient after displaying
1001 298 }
@@ -1004,9 +301,9 @@
1004 301 if ($message = get_transient('mxchat_admin_notice_error')) {
1005 302 ?>
1006 303 <div class="notice notice-error is-dismissible">
1007 304 <p><?php echo esc_html($message); ?></p>
1008 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'mxchat'); ?></span></button>
305 + <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
1009 306 </div>
1010 307 <?php
1011 308 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1012 309 }
@@ -1011,4870 +308,2143 @@
1011 308 delete_transient('mxchat_admin_notice_error'); // Clear the transient after displaying
1012 309 }
1013 310 }
1014 311
1015 -public function show_live_agent_disabled_banner() {
1016 - $show_disabled_notice = get_option('mxchat_show_live_agent_disabled_notice', false);
1017 312
1018 - if ($show_disabled_notice) {
1019 - ?>
1020 - <div class="mxchat-live-agent-disabled-notice" id="mxchat-disabled-notice">
1021 - <div class="mxchat-pro-notification">
1022 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissLiveAgentNotice()" aria-label="Dismiss notification">
1023 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1024 - <line x1="18" y1="6" x2="6" y2="18"></line>
1025 - <line x1="6" y1="6" x2="18" y2="18"></line>
1026 - </svg>
1027 - </button>
1028 - <div class="mxchat-live-agent-content">
1029 - <h3>🔧 Live Agent Integration Updated!</h3>
1030 - <p>We've temporarily disabled your Live Agent integration due to recent enhancements that have made it much better! You can easily turn it back on by going to <strong>Toolbar & Components → Live Agent Settings</strong> and reviewing the new configuration options.</p>
1031 - </div>
1032 - </div>
1033 - </div>
1034 - <?php
1035 - }
1036 -}
1037 -public function mxchat_create_admin_page() {
1038 - $this->add_live_agent_nonce();
1039 - $this->add_theme_migration_nonce();
1040 313
1041 - // Include and render the new sidebar-based settings page
1042 - require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php';
1043 - mxchat_render_settings_page($this);
1044 -}
1045 314
1046 -public function dismiss_live_agent_notice() {
1047 - // Add debugging
1048 - //error_log('dismiss_live_agent_notice called');
1049 - //error_log('POST data: ' . print_r($_POST, true));
1050 315
1051 - // Verify nonce
1052 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_live_agent_notice')) {
1053 - //error_log('Nonce verification failed');
1054 - wp_die('Security check failed');
1055 - }
316 +public function mxchat_create_admin_page() {
317 + ?>
318 + <div class="wrap mxchat-admin">
319 + <?php if (!$this->is_activated): ?>
320 + <div class="mxchat-pro-banner">
321 + <p>
322 + For a limited time, get lifetime access and save $20 on MxChat Pro!
323 + <a href="https://mxchat.ai/" target="_blank">Upgrade to Pro today</a>
324 + </p>
325 + </div>
326 + <?php endif; ?>
1056 327
1057 - // Remove the notice flag
1058 - $deleted = delete_option('mxchat_show_live_agent_disabled_notice');
1059 - //error_log('Option deleted: ' . ($deleted ? 'yes' : 'no'));
328 + <div class="mxchat-agents-banner">
329 + <p>
330 + Pro users get exclusive access to <a href="https://mxchat.ai/agents/" target="_blank">MxChat AI Agents</a> – our groundbreaking platform to test, refine, and deploy your chatbot with confidence. Take your AI assistant to the next level!
331 + </p>
332 + </div>
1060 333
1061 - wp_send_json_success();
1062 -}
1063 -public function add_live_agent_nonce() {
1064 - if (get_option('mxchat_show_live_agent_disabled_notice', false)) {
1065 - // Make sure your admin script is enqueued and localize the data
1066 - wp_localize_script('mxchat-admin-js', 'mxchatLiveAgent', array(
1067 - 'nonce' => wp_create_nonce('dismiss_live_agent_notice'),
1068 - 'ajaxurl' => admin_url('admin-ajax.php')
1069 - ));
1070 - }
1071 -}
334 + <h2 class="mxchat-nav-tab-wrapper">
335 + <a href="#chatbot" class="mxchat-nav-tab mxchat-nav-tab-active" data-tab="chatbot">Chatbot</a>
336 + <a href="#embed" class="mxchat-nav-tab" data-tab="embed">Integrations</a>
337 + <a href="#theme" class="mxchat-nav-tab" data-tab="theme">Theme</a>
338 + <a href="#general" class="mxchat-nav-tab" data-tab="general">FAQ</a>
339 + </h2>
1072 340
1073 -/**
1074 - * Show theme migration notice for Pro users with AI-generated themes
1075 - * Only shown once - dismissible and stored in options
1076 - */
1077 -public function show_theme_migration_banner() {
1078 - // Only show if Pro is activated
1079 - if (!$this->is_activated) {
1080 - return;
1081 - }
1082 -
1083 - // Check if notice should be shown
1084 - $show_notice = get_option('mxchat_show_theme_migration_notice', false);
1085 -
1086 - if ($show_notice) {
1087 - ?>
1088 - <div class="mxchat-theme-migration-notice" id="mxchat-theme-migration-notice">
1089 - <div class="mxchat-pro-notification">
1090 - <button type="button" class="mxchat-dismiss-btn" onclick="dismissThemeMigrationNotice()" aria-label="Dismiss notification">
1091 - <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1092 - <line x1="18" y1="6" x2="6" y2="18"></line>
1093 - <line x1="6" y1="6" x2="18" y2="18"></line>
1094 - </svg>
1095 - </button>
1096 - <div class="mxchat-theme-migration-content">
1097 - <h3>🎨 AI Theme Migration Required</h3>
1098 - <p>If you're using an AI-generated chatbot theme, you'll need to migrate it to match the new CSS structure. Go to <strong>Theme Settings</strong>, select your theme from the sidebar, and click the <strong>Migrate</strong> button.</p>
1099 - </div>
341 + <div id="chatbot" class="mxchat-tab-content active">
342 + <div class="mxchat-autosave-section">
343 + <?php do_settings_sections('mxchat-chatbot'); ?>
1100 344 </div>
1101 345 </div>
1102 - <?php
1103 - }
1104 -}
1105 346
1106 -/**
1107 - * Dismiss theme migration notice via AJAX
1108 - */
1109 -public function dismiss_theme_migration_notice() {
1110 - // Verify nonce
1111 - if (!wp_verify_nonce($_POST['nonce'], 'dismiss_theme_migration_notice')) {
1112 - wp_die('Security check failed');
1113 - }
347 + <div id="embed" class="mxchat-tab-content">
348 + <div class="mxchat-autosave-section">
349 + <div class="mxchat-settings-section">
350 + <h2>WooCommerce Settings</h2>
351 + <table class="form-table">
352 + <?php do_settings_fields('mxchat-embed', 'mxchat_woocommerce_section'); ?>
353 + </table>
354 + </div>
355 + <div class="section-divider"></div>
1114 356
1115 - // Remove the notice flag
1116 - delete_option('mxchat_show_theme_migration_notice');
357 + <div class="mxchat-settings-section">
358 + <h2>Loops Settings</h2>
359 + <table class="form-table">
360 + <?php do_settings_fields('mxchat-embed', 'mxchat_loops_section'); ?>
361 + </table>
362 + </div>
1117 363
1118 - wp_send_json_success();
1119 -}
364 + <div class="section-divider"></div>
1120 365
1121 -/**
1122 - * Add nonce for theme migration notice dismiss
1123 - */
1124 -public function add_theme_migration_nonce() {
1125 - if (get_option('mxchat_show_theme_migration_notice', false) && $this->is_activated) {
1126 - wp_localize_script('mxchat-admin-js', 'mxchatThemeMigration', array(
1127 - 'nonce' => wp_create_nonce('dismiss_theme_migration_notice'),
1128 - 'ajaxurl' => admin_url('admin-ajax.php')
1129 - ));
1130 - }
1131 -}
366 + <div class="mxchat-settings-section">
367 + <h2>Brave Search Settings</h2>
368 + <table class="form-table">
369 + <?php do_settings_fields('mxchat-embed', 'mxchat_brave_section'); ?>
370 + </table>
371 + </div>
1132 372
1133 -public function mxchat_create_transcripts_page() {
1134 - global $wpdb;
1135 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
373 + <div class="section-divider"></div>
1136 374
1137 - // Get basic stats
1138 - $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name") ?: 0;
1139 - $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name") ?: 0;
375 + <div class="mxchat-settings-section">
376 + <h2>Toolbar Settings & Intents</h2>
377 + <table class="form-table">
378 + <?php do_settings_fields('mxchat-embed', 'mxchat_pdf_intent_section'); ?>
379 + </table>
380 + </div>
1140 381
1141 - // Count unique users with detailed breakdown
1142 - $total_users = $wpdb->get_var("
1143 - SELECT COUNT(DISTINCT
1144 - CASE
1145 - WHEN user_email != '' AND user_email IS NOT NULL THEN user_email
1146 - WHEN user_id != 0 THEN CONCAT('user_', user_id)
1147 - WHEN user_identifier NOT LIKE 'Tech-Savvy User'
1148 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1149 - AND user_identifier NOT LIKE 'Language Learner'
1150 - AND user_identifier NOT LIKE 'Casual Browser'
1151 - AND user_identifier NOT LIKE 'Policy Enforcer'
1152 - AND user_identifier NOT LIKE 'Researcher'
1153 - AND user_identifier NOT LIKE 'Loyalty Member'
1154 - AND user_identifier NOT LIKE 'Gift Buyer'
1155 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1156 - THEN user_identifier
1157 - ELSE session_id
1158 - END
1159 - )
1160 - FROM $table_name
1161 - WHERE role != 'assistant'
1162 - ");
382 + <div class="section-divider"></div>
1163 383
1164 - // Get user type breakdown
1165 - $registered_users = $wpdb->get_var("
1166 - SELECT COUNT(DISTINCT user_email)
1167 - FROM $table_name
1168 - WHERE user_email != '' AND user_email IS NOT NULL
1169 - ");
1170 384
1171 - $guest_users = $wpdb->get_var("
1172 - SELECT COUNT(DISTINCT user_identifier)
1173 - FROM $table_name
1174 - WHERE (user_email = '' OR user_email IS NULL)
1175 - AND role != 'assistant'
1176 - AND user_identifier NOT LIKE 'Tech-Savvy User'
1177 - AND user_identifier NOT LIKE 'Detail-Oriented User'
1178 - AND user_identifier NOT LIKE 'Language Learner'
1179 - AND user_identifier NOT LIKE 'Casual Browser'
1180 - AND user_identifier NOT LIKE 'Policy Enforcer'
1181 - AND user_identifier NOT LIKE 'Researcher'
1182 - AND user_identifier NOT LIKE 'Loyalty Member'
1183 - AND user_identifier NOT LIKE 'Gift Buyer'
1184 - AND user_identifier NOT LIKE 'Parent or Caregiver'
1185 - ");
385 + <!-- Live Agent Settings Section -->
386 + <div class="mxchat-settings-section">
387 + <h2>Live Agent Settings</h2>
388 + <p>Visit our <a href="https://mxchat.ai/documentation/#slack_integration" target="_blank">documentation page</a> to set up live agent transfer via Slack.</p>
389 + <table class="form-table">
390 + <?php do_settings_fields('mxchat-embed', 'mxchat_live_agent_section'); ?>
391 + </table>
392 + </div>
393 + </div>
394 + </div>
1186 395
1187 - // Get agent test messages count
1188 - $agent_tests = $wpdb->get_var("
1189 - SELECT COUNT(DISTINCT session_id)
1190 - FROM $table_name
1191 - WHERE user_identifier IN (
1192 - 'Tech-Savvy User',
1193 - 'Detail-Oriented User',
1194 - 'Language Learner',
1195 - 'Casual Browser',
1196 - 'Policy Enforcer',
1197 - 'Researcher',
1198 - 'Loyalty Member',
1199 - 'Gift Buyer',
1200 - 'Parent or Caregiver'
1201 - )
1202 - ");
1203 - // Get activity metrics
1204 - $today_chats = $wpdb->get_var("
1205 - SELECT COUNT(DISTINCT session_id)
1206 - FROM $table_name
1207 - WHERE DATE(timestamp) = CURDATE()
1208 - ");
1209 -
1210 - $week_chats = $wpdb->get_var("
1211 - SELECT COUNT(DISTINCT session_id)
1212 - FROM $table_name
1213 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1214 - ");
1215 -
1216 - $month_chats = $wpdb->get_var("
1217 - SELECT COUNT(DISTINCT session_id)
1218 - FROM $table_name
1219 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 30 DAY)
1220 - ");
1221 -
1222 - // Get daily chat data for last 7 days
1223 - $daily_stats = $wpdb->get_results("
1224 - SELECT
1225 - DATE(timestamp) as date,
1226 - COUNT(DISTINCT session_id) as chats,
1227 - COUNT(*) as messages
1228 - FROM $table_name
1229 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1230 - GROUP BY DATE(timestamp)
1231 - ORDER BY date ASC
1232 - ");
1233 -
1234 - // Get average messages per chat
1235 - $avg_messages = $wpdb->get_var("
1236 - SELECT AVG(message_count)
1237 - FROM (
1238 - SELECT session_id, COUNT(*) as message_count
1239 - FROM $table_name
1240 - GROUP BY session_id
1241 - ) as chat_counts
1242 - ");
1243 - $avg_messages = $avg_messages ? round($avg_messages, 1) : 0;
1244 -
1245 - // Get busiest hour
1246 - $busiest_hour = $wpdb->get_row("
1247 - SELECT HOUR(timestamp) as hour, COUNT(DISTINCT session_id) as chat_count
1248 - FROM $table_name
1249 - GROUP BY HOUR(timestamp)
1250 - ORDER BY chat_count DESC
1251 - LIMIT 1
1252 - ");
1253 -
1254 - // Prepare chart data
1255 - $chart_labels = array();
1256 - $chart_chats = array();
1257 - $chart_messages = array();
1258 -
1259 - // Fill last 7 days with data
1260 - for ($i = 6; $i >= 0; $i--) {
1261 - $date = date('Y-m-d', strtotime("-$i days"));
1262 - $day_name = date('D', strtotime("-$i days"));
1263 - $chart_labels[] = $day_name;
1264 -
1265 - $found = false;
1266 - foreach ($daily_stats as $stat) {
1267 - if ($stat->date === $date) {
1268 - $chart_chats[] = (int)$stat->chats;
1269 - $chart_messages[] = (int)$stat->messages;
1270 - $found = true;
1271 - break;
1272 - }
1273 - }
1274 - if (!$found) {
1275 - $chart_chats[] = 0;
1276 - $chart_messages[] = 0;
1277 - }
1278 - }
396 + <div id="theme" class="mxchat-tab-content">
397 + <div class="mxchat-autosave-section">
398 + <?php do_settings_sections('mxchat-theme'); ?>
399 + </div>
400 + </div>
1279 401
1280 - // Satisfaction rating rollup — last 30 days, grouped by bot (plan-a5b006).
1281 - $satisfaction_stats = $this->get_satisfaction_rating_stats(30);
402 +<div id="general" class="mxchat-tab-content">
403 + <?php do_settings_sections('mxchat-general'); ?>
404 +<p>
405 + If you’re having trouble with setup or getting the responses you need, we encourage you to review our
406 + <a href="https://mxchat.ai/documentation/" target="_blank" rel="noopener noreferrer">documentation</a> or
407 + <a href="https://wordpress.org/support/plugin/mxchat-basic/" target="_blank" rel="noopener noreferrer">create a support ticket</a>.
408 +</p>
409 +<p>
410 + If you like our plugin, please consider <a href="https://wordpress.org/plugins/mxchat-basic/#reviews" target="_blank" rel="noopener noreferrer">leaving us a review</a>.
411 +</p>
1282 412
1283 - // Prepare page data for the template
1284 - $page_data = array(
1285 - 'total_chats' => $total_chats,
1286 - 'total_messages' => $total_messages,
1287 - 'total_users' => $total_users,
1288 - 'registered_users' => $registered_users,
1289 - 'guest_users' => $guest_users,
1290 - 'agent_tests' => $agent_tests,
1291 - 'today_chats' => $today_chats,
1292 - 'week_chats' => $week_chats,
1293 - 'month_chats' => $month_chats,
1294 - 'avg_messages' => $avg_messages,
1295 - 'busiest_hour' => $busiest_hour,
1296 - 'chart_labels' => $chart_labels,
1297 - 'chart_chats' => $chart_chats,
1298 - 'chart_messages' => $chart_messages,
1299 - 'satisfaction_stats' => $satisfaction_stats,
1300 - );
413 +<div class="faq-item">
414 + <h3>How does the Claude API integration work?</h3>
415 + <p>
416 + The Claude API, provided by Anthropic, allows for intelligent, context-aware chatbot responses in MxChat. To use it, you will need both an OpenAI API key and a Claude API key. This is necessary because the system utilizes OpenAI for vector embedding in the Retrieval-Augmented Generation (RAG) process, as Claude does not currently offer an embedding API.
417 + </p>
418 + <p>
419 + When using the Claude API, your custom content is sent to Claude for generating responses, while the embeddings are processed through OpenAI. This ensures your chatbot provides accurate and engaging responses while maintaining knowledge relevant to your website.
420 + </p>
421 + <p>
422 + You can obtain your Claude API key by signing up on the <a href="https://www.anthropic.com/api" target="_blank" rel="noopener">Anthropic API page</a>.
423 + </p>
424 +</div>
1301 425
1302 - // Include and render the new template
1303 - require_once plugin_dir_path(__FILE__) . 'admin-transcripts-page.php';
1304 - mxchat_render_transcripts_page($this, $page_data);
1305 -}
1306 -
1307 -/**
1308 - * Per-bot satisfaction rating rollup over the last $days days. Used by the
1309 - * Satisfaction card on the Transcripts dashboard (plan-a5b006).
1310 - *
1311 - * @param int $days Window in days.
1312 - * @return array Each entry: ['bot_id', 'total', 'positive', 'negative', 'positive_pct', 'negative_pct'].
1313 - */
1314 -public function get_satisfaction_rating_stats($days = 30) {
1315 - global $wpdb;
1316 - $table = $wpdb->prefix . 'mxchat_session_ratings';
1317 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
1318 - return array();
1319 - }
1320 - $days = max(1, (int) $days);
1321 - $rows = $wpdb->get_results($wpdb->prepare(
1322 - "SELECT bot_id,
1323 - COUNT(*) AS total,
1324 - SUM(CASE WHEN rating_value = 1 THEN 1 ELSE 0 END) AS positive,
1325 - SUM(CASE WHEN rating_value = -1 THEN 1 ELSE 0 END) AS negative
1326 - FROM {$table}
1327 - WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
1328 - GROUP BY bot_id
1329 - ORDER BY total DESC",
1330 - $days
1331 - ));
1332 - $out = array();
1333 - foreach ((array) $rows as $row) {
1334 - $total = (int) $row->total;
1335 - $positive = (int) $row->positive;
1336 - $negative = (int) $row->negative;
1337 - $out[] = array(
1338 - 'bot_id' => $row->bot_id ?: 'default',
1339 - 'total' => $total,
1340 - 'positive' => $positive,
1341 - 'negative' => $negative,
1342 - 'positive_pct' => $total > 0 ? (int) round(($positive / $total) * 100) : 0,
1343 - 'negative_pct' => $total > 0 ? (int) round(($negative / $total) * 100) : 0,
1344 - );
1345 - }
1346 - return $out;
1347 -}
1348 -
1349 -/**
1350 - * Get chart data for transcripts page
1351 - * Used by both page render and script localization
1352 - *
1353 - * @return array Chart data with labels, chats, and messages arrays
1354 - */
1355 -private function get_transcripts_chart_data() {
1356 - global $wpdb;
1357 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1358 -
1359 - // Get daily chat data for last 7 days - same query as mxchat_transcripts_page()
1360 - $daily_stats = $wpdb->get_results("
1361 - SELECT
1362 - DATE(timestamp) as date,
1363 - COUNT(DISTINCT session_id) as chats,
1364 - COUNT(*) as messages
1365 - FROM $table_name
1366 - WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
1367 - GROUP BY DATE(timestamp)
1368 - ORDER BY date ASC
1369 - ");
1370 -
1371 - // Prepare chart data
1372 - $chart_labels = array();
1373 - $chart_chats = array();
1374 - $chart_messages = array();
1375 -
1376 - // Fill last 7 days with data - same logic as mxchat_transcripts_page()
1377 - for ($i = 6; $i >= 0; $i--) {
1378 - $date = date('Y-m-d', strtotime("-$i days"));
1379 - $day_name = date('D', strtotime("-$i days"));
1380 - $chart_labels[] = $day_name;
1381 -
1382 - $found = false;
1383 - if ($daily_stats) {
1384 - foreach ($daily_stats as $stat) {
1385 - if ($stat->date === $date) {
1386 - $chart_chats[] = (int)$stat->chats;
1387 - $chart_messages[] = (int)$stat->messages;
1388 - $found = true;
1389 - break;
1390 - }
1391 - }
1392 - }
1393 - if (!$found) {
1394 - $chart_chats[] = 0;
1395 - $chart_messages[] = 0;
1396 - }
1397 - }
1398 -
1399 - return array(
1400 - 'labels' => $chart_labels,
1401 - 'chats' => $chart_chats,
1402 - 'messages' => $chart_messages
1403 - );
1404 -}
1405 -
1406 -public function mxchat_transcripts_notification_section_callback() {
1407 - echo '<p>' . esc_html__('Configure email notifications for new chat transcripts. You will receive an email notification when a new chat session begins.', 'mxchat') . '</p>';
1408 -}
1409 -public function mxchat_enable_notifications_callback() {
1410 - $options = get_option('mxchat_transcripts_options', array());
1411 - $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0;
1412 - ?>
1413 - <label for="mxchat_enable_notifications">
1414 - <input type="checkbox" id="mxchat_enable_notifications"
1415 - name="mxchat_transcripts_options[mxchat_enable_notifications]"
1416 - value="1" <?php checked(1, $enabled); ?>>
1417 - <?php esc_html_e('Send email notification when a new chat session starts', 'mxchat'); ?>
1418 - </label>
1419 - <p class="description">
1420 - <?php esc_html_e('Enable this option to receive email notifications for new chat sessions.', 'mxchat'); ?>
426 +<div class="faq-item">
427 + <h3>How does the X.AI API integration work?</h3>
428 + <p>
429 + The X.AI API, released on 10.21.24, is currently in beta. To use it, you will need both an OpenAI API key and an X.AI API key. This is because OpenAI handles vector embeddings in the Retrieval-Augmented Generation (RAG) process, as X.AI does not yet provide an embedding API.
1421 430 </p>
1422 - <?php
1423 -}
1424 -public function mxchat_notification_email_callback() {
1425 - $options = get_option('mxchat_transcripts_options', array());
1426 - $email = isset($options['mxchat_notification_email']) ? $options['mxchat_notification_email'] : get_option('admin_email');
1427 - ?>
1428 - <input type="email" id="mxchat_notification_email"
1429 - name="mxchat_transcripts_options[mxchat_notification_email]"
1430 - value="<?php echo esc_attr($email); ?>"
1431 - class="regular-text">
1432 - <p class="description">
1433 - <?php esc_html_e('Enter the email address where notifications should be sent. Defaults to the admin email address.', 'mxchat'); ?>
431 + <p>
432 + Custom content is sent to the X.AI API for generating responses, while OpenAI processes the embeddings. This allows the chatbot to provide advanced responses while maintaining context from your website. You can get your X.AI API key from the <a href="https://docs.x.ai/docs" target="_blank" rel="noopener">X.AI API documentation</a>.
1434 433 </p>
1435 - <?php
1436 -}
434 +</div>
1437 435
1438 -public function mxchat_auto_delete_transcripts_callback() {
1439 - $options = get_option('mxchat_transcripts_options', array());
1440 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1441 - ?>
1442 - <select id="mxchat_auto_delete_transcripts"
1443 - name="mxchat_transcripts_options[mxchat_auto_delete_transcripts]">
1444 - <option value="never" <?php selected($interval, 'never'); ?>>
1445 - <?php esc_html_e('Never (Keep All Transcripts)', 'mxchat'); ?>
1446 - </option>
1447 - <option value="1week" <?php selected($interval, '1week'); ?>>
1448 - <?php esc_html_e('After 1 Week', 'mxchat'); ?>
1449 - </option>
1450 - <option value="2weeks" <?php selected($interval, '2weeks'); ?>>
1451 - <?php esc_html_e('After 2 Weeks', 'mxchat'); ?>
1452 - </option>
1453 - <option value="1month" <?php selected($interval, '1month'); ?>>
1454 - <?php esc_html_e('After 1 Month', 'mxchat'); ?>
1455 - </option>
1456 - </select>
1457 - <p class="description">
1458 - <?php esc_html_e('Automatically delete old chat transcripts after the selected time period. This helps manage database size and privacy.', 'mxchat'); ?>
436 +<div class="faq-item">
437 + <h3>Do I need an OpenAI API key to use the chatbot?</h3>
438 + <p>
439 + Yes, you will need an OpenAI API key to power the chatbot. You can obtain an API key by signing up on the <a href="https://platform.openai.com/signup" target="_blank" rel="noopener">OpenAI platform</a>. After signing up, you must add credits to your account—typically, $5 in credits is sufficient to get started.
1459 440 </p>
1460 - <?php
1461 -}
1462 -
1463 -/**
1464 - * Custom retention-days input. When > 0 it overrides the bucket dropdown above
1465 - * and deletes transcripts older than the given number of days. Set to 0 to fall
1466 - * back to the dropdown (or "Never" if the dropdown is also Never).
1467 - *
1468 - * Devs can override the final day count via the `mxchat_transcript_retention_days`
1469 - * filter — runs in `cleanup_old_transcripts()` after this option is read.
1470 - *
1471 - * (plan-mxchat-20260509-9b80b1)
1472 - */
1473 -public function mxchat_retention_days_callback() {
1474 - $options = get_option('mxchat_transcripts_options', array());
1475 - $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
1476 - ?>
1477 - <input type="number"
1478 - id="mxchat_retention_days"
1479 - name="mxchat_transcripts_options[mxchat_retention_days]"
1480 - value="<?php echo esc_attr($days); ?>"
1481 - min="0"
1482 - max="3650"
1483 - step="1"
1484 - style="width: 90px;" />
1485 - <p class="description">
1486 - <?php esc_html_e('Number of days to retain transcripts. When set to a value greater than 0, this overrides the dropdown above. Set to 0 to use the dropdown. Maximum 3650 (10 years). A daily wp-cron task removes anything older, cascading to translations and click-tracking rows.', 'mxchat'); ?>
1487 - <br>
1488 - <code>apply_filters( 'mxchat_transcript_retention_days', $days )</code>
1489 - <?php esc_html_e('lets developers override the final day count programmatically.', 'mxchat'); ?>
441 + <p>
442 + Once you have your API key, simply enter it in the chatbot's settings to enable functionality. The chatbot relies on OpenAI’s models for generating responses, so having sufficient credits in your OpenAI account is essential for smooth operation.
1490 443 </p>
1491 - <?php
1492 -}
444 +</div>
1493 445
1494 -public function mxchat_auto_email_transcript_callback() {
1495 - $options = get_option('mxchat_transcripts_options', array());
1496 - $enabled = isset($options['mxchat_auto_email_transcript_enabled']) ? $options['mxchat_auto_email_transcript_enabled'] : 0;
1497 - $delay = isset($options['mxchat_auto_email_transcript_delay']) ? $options['mxchat_auto_email_transcript_delay'] : '30';
1498 - $require_contact = isset($options['mxchat_auto_email_transcript_require_contact']) ? $options['mxchat_auto_email_transcript_require_contact'] : 0;
1499 - ?>
1500 - <label>
1501 - <input type="checkbox"
1502 - id="mxchat_auto_email_transcript_enabled"
1503 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_enabled]"
1504 - value="1"
1505 - <?php checked($enabled, 1); ?>>
1506 - <?php esc_html_e('Enable Auto-Email of Full Transcript', 'mxchat'); ?>
1507 - </label>
1508 - <br><br>
1509 - <label for="mxchat_auto_email_transcript_delay">
1510 - <?php esc_html_e('Send transcript after:', 'mxchat'); ?>
1511 - </label>
1512 - <select id="mxchat_auto_email_transcript_delay"
1513 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_delay]">
1514 - <option value="15" <?php selected($delay, '15'); ?>>
1515 - <?php esc_html_e('15 minutes', 'mxchat'); ?>
1516 - </option>
1517 - <option value="30" <?php selected($delay, '30'); ?>>
1518 - <?php esc_html_e('30 minutes', 'mxchat'); ?>
1519 - </option>
1520 - <option value="60" <?php selected($delay, '60'); ?>>
1521 - <?php esc_html_e('1 hour', 'mxchat'); ?>
1522 - </option>
1523 - </select>
1524 - <br><br>
1525 - <label>
1526 - <input type="checkbox"
1527 - id="mxchat_auto_email_transcript_require_contact"
1528 - name="mxchat_transcripts_options[mxchat_auto_email_transcript_require_contact]"
1529 - value="1"
1530 - <?php checked($require_contact, 1); ?>>
1531 - <?php esc_html_e('Only send if visitor provided contact info', 'mxchat'); ?>
1532 - </label>
1533 - <p class="description">
1534 - <?php esc_html_e('Automatically email the full transcript as a .txt file after the specified time has passed since the last user message. The scheduled email will be cancelled if a new message is received.', 'mxchat'); ?>
1535 - <br>
1536 - <?php esc_html_e('When "Only send if visitor provided contact info" is enabled, transcripts will only be emailed if the visitor shared an email address or phone number (including WhatsApp) in the chat.', 'mxchat'); ?>
1537 - </p>
1538 - <?php
1539 -}
446 + <div class="faq-item">
447 + <h3>How do I add the chatbot to my site?</h3>
448 + <p>
449 + You can add the chatbot using the shortcode <code>[mxchat_chatbot floating="yes"]</code> or <code>[mxchat_chatbot floating="no"]</code>. For initial testing and styling, it's best to use the shortcode on a draft or non-public page. Once you’re ready to go live, enable the “Append Chat Widget to Body” option in the settings for site-wide integration (recommended) or add shortcode to the footer.
450 + </p>
451 + </div>
1540 452
453 + <div class="faq-item">
454 + <h3>How does the chatbot use my content to generate responses?</h3>
455 + <p>
456 + The chatbot uses AI and vector embeddings to connect users with relevant information. When you submit content, it converts it into a mathematical format. When a user asks a question, the bot matches it to your stored content and generates a response based on relevance. For example, submitting "Our phone number is 910-123-4567" allows the bot to retrieve this information when asked about contact details. To ensure related information is provided together, submit it in one entry.
457 + </p>
458 + </div>
1541 459
460 + <div class="faq-item">
461 + <h3>Why does the chatbot sometimes make up links or information?</h3>
462 + <p>
463 + Occasionally, the chatbot may generate inaccurate links or information, known as "hallucinations." To minimize this, you can add system instructions to guide its behavior. For example, include an instruction like: "Only provide links you directly have access to or retrieve from the knowledge base. Do not make up links or information that you do not have direct access to." This helps the bot stay aligned with your content.
464 + </p>
465 + </div>
1542 466
1543 -public function sanitize_transcripts_options($input) {
1544 - $sanitized = array();
467 + <div class="faq-item">
468 + <h3>How do intents work in MxChat?</h3>
469 + <p>
470 + Intents allow MxChat to recognize user requests and trigger specific actions, such as capturing emails or displaying product information. This helps provide a more interactive and responsive experience. For a detailed explanation of each intent, please refer to our <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">Intents Documentation</a>.
471 + </p>
472 + </div>
1545 473
1546 - $sanitized['mxchat_enable_notifications'] = isset($input['mxchat_enable_notifications']) ? 1 : 0;
1547 474
1548 - if (isset($input['mxchat_notification_email'])) {
1549 - $sanitized['mxchat_notification_email'] = sanitize_email($input['mxchat_notification_email']);
1550 - if (!is_email($sanitized['mxchat_notification_email'])) {
1551 - add_settings_error(
1552 - 'mxchat_transcripts_options',
1553 - 'invalid_email',
1554 - __('Please enter a valid email address for notifications.', 'mxchat'),
1555 - 'error'
1556 - );
1557 - $sanitized['mxchat_notification_email'] = get_option('admin_email');
1558 - }
1559 - }
475 + <div class="faq-item">
476 + <h3>How does the Complianz integration work?</h3>
477 + <p>
478 + The Pro version offers direct integration with the Complianz GDPR plugin, making it easy to stay compliant with GDPR. If Complianz is enabled on your website, users must accept consent before the chatbot widget appears. The chatbot will only display once the user has accepted, ensuring compliance with data privacy regulations.
479 + </p>
480 + </div>
1560 481
1561 - // Sanitize auto-delete setting
1562 - $valid_intervals = array('never', '1week', '2weeks', '1month');
1563 - if (isset($input['mxchat_auto_delete_transcripts'])) {
1564 - $sanitized['mxchat_auto_delete_transcripts'] = in_array($input['mxchat_auto_delete_transcripts'], $valid_intervals)
1565 - ? $input['mxchat_auto_delete_transcripts']
1566 - : 'never';
1567 - } else {
1568 - $sanitized['mxchat_auto_delete_transcripts'] = 'never';
1569 - }
482 + <div class="faq-item">
483 + <h3>How does the WooCommerce integration work?</h3>
484 + <p>
485 + With WooCommerce integration, the chatbot automatically embeds new products and updates existing ones. For already-published products, you can click update or submit the product sitemap. The “Order History Access” setting allows the bot to access users' order history (requires login) and assist with order inquiries. To enable the “Add to Cart” feature, add this system instruction: “After discussing a product, ask if the user wants to add it to their cart. The user must say 'Add to cart' exactly.” Currently, this feature supports English only, with more languages coming soon.
486 + </p>
487 + </div>
1570 488
1571 - // Sanitize custom retention-days override (plan-9b80b1).
1572 - if (isset($input['mxchat_retention_days'])) {
1573 - $days = (int) $input['mxchat_retention_days'];
1574 - $sanitized['mxchat_retention_days'] = max(0, min(3650, $days));
1575 - } else {
1576 - $sanitized['mxchat_retention_days'] = 0;
1577 - }
489 + <div class="faq-item">
490 + <h3>Why isn't my chatbot responding as expected?</h3>
491 + <p>
492 + AI chatbots can sometimes behave in unexpected ways, especially if you're new to configuring AI for specific tasks. We're committed to helping you get the most out of your chatbot experience. While we’re working on comprehensive guides and video tutorials, our team is here to assist you directly. If your chatbot isn't delivering the responses you need, please don’t hesitate to <a href="https://mxchat.ai/contact/" target="_blank" rel="noopener noreferrer">contact us</a> for personalized support.
493 + </p>
494 + <p>
495 + We’re dedicated to your success and ready to guide you in aligning the AI's behavior to meet your goals.
496 + </p>
497 + </div>
1578 498
1579 - // Get old values to check if auto-delete or retention-days changed.
1580 - $old_options = get_option('mxchat_transcripts_options');
1581 - $old_interval = isset($old_options['mxchat_auto_delete_transcripts']) ? $old_options['mxchat_auto_delete_transcripts'] : 'never';
1582 - $old_retention = isset($old_options['mxchat_retention_days']) ? (int) $old_options['mxchat_retention_days'] : 0;
499 + <div class="faq-item">
500 + <h3>What is Loops, and how do I get an API key?</h3>
501 + <p>
502 + Loops is a powerful SaaS email service that helps you automate and enhance your email marketing campaigns, making it easy to reach and engage with your audience. To integrate Loops with MxChat, you’ll need an API key from Loops. You can obtain this key by logging into your Loops account and navigating to the API settings. Visit the <a href="https://loops.so" target="_blank" rel="noopener noreferrer">Loops website</a> to get started or to sign up for an account.
503 + </p>
504 + </div>
1583 505
1584 - // If either setting changed, reschedule the cron job. The schedule_transcript_cleanup
1585 - // helper now treats "any active retention" (dropdown != never OR custom days > 0) as a
1586 - // reason to keep the daily cron registered.
1587 - $interval_changed = ($old_interval !== $sanitized['mxchat_auto_delete_transcripts']);
1588 - $retention_changed = ($old_retention !== $sanitized['mxchat_retention_days']);
1589 - if ($interval_changed || $retention_changed) {
1590 - $any_active = ($sanitized['mxchat_auto_delete_transcripts'] !== 'never') || ($sanitized['mxchat_retention_days'] > 0);
1591 - $this->schedule_transcript_cleanup($any_active ? 'active' : 'never');
1592 - }
1593 506
1594 - // Sanitize auto-email transcript settings
1595 - $sanitized['mxchat_auto_email_transcript_enabled'] = isset($input['mxchat_auto_email_transcript_enabled']) ? 1 : 0;
507 + </div>
508 + </div>
509 + <?php
510 +}
1596 511
1597 - $valid_delays = array('15', '30', '60');
1598 - if (isset($input['mxchat_auto_email_transcript_delay'])) {
1599 - $sanitized['mxchat_auto_email_transcript_delay'] = in_array($input['mxchat_auto_email_transcript_delay'], $valid_delays)
1600 - ? $input['mxchat_auto_email_transcript_delay']
1601 - : '30';
1602 - } else {
1603 - $sanitized['mxchat_auto_email_transcript_delay'] = '30';
1604 - }
1605 512
1606 - // Sanitize require contact info setting
1607 - $sanitized['mxchat_auto_email_transcript_require_contact'] = isset($input['mxchat_auto_email_transcript_require_contact']) ? 1 : 0;
1608 513
1609 - return $sanitized;
1610 -}
514 +public function mxchat_create_transcripts_page() {
515 + global $wpdb;
516 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1611 517
1612 -/**
1613 - * Schedule or unschedule the transcript cleanup cron job
1614 - */
1615 -public function schedule_transcript_cleanup($interval) {
1616 - // Clear any existing scheduled event
1617 - $timestamp = wp_next_scheduled('mxchat_cleanup_old_transcripts');
1618 - if ($timestamp) {
1619 - wp_unschedule_event($timestamp, 'mxchat_cleanup_old_transcripts');
1620 - }
518 + // Get basic stats
519 + $total_chats = $wpdb->get_var("SELECT COUNT(DISTINCT session_id) FROM $table_name");
520 + $total_messages = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
521 + $total_users = $wpdb->get_var("SELECT COUNT(DISTINCT user_email) FROM $table_name WHERE user_email != ''");
522 + ?>
523 + <div class="wrap mxchat-admin">
524 + <!-- Stats Cards -->
525 + <div class="mxchat-stats-grid">
526 + <div class="mxchat-stat-card">
527 + <div class="stat-icon">💬</div>
528 + <div class="stat-content">
529 + <span class="stat-value"><?php echo esc_html($total_chats); ?></span>
530 + <span class="stat-label"><?php esc_html_e('Total Chats', 'mxchat'); ?></span>
531 + </div>
532 + </div>
533 + <div class="mxchat-stat-card">
534 + <div class="stat-icon">📝</div>
535 + <div class="stat-content">
536 + <span class="stat-value"><?php echo esc_html($total_messages); ?></span>
537 + <span class="stat-label"><?php esc_html_e('Total Messages', 'mxchat'); ?></span>
538 + </div>
539 + </div>
540 + <div class="mxchat-stat-card">
541 + <div class="stat-icon">👥</div>
542 + <div class="stat-content">
543 + <span class="stat-value"><?php echo esc_html($total_users); ?></span>
544 + <span class="stat-label"><?php esc_html_e('Unique Users', 'mxchat'); ?></span>
545 + </div>
546 + </div>
547 + </div>
1621 548
1622 - // Schedule new event whenever retention is active. "active" is the canonical
1623 - // value passed by sanitize_transcripts_options when either the dropdown != never
1624 - // OR the custom retention-days > 0; "never" turns the cron off. Any other value
1625 - // (the legacy "1week" / "2weeks" / "1month" strings) is also treated as active.
1626 - if ($interval !== 'never') {
1627 - // Schedule to run daily at 3 AM
1628 - $next_run = strtotime('tomorrow 3:00 AM');
1629 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1630 - }
1631 -}
549 + <!-- Search and Filter Controls -->
550 + <div class="mxchat-controls-wrapper">
551 + <div class="mxchat-search-box">
552 + <input type="text" id="mxchat-search-transcripts"
553 + placeholder="<?php esc_attr_e('Search transcripts...', 'mxchat'); ?>"
554 + class="regular-text">
555 + </div>
1632 556
1633 -/**
1634 - * Delete old transcripts based on the configured interval
1635 - */
1636 -public function cleanup_old_transcripts() {
1637 - $options = get_option('mxchat_transcripts_options', array());
1638 - $interval = isset($options['mxchat_auto_delete_transcripts']) ? $options['mxchat_auto_delete_transcripts'] : 'never';
1639 - $custom_days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0;
557 + <form id="mxchat-delete-form" method="post">
558 + <?php wp_nonce_field('mxchat_delete_chat_history', 'mxchat_delete_chat_nonce'); ?>
559 + <div class="mxchat-controls">
560 + <button type="button" id="mxchat-select-all-transcripts" class="mxchat-select-button">
561 + <span class="dashicons dashicons-yes-alt"></span>
562 + <span class="button-text"><?php esc_html_e('Select All', 'mxchat'); ?></span>
563 + </button>
564 + <button type="submit" class="button delete-chats-button">
565 + <span class="dashicons dashicons-trash"></span>
566 + <?php esc_html_e('Delete Selected', 'mxchat'); ?>
567 + </button>
568 + </div>
569 + </form>
570 + </div>
1640 571
1641 - // Custom retention-days (plan-9b80b1) takes precedence over the bucket dropdown.
1642 - $days = 0;
1643 - if ($custom_days > 0) {
1644 - $days = $custom_days;
1645 - } else {
1646 - switch ($interval) {
1647 - case '1week': $days = 7; break;
1648 - case '2weeks': $days = 14; break;
1649 - case '1month': $days = 30; break;
1650 - case 'never':
1651 - default:
1652 - $days = 0;
572 + <!-- Transcripts Container -->
573 + <div id="mxchat-transcripts"></div>
574 + </div>
575 + <?php
1653 576 }
1654 - }
1655 577
1656 - // Devs can override the final day count programmatically.
1657 - $days = (int) apply_filters('mxchat_transcript_retention_days', $days);
1658 578
1659 - if ($days <= 0) {
1660 - return; // Retention disabled — bail.
1661 - }
1662 579
580 +
581 +public function mxchat_create_prompts_page() {
1663 582 global $wpdb;
1664 - $transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1665 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
1666 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
583 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1667 584
1668 - // Defensive: if the main table doesn't exist (fresh-ish install), bail.
1669 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $transcripts_table)) !== $transcripts_table) {
1670 - return;
585 + // Display success message if all prompts were deleted
586 + if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
587 + echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p></div>';
1671 588 }
1672 589
1673 - $cutoff_date = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
590 + // Set up pagination and search query
591 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
592 + $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
593 + $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
594 + $per_page = 10;
595 + $offset = ($current_page - 1) * $per_page;
1674 596
1675 - // Cap at 5000 session_ids per run so a large unattended site doesn't OOM —
1676 - // the cron will pick up where it left off on the next tick (within hours).
1677 - $batch_cap = (int) apply_filters('mxchat_transcript_retention_batch_cap', 5000);
1678 -
1679 - $sessions_to_delete = $wpdb->get_col(
1680 - $wpdb->prepare(
1681 - "SELECT DISTINCT session_id FROM {$transcripts_table} WHERE timestamp IS NOT NULL AND timestamp < %s LIMIT %d",
1682 - $cutoff_date,
1683 - $batch_cap
1684 - )
1685 - );
1686 -
1687 - if (empty($sessions_to_delete)) {
1688 - return;
597 + // Modify query to handle search input
598 + $sql_search = "";
599 + if ($search_query) {
600 + $sql_search = $wpdb->prepare("WHERE article_content LIKE %s", '%' . $wpdb->esc_like($search_query) . '%');
1689 601 }
1690 602
1691 - $placeholders = implode(',', array_fill(0, count($sessions_to_delete), '%s'));
603 + // Retrieve total number of prompts, considering search filter
604 + $total_prompts = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} {$sql_search}");
605 + $total_pages = ceil($total_prompts / $per_page);
1692 606
1693 - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1694 - // $placeholders is a server-built list of literal "%s" tokens.
1695 - $deleted_transcripts = (int) $wpdb->query(
607 + // Retrieve prompts from the database
608 + $prompts = $wpdb->get_results(
1696 609 $wpdb->prepare(
1697 - "DELETE FROM {$transcripts_table} WHERE session_id IN ($placeholders)",
1698 - $sessions_to_delete
610 + "SELECT * FROM {$table_name} {$sql_search} ORDER BY timestamp DESC LIMIT %d OFFSET %d",
611 + $per_page,
612 + $offset
1699 613 )
1700 614 );
1701 615
1702 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $translations_table)) === $translations_table) {
1703 - $wpdb->query(
1704 - $wpdb->prepare(
1705 - "DELETE FROM {$translations_table} WHERE session_id IN ($placeholders)",
1706 - $sessions_to_delete
1707 - )
1708 - );
1709 - }
616 + ?>
1710 617
1711 - if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $url_clicks_table)) === $url_clicks_table) {
1712 - $wpdb->query(
1713 - $wpdb->prepare(
1714 - "DELETE FROM {$url_clicks_table} WHERE session_id IN ($placeholders)",
1715 - $sessions_to_delete
1716 - )
1717 - );
1718 - }
1719 - // phpcs:enable
618 + <div class="wrap mxchat-admin">
619 + <div class="mxchat-grid-container">
620 + <!-- Submit Content Form -->
621 + <div class="mxchat-grid-item">
622 + <h2>Submit Content</h2>
623 + <form id="mxchat-content-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_content')); ?>">
624 + <?php wp_nonce_field('mxchat_submit_content_action', 'mxchat_submit_content_nonce'); ?>
625 + <div class="mxchat-form-group">
626 + <label for="article_content">Article Content:</label>
627 + <textarea name="article_content" id="article_content" required></textarea>
628 + </div>
629 + <div class="mxchat-form-group">
630 + <label for="article_url">Article URL (Optional):</label>
631 + <input type="url" name="article_url" id="article_url" placeholder="Enter related URL for the content">
632 + </div>
633 + <input type="submit" name="submit_content" value="Submit Content" class="button button-primary submit-content-button" />
634 + </form>
635 + <div id="mxchat-content-loading" class="mxchat-content-spinner" style="display: none;"></div>
636 + <div id="mxchat-content-loading-text" class="mxchat-loading-text">Submitting content, please wait...</div>
637 + </div>
1720 638
1721 - update_option('mxchat_retention_last_swept_at', time(), false);
1722 - update_option('mxchat_retention_rows_last_deleted', $deleted_transcripts, false);
1723 -}
1724 639
1725 -public function export_chat_transcripts() {
1726 - if (!current_user_can('manage_options')) {
1727 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
1728 - }
640 +<!-- Combined Knowledge Import Settings -->
641 +<div class="mxchat-grid-item">
642 + <div class="mxchat-flex-section">
643 + <h2><?php esc_html_e('Content Import Settings', 'mxchat'); ?></h2>
1729 644
1730 - check_ajax_referer('mxchat_export_transcripts', 'security');
645 + <div class="mxchat-settings-row">
646 + <!-- Auto-Sync Toggle Section -->
647 +<div class="mxchat-sync-settings">
648 + <form method="post" action="options.php" class="mxchat-sync-settings-form">
649 + <?php
650 + settings_fields('mxchat_prompts_options');
651 + $posts_sync = get_option('mxchat_auto_sync_posts');
652 + $pages_sync = get_option('mxchat_auto_sync_pages');
653 + ?>
654 + <div class="mxchat-toggle-group">
655 + <div class="mxchat-toggle-container">
656 + <label class="mxchat-toggle-switch">
657 + <input type="checkbox"
658 + name="mxchat_auto_sync_posts"
659 + value="1"
660 + <?php checked($posts_sync, '1'); ?>>
661 + <span class="mxchat-toggle-slider"></span>
662 + </label>
663 + <span class="mxchat-toggle-label">
664 + <?php esc_html_e('Auto-sync Posts', 'mxchat'); ?>
665 + </span>
666 + </div>
1731 667
1732 - global $wpdb;
1733 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
668 + <div class="mxchat-toggle-container">
669 + <label class="mxchat-toggle-switch">
670 + <input type="checkbox"
671 + name="mxchat_auto_sync_pages"
672 + value="1"
673 + <?php checked($pages_sync, '1'); ?>>
674 + <span class="mxchat-toggle-slider"></span>
675 + </label>
676 + <span class="mxchat-toggle-label">
677 + <?php esc_html_e('Auto-sync Pages', 'mxchat'); ?>
678 + </span>
679 + </div>
680 + <div class="mxchat-submit-wrapper">
681 + <?php submit_button('Save Settings', 'save-button-settings', 'submit', false); ?>
682 + </div>
683 + </div>
684 + </form>
685 +</div>
1734 686
1735 - // Get all transcripts ordered by session and timestamp
1736 - $results = $wpdb->get_results(
1737 - "SELECT session_id, user_email, user_identifier, role, message, timestamp
1738 - FROM {$table_name}
1739 - ORDER BY session_id, timestamp ASC"
1740 - );
687 + <!-- URL Import Section with Processing Status -->
688 + <div class="mxchat-import-section">
689 + <?php
690 + // Check for any active processing
691 + $pdf_url = get_transient('mxchat_last_pdf_url');
692 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
693 + $pdf_status = $pdf_url ? $this->get_pdf_processing_status($pdf_url) : false;
694 + $sitemap_status = $sitemap_url ? $this->get_sitemap_processing_status($sitemap_url) : false;
1741 695
1742 - if (empty($results)) {
1743 - wp_send_json_error(array('message' => 'No transcripts found.'));
1744 - wp_die();
1745 - }
696 + // Clear old completed statuses
697 + if ($pdf_status && $pdf_status['status'] === 'complete') {
698 + delete_transient('mxchat_last_pdf_url');
699 + $pdf_status = false;
700 + }
701 + if ($sitemap_status && $sitemap_status['status'] === 'complete') {
702 + delete_transient('mxchat_last_sitemap_url');
703 + $sitemap_status = false;
704 + }
1746 705
1747 - // Set headers for CSV download
1748 - header('Content-Type: text/csv');
1749 - header('Content-Disposition: attachment; filename="chat-transcripts-' . date('Y-m-d') . '.csv"');
1750 - header('Pragma: no-cache');
1751 - header('Expires: 0');
706 + $is_processing = ($pdf_status && $pdf_status['status'] === 'processing') ||
707 + ($sitemap_status && $sitemap_status['status'] === 'processing');
708 + ?>
1752 709
1753 - // Create output stream
1754 - $output = fopen('php://output', 'w');
710 + <!-- Import Description -->
711 + <div class="mxchat-import-description">
712 + <p class="description-text">
713 + Import content from various sources:
714 + </p>
715 + <ul class="import-options">
716 + <li><strong>Sitemap URL:</strong> Add all pages from your sitemap</li>
717 + <li><strong>PDF URL:</strong> Import content from an online PDF</li>
718 + <li><strong>Single URL:</strong> Import from any webpage</li>
719 + </ul>
720 + </div>
1755 721
1756 - // Add UTF-8 BOM for proper Excel encoding
1757 - fputs($output, "\xEF\xBB\xBF");
722 + <!-- URL Import Form -->
723 + <?php if (!$is_processing) : ?>
724 + <form id="mxchat-sitemap-form" method="post" class="mxchat-sitemap-form"
725 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_submit_sitemap')); ?>">
726 + <?php wp_nonce_field('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce'); ?>
727 + <div class="mxchat-url-input-group">
728 + <input type="url"
729 + name="sitemap_url"
730 + id="sitemap_url"
731 + placeholder="<?php esc_attr_e('Enter URL (Sitemap, PDF, or webpage)', 'mxchat'); ?>"
732 + required
733 + aria-label="<?php esc_attr_e('URL Input', 'mxchat'); ?>"
734 + />
735 + <input type="submit"
736 + name="submit_sitemap"
737 + value="<?php esc_attr_e('Import', 'mxchat'); ?>"
738 + class="button button-primary"
739 + />
740 + </div>
741 + </form>
742 + <?php endif; ?>
1758 743
1759 - // Add CSV headers
1760 - fputcsv($output, array(
1761 - 'Session ID',
1762 - 'Email',
1763 - 'User Identifier',
1764 - 'Role',
1765 - 'Message',
1766 - 'Timestamp'
1767 - ));
744 + <!-- Loading Indicators -->
745 + <div id="mxchat-sitemap-loading" class="mxchat-spinner" style="display: none;"
746 + aria-hidden="true"></div>
747 + <div id="mxchat-loading-text" class="screen-reader-text" style="display: none;">
748 + <?php esc_html_e('Loading information into database, please wait...', 'mxchat'); ?>
749 + </div>
1768 750
1769 - // Add data rows
1770 - foreach ($results as $row) {
1771 - fputcsv($output, array(
1772 - $row->session_id,
1773 - $row->user_email,
1774 - $row->user_identifier,
1775 - $row->role,
1776 - $row->message,
1777 - $row->timestamp
1778 - ));
1779 - }
751 + <!-- PDF Processing Status -->
752 + <?php if ($pdf_status && $pdf_status['status'] !== 'complete') : ?>
753 + <div class="mxchat-process-status pdf" role="alert" aria-live="polite">
754 + <h3><?php esc_html_e('PDF Processing Status (Refresh page for update)', 'mxchat'); ?></h3>
755 + <p><?php printf(esc_html__('Progress: %1$d of %2$d pages (%3$d%%)', 'mxchat'),
756 + absint($pdf_status['processed_pages']),
757 + absint($pdf_status['total_pages']),
758 + absint($pdf_status['percentage']));
759 + ?></p>
760 + <p><?php printf(esc_html__('Status: %s', 'mxchat'),
761 + esc_html(ucfirst($pdf_status['status'])));
762 + ?></p>
763 + <p><?php printf(esc_html__('Last update: %s', 'mxchat'),
764 + esc_html($pdf_status['last_update']));
765 + ?></p>
766 + </div>
767 + <?php endif; ?>
1780 768
1781 - fclose($output);
1782 - wp_die();
1783 -}
769 + <!-- Sitemap Processing Status -->
770 + <?php if ($sitemap_status && $sitemap_status['status'] !== 'complete') : ?>
771 + <div class="mxchat-process-status sitemap" role="alert" aria-live="polite">
772 + <h3><?php esc_html_e('Sitemap Processing Status (Refresh page for update)', 'mxchat'); ?></h3>
773 + <p><?php printf(esc_html__('Progress: %1$d of %2$d URLs (%3$d%%)', 'mxchat'),
774 + absint($sitemap_status['processed_urls']),
775 + absint($sitemap_status['total_urls']),
776 + absint($sitemap_status['percentage']));
777 + ?></p>
778 + <p><?php printf(esc_html__('Status: %s', 'mxchat'),
779 + esc_html(ucfirst($sitemap_status['status'])));
780 + ?></p>
781 + <p><?php printf(esc_html__('Last update: %s', 'mxchat'),
782 + esc_html($sitemap_status['last_update']));
783 + ?></p>
784 + </div>
785 + <?php endif; ?>
1784 786
1785 -// ============================================================================
1786 -// Leads tab (inside Transcripts)
1787 -//
1788 -// Leads are derived from existing data — no dedicated table. Primary source:
1789 -// wp_mxchat_chat_transcripts rows where user_email is populated. Secondary
1790 -// source: wp_options entries `mxchat_email_{session_id}` / `mxchat_name_{sid}`
1791 -// for "orphan" leads who submitted the pre-chat form but never chatted.
1792 -// ============================================================================
787 + <!-- Stop Processing Button -->
788 + <?php if ($is_processing) : ?>
789 + <form id="mxchat-stop-form" method="post" class="mxchat-stop-form"
790 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_stop_processing')); ?>">
791 + <?php wp_nonce_field('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce'); ?>
792 + <input type="submit"
793 + name="stop_processing"
794 + value="<?php esc_attr_e('Stop Processing', 'mxchat'); ?>"
795 + class="button button-secondary"
796 + />
797 + </form>
798 + <?php endif; ?>
799 + </div>
800 + </div>
801 + </div>
802 +</div>
1793 803
1794 -/**
1795 - * Fetch leads: dedup-by-email rows, stats strip, and top pages in one call.
1796 - */
1797 -public function mxchat_fetch_leads() {
1798 - if (!current_user_can('manage_options')) {
1799 - wp_send_json_error(['message' => 'Insufficient permissions']);
1800 - wp_die();
1801 - }
804 +</div>
1802 805
1803 - global $wpdb;
1804 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
806 +<!-- Knowledge Base Management Section -->
807 +<div class="mxchat-knowledge-container">
808 + <!-- Left Column: Management Controls -->
809 + <div class="mxchat-knowledge-controls">
810 + <div class="mxchat-controls-header">
811 + <span class="displaying-num"><?php echo esc_html($total_prompts); ?> items</span>
812 + </div>
1805 813
1806 - $page = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
1807 - $per_page = isset($_POST['per_page']) ? min(100, max(10, absint($_POST['per_page']))) : 25;
1808 - $offset = ($page - 1) * $per_page;
1809 - $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
1810 - $date_range = isset($_POST['date_range']) ? sanitize_key($_POST['date_range']) : 'all';
1811 - $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
1812 - $page_filter = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
1813 - $sort = isset($_POST['sort']) ? sanitize_key($_POST['sort']) : 'last_seen';
1814 - $sort_dir = (isset($_POST['sort_dir']) && $_POST['sort_dir'] === 'asc') ? 'ASC' : 'DESC';
814 + <?php
815 + // Generate pagination links
816 + $page_links = paginate_links(array(
817 + 'base' => add_query_arg(array(
818 + 'paged' => '%#%',
819 + 'search' => urlencode($search_query),
820 + '_wpnonce' => wp_create_nonce('mxchat_prompts_search_nonce')
821 + ), admin_url('admin.php?page=mxchat-prompts')),
822 + 'format' => '',
823 + 'prev_text' => __('&laquo; Previous'),
824 + 'next_text' => __('Next &raquo;'),
825 + 'total' => $total_pages,
826 + 'current' => $current_page,
827 + ));
1815 828
1816 - $date_cutoff = self::mxchat_leads_date_cutoff($date_range);
1817 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
829 + if ($page_links) : ?>
830 + <div class="mxchat-pagination">
831 + <?php echo wp_kses_post($page_links); ?>
832 + </div>
833 + <?php endif; ?>
1818 834
1819 - // Base WHERE for transcripts leads.
1820 - $where_clauses = ["user_email IS NOT NULL", "user_email != ''"];
1821 - $where_params = [];
1822 835
1823 - if ($date_cutoff) {
1824 - $where_clauses[] = 'timestamp >= %s';
1825 - $where_params[] = $date_cutoff;
1826 - }
1827 - if ($page_filter && $has_page_url_column) {
1828 - $where_clauses[] = 'originating_page_url = %s';
1829 - $where_params[] = $page_filter;
1830 - }
1831 - if ($search !== '') {
1832 - $like = '%' . $wpdb->esc_like($search) . '%';
1833 - $where_clauses[] = '(user_email LIKE %s OR user_name LIKE %s)';
1834 - $where_params[] = $like;
1835 - $where_params[] = $like;
1836 - }
1837 - $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
836 + <form method="post"
837 + action="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_all_prompts')); ?>"
838 + class="delete-form"
839 + onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete all prompts? This action cannot be undone.', 'mxchat'); ?>');">
840 + <?php wp_nonce_field('mxchat_delete_all_prompts_action', 'mxchat_delete_all_prompts_nonce'); ?>
841 + <input type="submit"
842 + name="delete_all_prompts"
843 + value="<?php esc_attr_e('Delete All Knowledge', 'mxchat'); ?>"
844 + class="button button-link-delete mxchat-delete-all" />
845 + </form>
1838 846
1839 - // Aggregate query grouped by email.
1840 - $select_sql = $has_page_url_column
1841 - ? "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
1842 - COUNT(DISTINCT session_id) AS conversation_count"
1843 - : "SELECT user_email, MAX(timestamp) AS last_seen, MIN(timestamp) AS first_seen,
1844 - COUNT(DISTINCT session_id) AS conversation_count";
847 + </div>
1845 848
1846 - $order_column = in_array($sort, ['last_seen', 'conversation_count', 'first_seen'], true) ? $sort : 'last_seen';
1847 - $group_order_limit = " GROUP BY user_email ORDER BY {$order_column} {$sort_dir} LIMIT %d OFFSET %d";
849 + <!-- Right Column: Search -->
850 + <div class="mxchat-knowledge-search">
851 + <form method="get" id="knowledge-search" class="search-form">
852 + <?php wp_nonce_field('mxchat_prompts_search_nonce'); ?>
853 + <input type="hidden" name="page" value="mxchat-prompts" />
854 + <div class="mxchat-search-group">
855 + <input type="text"
856 + name="search"
857 + placeholder="Search Knowledge"
858 + value="<?php echo esc_attr($search_query); ?>"
859 + class="search-input" />
860 + <button type="submit" class="button button-primary search-button">
861 + <span class="dashicons dashicons-search"></span>
862 + Search
863 + </button>
864 + </div>
865 + </form>
866 + </div>
867 +</div>
1848 868
1849 - $transcripts_sql = $wpdb->prepare(
1850 - "{$select_sql} FROM {$table} {$where_sql}{$group_order_limit}",
1851 - array_merge($where_params, [$per_page, $offset])
1852 - );
1853 - $transcript_rows = $wpdb->get_results($transcripts_sql);
1854 869
1855 - // Count of unique transcript-based leads under the same filters.
1856 - $count_sql = $wpdb->prepare(
1857 - "SELECT COUNT(DISTINCT user_email) FROM {$table} {$where_sql}",
1858 - $where_params
1859 - );
1860 - $transcripts_lead_count = (int) $wpdb->get_var($count_sql);
1861 -
1862 - // Hydrate each row: name, latest_session_id, top page.
1863 - $leads = [];
1864 - foreach ($transcript_rows as $row) {
1865 - $detail = $has_page_url_column
1866 - ? $wpdb->get_row($wpdb->prepare(
1867 - "SELECT session_id, user_name, originating_page_url, originating_page_title
1868 - FROM {$table} WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
1869 - $row->user_email
1870 - ))
1871 - : $wpdb->get_row($wpdb->prepare(
1872 - "SELECT session_id, user_name FROM {$table}
1873 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
1874 - $row->user_email
1875 - ));
1876 -
1877 - $leads[] = [
1878 - 'email' => $row->user_email,
1879 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
1880 - 'conversation_count' => (int) $row->conversation_count,
1881 - 'last_seen' => $row->last_seen,
1882 - 'last_seen_display' => self::mxchat_leads_format_relative($row->last_seen),
1883 - 'first_seen' => $row->first_seen,
1884 - 'latest_session_id' => isset($detail->session_id) ? $detail->session_id : '',
1885 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
1886 - 'top_page_title' => isset($detail->originating_page_title) ? $detail->originating_page_title : '',
1887 - 'is_orphan' => false,
1888 - 'status' => 'active',
1889 - ];
870 + <!-- Prompts Table -->
871 + <table class="mxchat-table">
872 + <thead>
873 + <tr>
874 + <th>ID</th>
875 + <th>Article Content</th>
876 + <th>URL</th>
877 + <th>Actions</th>
878 + </tr>
879 + </thead>
880 + <tbody>
881 + <?php if ($prompts) : ?>
882 + <?php foreach ($prompts as $prompt) : ?>
883 + <tr id="prompt-<?php echo esc_attr($prompt->id); ?>">
884 + <td><?php echo esc_html($prompt->id); ?></td>
885 + <td class="mxchat_article_content_dashboard">
886 + <span class="content-view"><?php echo wp_kses_post(wpautop(esc_textarea($prompt->article_content))); ?></span>
887 + <textarea class="content-edit" style="display:none;"><?php echo esc_textarea($prompt->article_content); ?></textarea>
888 + </td>
889 + <td class="mxchat_article_url_dashboard">
890 + <span class="url-view">
891 + <?php if (!empty($prompt->source_url)) : ?>
892 + <a href="<?php echo esc_url($prompt->source_url); ?>" target="_blank"><?php echo esc_html($prompt->source_url); ?></a>
893 + <?php else : ?>
894 + N/A
895 + <?php endif; ?>
896 + </span>
897 + <input type="url" class="url-edit" value="<?php echo esc_attr($prompt->source_url); ?>" style="display:none;" />
898 + </td>
899 + <td>
900 + <button class="button edit-button" data-id="<?php echo esc_attr($prompt->id); ?>">Edit</button>
901 + <button class="button save-button" data-id="<?php echo esc_attr($prompt->id); ?>" style="display:none;">Save</button>
902 + <a href="<?php echo esc_url(admin_url('admin-post.php?action=mxchat_delete_prompt&id=' . esc_attr($prompt->id) . '&_wpnonce=' . wp_create_nonce('mxchat_delete_prompt_nonce'))); ?>" class="button delete-button">Delete</a>
903 + </td>
904 + </tr>
905 + <?php endforeach; ?>
906 + <?php else : ?>
907 + <tr>
908 + <td colspan="4"><?php esc_html_e('No prompts found.', 'mxchat'); ?></td>
909 + </tr>
910 + <?php endif; ?>
911 + </tbody>
912 + </table>
913 + </div>
914 + <?php
915 +}
916 +public function mxchat_handle_delete_all_prompts() {
917 + // Verify nonce
918 + if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
919 + wp_die(__('Nonce verification failed.', 'mxchat'));
1890 920 }
1891 921
1892 - // Non-transcript lead sources. Built once here, then filtered/merged based on the
1893 - // status filter below. Deduplication priority when the same email appears in multiple
1894 - // sources: transcripts > chat_deleted > orphan.
1895 - $transcripts_emails_seen = array_flip(array_map(
1896 - function ($r) { return strtolower($r['email']); },
1897 - $leads
1898 - ));
1899 -
1900 - // Chat-deleted leads: had a conversation that an admin removed. Preserved via
1901 - // mxchat_lead_del_* options, with timestamps so they respect date filters.
1902 - $chat_deleted_leads_all = [];
1903 - if ($status === 'all' || $status === 'chat_deleted') {
1904 - $chat_deleted_leads_all = self::mxchat_collect_chat_deleted_leads($search, $date_cutoff);
1905 - // Dedup: drop any chat_deleted row whose email is already in the transcripts set.
1906 - $chat_deleted_leads_all = array_values(array_filter(
1907 - $chat_deleted_leads_all,
1908 - function ($row) use ($transcripts_emails_seen) {
1909 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
1910 - }
1911 - ));
1912 - foreach ($chat_deleted_leads_all as $row) {
1913 - $transcripts_emails_seen[strtolower($row['email'])] = true;
1914 - }
922 + // Check permissions
923 + if (!current_user_can('manage_options')) {
924 + wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
1915 925 }
1916 926
1917 - // Orphans: pre-chat form captures with no conversation. No timestamp, so skipped
1918 - // when a date filter is active.
1919 - $orphan_leads_all = [];
1920 - if (($status === 'all' || $status === 'orphan') && !$date_cutoff && !$page_filter) {
1921 - $orphan_leads_all = self::mxchat_collect_orphan_leads($search);
1922 - $orphan_leads_all = array_values(array_filter(
1923 - $orphan_leads_all,
1924 - function ($row) use ($transcripts_emails_seen) {
1925 - return !isset($transcripts_emails_seen[strtolower($row['email'])]);
1926 - }
1927 - ));
1928 - }
927 + global $wpdb;
928 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
1929 929
1930 - // Apply status filter to the transcripts-derived list.
1931 - if ($status === 'orphan' || $status === 'chat_deleted') {
1932 - $leads = [];
1933 - $transcripts_lead_count = 0;
1934 - }
930 + // Delete all prompts from the table
931 + $wpdb->query("DELETE FROM {$table_name}");
1935 932
1936 - // Stitch the current page from the three buckets in priority order.
1937 - $total_count = $transcripts_lead_count + count($chat_deleted_leads_all) + count($orphan_leads_all);
1938 - $remaining_slots = $per_page - count($leads);
933 + // Clear relevant cache
934 + wp_cache_delete('all_prompts', 'mxchat_prompts');
1939 935
1940 - if ($remaining_slots > 0 && !empty($chat_deleted_leads_all)) {
1941 - $start = max(0, ($page - 1) * $per_page - $transcripts_lead_count);
1942 - if ($start < count($chat_deleted_leads_all)) {
1943 - $leads = array_merge($leads, array_slice($chat_deleted_leads_all, $start, $remaining_slots));
1944 - $remaining_slots = $per_page - count($leads);
1945 - }
1946 - }
936 + // Redirect back with a success message
937 + $redirect_url = add_query_arg(array(
938 + 'page' => 'mxchat-prompts',
939 + 'all_deleted' => 'true'
940 + ), admin_url('admin.php'));
1947 941
1948 - if ($remaining_slots > 0 && !empty($orphan_leads_all)) {
1949 - $before = $transcripts_lead_count + count($chat_deleted_leads_all);
1950 - $start = max(0, ($page - 1) * $per_page - $before);
1951 - if ($start < count($orphan_leads_all)) {
1952 - $leads = array_merge($leads, array_slice($orphan_leads_all, $start, $remaining_slots));
1953 - }
942 + wp_safe_redirect($redirect_url);
943 + exit;
944 +}
945 +public function mxchat_handle_delete_prompt() {
946 + // Sanitize and validate nonce
947 + $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
948 + if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
949 + wp_die('Nonce verification failed.');
1954 950 }
1955 951
1956 - $total_pages = $per_page > 0 ? (int) ceil($total_count / $per_page) : 1;
1957 -
1958 - // Stats strip: always computed over full dataset, unaffected by filters.
1959 - $stats = self::mxchat_leads_stats($table, $has_page_url_column);
1960 -
1961 - // Top pages: top 5 by distinct emails captured.
1962 - $top_pages = [];
1963 - if ($has_page_url_column) {
1964 - $top_pages_rows = $wpdb->get_results(
1965 - "SELECT originating_page_url AS url,
1966 - MAX(originating_page_title) AS title,
1967 - COUNT(DISTINCT user_email) AS lead_count
1968 - FROM {$table}
1969 - WHERE user_email IS NOT NULL AND user_email != ''
1970 - AND originating_page_url IS NOT NULL AND originating_page_url != ''
1971 - GROUP BY originating_page_url
1972 - ORDER BY lead_count DESC, url ASC
1973 - LIMIT 5"
1974 - );
1975 - foreach ($top_pages_rows as $p) {
1976 - $top_pages[] = [
1977 - 'url' => $p->url,
1978 - 'title' => $p->title ?: $p->url,
1979 - 'lead_count' => (int) $p->lead_count,
1980 - ];
1981 - }
952 + // Check permissions
953 + if (!current_user_can('manage_options')) {
954 + wp_die('You do not have sufficient permissions to delete prompts.');
1982 955 }
1983 956
1984 - wp_send_json([
1985 - 'success' => true,
1986 - 'leads' => $leads,
1987 - 'page' => $page,
1988 - 'per_page' => $per_page,
1989 - 'total_count' => $total_count,
1990 - 'total_pages' => $total_pages,
1991 - 'showing_start' => $total_count === 0 ? 0 : ($offset + 1),
1992 - 'showing_end' => min($offset + $per_page, $total_count),
1993 - 'stats' => $stats,
1994 - 'top_pages' => $top_pages,
1995 - ]);
1996 - wp_die();
1997 -}
1998 -
1999 -/**
2000 - * Delete one or more leads by email. Removes every transcripts row for that
2001 - * email and cleans up related wp_options (mxchat_email_{sid}, mxchat_name_{sid},
2002 - * mxchat_history_{sid}) and any orphan option entries matching the email.
2003 - */
2004 -public function mxchat_delete_leads() {
2005 - if (!current_user_can('manage_options')) {
2006 - wp_send_json_error(['message' => 'Insufficient permissions']);
2007 - wp_die();
957 + // Validate and sanitize ID parameter
958 + $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
959 + if ($id <= 0) {
960 + wp_die('Invalid prompt ID.');
2008 961 }
2009 - check_ajax_referer('mxchat_delete_leads', 'security');
2010 962
2011 - $emails_raw = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
2012 - $emails = [];
2013 - foreach ($emails_raw as $e) {
2014 - $clean = sanitize_email((string) $e);
2015 - if ($clean) {
2016 - $emails[] = $clean;
2017 - }
2018 - }
2019 - if (empty($emails)) {
2020 - wp_send_json_error(['message' => 'No emails provided']);
2021 - wp_die();
2022 - }
963 + global $wpdb;
964 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2023 965
2024 - $summary = self::mxchat_wipe_leads_by_email($emails);
966 + // Clear cache and delete prompt
967 + wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
968 + $wpdb->delete($table_name, array('id' => $id), array('%d'));
2025 969
2026 - wp_send_json([
2027 - 'success' => true,
2028 - 'deleted_leads' => count($emails),
2029 - 'deleted_sessions' => $summary['deleted_sessions'],
2030 - 'deleted_rows' => $summary['deleted_rows'],
2031 - ]);
2032 - wp_die();
970 + wp_safe_redirect(add_query_arg(array('page' => 'mxchat-prompts', 'deleted' => 'true'), admin_url('admin.php')));
971 + exit;
2033 972 }
973 +public function mxchat_generate_embedding($text) {
974 + $options = get_option('mxchat_options');
975 + $api_key = $options['api_key'] ?? 'default_api_key';
2034 976
2035 -/**
2036 - * Fully wipe one or more leads by email: every transcripts row, every related wp_options
2037 - * entry (history, pre-chat capture, chat_deleted preservation, agent name, translations).
2038 - *
2039 - * Shared between the Leads-tab Delete button and the transcript-delete opt-in checkbox.
2040 - * Input emails must already be sanitized with sanitize_email().
2041 - */
2042 -private static function mxchat_wipe_leads_by_email(array $emails) {
2043 - global $wpdb;
2044 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2045 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
2046 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
2047 -
2048 - $deleted_sessions = 0;
2049 - $deleted_rows = 0;
2050 - $emails_lc = array_map('strtolower', $emails);
2051 -
2052 - foreach ($emails as $email) {
2053 - $session_ids = $wpdb->get_col($wpdb->prepare(
2054 - "SELECT DISTINCT session_id FROM {$table} WHERE user_email = %s",
2055 - $email
977 + $response = wp_remote_post('https://api.openai.com/v1/embeddings', array(
978 + 'body' => wp_json_encode(array(
979 + 'model' => 'text-embedding-ada-002',
980 + 'input' => $text
981 + )),
982 + 'headers' => array(
983 + 'Authorization' => 'Bearer ' . $api_key,
984 + 'Content-Type' => 'application/json'
985 + ),
2056 986 ));
2057 987
2058 - $rows_removed = $wpdb->delete($table, ['user_email' => $email], ['%s']);
2059 - if ($rows_removed !== false) {
2060 - $deleted_rows += (int) $rows_removed;
988 + if (is_wp_error($response)) {
989 + return null;
2061 990 }
2062 991
2063 - foreach ($session_ids as $sid) {
2064 - $deleted_sessions++;
2065 - wp_cache_delete('chat_session_' . $sid, 'mxchat_chat_sessions');
2066 - delete_option('mxchat_history_' . $sid);
2067 - delete_option('mxchat_email_' . $sid);
2068 - delete_option('mxchat_name_' . $sid);
2069 - delete_option('mxchat_agent_name_' . $sid);
2070 - delete_option('mxchat_lead_del_email_' . $sid);
2071 - delete_option('mxchat_lead_del_name_' . $sid);
2072 - delete_option('mxchat_lead_del_ts_' . $sid);
2073 - if ($has_translations) {
2074 - $wpdb->delete($translations_table, ['session_id' => $sid], ['%s']);
2075 - }
2076 - }
992 + $response_data = json_decode(wp_remote_retrieve_body($response), true);
993 + return $response_data['data'][0]['embedding'] ?? null;
2077 994 }
2078 -
2079 - // Clean up any lingering option entries (orphan pre-chat captures + chat_deleted
2080 - // preservations) whose stored value matches one of the emails being wiped.
2081 - $lingering = $wpdb->get_results(
2082 - "SELECT option_name, option_value FROM {$wpdb->options}
2083 - WHERE option_name LIKE 'mxchat_email_%' OR option_name LIKE 'mxchat_lead_del_email_%'"
2084 - );
2085 - foreach ($lingering as $opt) {
2086 - if (!in_array(strtolower(trim($opt->option_value)), $emails_lc, true)) {
2087 - continue;
995 +public function mxchat_delete_chat_history() {
996 + if (!current_user_can('manage_options')) {
997 + echo wp_json_encode(['error' => 'You do not have sufficient permissions.']);
998 + wp_die();
2088 999 }
2089 - if (strpos($opt->option_name, 'mxchat_lead_del_email_') === 0) {
2090 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2091 - delete_option('mxchat_lead_del_email_' . $sid);
2092 - delete_option('mxchat_lead_del_name_' . $sid);
2093 - delete_option('mxchat_lead_del_ts_' . $sid);
2094 - } else {
2095 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2096 - delete_option('mxchat_email_' . $sid);
2097 - delete_option('mxchat_name_' . $sid);
2098 - }
2099 - }
2100 1000
2101 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
1001 + check_ajax_referer('mxchat_delete_chat_history', 'security');
2102 1002
2103 - return [
2104 - 'deleted_sessions' => $deleted_sessions,
2105 - 'deleted_rows' => $deleted_rows,
2106 - ];
2107 -}
1003 + global $wpdb;
1004 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
2108 1005
2109 -/**
2110 - * Stream a leads CSV. scope=all exports every lead under current filters is not
2111 - * supported to keep semantics simple; caller either exports all leads or a
2112 - * specific set of selected emails.
2113 - */
2114 -public function mxchat_export_leads() {
2115 - if (!current_user_can('manage_options')) {
2116 - wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mxchat'));
2117 - }
2118 - check_ajax_referer('mxchat_export_leads', 'security');
1006 + if (isset($_POST['delete_session_ids']) && is_array($_POST['delete_session_ids'])) {
1007 + foreach ($_POST['delete_session_ids'] as $session_id) {
1008 + $session_id_sanitized = sanitize_text_field($session_id);
2119 1009
2120 - $scope = isset($_POST['scope']) ? sanitize_key($_POST['scope']) : 'all';
2121 - $fields_mode = isset($_POST['fields']) ? sanitize_key($_POST['fields']) : 'email_and_name';
2122 - $emails_in = isset($_POST['emails']) ? (array) wp_unslash($_POST['emails']) : [];
1010 + // Clear relevant cache before deletion
1011 + $cache_key = 'chat_session_' . $session_id_sanitized;
1012 + wp_cache_delete($cache_key, 'mxchat_chat_sessions');
2123 1013
2124 - $emails_in_clean = [];
2125 - foreach ($emails_in as $e) {
2126 - $clean = sanitize_email((string) $e);
2127 - if ($clean) {
2128 - $emails_in_clean[] = $clean;
2129 - }
2130 - }
1014 + // Perform the deletion
1015 + $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
1016 + }
2131 1017
2132 - global $wpdb;
2133 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2134 - $has_page_url_column = !empty($wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'originating_page_url'"));
1018 + // Optionally, clear a general cache if you have one
1019 + wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
2135 1020
2136 - // Collect leads from transcripts.
2137 - $transcripts_sql = "SELECT user_email AS email,
2138 - MAX(timestamp) AS last_seen,
2139 - COUNT(DISTINCT session_id) AS conversation_count
2140 - FROM {$table}
2141 - WHERE user_email IS NOT NULL AND user_email != ''";
2142 - $params = [];
2143 - if ($scope === 'selected' && !empty($emails_in_clean)) {
2144 - $placeholders = implode(',', array_fill(0, count($emails_in_clean), '%s'));
2145 - $transcripts_sql .= " AND user_email IN ({$placeholders})";
2146 - $params = $emails_in_clean;
2147 - }
2148 - $transcripts_sql .= " GROUP BY user_email ORDER BY last_seen DESC";
2149 -
2150 - $rows = !empty($params)
2151 - ? $wpdb->get_results($wpdb->prepare($transcripts_sql, $params))
2152 - : $wpdb->get_results($transcripts_sql);
2153 -
2154 - // Hydrate each row with name + top page.
2155 - $export_rows = [];
2156 - foreach ($rows as $row) {
2157 - $detail = $has_page_url_column
2158 - ? $wpdb->get_row($wpdb->prepare(
2159 - "SELECT user_name, originating_page_url FROM {$table}
2160 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2161 - $row->email
2162 - ))
2163 - : $wpdb->get_row($wpdb->prepare(
2164 - "SELECT user_name FROM {$table}
2165 - WHERE user_email = %s ORDER BY timestamp DESC LIMIT 1",
2166 - $row->email
2167 - ));
2168 - $export_rows[] = [
2169 - 'email' => $row->email,
2170 - 'name' => isset($detail->user_name) ? (string) $detail->user_name : '',
2171 - 'conversation_count' => (int) $row->conversation_count,
2172 - 'last_seen' => $row->last_seen,
2173 - 'top_page_url' => isset($detail->originating_page_url) ? $detail->originating_page_url : '',
2174 - ];
2175 - }
2176 -
2177 - // Include orphan + chat_deleted leads when exporting all.
2178 - if ($scope === 'all') {
2179 - $transcripts_emails_lc = array_flip(array_map(
2180 - function ($r) { return strtolower($r['email']); },
2181 - $export_rows
2182 - ));
2183 - foreach (self::mxchat_collect_chat_deleted_leads('') as $cd) {
2184 - if (isset($transcripts_emails_lc[strtolower($cd['email'])])) continue;
2185 - $transcripts_emails_lc[strtolower($cd['email'])] = true;
2186 - $export_rows[] = [
2187 - 'email' => $cd['email'],
2188 - 'name' => $cd['name'],
2189 - 'conversation_count' => 0,
2190 - 'last_seen' => $cd['last_seen'],
2191 - 'top_page_url' => '',
2192 - ];
1021 + echo wp_json_encode(['success' => 'Selected chat sessions have been deleted.']);
1022 + } else {
1023 + echo wp_json_encode(['error' => 'No chat sessions selected for deletion.']);
2193 1024 }
2194 - foreach (self::mxchat_collect_orphan_leads('') as $orphan) {
2195 - if (isset($transcripts_emails_lc[strtolower($orphan['email'])])) continue;
2196 - $transcripts_emails_lc[strtolower($orphan['email'])] = true;
2197 - $export_rows[] = [
2198 - 'email' => $orphan['email'],
2199 - 'name' => $orphan['name'],
2200 - 'conversation_count' => 0,
2201 - 'last_seen' => '',
2202 - 'top_page_url' => '',
2203 - ];
2204 - }
2205 - }
2206 1025
2207 - if (empty($export_rows)) {
2208 - wp_send_json_error(['message' => 'No leads to export.']);
2209 1026 wp_die();
2210 1027 }
1028 +public function mxchat_save_inline_prompt() {
1029 + // Check for nonce security
1030 + check_ajax_referer('mxchat_save_inline_nonce');
2211 1031
2212 - $filename = 'mxchat-leads-' . date('Y-m-d') . '.csv';
2213 - header('Content-Type: text/csv');
2214 - header('Content-Disposition: attachment; filename="' . $filename . '"');
2215 - header('Pragma: no-cache');
2216 - header('Expires: 0');
2217 -
2218 - $output = fopen('php://output', 'w');
2219 - fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
2220 -
2221 - if ($fields_mode === 'email_only') {
2222 - fputcsv($output, ['Email']);
2223 - foreach ($export_rows as $r) {
2224 - fputcsv($output, [$r['email']]);
2225 - }
2226 - } else {
2227 - fputcsv($output, ['Email', 'Name', 'Conversations', 'Last seen', 'Top page']);
2228 - foreach ($export_rows as $r) {
2229 - fputcsv($output, [
2230 - $r['email'],
2231 - $r['name'],
2232 - $r['conversation_count'],
2233 - $r['last_seen'],
2234 - $r['top_page_url'],
2235 - ]);
2236 - }
1032 + // Verify permissions
1033 + if (!current_user_can('manage_options')) {
1034 + wp_send_json_error('Permission denied.');
1035 + return;
2237 1036 }
2238 1037
2239 - fclose($output);
2240 - wp_die();
2241 -}
2242 -
2243 -/**
2244 - * Stats strip payload (independent of filters).
2245 - */
2246 -private static function mxchat_leads_stats($table, $has_page_url_column) {
2247 1038 global $wpdb;
1039 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2248 1040
2249 - $total_transcripts_emails = (int) $wpdb->get_var(
2250 - "SELECT COUNT(DISTINCT user_email) FROM {$table}
2251 - WHERE user_email IS NOT NULL AND user_email != ''"
2252 - );
1041 + // Validate and sanitize input data
1042 + $prompt_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
1043 + $article_content = isset($_POST['article_content']) ? sanitize_textarea_field($_POST['article_content']) : '';
1044 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : '';
2253 1045
2254 - $new_this_week = (int) $wpdb->get_var($wpdb->prepare(
2255 - "SELECT COUNT(*) FROM (
2256 - SELECT user_email FROM {$table}
2257 - WHERE user_email IS NOT NULL AND user_email != ''
2258 - GROUP BY user_email
2259 - HAVING MIN(timestamp) >= %s
2260 - ) AS new_leads",
2261 - gmdate('Y-m-d H:i:s', strtotime('-7 days'))
2262 - ));
1046 + if ($prompt_id > 0 && !empty($article_content)) {
1047 + // Re-generate the embedding vector for the updated content
1048 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
2263 1049
2264 - $total_convos = (int) $wpdb->get_var(
2265 - "SELECT COUNT(DISTINCT session_id) FROM {$table}
2266 - WHERE user_email IS NOT NULL AND user_email != ''"
2267 - );
1050 + if (is_array($embedding_vector)) {
1051 + // Serialize the embedding vector before storing it
1052 + $embedding_vector_serialized = serialize($embedding_vector);
2268 1053
2269 - $orphan_count = count(self::mxchat_collect_orphan_leads(''));
2270 - $chat_deleted_count = self::mxchat_count_chat_deleted_leads();
1054 + // Update the prompt in the database
1055 + $updated = $wpdb->update(
1056 + $table_name,
1057 + array(
1058 + 'article_content' => $article_content,
1059 + 'embedding_vector' => $embedding_vector_serialized,
1060 + 'source_url' => $article_url,
1061 + ),
1062 + array('id' => $prompt_id),
1063 + array('%s', '%s', '%s'),
1064 + array('%d')
1065 + );
2271 1066
2272 - // Total leads = unique emails across all three sources (dedup priority: transcripts > chat_deleted > orphan
2273 - // is already enforced at collection time in mxchat_fetch_leads; stats re-apply it here).
2274 - $total_leads = $total_transcripts_emails + $chat_deleted_count + $orphan_count;
2275 -
2276 - $avg = $total_transcripts_emails > 0
2277 - ? round($total_convos / $total_transcripts_emails, 1)
2278 - : 0;
2279 -
2280 - // Orphan % reflects *true* orphans only (pre-chat dropoffs). Chat-deleted leads are
2281 - // excluded so the metric stays meaningful — admins shouldn't see their cleanups
2282 - // inflate this number.
2283 - $orphan_pct = $total_leads > 0
2284 - ? (int) round(($orphan_count / $total_leads) * 100)
2285 - : 0;
2286 -
2287 - return [
2288 - 'total_leads' => $total_leads,
2289 - 'new_this_week' => $new_this_week,
2290 - 'avg_convos' => $avg,
2291 - 'orphan_pct' => $orphan_pct,
2292 - 'orphan_count' => $orphan_count,
2293 - 'chat_deleted_count' => $chat_deleted_count,
2294 - ];
2295 -}
2296 -
2297 -/**
2298 - * Collect leads who had a conversation that an admin later deleted (preserved via
2299 - * mxchat_lead_del_* options). Returns rows tagged status='chat_deleted' with the
2300 - * original last-seen timestamp so they still sort and filter sensibly.
2301 - *
2302 - * @param string $search Optional email/name substring filter.
2303 - * @param string $date_cutoff Optional 'Y-m-d H:i:s' cutoff — only rows with last_ts >= cutoff.
2304 - * @return array
2305 - */
2306 -private static function mxchat_collect_chat_deleted_leads($search = '', $date_cutoff = '') {
2307 - global $wpdb;
2308 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2309 -
2310 - $rows = $wpdb->get_results(
2311 - "SELECT option_name, option_value FROM {$wpdb->options}
2312 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2313 - );
2314 - if (empty($rows)) {
2315 - return [];
2316 - }
2317 -
2318 - // Emails that currently have transcripts rows should not appear as chat_deleted —
2319 - // they've come back and chatted, so they're active leads again.
2320 - $emails_in_transcripts = array_map(
2321 - 'strtolower',
2322 - (array) $wpdb->get_col(
2323 - "SELECT DISTINCT user_email FROM {$table}
2324 - WHERE user_email IS NOT NULL AND user_email != ''"
2325 - )
2326 - );
2327 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2328 -
2329 - $needle = strtolower(trim((string) $search));
2330 - $by_email = [];
2331 -
2332 - foreach ($rows as $opt) {
2333 - $email = sanitize_email(trim((string) $opt->option_value));
2334 - if (!$email) {
2335 - continue;
2336 - }
2337 - if (isset($emails_in_transcripts[strtolower($email)])) {
2338 - continue;
2339 - }
2340 - $sid = substr($opt->option_name, strlen('mxchat_lead_del_email_'));
2341 - if (!$sid) {
2342 - continue;
2343 - }
2344 - $name = (string) get_option('mxchat_lead_del_name_' . $sid, '');
2345 - $ts = (string) get_option('mxchat_lead_del_ts_' . $sid, '');
2346 -
2347 - if ($date_cutoff !== '' && ($ts === '' || $ts < $date_cutoff)) {
2348 - continue;
2349 - }
2350 - if ($needle !== '') {
2351 - $hay = strtolower($email . ' ' . $name);
2352 - if (strpos($hay, $needle) === false) {
2353 - continue;
1067 + if ($updated !== false) {
1068 + wp_send_json_success();
1069 + } else {
1070 + wp_send_json_error('Database update failed.');
2354 1071 }
1072 + } else {
1073 + wp_send_json_error('Embedding generation failed.');
2355 1074 }
2356 -
2357 - $key = strtolower($email);
2358 - if (!isset($by_email[$key]) || (isset($by_email[$key]['last_seen']) && $ts > $by_email[$key]['last_seen'])) {
2359 - $by_email[$key] = [
2360 - 'email' => $email,
2361 - 'name' => $name,
2362 - 'conversation_count' => 0,
2363 - 'last_seen' => $ts,
2364 - 'last_seen_display' => $ts ? self::mxchat_leads_format_relative($ts) : __('Chat deleted', 'mxchat'),
2365 - 'first_seen' => $ts,
2366 - 'latest_session_id' => '',
2367 - 'top_page_url' => '',
2368 - 'top_page_title' => '',
2369 - 'is_orphan' => false,
2370 - 'status' => 'chat_deleted',
2371 - ];
2372 - }
1075 + } else {
1076 + wp_send_json_error('Invalid data.');
2373 1077 }
2374 -
2375 - // Newest chat_deleted first.
2376 - usort($by_email, function ($a, $b) {
2377 - return strcmp((string) $b['last_seen'], (string) $a['last_seen']);
2378 - });
2379 - return array_values($by_email);
2380 1078 }
1079 +// Add this method to handle post updates
1080 +public function handle_post_update($post_id, $post, $update) {
1081 + // Don't process auto-saves or revisions
1082 + if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
1083 + //error_log('MXChat: Skipping - autosave');
1084 + return;
1085 + }
1086 + if (wp_is_post_revision($post_id)) {
1087 + //error_log('MXChat: Skipping - revision');
1088 + return;
1089 + }
2381 1090
2382 -/**
2383 - * Count unique emails preserved as "chat deleted" (for the stats strip).
2384 - */
2385 -private static function mxchat_count_chat_deleted_leads() {
2386 - global $wpdb;
2387 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
2388 -
2389 - $emails = $wpdb->get_col(
2390 - "SELECT DISTINCT option_value FROM {$wpdb->options}
2391 - WHERE option_name LIKE 'mxchat_lead_del_email_%'"
2392 - );
2393 - if (empty($emails)) {
2394 - return 0;
1091 + // Only process published content
1092 + if (!in_array($post->post_status, array('publish'))) {
1093 + //error_log('MXChat: Skipping - not published');
1094 + return;
2395 1095 }
2396 1096
2397 - $transcripts_emails = array_map(
2398 - 'strtolower',
2399 - (array) $wpdb->get_col(
2400 - "SELECT DISTINCT user_email FROM {$table}
2401 - WHERE user_email IS NOT NULL AND user_email != ''"
2402 - )
2403 - );
2404 - $transcripts_emails = array_flip($transcripts_emails);
1097 + // Check if sync is enabled for this post type
1098 + $post_type = $post->post_type;
1099 + $sync_option = ($post_type === 'post') ? 'mxchat_auto_sync_posts' : 'mxchat_auto_sync_pages';
2405 1100
2406 - $count = 0;
2407 - $seen = [];
2408 - foreach ($emails as $raw) {
2409 - $email = strtolower(trim((string) $raw));
2410 - if (!$email || isset($seen[$email]) || isset($transcripts_emails[$email])) {
2411 - continue;
2412 - }
2413 - $seen[$email] = true;
2414 - $count++;
1101 + if (get_option($sync_option) !== '1') {
1102 + //error_log('MXChat: Skipping - sync not enabled for this type');
1103 + return;
2415 1104 }
2416 - return $count;
2417 -}
2418 1105
2419 -/**
2420 - * Find leads who submitted the pre-chat form but never produced a transcripts row.
2421 - * Returned rows have no conversation_count, no timestamp.
2422 - *
2423 - * @param string $search Optional email/name substring filter.
2424 - * @return array
2425 - */
2426 -private static function mxchat_collect_orphan_leads($search = '') {
1106 + // Only process posts and pages
1107 + if (!in_array($post_type, array('post', 'page'))) return;
1108 +
2427 1109 global $wpdb;
2428 - $table = $wpdb->prefix . 'mxchat_chat_transcripts';
1110 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2429 1111
2430 - $option_rows = $wpdb->get_results(
2431 - "SELECT option_name, option_value FROM {$wpdb->options}
2432 - WHERE option_name LIKE 'mxchat_email_%'"
2433 - );
2434 - if (empty($option_rows)) {
2435 - return [];
2436 - }
1112 + // Get the post content and URL
1113 + $content = wp_strip_all_tags($post->post_content);
1114 + $url = get_permalink($post_id);
2437 1115
2438 - // Collect all session_ids that have real transcripts rows so we can exclude them.
2439 - $session_ids_with_rows = $wpdb->get_col(
2440 - "SELECT DISTINCT session_id FROM {$table}
2441 - WHERE user_email IS NOT NULL AND user_email != ''"
2442 - );
2443 - $session_ids_with_rows = array_flip($session_ids_with_rows);
2444 -
2445 - // Seen emails in transcripts (so orphans only include truly never-chatted leads).
2446 - $emails_in_transcripts = array_map(
2447 - 'strtolower',
2448 - (array) $wpdb->get_col(
2449 - "SELECT DISTINCT user_email FROM {$table}
2450 - WHERE user_email IS NOT NULL AND user_email != ''"
1116 + // Check if this URL already exists in the database
1117 + $existing_entry = $wpdb->get_row(
1118 + $wpdb->prepare(
1119 + "SELECT id FROM $table_name WHERE source_url = %s",
1120 + $url
2451 1121 )
2452 1122 );
2453 - $emails_in_transcripts = array_flip($emails_in_transcripts);
2454 1123
2455 - $orphans_by_email = [];
2456 - $needle = strtolower(trim((string) $search));
1124 + // Generate embedding for the content
1125 + $embedding_vector = $this->mxchat_generate_embedding($content);
1126 + if (!$embedding_vector) return;
2457 1127
2458 - foreach ($option_rows as $opt) {
2459 - $email = sanitize_email(trim((string) $opt->option_value));
2460 - if (!$email) {
2461 - continue;
2462 - }
2463 - $sid = substr($opt->option_name, strlen('mxchat_email_'));
2464 - if (!$sid) {
2465 - continue;
2466 - }
2467 - // Exclude leads who have any transcripts rows (they appear in the main list).
2468 - if (isset($emails_in_transcripts[strtolower($email)])) {
2469 - continue;
2470 - }
2471 - if (isset($session_ids_with_rows[$sid])) {
2472 - continue;
2473 - }
2474 -
2475 - $name_option = get_option('mxchat_name_' . $sid, '');
2476 - $name = is_string($name_option) ? trim($name_option) : '';
2477 -
2478 - if ($needle !== '') {
2479 - $hay = strtolower($email . ' ' . $name);
2480 - if (strpos($hay, $needle) === false) {
2481 - continue;
2482 - }
2483 - }
2484 -
2485 - $key = strtolower($email);
2486 - if (!isset($orphans_by_email[$key])) {
2487 - $orphans_by_email[$key] = [
2488 - 'email' => $email,
2489 - 'name' => $name,
2490 - 'conversation_count' => 0,
2491 - 'last_seen' => '',
2492 - 'last_seen_display' => __('No conversation yet', 'mxchat'),
2493 - 'first_seen' => '',
2494 - 'latest_session_id' => '',
2495 - 'top_page_url' => '',
2496 - 'top_page_title' => '',
2497 - 'is_orphan' => true,
2498 - 'status' => 'orphan',
2499 - ];
2500 - }
1128 + if ($existing_entry) {
1129 + // Update existing entry
1130 + $wpdb->update(
1131 + $table_name,
1132 + array(
1133 + 'article_content' => $content,
1134 + 'embedding_vector' => serialize($embedding_vector),
1135 + 'timestamp' => current_time('mysql')
1136 + ),
1137 + array('id' => $existing_entry->id),
1138 + array('%s', '%s', '%s'),
1139 + array('%d')
1140 + );
1141 + } else {
1142 + // Insert new entry
1143 + $wpdb->insert(
1144 + $table_name,
1145 + array(
1146 + 'article_content' => $content,
1147 + 'source_url' => $url,
1148 + 'embedding_vector' => serialize($embedding_vector),
1149 + 'timestamp' => current_time('mysql')
1150 + ),
1151 + array('%s', '%s', '%s', '%s')
1152 + );
2501 1153 }
2502 -
2503 - return array_values($orphans_by_email);
2504 1154 }
1155 +public function mxchat_handle_content_submission() {
1156 + // Check if the form was submitted and the user has sufficient permissions
1157 + if (!isset($_POST['submit_content']) || !current_user_can('manage_options')) {
1158 + return;
1159 + }
2505 1160
2506 -/**
2507 - * Map a date_range key to a SQL-comparable cutoff string, or '' for all-time.
2508 - */
2509 -private static function mxchat_leads_date_cutoff($date_range) {
2510 - switch ($date_range) {
2511 - case 'today': return gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
2512 - case '7d': return gmdate('Y-m-d H:i:s', strtotime('-7 days'));
2513 - case '30d': return gmdate('Y-m-d H:i:s', strtotime('-30 days'));
2514 - case '90d': return gmdate('Y-m-d H:i:s', strtotime('-90 days'));
2515 - case 'all':
2516 - default: return '';
1161 + // Verify the nonce field for security
1162 + $nonce = isset($_POST['mxchat_submit_content_nonce']) ? sanitize_text_field(wp_unslash($_POST['mxchat_submit_content_nonce'])) : '';
1163 + if (!wp_verify_nonce($nonce, 'mxchat_submit_content_action')) {
1164 + wp_die('Nonce verification failed.');
2517 1165 }
2518 -}
2519 1166
2520 -/**
2521 - * Turn a UTC timestamp into a short relative display like "2h ago" or "Apr 12".
2522 - */
2523 -private static function mxchat_leads_format_relative($timestamp) {
2524 - if (!$timestamp) {
2525 - return '';
2526 - }
2527 - $ts = strtotime($timestamp . ' UTC');
2528 - if (!$ts) {
2529 - return '';
2530 - }
2531 - $diff = time() - $ts;
2532 - if ($diff < 60) return __('just now', 'mxchat');
2533 - if ($diff < 3600) return floor($diff / 60) . __('m ago', 'mxchat');
2534 - if ($diff < 86400) return floor($diff / 3600) . __('h ago', 'mxchat');
2535 - if ($diff < 604800) return floor($diff / 86400) . __('d ago', 'mxchat');
2536 - return wp_date('M j', $ts);
2537 -}
1167 + // Sanitize the content input
1168 + $article_content = sanitize_textarea_field($_POST['article_content']);
2538 1169
2539 -/**
2540 - * Handle translation of chat messages via AJAX
2541 - */
2542 -public function mxchat_translate_messages() {
2543 - if (!current_user_can('manage_options')) {
2544 - wp_send_json_error(['error' => 'Insufficient permissions']);
2545 - wp_die();
2546 - }
1170 + // Sanitize the URL input (optional URL)
1171 + $article_url = isset($_POST['article_url']) ? esc_url_raw($_POST['article_url']) : ''; // Default to empty if not provided
2547 1172
2548 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
2549 - $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'en';
2550 - $messages_json = isset($_POST['messages']) ? wp_unslash($_POST['messages']) : '[]';
2551 - $messages = json_decode($messages_json, true);
1173 + // Generate the embedding vector for the content
1174 + $embedding_vector = $this->mxchat_generate_embedding($article_content);
2552 1175
2553 - if (empty($session_id)) {
2554 - wp_send_json_error(['error' => 'No session ID provided']);
2555 - wp_die();
2556 - }
1176 + global $wpdb;
1177 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
2557 1178
2558 - if (empty($messages) || !is_array($messages)) {
2559 - wp_send_json_error(['error' => 'No messages to translate']);
2560 - wp_die();
1179 + // Check if the 'source_url' column exists in the table and add it if it doesn't
1180 + if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$table_name} LIKE %s", 'source_url')) != 'source_url') {
1181 + // Use wpdb::query and a prepared statement to avoid SQL injection
1182 + $wpdb->query($wpdb->prepare("ALTER TABLE {$table_name} ADD source_url VARCHAR(255) DEFAULT ''"));
2561 1183 }
2562 1184
2563 - // Language names for prompting
2564 - $languages = [
2565 - 'en' => 'English',
2566 - 'es' => 'Spanish',
2567 - 'fr' => 'French',
2568 - 'de' => 'German',
2569 - 'it' => 'Italian',
2570 - 'pt' => 'Portuguese',
2571 - 'nl' => 'Dutch',
2572 - 'ru' => 'Russian',
2573 - 'zh' => 'Chinese',
2574 - 'ja' => 'Japanese',
2575 - 'ko' => 'Korean',
2576 - 'ar' => 'Arabic',
2577 - 'hi' => 'Hindi',
2578 - 'tr' => 'Turkish',
2579 - 'pl' => 'Polish',
2580 - 'vi' => 'Vietnamese',
2581 - 'th' => 'Thai',
2582 - 'id' => 'Indonesian',
2583 - 'sv' => 'Swedish',
2584 - 'da' => 'Danish'
2585 - ];
1185 + if (is_array($embedding_vector)) {
1186 + // Serialize the embedding vector before storing it
1187 + $embedding_vector_serialized = serialize($embedding_vector);
2586 1188
2587 - $target_lang_name = isset($languages[$target_lang]) ? $languages[$target_lang] : 'English';
1189 + // Insert the content, embedding vector, and source URL into the database, using a prepared statement
1190 + $inserted = $wpdb->insert(
1191 + $table_name,
1192 + array(
1193 + 'article_content' => $article_content,
1194 + 'embedding_vector' => $embedding_vector_serialized,
1195 + 'source_url' => $article_url, // Insert the URL, empty string if not provided
1196 + ),
1197 + array(
1198 + '%s', // Format for article_content (string)
1199 + '%s', // Format for embedding_vector (serialized string)
1200 + '%s', // Format for source_url (string)
1201 + )
1202 + );
2588 1203
2589 - // Build combined text for translation (numbered for parsing)
2590 - $numbered_messages = [];
2591 - foreach ($messages as $i => $msg) {
2592 - $content = isset($msg['content']) ? trim($msg['content']) : '';
2593 - if (!empty($content)) {
2594 - $numbered_messages[] = "[MSG" . $i . "]" . $content . "[/MSG" . $i . "]";
1204 + if ($inserted === false) {
1205 + //error_log('Error inserting content: ' . $wpdb->last_error);
1206 + set_transient('mxchat_admin_notice_error', 'Error inserting content into the database. Please try again.', 30);
1207 + } else {
1208 + set_transient('mxchat_admin_notice_success', 'Content successfully submitted!', 30);
2595 1209 }
2596 - }
2597 1210
2598 - if (empty($numbered_messages)) {
2599 - wp_send_json_error(['error' => 'No valid messages to translate']);
2600 - wp_die();
2601 - }
2602 -
2603 - $combined_text = implode("\n\n", $numbered_messages);
2604 -
2605 - // Prepare the translation prompt
2606 - $system_prompt = "You are a translator. Translate the following messages to {$target_lang_name}. Keep the [MSG#] and [/MSG#] tags exactly as they are - only translate the content between them. Maintain the original formatting, line breaks, and any HTML tags. Return ONLY the translated messages with the tags, no explanations.";
2607 -
2608 - // Get user's selected model and determine provider
2609 - $options = get_option('mxchat_options', []);
2610 - $selected_model = $options['model'] ?? 'gpt-5.1-chat-latest';
2611 -
2612 - // Check if using OpenRouter
2613 - if ($selected_model === 'openrouter') {
2614 - $provider = 'openrouter';
2615 - $selected_model = $options['openrouter_selected_model'] ?? '';
2616 - $api_key = $options['openrouter_api_key'] ?? '';
2617 -
2618 - if (empty($selected_model)) {
2619 - wp_send_json_error(['error' => 'No OpenRouter model selected']);
2620 - wp_die();
2621 - }
2622 1211 } else {
2623 - // Determine provider from model name
2624 - $model_parts = explode('-', $selected_model);
2625 - $provider = strtolower($model_parts[0]);
2626 -
2627 - // Get the appropriate API key based on provider
2628 - $api_key = '';
2629 - switch ($provider) {
2630 - case 'gpt':
2631 - case 'o1':
2632 - $api_key = $options['api_key'] ?? '';
2633 - break;
2634 - case 'claude':
2635 - $api_key = $options['claude_api_key'] ?? '';
2636 - break;
2637 - case 'grok':
2638 - $api_key = $options['xai_api_key'] ?? '';
2639 - break;
2640 - case 'deepseek':
2641 - $api_key = $options['deepseek_api_key'] ?? '';
2642 - break;
2643 - case 'gemini':
2644 - $api_key = $options['gemini_api_key'] ?? '';
2645 - break;
2646 - default:
2647 - // Default to OpenAI
2648 - $api_key = $options['api_key'] ?? '';
2649 - $provider = 'gpt';
2650 - break;
2651 - }
1212 + //error_log('Embedding generation failed for article content: ' . $article_content);
1213 + set_transient('mxchat_admin_notice_error', 'Embedding generation failed. Please ensure your API key is correct and try again.', 30);
2652 1214 }
2653 1215
2654 - if (empty($api_key)) {
2655 - wp_send_json_error(['error' => 'No API key configured for ' . $provider]);
2656 - wp_die();
2657 - }
2658 -
2659 - // Make API request based on provider
2660 - $response = $this->translate_with_provider($provider, $selected_model, $api_key, $system_prompt, $combined_text);
2661 -
2662 - if (is_wp_error($response)) {
2663 - wp_send_json_error(['error' => $response->get_error_message()]);
2664 - wp_die();
2665 - }
2666 -
2667 - // Parse the response to extract translated messages
2668 - $translations = [];
2669 - foreach ($messages as $msg) {
2670 - $index = $msg['index'];
2671 - $pattern = '/\[MSG' . $index . '\](.*?)\[\/MSG' . $index . '\]/s';
2672 - if (preg_match($pattern, $response, $matches)) {
2673 - $translations[] = [
2674 - 'index' => $index,
2675 - 'translated' => trim($matches[1])
2676 - ];
2677 - }
2678 - }
2679 -
2680 - // Save translations to database
2681 - if (!empty($translations)) {
2682 - $this->save_transcript_translation($session_id, $target_lang, $translations);
2683 - }
2684 -
2685 - wp_send_json(['success' => true, 'translations' => $translations, 'language' => $target_lang]);
2686 - wp_die();
1216 + // Redirect after setting the transient
1217 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1218 + exit;
2687 1219 }
1220 +private function is_pdf_url($url, $response) {
1221 + $content_type = wp_remote_retrieve_header($response, 'content-type');
1222 + $file_extension = strtolower(pathinfo($url, PATHINFO_EXTENSION));
2688 1223
2689 -/**
2690 - * Save transcript translation to database
2691 - */
2692 -private function save_transcript_translation($session_id, $language_code, $translations) {
2693 - global $wpdb;
2694 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
2695 -
2696 - // Check if table exists, create if not
2697 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
2698 - mxchat_create_translations_table();
2699 - }
2700 -
2701 - $now = current_time('mysql');
2702 - $translations_json = wp_json_encode($translations);
2703 -
2704 - // Use REPLACE to insert or update
2705 - $wpdb->query($wpdb->prepare(
2706 - "REPLACE INTO $table_name (session_id, language_code, translations, created_at, updated_at)
2707 - VALUES (%s, %s, %s, %s, %s)",
2708 - $session_id,
2709 - $language_code,
2710 - $translations_json,
2711 - $now,
2712 - $now
2713 - ));
1224 + return strpos($content_type, 'pdf') !== false || $file_extension === 'pdf';
2714 1225 }
2715 -
2716 -/**
2717 - * Get saved translation for a session
2718 - */
2719 -public function mxchat_get_transcript_translation() {
1226 +private function handle_pdf_for_knowledge_base($pdf_url, $response) {
2720 1227 if (!current_user_can('manage_options')) {
2721 - wp_send_json_error(['error' => 'Insufficient permissions']);
2722 - wp_die();
1228 + //error_log('Unauthorized PDF processing attempt');
1229 + return false;
2723 1230 }
2724 1231
2725 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
1232 + $pdf_url = esc_url_raw($pdf_url);
1233 + $upload_dir = wp_upload_dir();
2726 1234
2727 - if (empty($session_id)) {
2728 - wp_send_json_error(['error' => 'No session ID provided']);
2729 - wp_die();
1235 + if (isset($upload_dir['error']) && $upload_dir['error'] !== false) {
1236 + //error_log(sprintf('Upload directory error: %s', esc_html($upload_dir['error'])));
1237 + return false;
2730 1238 }
2731 1239
2732 - global $wpdb;
2733 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
1240 + $pdf_filename = sanitize_file_name('mxchat_kb_' . time() . '.pdf');
1241 + $pdf_path = trailingslashit($upload_dir['path']) . $pdf_filename;
2734 1242
2735 - // Check if table exists
2736 - if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") !== $table_name) {
2737 - wp_send_json(['success' => true, 'has_translation' => false]);
2738 - wp_die();
1243 + $response_body = wp_remote_retrieve_body($response);
1244 + if (empty($response_body)) {
1245 + //error_log('Empty PDF response body');
1246 + return false;
2739 1247 }
2740 1248
2741 - // Get the most recent translation for this session
2742 - $result = $wpdb->get_row($wpdb->prepare(
2743 - "SELECT language_code, translations FROM $table_name WHERE session_id = %s ORDER BY updated_at DESC LIMIT 1",
2744 - $session_id
2745 - ));
2746 -
2747 - if ($result) {
2748 - $translations = json_decode($result->translations, true);
2749 - wp_send_json([
2750 - 'success' => true,
2751 - 'has_translation' => true,
2752 - 'language' => $result->language_code,
2753 - 'translations' => $translations
2754 - ]);
2755 - } else {
2756 - wp_send_json(['success' => true, 'has_translation' => false]);
1249 + if (!wp_mkdir_p(dirname($pdf_path))) {
1250 + //error_log(sprintf('Failed to create directory for PDF: %s', esc_html($pdf_path)));
1251 + return false;
2757 1252 }
2758 - wp_die();
2759 -}
2760 1253
2761 -/**
2762 - * Translate text using the user's selected provider and model
2763 - */
2764 -private function translate_with_provider($provider, $model, $api_key, $system_prompt, $text) {
2765 - switch ($provider) {
2766 - case 'claude':
2767 - return $this->translate_with_claude($api_key, $model, $system_prompt, $text);
2768 - case 'grok':
2769 - return $this->translate_with_xai($api_key, $model, $system_prompt, $text);
2770 - case 'deepseek':
2771 - return $this->translate_with_deepseek($api_key, $model, $system_prompt, $text);
2772 - case 'gemini':
2773 - return $this->translate_with_gemini($api_key, $model, $system_prompt, $text);
2774 - case 'openrouter':
2775 - return $this->translate_with_openrouter($api_key, $model, $system_prompt, $text);
2776 - case 'gpt':
2777 - case 'o1':
2778 - default:
2779 - return $this->translate_with_openai($api_key, $model, $system_prompt, $text);
2780 - }
2781 -}
1254 + try {
1255 + file_put_contents($pdf_path, $response_body);
2782 1256
2783 -/**
2784 - * Translate text using OpenAI API
2785 - */
2786 -private function translate_with_openai($api_key, $model, $system_prompt, $text) {
2787 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
2788 - 'timeout' => 60,
2789 - 'headers' => [
2790 - 'Authorization' => 'Bearer ' . $api_key,
2791 - 'Content-Type' => 'application/json'
2792 - ],
2793 - 'body' => wp_json_encode([
2794 - 'model' => $model,
2795 - 'messages' => [
2796 - ['role' => 'system', 'content' => $system_prompt],
2797 - ['role' => 'user', 'content' => $text]
2798 - ],
2799 - 'temperature' => 0.3
2800 - ])
2801 - ]);
1257 + if (!file_exists($pdf_path)) {
1258 + throw new Exception('Failed to save PDF file');
1259 + }
2802 1260
2803 - if (is_wp_error($response)) {
2804 - return $response;
2805 - }
1261 + $parser = new \Smalot\PdfParser\Parser();
1262 + $pdf = $parser->parseFile($pdf_path);
1263 + $total_pages = absint(count($pdf->getPages()));
2806 1264
2807 - $body = json_decode(wp_remote_retrieve_body($response), true);
1265 + if ($total_pages < 1) {
1266 + throw new Exception('Invalid PDF: no pages found');
1267 + }
2808 1268
2809 - if (isset($body['error'])) {
2810 - return new WP_Error('api_error', $body['error']['message']);
2811 - }
1269 + wp_schedule_single_event(time(), 'mxchat_process_pdf_pages', array(
1270 + 'pdf_path' => $pdf_path,
1271 + 'pdf_url' => $pdf_url,
1272 + 'total_pages' => $total_pages,
1273 + 'batch_size' => absint(15),
1274 + 'batch_pause' => absint(10)
1275 + ));
2812 1276
2813 - if (isset($body['choices'][0]['message']['content'])) {
2814 - return $body['choices'][0]['message']['content'];
2815 - }
1277 + $status_data = array(
1278 + 'total_pages' => $total_pages,
1279 + 'processed_pages' => 0,
1280 + 'status' => 'processing',
1281 + 'last_update' => time()
1282 + );
2816 1283
2817 - return new WP_Error('api_error', 'Invalid API response');
2818 -}
1284 + set_transient(
1285 + sanitize_key('mxchat_pdf_status_' . md5($pdf_url)),
1286 + array_map('sanitize_text_field', $status_data),
1287 + DAY_IN_SECONDS
1288 + );
2819 1289
2820 -/**
2821 - * Translate text using Claude API
2822 - */
2823 -private function translate_with_claude($api_key, $model, $system_prompt, $text) {
2824 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
2825 - 'timeout' => 60,
2826 - 'headers' => [
2827 - 'x-api-key' => $api_key,
2828 - 'anthropic-version' => '2023-06-01',
2829 - 'Content-Type' => 'application/json'
2830 - ],
2831 - 'body' => wp_json_encode([
2832 - 'model' => $model,
2833 - 'max_tokens' => 4096,
2834 - 'system' => $system_prompt,
2835 - 'messages' => [
2836 - ['role' => 'user', 'content' => $text]
2837 - ]
2838 - ])
2839 - ]);
1290 + return 'scheduled';
2840 1291
2841 - if (is_wp_error($response)) {
2842 - return $response;
1292 + } catch (Exception $e) {
1293 + //error_log(sprintf('Error preparing PDF for processing: %s', esc_html($e->getMessage())));
1294 + if (file_exists($pdf_path)) {
1295 + wp_delete_file($pdf_path);
1296 + }
1297 + return false;
2843 1298 }
1299 +}
1300 +public static function process_pdf_pages_cron($pdf_path, $pdf_url, $total_pages, $batch_size, $batch_pause) {
1301 + // Validate inputs
1302 + $pdf_path = sanitize_text_field($pdf_path);
1303 + $pdf_url = esc_url_raw($pdf_url);
1304 + $total_pages = absint($total_pages);
1305 + $batch_size = absint($batch_size);
1306 + $batch_pause = absint($batch_pause);
2844 1307
2845 - $body = json_decode(wp_remote_retrieve_body($response), true);
1308 + try {
1309 + if (!file_exists($pdf_path)) {
1310 + throw new Exception(sprintf('PDF file not found at path: %s', esc_html($pdf_path)));
1311 + }
2846 1312
2847 - if (isset($body['error'])) {
2848 - return new WP_Error('api_error', $body['error']['message']);
2849 - }
1313 + $parser = new \Smalot\PdfParser\Parser();
1314 + $pdf = $parser->parseFile($pdf_path);
1315 + $pages = $pdf->getPages();
2850 1316
2851 - if (isset($body['content'][0]['text'])) {
2852 - return $body['content'][0]['text'];
2853 - }
1317 + // Get current progress
1318 + $status_key = sanitize_key('mxchat_pdf_status_' . md5($pdf_url));
1319 + $status = get_transient($status_key);
2854 1320
2855 - return new WP_Error('api_error', 'Invalid API response');
2856 -}
1321 + if (!$status || !is_array($status)) {
1322 + throw new Exception('Invalid status data retrieved from transient');
1323 + }
2857 1324
2858 -/**
2859 - * Translate text using xAI (Grok) API
2860 - */
2861 -private function translate_with_xai($api_key, $model, $system_prompt, $text) {
2862 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', [
2863 - 'timeout' => 60,
2864 - 'headers' => [
2865 - 'Authorization' => 'Bearer ' . $api_key,
2866 - 'Content-Type' => 'application/json'
2867 - ],
2868 - 'body' => wp_json_encode([
2869 - 'model' => $model,
2870 - 'messages' => [
2871 - ['role' => 'system', 'content' => $system_prompt],
2872 - ['role' => 'user', 'content' => $text]
2873 - ],
2874 - 'temperature' => 0.3
2875 - ])
2876 - ]);
1325 + $start_page = absint($status['processed_pages']);
1326 + $end_page = min($start_page + $batch_size, $total_pages);
2877 1327
2878 - if (is_wp_error($response)) {
2879 - return $response;
2880 - }
1328 + $instance = new self(); // Create an instance of the class
2881 1329
2882 - $body = json_decode(wp_remote_retrieve_body($response), true);
1330 + for ($i = $start_page; $i < $end_page; $i++) {
1331 + $text = $pages[$i]->getText();
1332 + $sanitized_content = $instance->mxchat_sanitize_content_for_api($text); // Call via instance
2883 1333
2884 - if (isset($body['error'])) {
2885 - return new WP_Error('api_error', $body['error']['message']);
2886 - }
1334 + if (!empty($sanitized_content)) {
1335 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
1336 + if (is_array($embedding_vector)) {
1337 + $metadata = array(
1338 + 'document_type' => 'pdf',
1339 + 'total_pages' => $total_pages,
1340 + 'current_page' => $i + 1,
1341 + 'prev_page' => $i > 0 ? $i : null,
1342 + 'next_page' => $i < ($total_pages - 1) ? $i + 2 : null,
1343 + 'source_url' => $pdf_url
1344 + );
2887 1345
2888 - if (isset($body['choices'][0]['message']['content'])) {
2889 - return $body['choices'][0]['message']['content'];
2890 - }
1346 + $content_with_metadata = wp_json_encode($metadata) . "\n---\n" . $sanitized_content;
1347 + $page_url = esc_url($pdf_url . "#page=" . ($i + 1));
2891 1348
2892 - return new WP_Error('api_error', 'Invalid API response');
2893 -}
1349 + $options = get_option('mxchat_options');
1350 + MxChat_Utils::submit_content_to_db($content_with_metadata, $page_url, $options['api_key']);
1351 + }
1352 + }
2894 1353
2895 -/**
2896 - * Translate text using DeepSeek API
2897 - */
2898 -private function translate_with_deepseek($api_key, $model, $system_prompt, $text) {
2899 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', [
2900 - 'timeout' => 60,
2901 - 'headers' => [
2902 - 'Authorization' => 'Bearer ' . $api_key,
2903 - 'Content-Type' => 'application/json'
2904 - ],
2905 - 'body' => wp_json_encode([
2906 - 'model' => $model,
2907 - 'messages' => [
2908 - ['role' => 'system', 'content' => $system_prompt],
2909 - ['role' => 'user', 'content' => $text]
2910 - ],
2911 - 'temperature' => 0.3
2912 - ])
2913 - ]);
1354 + // Update progress with sanitized data
1355 + $status['processed_pages'] = absint($i + 1);
1356 + $status['last_update'] = time();
1357 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
1358 + }
2914 1359
2915 - if (is_wp_error($response)) {
2916 - return $response;
2917 - }
1360 + // Schedule next batch if needed
1361 + if ($end_page < $total_pages) {
1362 + wp_schedule_single_event(time() + $batch_pause, 'mxchat_process_pdf_pages', array(
1363 + 'pdf_path' => $pdf_path,
1364 + 'pdf_url' => $pdf_url,
1365 + 'total_pages' => $total_pages,
1366 + 'batch_size' => $batch_size,
1367 + 'batch_pause' => $batch_pause
1368 + ));
1369 + } else {
1370 + // Processing complete
1371 + $status['status'] = 'complete';
1372 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
1373 + if (file_exists($pdf_path)) {
1374 + wp_delete_file($pdf_path);
1375 + }
1376 + }
2918 1377
2919 - $body = json_decode(wp_remote_retrieve_body($response), true);
2920 -
2921 - if (isset($body['error'])) {
2922 - return new WP_Error('api_error', $body['error']['message']);
1378 + } catch (\Exception $e) {
1379 + $status['status'] = 'error';
1380 + $status['error'] = sanitize_text_field($e->getMessage());
1381 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
1382 + if (file_exists($pdf_path)) {
1383 + wp_delete_file($pdf_path);
1384 + }
2923 1385 }
2924 -
2925 - if (isset($body['choices'][0]['message']['content'])) {
2926 - return $body['choices'][0]['message']['content'];
2927 - }
2928 -
2929 - return new WP_Error('api_error', 'Invalid API response');
2930 1386 }
1387 +public function get_pdf_processing_status($pdf_url) {
1388 + $pdf_url = esc_url_raw($pdf_url);
1389 + $status = get_transient(sanitize_key('mxchat_pdf_status_' . md5($pdf_url)));
2931 1390
2932 -/**
2933 - * Translate text using Google Gemini API
2934 - */
2935 -private function translate_with_gemini($api_key, $model, $system_prompt, $text) {
2936 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $api_key;
2937 -
2938 - $response = wp_remote_post($url, [
2939 - 'timeout' => 60,
2940 - 'headers' => [
2941 - 'Content-Type' => 'application/json'
2942 - ],
2943 - 'body' => wp_json_encode([
2944 - 'contents' => [
2945 - [
2946 - 'parts' => [
2947 - ['text' => $system_prompt . "\n\n" . $text]
2948 - ]
2949 - ]
2950 - ],
2951 - 'generationConfig' => [
2952 - 'temperature' => 0.3
2953 - ]
2954 - ])
2955 - ]);
2956 -
2957 - if (is_wp_error($response)) {
2958 - return $response;
1391 + if (!$status || !is_array($status)) {
1392 + return false;
2959 1393 }
2960 1394
2961 - $body = json_decode(wp_remote_retrieve_body($response), true);
2962 -
2963 - if (isset($body['error'])) {
2964 - return new WP_Error('api_error', $body['error']['message']);
2965 - }
2966 -
2967 - if (isset($body['candidates'][0]['content']['parts'][0]['text'])) {
2968 - return $body['candidates'][0]['content']['parts'][0]['text'];
2969 - }
2970 -
2971 - return new WP_Error('api_error', 'Invalid API response');
1395 + return array(
1396 + 'total_pages' => absint($status['total_pages']),
1397 + 'processed_pages' => absint($status['processed_pages']),
1398 + 'percentage' => round((absint($status['processed_pages']) / absint($status['total_pages'])) * 100),
1399 + 'status' => sanitize_text_field($status['status']),
1400 + 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ago'
1401 + );
2972 1402 }
2973 -
2974 -/**
2975 - * Translate text using OpenRouter API
2976 - */
2977 -private function translate_with_openrouter($api_key, $model, $system_prompt, $text) {
2978 - $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', [
2979 - 'timeout' => 60,
2980 - 'headers' => [
2981 - 'Authorization' => 'Bearer ' . $api_key,
2982 - 'Content-Type' => 'application/json',
2983 - 'HTTP-Referer' => home_url(),
2984 - 'X-Title' => 'MxChat Translation'
2985 - ],
2986 - 'body' => wp_json_encode([
2987 - 'model' => $model,
2988 - 'messages' => [
2989 - ['role' => 'system', 'content' => $system_prompt],
2990 - ['role' => 'user', 'content' => $text]
2991 - ],
2992 - 'temperature' => 0.3
2993 - ])
2994 - ]);
2995 -
2996 - if (is_wp_error($response)) {
2997 - return $response;
1403 +public function mxchat_handle_sitemap_submission() {
1404 + // Check if the form was submitted and verify permissions
1405 + if (!isset($_POST['submit_sitemap']) || !current_user_can('manage_options')) {
1406 + wp_die(esc_html__('Unauthorized access', 'mxchat'));
2998 1407 }
2999 1408
3000 - $body = json_decode(wp_remote_retrieve_body($response), true);
1409 + // Verify nonce
1410 + check_admin_referer('mxchat_submit_sitemap_action', 'mxchat_submit_sitemap_nonce');
3001 1411
3002 - if (isset($body['error'])) {
3003 - return new WP_Error('api_error', $body['error']['message']);
1412 + // Validate URL
1413 + if (!isset($_POST['sitemap_url']) || empty($_POST['sitemap_url'])) {
1414 + set_transient('mxchat_admin_notice_error',
1415 + esc_html__('Please provide a valid URL.', 'mxchat'),
1416 + 30
1417 + );
1418 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1419 + exit;
3004 1420 }
3005 1421
3006 - if (isset($body['choices'][0]['message']['content'])) {
3007 - return $body['choices'][0]['message']['content'];
3008 - }
1422 + $submitted_url = esc_url_raw($_POST['sitemap_url']);
1423 + $response = wp_remote_get($submitted_url, array('timeout' => 30));
3009 1424
3010 - return new WP_Error('api_error', 'Invalid API response');
3011 -}
3012 -
3013 -public function mxchat_fetch_chat_history() {
3014 - global $wpdb;
3015 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3016 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
3017 -
3018 - if (!current_user_can('manage_options')) {
3019 - wp_send_json_error(['message' => 'Insufficient permissions']);
3020 - wp_die();
1425 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1426 + $error_message = is_wp_error($response) ? $response->get_error_message() : 'Failed to fetch URL';
1427 + set_transient('mxchat_admin_notice_error',
1428 + sprintf(
1429 + esc_html__('Failed to fetch the URL: %s', 'mxchat'),
1430 + esc_html($error_message)
1431 + ),
1432 + 30
1433 + );
1434 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1435 + exit;
3021 1436 }
3022 1437
3023 - $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
3024 - $per_page = isset($_POST['per_page']) ? absint($_POST['per_page']) : 50;
3025 - $offset = ($page - 1) * $per_page;
3026 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
3027 - $sort_raw = isset($_POST['sort_order']) ? sanitize_key($_POST['sort_order']) : 'desc';
3028 - $allowed_sorts = array('asc', 'desc', 'rating_positive', 'rating_negative');
3029 - if (!in_array($sort_raw, $allowed_sorts, true)) { $sort_raw = 'desc'; }
3030 - $sort_order = ($sort_raw === 'asc') ? 'ASC' : 'DESC';
3031 - $ratings_table = $wpdb->prefix . 'mxchat_session_ratings';
3032 - $ratings_join = '';
3033 - $rating_table_exists = ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $ratings_table)) === $ratings_table);
3034 - if ($rating_table_exists && ($sort_raw === 'rating_positive' || $sort_raw === 'rating_negative')) {
3035 - // We sort by rating then recency. Wrap rating_value so NULL sorts last.
3036 - $rating_dir = ($sort_raw === 'rating_positive') ? 'DESC' : 'ASC';
3037 - $ratings_join = " LEFT JOIN {$ratings_table} r ON r.session_id = t.session_id ";
3038 - }
1438 + $content_type = wp_remote_retrieve_header($response, 'content-type');
1439 + $body_content = wp_remote_retrieve_body($response);
3039 1440
3040 - // Build search condition
3041 - $search_condition = '';
3042 - $search_params = [];
3043 - if (!empty($search)) {
3044 - $search_condition = "WHERE (
3045 - session_id LIKE %s
3046 - OR user_email LIKE %s
3047 - OR user_name LIKE %s
3048 - OR user_identifier LIKE %s
3049 - OR message LIKE %s
3050 - )";
3051 - $search_params = array_fill(0, 5, '%' . $wpdb->esc_like($search) . '%');
3052 - }
3053 -
3054 - // Get total count
3055 - $count_query = !empty($search)
3056 - ? $wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$table_name} {$search_condition}", $search_params)
3057 - : "SELECT COUNT(DISTINCT session_id) FROM {$table_name}";
3058 - $total_sessions = (int) $wpdb->get_var($count_query);
3059 -
3060 - // Get session IDs for current page. Default sort is recency; rating sorts join the ratings table
3061 - // and order by rating value (NULLs last) with recency as tiebreaker.
3062 - if ($ratings_join) {
3063 - $order_by = "ORDER BY (r.rating_value IS NULL), r.rating_value {$rating_dir}, MAX(t.timestamp) DESC";
3064 - } else {
3065 - $order_by = "ORDER BY MAX(t.timestamp) {$sort_order}";
3066 - }
3067 - $session_query = !empty($search)
3068 - ? $wpdb->prepare(
3069 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join} {$search_condition}
3070 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3071 - array_merge($search_params, [$per_page, $offset])
3072 - )
3073 - : $wpdb->prepare(
3074 - "SELECT DISTINCT t.session_id FROM {$table_name} t {$ratings_join}
3075 - GROUP BY t.session_id {$order_by} LIMIT %d OFFSET %d",
3076 - $per_page, $offset
1441 + if (empty($body_content)) {
1442 + set_transient('mxchat_admin_notice_error',
1443 + esc_html__('Empty response received from URL.', 'mxchat'),
1444 + 30
3077 1445 );
3078 - $session_ids = $wpdb->get_col($session_query);
3079 -
3080 - $total_pages = ceil($total_sessions / $per_page);
3081 -
3082 - if (empty($session_ids)) {
3083 - wp_send_json([
3084 - 'success' => true,
3085 - 'sessions' => [],
3086 - 'page' => $page,
3087 - 'total_pages' => 0,
3088 - 'total_sessions' => 0,
3089 - 'showing_start' => 0,
3090 - 'showing_end' => 0
3091 - ]);
3092 - wp_die();
1446 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1447 + exit;
3093 1448 }
3094 1449
3095 - // Check for optional columns/tables
3096 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3097 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
1450 + // Handle PDF URL
1451 + if ($this->is_pdf_url($submitted_url, $response)) {
1452 + $result = $this->handle_pdf_for_knowledge_base($submitted_url, $response);
3098 1453
3099 - // Batch-fetch session ratings for this page (plan-a5b006).
3100 - $ratings_map = array();
3101 - if ($rating_table_exists && !empty($session_ids)) {
3102 - $placeholders = implode(',', array_fill(0, count($session_ids), '%s'));
3103 - $rating_rows = $wpdb->get_results($wpdb->prepare(
3104 - "SELECT session_id, rating_value, rating_feedback FROM {$ratings_table} WHERE session_id IN ($placeholders)",
3105 - $session_ids
3106 - ));
3107 - foreach ($rating_rows as $row) {
3108 - $ratings_map[$row->session_id] = array(
3109 - 'value' => (int) $row->rating_value,
3110 - 'feedback' => (string) $row->rating_feedback,
1454 + if ($result === 'scheduled') {
1455 + set_transient(
1456 + 'mxchat_last_pdf_url',
1457 + sanitize_text_field($submitted_url),
1458 + DAY_IN_SECONDS
3111 1459 );
3112 - }
3113 - }
3114 -
3115 - // Build session list data
3116 - $sessions = [];
3117 - foreach ($session_ids as $session_id) {
3118 - // Get session metadata
3119 - $session_data = $originating_columns_exist
3120 - ? $wpdb->get_row($wpdb->prepare(
3121 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3122 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3123 - $session_id
3124 - ))
3125 - : $wpdb->get_row($wpdb->prepare(
3126 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3127 - WHERE session_id = %s LIMIT 1",
3128 - $session_id
3129 - ));
3130 -
3131 - // Get message count and latest timestamp
3132 - $message_stats = $wpdb->get_row($wpdb->prepare(
3133 - "SELECT COUNT(*) as count, MAX(timestamp) as latest FROM {$table_name} WHERE session_id = %s",
3134 - $session_id
3135 - ));
3136 -
3137 - // Get first user message as preview
3138 - $first_user_msg = $wpdb->get_var($wpdb->prepare(
3139 - "SELECT message FROM {$table_name} WHERE session_id = %s AND role = 'user' ORDER BY timestamp ASC LIMIT 1",
3140 - $session_id
3141 - ));
3142 - $preview = $first_user_msg ? wp_trim_words(wp_strip_all_tags(stripslashes($first_user_msg)), 12, '...') : 'No messages';
3143 -
3144 - // Build display name
3145 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3146 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3147 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3148 -
3149 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3150 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3151 -
3152 - // Format time - show relative for recent, date for older
3153 - $timestamp = strtotime($message_stats->latest . ' UTC');
3154 - $now = time();
3155 - $diff = $now - $timestamp;
3156 - if ($diff < 3600) {
3157 - $time_display = floor($diff / 60) . 'm ago';
3158 - } elseif ($diff < 86400) {
3159 - $time_display = floor($diff / 3600) . 'h ago';
3160 - } elseif ($diff < 604800) {
3161 - $time_display = floor($diff / 86400) . 'd ago';
1460 + set_transient('mxchat_admin_notice_info',
1461 + esc_html__('PDF processing has started in the background. You can check the progress in the Knowledge Base section.', 'mxchat'),
1462 + 30
1463 + );
3162 1464 } else {
3163 - $time_display = wp_date('M j', $timestamp);
1465 + set_transient('mxchat_admin_notice_error',
1466 + esc_html__('Failed to start PDF processing. Please try again.', 'mxchat'),
1467 + 30
1468 + );
3164 1469 }
3165 1470
3166 - // Get initials for avatar
3167 - $initials = strtoupper(substr($display_name, 0, 2));
3168 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3169 - $parts = explode(' ', $display_name);
3170 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
3171 - }
3172 -
3173 - $rating_entry = isset($ratings_map[$session_id]) ? $ratings_map[$session_id] : null;
3174 - $rating_value = $rating_entry ? $rating_entry['value'] : null;
3175 - $rating_feedback = $rating_entry ? $rating_entry['feedback'] : '';
3176 -
3177 - $sessions[] = [
3178 - 'session_id' => $session_id,
3179 - 'display_name' => $display_name,
3180 - 'display_sub' => $display_sub,
3181 - 'initials' => $initials,
3182 - 'preview' => $preview,
3183 - 'message_count' => (int) $message_stats->count,
3184 - 'time_display' => $time_display,
3185 - 'timestamp' => $message_stats->latest,
3186 - 'rating_value' => $rating_value,
3187 - 'rating_feedback' => $rating_feedback,
3188 - ];
1471 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1472 + exit;
3189 1473 }
3190 1474
3191 - wp_send_json([
3192 - 'success' => true,
3193 - 'sessions' => $sessions,
3194 - 'page' => $page,
3195 - 'total_pages' => $total_pages,
3196 - 'total_sessions' => $total_sessions,
3197 - 'showing_start' => $offset + 1,
3198 - 'showing_end' => min($offset + $per_page, $total_sessions)
3199 - ]);
3200 - wp_die();
3201 -}
1475 + // Handle Sitemap XML
1476 + if (strpos($content_type, 'xml') !== false || strpos($body_content, '<urlset') !== false) {
1477 + libxml_use_internal_errors(true);
1478 + $xml = simplexml_load_string($body_content);
1479 + $xml_errors = libxml_get_errors();
1480 + libxml_clear_errors();
3202 1481
3203 -/**
3204 - * Fetch single conversation details for split-panel view
3205 - */
3206 -public function mxchat_fetch_conversation() {
3207 - global $wpdb;
3208 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3209 - $url_clicks_table = $wpdb->prefix . 'mxchat_url_clicks';
1482 + if ($xml === false || !empty($xml_errors)) {
1483 + set_transient('mxchat_admin_notice_error',
1484 + esc_html__('Invalid sitemap XML. Please provide a valid sitemap.', 'mxchat'),
1485 + 30
1486 + );
1487 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1488 + exit;
1489 + }
3210 1490
3211 - if (!current_user_can('manage_options')) {
3212 - wp_send_json_error(['message' => 'Insufficient permissions']);
3213 - wp_die();
3214 - }
1491 + $result = $this->handle_sitemap_for_knowledge_base($xml, $submitted_url);
3215 1492
3216 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
3217 - if (empty($session_id)) {
3218 - wp_send_json_error(['message' => 'No session ID provided']);
3219 - wp_die();
3220 - }
3221 -
3222 - // Check for optional columns/tables
3223 - $url_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$url_clicks_table'") === $url_clicks_table;
3224 - $originating_columns_exist = !empty($wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'"));
3225 -
3226 - // Get session metadata
3227 - $session_data = $originating_columns_exist
3228 - ? $wpdb->get_row($wpdb->prepare(
3229 - "SELECT user_email, user_name, user_identifier, originating_page_url, originating_page_title, timestamp
3230 - FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC LIMIT 1",
3231 - $session_id
3232 - ))
3233 - : $wpdb->get_row($wpdb->prepare(
3234 - "SELECT user_email, user_name, user_identifier, timestamp FROM {$table_name}
3235 - WHERE session_id = %s LIMIT 1",
3236 - $session_id
3237 - ));
3238 -
3239 - if (!$session_data) {
3240 - wp_send_json_error(['message' => 'Session not found']);
3241 - wp_die();
3242 - }
3243 -
3244 - // Get clicked URLs
3245 - $clicked_urls = [];
3246 - if ($url_table_exists) {
3247 - $url_clicks = $wpdb->get_results($wpdb->prepare(
3248 - "SELECT DISTINCT clicked_url FROM {$url_clicks_table}
3249 - WHERE session_id = %s ORDER BY click_timestamp ASC",
3250 - $session_id
3251 - ));
3252 - foreach ($url_clicks as $click) {
3253 - $clicked_urls[] = $click->clicked_url;
1493 + if ($result === 'scheduled') {
1494 + set_transient(
1495 + 'mxchat_last_sitemap_url',
1496 + sanitize_text_field($submitted_url),
1497 + DAY_IN_SECONDS
1498 + );
1499 + set_transient('mxchat_admin_notice_info',
1500 + esc_html__('Sitemap processing has started in the background. You can check the progress in the Knowledge Base section.', 'mxchat'),
1501 + 30
1502 + );
1503 + } else {
1504 + set_transient('mxchat_admin_notice_error',
1505 + esc_html__('Failed to start sitemap processing. Please try again.', 'mxchat'),
1506 + 30
1507 + );
3254 1508 }
3255 - }
3256 1509
3257 - // Get all messages
3258 - $messages = $wpdb->get_results($wpdb->prepare(
3259 - "SELECT * FROM {$table_name} WHERE session_id = %s ORDER BY timestamp ASC",
3260 - $session_id
3261 - ));
3262 -
3263 - // Build user info
3264 - $user_email = !empty($session_data->user_email) ? $session_data->user_email : '';
3265 - $user_name = !empty($session_data->user_name) ? $session_data->user_name : '';
3266 - $user_identifier = !empty($session_data->user_identifier) ? $session_data->user_identifier : 'Guest';
3267 -
3268 - $display_name = $user_name ?: ($user_email ? explode('@', $user_email)[0] : $user_identifier);
3269 - $display_sub = $user_email ?: ('ID: ' . $user_identifier);
3270 -
3271 - // Get initials
3272 - $initials = strtoupper(substr($display_name, 0, 2));
3273 - if (strlen($display_name) > 2 && strpos($display_name, ' ') !== false) {
3274 - $parts = explode(' ', $display_name);
3275 - $initials = strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
1510 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1511 + exit;
3276 1512 }
3277 1513
3278 - // Page info
3279 - $page_url = $originating_columns_exist && !empty($session_data->originating_page_url) ? $session_data->originating_page_url : '';
3280 - $page_title = '';
3281 - if ($page_url) {
3282 - $page_title = !empty($session_data->originating_page_title) ? $session_data->originating_page_title : parse_url($page_url, PHP_URL_PATH);
3283 - }
1514 + // Handle Regular URL
1515 + $page_content = $this->mxchat_extract_main_content($body_content);
1516 + $sanitized_content = $this->mxchat_sanitize_content_for_api($page_content);
3284 1517
3285 - // Format messages for output
3286 - $formatted_messages = [];
3287 - foreach ($messages as $msg) {
3288 - $is_user = ($msg->role === 'user');
3289 - $is_bot = ($msg->role === 'bot' || $msg->role === 'assistant');
3290 -
3291 - $content = wp_kses(
3292 - stripslashes($msg->message),
3293 - [
3294 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3295 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3296 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []],
3297 - 'div' => ['class' => [], 'id' => [], 'data-nonce' => []],
3298 - 'img' => ['src' => [], 'alt' => [], 'class' => []],
3299 - 'h3' => ['class' => []],
3300 - 'h4' => ['class' => []],
3301 - 'button' => ['type' => [], 'class' => [], 'data-product-id' => [], 'data-nonce' => [], 'data-product-type' => [], 'data-original-text' => [], 'data-mxchat-action' => []],
3302 - 'select' => ['class' => [], 'data-attribute' => []],
3303 - 'option' => ['value' => []],
3304 - 'span' => ['class' => []],
3305 - 'del' => [], 'ins' => [],
3306 - ]
1518 + if (empty($sanitized_content)) {
1519 + set_transient('mxchat_admin_notice_error',
1520 + esc_html__('No valid content found on the provided URL.', 'mxchat'),
1521 + 30
3307 1522 );
3308 - $formatted_content = $this->format_transcript_message($content);
3309 -
3310 - $has_rag = $is_bot && !empty($msg->rag_context);
3311 -
3312 - $formatted_messages[] = [
3313 - 'id' => $msg->id,
3314 - 'role' => $msg->role,
3315 - 'is_user' => $is_user,
3316 - 'is_bot' => $is_bot,
3317 - 'content' => $formatted_content,
3318 - 'timestamp' => wp_date('g:i A', strtotime($msg->timestamp . ' UTC')),
3319 - 'full_timestamp' => wp_date('F j, Y g:i A', strtotime($msg->timestamp . ' UTC')),
3320 - 'has_rag' => $has_rag
3321 - ];
1523 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1524 + exit;
3322 1525 }
3323 1526
3324 - // First message timestamp for "started" display
3325 - $started = !empty($messages) ? wp_date('M j, Y g:i A', strtotime($messages[0]->timestamp . ' UTC')) : '-';
3326 -
3327 - // Pull rating_feedback for this session (if any) so the details drawer can show it.
3328 - $rating_feedback = '';
3329 - $ratings_table_det = $wpdb->prefix . 'mxchat_session_ratings';
3330 - if ($wpdb->get_var("SHOW TABLES LIKE '$ratings_table_det'") === $ratings_table_det) {
3331 - $rating_feedback = (string) $wpdb->get_var($wpdb->prepare(
3332 - "SELECT rating_feedback FROM {$ratings_table_det} WHERE session_id = %s LIMIT 1",
3333 - $session_id
3334 - ));
3335 - }
3336 -
3337 - wp_send_json([
3338 - 'success' => true,
3339 - 'session_id' => $session_id,
3340 - 'user' => [
3341 - 'name' => $display_name,
3342 - 'sub' => $display_sub,
3343 - 'initials' => $initials,
3344 - 'email' => $user_email,
3345 - 'identifier' => $user_identifier
3346 - ],
3347 - 'page' => [
3348 - 'url' => $page_url,
3349 - 'title' => $page_title
3350 - ],
3351 - 'clicked_urls' => $clicked_urls,
3352 - 'messages' => $formatted_messages,
3353 - 'message_count' => count($messages),
3354 - 'started' => $started,
3355 - 'rating_feedback' => $rating_feedback
3356 - ]);
3357 - wp_die();
3358 -}
3359 -
3360 -
3361 -/**
3362 - * ALTERNATIVE: Simpler helper method using string replacement
3363 - */
3364 -private function highlight_clicked_links($message_content, $clicked_urls) {
3365 - if (empty($clicked_urls)) {
3366 - return wp_kses(
3367 - $message_content,
3368 - [
3369 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3370 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3371 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3372 - ]
1527 + $embedding_vector = $this->mxchat_generate_embedding($sanitized_content);
1528 + if (is_array($embedding_vector)) {
1529 + MxChat_Utils::submit_content_to_db(
1530 + $sanitized_content,
1531 + $submitted_url,
1532 + $this->options['api_key']
3373 1533 );
1534 + set_transient('mxchat_admin_notice_success',
1535 + esc_html__('URL content successfully submitted!', 'mxchat'),
1536 + 30
1537 + );
1538 + } else {
1539 + set_transient('mxchat_admin_notice_error',
1540 + esc_html__('Failed to generate embedding for the URL content. Please check your API key and try again.', 'mxchat'),
1541 + 30
1542 + );
3374 1543 }
3375 1544
3376 - // First apply standard sanitization
3377 - $message_content = wp_kses(
3378 - $message_content,
3379 - [
3380 - 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
3381 - 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
3382 - 'a' => ['href' => [], 'title' => [], 'target' => [], 'class' => []]
3383 - ]
3384 - );
3385 -
3386 - // Process each clicked URL
3387 - foreach ($clicked_urls as $clicked_url) {
3388 - // Try multiple patterns to catch different link formats
3389 - $patterns = [
3390 - // Standard link format
3391 - '/<a([^>]*href=["\']' . preg_quote($clicked_url, '/') . '["\'][^>]*)>/i',
3392 - // Link with trailing slash
3393 - '/<a([^>]*href=["\']' . preg_quote(rtrim($clicked_url, '/'), '/') . '\/?["\'][^>]*)>/i',
3394 - // Encoded entities version
3395 - '/<a([^>]*href=["\']' . preg_quote(htmlentities($clicked_url), '/') . '["\'][^>]*)>/i',
3396 - ];
3397 -
3398 - foreach ($patterns as $pattern) {
3399 - if (preg_match($pattern, $message_content)) {
3400 - $message_content = preg_replace_callback(
3401 - $pattern,
3402 - function($matches) {
3403 - $full_match = $matches[0];
3404 - $attributes = $matches[1];
3405 -
3406 - // Check if it already has the class
3407 - if (strpos($full_match, 'mxchat-clicked-link') !== false) {
3408 - return $full_match;
3409 - }
3410 -
3411 - // Check if class attribute exists
3412 - if (preg_match('/class=["\']([^"\']*)["\']/', $attributes, $class_matches)) {
3413 - // Add to existing class
3414 - $new_attributes = preg_replace(
3415 - '/class=["\']([^"\']*)["\']/',
3416 - 'class="$1 mxchat-clicked-link"',
3417 - $attributes
3418 - );
3419 - } else {
3420 - // Add new class attribute
3421 - $new_attributes = $attributes . ' class="mxchat-clicked-link"';
3422 - }
3423 -
3424 - // Add title if not present
3425 - if (strpos($new_attributes, 'title=') === false) {
3426 - $new_attributes .= ' title="User clicked this link"';
3427 - }
3428 -
3429 - return '<a' . $new_attributes . '>';
3430 - },
3431 - $message_content
3432 - );
3433 -
3434 - // If we found and replaced, break out of the patterns loop
3435 - break;
3436 - }
3437 - }
3438 - }
3439 -
3440 - return $message_content;
1545 + wp_safe_redirect(esc_url(admin_url('admin.php?page=mxchat-prompts')));
1546 + exit;
3441 1547 }
3442 -
3443 -public function mxchat_create_prompts_page() {
3444 - //error_log('=== DEBUG: mxchat_create_prompts_page started ===');
3445 -
3446 - global $wpdb;
3447 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
3448 -
3449 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
3450 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
3451 -
3452 - // Display success message if all prompts were deleted
3453 - if (isset($_GET['all_deleted']) && $_GET['all_deleted'] === 'true') {
3454 - echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button></div>';
1548 +private function handle_sitemap_for_knowledge_base($xml, $sitemap_url) {
1549 + if (!current_user_can('manage_options')) {
1550 + //error_log('Unauthorized sitemap processing attempt');
1551 + return false;
3455 1552 }
3456 1553
3457 - // Set up pagination, search query, and content type filter
3458 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';
3459 - $search_query = (!empty($nonce) && wp_verify_nonce($nonce, 'mxchat_prompts_search_nonce') && isset($_GET['search'])) ? sanitize_text_field($_GET['search']) : '';
3460 - $content_type_filter = isset($_GET['content_type']) ? sanitize_key($_GET['content_type']) : ''; // ADDED 2.5.6
3461 - $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
3462 - $per_page = 25;
1554 + try {
1555 + $sitemap_url = esc_url_raw($sitemap_url);
3463 1556
3464 - //error_log('DEBUG: Search query: ' . $search_query);
3465 - //error_log('DEBUG: Content type filter: ' . $content_type_filter);
3466 - //error_log('DEBUG: Current page: ' . $current_page);
3467 - //error_log('DEBUG: Per page: ' . $per_page);
3468 -
3469 - // ================================
3470 - // MULTI-BOT CONFIGURATION
3471 - // ================================
3472 -
3473 - // Check for multi-bot and set up bot selection
3474 - if (class_exists('MxChat_Multi_Bot_Manager')) {
3475 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
3476 - $available_bots = $multi_bot_manager->get_available_bots();
3477 -
3478 - // Get saved bot selection (user-specific first, then site-wide default)
3479 - $user_id = get_current_user_id();
3480 - $saved_bot_id = get_user_meta($user_id, 'mxchat_selected_knowledge_bot', true);
3481 - if (empty($saved_bot_id)) {
3482 - $saved_bot_id = get_option('mxchat_current_knowledge_bot', 'default');
1557 + if (!$xml || !is_object($xml)) {
1558 + throw new Exception('Invalid XML object provided');
3483 1559 }
3484 -
3485 - // Allow URL override but default to saved selection
3486 - $current_bot_id = isset($_GET['bot_id']) ? sanitize_key($_GET['bot_id']) : $saved_bot_id;
3487 - $multibot_active = true;
3488 - } else {
3489 - $current_bot_id = 'default';
3490 - $multibot_active = false;
3491 - }
3492 1560
3493 - // ================================
3494 - // DATA SOURCE CONFIGURATION
3495 - // ================================
3496 -
3497 - // Get bot-specific Pinecone settings
3498 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($current_bot_id);
3499 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
3500 - $pinecone_api_key = $pinecone_options['mxchat_pinecone_api_key'] ?? '';
3501 -
3502 - // Get OpenAI Vector Store settings
3503 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
3504 - $use_vectorstore = ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1';
3505 -
3506 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3507 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Has API Key: ' . (!empty($pinecone_api_key) ? 'YES' : 'NO'));
3508 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Host: ' . ($pinecone_options['mxchat_pinecone_host'] ?? 'NOT SET'));
3509 - //error_log('DEBUG: Bot ' . $current_bot_id . ' - Namespace: ' . ($pinecone_options['mxchat_pinecone_namespace'] ?? 'NOT SET'));
3510 -
3511 - if ($use_pinecone && !empty($pinecone_api_key)) {
3512 - //error_log('DEBUG: Using PINECONE data source with bot-specific config');
3513 - // PINECONE DATA SOURCE
3514 - $data_source = 'pinecone';
3515 -
3516 - // IMPORTANT: Pass the bot-specific $pinecone_options, not default options!
3517 - // UPDATED 2.5.6: Added content_type_filter parameter
3518 - $records = $pinecone_manager->mxchat_fetch_pinecone_records($pinecone_options, $search_query, $current_page, $per_page, $current_bot_id, $content_type_filter);
3519 -
3520 - // TEMPORARY DEBUG - Add this right after the fetch call
3521 - //error_log('=== DEBUG: Bot switching issue ===');
3522 - //error_log('Current bot ID: ' . $current_bot_id);
3523 - //error_log('Use Pinecone: ' . ($use_pinecone ? 'YES' : 'NO'));
3524 - //error_log('Records returned: ' . count($records['data'] ?? []));
3525 - //error_log('Total records: ' . ($records['total'] ?? 0));
3526 -
3527 - // Check first few records to see their bot_id
3528 - if (!empty($records['data'])) {
3529 - foreach (array_slice($records['data'], 0, 3) as $i => $record) {
3530 - $record_bot_id = $record->bot_id ?? 'NOT_SET';
3531 - //error_log('Record ' . ($i+1) . ' bot_id: ' . $record_bot_id . ', content preview: ' . substr($record->article_content ?? '', 0, 30) . '...');
1561 + $urls = [];
1562 + foreach ($xml->url as $url_element) {
1563 + $url = esc_url_raw((string)$url_element->loc);
1564 + if ($url) {
1565 + $urls[] = $url;
3532 1566 }
3533 1567 }
3534 - //error_log('=== END DEBUG ===');
3535 1568
3536 - $total_records = $records['total'] ?? 0;
3537 - $prompts = $records['data'] ?? array();
3538 - $total_in_database = $records['total_in_database'] ?? 0;
3539 - $showing_recent_only = $records['showing_recent_only'] ?? false;
1569 + $total_urls = absint(count($urls));
3540 1570
3541 - $total_pages = ceil($total_records / $per_page);
1571 + if ($total_urls < 1) {
1572 + throw new Exception('No valid URLs found in sitemap');
1573 + }
3542 1574
3543 - } else {
3544 - //error_log('DEBUG: Using WORDPRESS DB data source');
3545 - // WORDPRESS DB DATA SOURCE (your existing logic)
3546 - $data_source = 'wordpress';
1575 + wp_schedule_single_event(time(), 'mxchat_process_sitemap_urls', array(
1576 + 'urls' => $urls,
1577 + 'sitemap_url' => $sitemap_url,
1578 + 'total_urls' => $total_urls,
1579 + 'batch_size' => absint(10),
1580 + 'batch_pause' => absint(5)
1581 + ));
3547 1582
3548 - // Initialize these variables for WordPress DB
3549 - $total_in_database = 0;
3550 - $showing_recent_only = false;
1583 + $status_data = array(
1584 + 'total_urls' => $total_urls,
1585 + 'processed_urls' => 0,
1586 + 'status' => 'processing',
1587 + 'last_update' => time()
1588 + );
3551 1589
3552 - $offset = ($current_page - 1) * $per_page;
1590 + set_transient(
1591 + sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)),
1592 + array_map('sanitize_text_field', $status_data),
1593 + DAY_IN_SECONDS
1594 + );
3553 1595
3554 - // UPDATED 2.5.6: Build WHERE clause for search and content type filtering
3555 - $where_clauses = array();
3556 - $where_values = array();
1596 + return 'scheduled';
3557 1597
3558 - if ($search_query) {
3559 - $where_clauses[] = "article_content LIKE %s";
3560 - $where_values[] = '%' . $wpdb->esc_like($search_query) . '%';
3561 - }
1598 + } catch (\Exception $e) {
1599 + //error_log(sprintf('Error preparing sitemap for processing: %s', esc_html($e->getMessage())));
1600 + return false;
1601 + }
1602 +}
1603 +public static function process_sitemap_urls_cron($urls, $sitemap_url, $total_urls, $batch_size, $batch_pause) {
1604 + // Validate inputs
1605 + $sitemap_url = esc_url_raw($sitemap_url);
1606 + $total_urls = absint($total_urls);
1607 + $batch_size = absint($batch_size);
1608 + $batch_pause = absint($batch_pause);
3562 1609
3563 - if ($content_type_filter) {
3564 - $where_clauses[] = "content_type = %s";
3565 - $where_values[] = $content_type_filter;
3566 - }
1610 + if (!is_array($urls) || empty($urls)) {
1611 + return;
1612 + }
3567 1613
3568 - $sql_where = "";
3569 - if (!empty($where_clauses)) {
3570 - $sql_where = "WHERE " . implode(" AND ", $where_clauses);
3571 - }
1614 + try {
1615 + $status_key = sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url));
1616 + $status = get_transient($status_key);
3572 1617
3573 - // UPDATED 2.6.3: Count unique entries (by source_url) instead of individual rows
3574 - // This ensures pagination shows X entries per page, not X chunks
3575 - // Entries with empty source_url are counted individually
3576 - if (!empty($where_values)) {
3577 - // Count unique source_urls + count of rows with empty source_url
3578 - $count_query = $wpdb->prepare(
3579 - "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} {$sql_where} AND source_url != '') +
3580 - (SELECT COUNT(*) FROM {$table_name} {$sql_where} AND (source_url = '' OR source_url IS NULL))",
3581 - array_merge($where_values, $where_values)
3582 - );
3583 - } else {
3584 - $count_query = "SELECT (SELECT COUNT(DISTINCT source_url) FROM {$table_name} WHERE source_url != '') +
3585 - (SELECT COUNT(*) FROM {$table_name} WHERE source_url = '' OR source_url IS NULL)";
1618 + if (!$status || !is_array($status)) {
1619 + throw new Exception('Invalid status data retrieved from transient');
3586 1620 }
3587 - $total_records = $wpdb->get_var($count_query);
3588 - $total_pages = ceil($total_records / $per_page);
3589 1621
3590 - // UPDATED 2.6.3: Get unique source_urls for pagination, then fetch all their rows
3591 - // Step 1: Get the source_urls for this page (distinct URLs ordered by latest timestamp)
3592 - if (!empty($where_values)) {
3593 - $urls_query = $wpdb->prepare(
3594 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name} {$sql_where}
3595 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3596 - array_merge($where_values, array($per_page, $offset))
3597 - );
3598 - } else {
3599 - $urls_query = $wpdb->prepare(
3600 - "SELECT source_url, MAX(timestamp) as latest_ts FROM {$table_name}
3601 - GROUP BY source_url ORDER BY latest_ts DESC LIMIT %d OFFSET %d",
3602 - $per_page, $offset
3603 - );
3604 - }
3605 - $page_urls = $wpdb->get_results($urls_query);
1622 + $start_url = absint($status['processed_urls']);
1623 + $end_url = min($start_url + $batch_size, $total_urls);
3606 1624
3607 - // Step 2: Fetch all rows for these source_urls
3608 - $prompts = array();
3609 - if (!empty($page_urls)) {
3610 - // Build URL order map to preserve newest-first ordering from step 1
3611 - $url_order_map = array();
3612 - $url_list = array();
3613 - $has_empty_url = false;
3614 - $order_index = 0;
3615 - foreach ($page_urls as $url_row) {
3616 - if (empty($url_row->source_url)) {
3617 - $has_empty_url = true;
3618 - $url_order_map['__empty__'] = $order_index++;
3619 - } else {
3620 - $url_list[] = $url_row->source_url;
3621 - $url_order_map[$url_row->source_url] = $order_index++;
3622 - }
3623 - }
1625 + $instance = new self(); // Create an instance of the class
1626 + $embedding_success = true;
3624 1627
3625 - // Build query to fetch all rows for these URLs
3626 - $url_conditions = array();
3627 - $url_values = array();
1628 + for ($i = $start_url; $i < $end_url; $i++) {
1629 + $page_url = esc_url_raw($urls[$i]);
1630 + $page_response = wp_remote_get($page_url);
3628 1631
3629 - if (!empty($url_list)) {
3630 - $placeholders = implode(',', array_fill(0, count($url_list), '%s'));
3631 - $url_conditions[] = "source_url IN ($placeholders)";
3632 - $url_values = array_merge($url_values, $url_list);
1632 + if (is_wp_error($page_response) || wp_remote_retrieve_response_code($page_response) !== 200) {
1633 + continue;
3633 1634 }
3634 1635
3635 - if ($has_empty_url) {
3636 - $url_conditions[] = "(source_url = '' OR source_url IS NULL)";
3637 - }
1636 + $page_html = wp_remote_retrieve_body($page_response);
1637 + $page_content = $instance->mxchat_extract_main_content($page_html); // Call via instance
1638 + $sanitized_content = $instance->mxchat_sanitize_content_for_api($page_content); // Call via instance
3638 1639
3639 - if (!empty($url_conditions)) {
3640 - $url_where = "WHERE (" . implode(" OR ", $url_conditions) . ")";
3641 -
3642 - // Add original filters back
3643 - if (!empty($where_clauses)) {
3644 - $url_where .= " AND " . implode(" AND ", $where_clauses);
3645 - $url_values = array_merge($url_values, $where_values);
3646 - }
3647 -
3648 - if (!empty($url_values)) {
3649 - $prompts_query = $wpdb->prepare(
3650 - "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC",
3651 - $url_values
3652 - );
1640 + if (!empty($sanitized_content)) {
1641 + $embedding_vector = $instance->mxchat_generate_embedding($sanitized_content); // Call via instance
1642 + if (is_array($embedding_vector)) {
1643 + $options = get_option('mxchat_options');
1644 + MxChat_Utils::submit_content_to_db($sanitized_content, $page_url, $options['api_key']);
3653 1645 } else {
3654 - $prompts_query = "SELECT * FROM {$table_name} {$url_where} ORDER BY timestamp DESC";
1646 + $embedding_success = false;
3655 1647 }
3656 -
3657 - $prompts = $wpdb->get_results($prompts_query);
3658 -
3659 - // Sort prompts by the original URL order (newest first), then by timestamp within each URL group
3660 - usort($prompts, function($a, $b) use ($url_order_map) {
3661 - $url_a = empty($a->source_url) ? '__empty__' : $a->source_url;
3662 - $url_b = empty($b->source_url) ? '__empty__' : $b->source_url;
3663 - $order_a = $url_order_map[$url_a] ?? PHP_INT_MAX;
3664 - $order_b = $url_order_map[$url_b] ?? PHP_INT_MAX;
3665 -
3666 - // First sort by URL order (newest URLs first)
3667 - if ($order_a !== $order_b) {
3668 - return $order_a - $order_b;
3669 - }
3670 -
3671 - // Within same URL, sort by timestamp DESC (newest chunks first)
3672 - return strtotime($b->timestamp) - strtotime($a->timestamp);
3673 - });
3674 1648 }
3675 - }
3676 - }
3677 1649
3678 - // ================================
3679 - // PAGINATION GENERATION
3680 - // ================================
3681 -
3682 - // Generate pagination links
3683 - if ($total_pages > 1) {
3684 - // Build a clean base URL with only necessary parameters
3685 - $pagination_args = array('page' => 'mxchat-prompts');
3686 -
3687 - // Preserve bot_id parameter if multi-bot is active
3688 - if ($multibot_active && !empty($current_bot_id) && $current_bot_id !== 'default') {
3689 - $pagination_args['bot_id'] = $current_bot_id;
1650 + $status['processed_urls'] = absint($i + 1);
1651 + $status['last_update'] = time();
1652 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3690 1653 }
3691 1654
3692 - // Preserve search query and nonce if present
3693 - if ($search_query) {
3694 - $pagination_args['search'] = $search_query;
3695 - if (!empty($nonce)) {
3696 - $pagination_args['_wpnonce'] = $nonce;
3697 - }
1655 + if ($end_url < $total_urls) {
1656 + wp_schedule_single_event(time() + $batch_pause, 'mxchat_process_sitemap_urls', array(
1657 + 'urls' => array_map('esc_url_raw', $urls),
1658 + 'sitemap_url' => $sitemap_url,
1659 + 'total_urls' => $total_urls,
1660 + 'batch_size' => $batch_size,
1661 + 'batch_pause' => $batch_pause,
1662 + ));
1663 + } else {
1664 + $status['status'] = 'complete';
1665 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
3698 1666 }
1667 + } catch (\Exception $e) {
1668 + $status['status'] = 'error';
1669 + $status['error'] = sanitize_text_field($e->getMessage());
1670 + set_transient($status_key, array_map('sanitize_text_field', $status), DAY_IN_SECONDS);
1671 + }
1672 +}
1673 +public function get_sitemap_processing_status($sitemap_url) {
1674 + $sitemap_url = esc_url_raw($sitemap_url);
1675 + $status = get_transient(sanitize_key('mxchat_sitemap_status_' . md5($sitemap_url)));
3699 1676
3700 - // Preserve content type filter if present
3701 - if ($content_type_filter) {
3702 - $pagination_args['content_type'] = $content_type_filter;
3703 - }
3704 -
3705 - // Build clean base URL
3706 - $base_url = add_query_arg($pagination_args, admin_url('admin.php'));
3707 -
3708 - $page_links = paginate_links(array(
3709 - 'base' => $base_url . '%_%',
3710 - 'format' => '&paged=%#%',
3711 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
3712 - 'next_text' => __('Next &raquo;', 'mxchat'),
3713 - 'total' => $total_pages,
3714 - 'current' => $current_page,
3715 - 'type' => 'plain',
3716 - ));
3717 - } else {
3718 - $page_links = '';
1677 + if (!$status || !is_array($status)) {
1678 + return false;
3719 1679 }
3720 1680
3721 - // ================================
3722 - // PROCESSING STATUS RETRIEVAL
3723 - // ================================
3724 -
3725 - // Retrieve processing statuses using queue-based method
3726 - $processing_statuses = $knowledge_manager->mxchat_get_processing_statuses();
3727 - $pdf_status = $processing_statuses['pdf_status'];
3728 - $sitemap_status = $processing_statuses['sitemap_status'];
3729 - $is_processing = $processing_statuses['is_processing'];
3730 -
3731 - //error_log('=== DEBUG: mxchat_create_prompts_page data preparation completed ===');
3732 -
3733 - // ================================
3734 - // RENDER PAGE WITH NEW SIDEBAR LAYOUT
3735 - // ================================
3736 -
3737 - // Include the new knowledge page template
3738 - require_once plugin_dir_path(__FILE__) . 'admin-knowledge-page.php';
3739 -
3740 - // Package all page data for the render function
3741 - $page_data = array(
3742 - 'prompts' => $prompts,
3743 - 'total_records' => $total_records,
3744 - 'total_pages' => $total_pages,
3745 - 'current_page' => $current_page,
3746 - 'per_page' => $per_page,
3747 - 'page_links' => $page_links,
3748 - 'search_query' => $search_query,
3749 - 'content_type_filter' => $content_type_filter,
3750 - 'data_source' => $data_source,
3751 - 'use_pinecone' => $use_pinecone,
3752 - 'use_vectorstore' => $use_vectorstore,
3753 - 'multibot_active' => $multibot_active,
3754 - 'current_bot_id' => $current_bot_id,
3755 - 'pdf_status' => $pdf_status,
3756 - 'sitemap_status' => $sitemap_status,
3757 - 'is_processing' => $is_processing,
3758 - 'total_in_database' => $total_in_database ?? 0,
3759 - 'showing_recent_only' => $showing_recent_only ?? false,
1681 + return array(
1682 + 'total_urls' => absint($status['total_urls']),
1683 + 'processed_urls' => absint($status['processed_urls']),
1684 + 'percentage' => round((absint($status['processed_urls']) / absint($status['total_urls'])) * 100),
1685 + 'status' => sanitize_text_field($status['status']),
1686 + 'last_update' => human_time_diff(absint($status['last_update']), time()) . ' ago'
3760 1687 );
3761 -
3762 - // Render the new sidebar-based page
3763 - mxchat_render_knowledge_page($this, $knowledge_manager, $page_data);
3764 1688 }
3765 -
3766 -/**
3767 - * Get bot-specific Pinecone configuration
3768 - * Used in the knowledge retrieval functions
3769 - */
3770 -private function get_bot_pinecone_config($bot_id = 'default') {
3771 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
3772 -
3773 - // If default bot or multi-bot add-on not active, use default Pinecone config
3774 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
3775 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
3776 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
3777 - $config = array(
3778 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
3779 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
3780 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
3781 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
3782 - );
3783 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
3784 - return $config;
1689 +public function mxchat_stop_processing() {
1690 + // Verify permissions
1691 + if (!current_user_can('manage_options')) {
1692 + wp_die(esc_html__('Unauthorized access', 'mxchat'));
3785 1693 }
3786 -
3787 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
3788 -
3789 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
3790 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
3791 -
3792 - if (!empty($bot_pinecone_config)) {
3793 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
3794 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
3795 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
3796 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
3797 - } else {
3798 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
3799 - }
3800 -
3801 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
3802 -}
3803 1694
3804 -public function mxchat_delete_chat_history() {
3805 - if (!current_user_can('manage_options')) {
3806 - echo wp_json_encode(['error' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
3807 - wp_die();
3808 - }
3809 - check_ajax_referer('mxchat_delete_chat_history', 'security');
1695 + // Verify nonce
1696 + check_admin_referer('mxchat_stop_processing_action', 'mxchat_stop_processing_nonce');
3810 1697
3811 - if (!isset($_POST['delete_session_ids']) || !is_array($_POST['delete_session_ids'])) {
3812 - echo wp_json_encode(['error' => esc_html__('No chat sessions selected for deletion.', 'mxchat')]);
3813 - wp_die();
1698 + // Get the last sitemap URL and clear its transient
1699 + $sitemap_url = get_transient('mxchat_last_sitemap_url');
1700 + if ($sitemap_url) {
1701 + delete_transient('mxchat_sitemap_status_' . md5($sitemap_url));
1702 + delete_transient('mxchat_last_sitemap_url');
3814 1703 }
3815 1704
3816 - global $wpdb;
3817 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3818 - $translations_table = $wpdb->prefix . 'mxchat_transcript_translations';
3819 - $has_translations = $wpdb->get_var("SHOW TABLES LIKE '$translations_table'") === $translations_table;
3820 -
3821 - // When true, any lead attached to these sessions is fully wiped (all their sessions,
3822 - // across the whole table). Default false: the chat rows go away but the lead is
3823 - // preserved as a separate "chat deleted" lead in the Leads tab.
3824 - $also_delete_lead = !empty($_POST['also_delete_lead']) && $_POST['also_delete_lead'] !== 'false';
3825 -
3826 - $deleted_count = 0;
3827 - $preserved_as_deleted_leads = 0;
3828 - $emails_to_fully_wipe = [];
3829 -
3830 - foreach ((array) $_POST['delete_session_ids'] as $session_id) {
3831 - $session_id_sanitized = sanitize_text_field($session_id);
3832 - if ($session_id_sanitized === '') {
3833 - continue;
3834 - }
3835 -
3836 - // Capture the lead info attached to this session *before* we delete the rows.
3837 - $lead_row = $wpdb->get_row($wpdb->prepare(
3838 - "SELECT user_email, user_name, MAX(timestamp) AS last_ts
3839 - FROM {$table_name}
3840 - WHERE session_id = %s AND user_email IS NOT NULL AND user_email != ''
3841 - GROUP BY user_email, user_name
3842 - ORDER BY last_ts DESC LIMIT 1",
3843 - $session_id_sanitized
3844 - ));
3845 -
3846 - wp_cache_delete('chat_session_' . $session_id_sanitized, 'mxchat_chat_sessions');
3847 - $wpdb->delete($table_name, ['session_id' => $session_id_sanitized]);
3848 -
3849 - if ($has_translations) {
3850 - $wpdb->delete($translations_table, ['session_id' => $session_id_sanitized]);
3851 - }
3852 -
3853 - delete_option('mxchat_history_' . $session_id_sanitized);
3854 - delete_option('mxchat_agent_name_' . $session_id_sanitized);
3855 -
3856 - if ($lead_row && !empty($lead_row->user_email)) {
3857 - if ($also_delete_lead) {
3858 - // Full-wipe requested — queue the email so that all their sessions and
3859 - // related options get swept below. Also clear this session's pre-chat
3860 - // capture options (they're no longer meaningful).
3861 - $emails_to_fully_wipe[strtolower($lead_row->user_email)] = $lead_row->user_email;
3862 - delete_option('mxchat_email_' . $session_id_sanitized);
3863 - delete_option('mxchat_name_' . $session_id_sanitized);
3864 - } else {
3865 - // Preserve the lead in a "Chat deleted" state via distinct option keys so
3866 - // they stay out of the orphan bucket (orphan = pre-chat form dropoff).
3867 - update_option('mxchat_lead_del_email_' . $session_id_sanitized, $lead_row->user_email, false);
3868 - if (!empty($lead_row->user_name)) {
3869 - update_option('mxchat_lead_del_name_' . $session_id_sanitized, $lead_row->user_name, false);
3870 - }
3871 - if (!empty($lead_row->last_ts)) {
3872 - update_option('mxchat_lead_del_ts_' . $session_id_sanitized, $lead_row->last_ts, false);
3873 - }
3874 - // Clean up pre-chat capture options for this session — chat_deleted supersedes.
3875 - delete_option('mxchat_email_' . $session_id_sanitized);
3876 - delete_option('mxchat_name_' . $session_id_sanitized);
3877 - $preserved_as_deleted_leads++;
3878 - }
3879 - } else {
3880 - // No lead attached — nothing to preserve. Clean up any orphan options anyway.
3881 - delete_option('mxchat_email_' . $session_id_sanitized);
3882 - delete_option('mxchat_name_' . $session_id_sanitized);
3883 - }
3884 -
3885 - $deleted_count++;
1705 + // Get the last PDF URL and clear its transient
1706 + $pdf_url = get_transient('mxchat_last_pdf_url');
1707 + if ($pdf_url) {
1708 + delete_transient('mxchat_pdf_status_' . md5($pdf_url));
1709 + delete_transient('mxchat_last_pdf_url');
3886 1710 }
3887 1711
3888 - // Opt-in full-lead wipe: sweep every remaining row + every option key (including
3889 - // chat_deleted preservation) for each affected email. Reuses the same internal
3890 - // helper as the Leads-tab Delete button for consistency.
3891 - if (!empty($emails_to_fully_wipe)) {
3892 - self::mxchat_wipe_leads_by_email(array_values($emails_to_fully_wipe));
1712 + // Unschedule any pending sitemap events
1713 + $timestamp = wp_next_scheduled('mxchat_process_sitemap_urls');
1714 + if ($timestamp) {
1715 + wp_unschedule_event($timestamp, 'mxchat_process_sitemap_urls');
3893 1716 }
3894 1717
3895 - wp_cache_delete('all_chat_sessions', 'mxchat_chat_sessions');
3896 -
3897 - echo wp_json_encode([
3898 - 'success' => sprintf(
3899 - esc_html__('%d chat session(s) have been deleted.', 'mxchat'),
3900 - $deleted_count
3901 - ),
3902 - 'preserved_as_deleted_leads' => $preserved_as_deleted_leads,
3903 - 'leads_fully_wiped' => count($emails_to_fully_wipe),
3904 - ]);
3905 - wp_die();
1718 + // Redirect back with a success message
1719 + set_transient('mxchat_admin_notice_success',
1720 + esc_html__('Processing has been stopped successfully.', 'mxchat'),
1721 + 30
1722 + );
1723 + wp_safe_redirect(admin_url('admin.php?page=mxchat-prompts'));
1724 + exit;
3906 1725 }
1726 +private function mxchat_sanitize_content_for_api($content) {
1727 + // Remove script, style tags, and HTML comments
1728 + $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
1729 + $content = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $content);
1730 + $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);
3907 1731
3908 -/**
3909 - * Format transcript message content with markdown processing
3910 - * Converts markdown links, bold, italic, code blocks, and plain URLs to HTML
3911 - */
3912 -private function format_transcript_message($text) {
3913 - if (empty($text)) {
3914 - return '';
3915 - }
1732 + // Remove all HTML tags and decode HTML entities
1733 + $content = wp_strip_all_tags($content);
1734 + $content = html_entity_decode($content, ENT_QUOTES | ENT_HTML5);
3916 1735
3917 - // Normalize line endings and clean up excessive whitespace
3918 - $text = str_replace("\r\n", "\n", $text);
3919 - $text = str_replace("\r", "\n", $text);
1736 + // Trim and normalize whitespace
1737 + $content = trim(preg_replace('/\s+/', ' ', $content));
3920 1738
3921 - // Clean up existing <br> tags that may have been saved (legacy data)
3922 - // Convert <br>, <br/>, <br /> back to newlines for consistent processing
3923 - $text = preg_replace('/<br\s*\/?>\s*/i', "\n", $text);
1739 + return $content;
1740 +}
3924 1741
3925 - // Collapse 3+ consecutive newlines to just 2 (paragraph break)
3926 - $text = preg_replace('/\n{3,}/', "\n\n", $text);
3927 1742
3928 - // Process markdown headers (# Header)
3929 - $text = preg_replace_callback('/^(#{1,6})\s+(.+)$/m', function($matches) {
3930 - $level = strlen($matches[1]);
3931 - $content = esc_html(trim($matches[2]));
3932 - return "<h{$level}>{$content}</h{$level}>";
3933 - }, $text);
3934 1743
3935 - // Process code blocks with triple backticks
3936 - $text = preg_replace_callback('/```(\w+)?\n?([\s\S]*?)```/', function($matches) {
3937 - $language = !empty($matches[1]) ? ' class="language-' . esc_attr($matches[1]) . '"' : '';
3938 - $code = esc_html($matches[2]);
3939 - return "<pre><code{$language}>{$code}</code></pre>";
3940 - }, $text);
3941 1744
3942 - // Process inline code with single backticks
3943 - $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
3944 1745
3945 - // Process bold text **text** or __text__
3946 - $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);
3947 - $text = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $text);
3948 1746
3949 - // Process italic text *text* or _text_ (but not if part of URL)
3950 - $text = preg_replace('/(?<![*_\w])\*([^*]+)\*(?![*\w])/', '<em>$1</em>', $text);
3951 - $text = preg_replace('/(?<![*_\w])_([^_]+)_(?![*\w])/', '<em>$1</em>', $text);
1747 +public function mxchat_fetch_chat_history() {
1748 + global $wpdb;
1749 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3952 1750
3953 - // Process markdown links [text](url)
3954 - $text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
3955 - $link_text = esc_html($matches[1]);
3956 - $url = esc_url($matches[2]);
3957 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$link_text}</a>";
3958 - }, $text);
1751 + if (!current_user_can('manage_options')) {
1752 + wp_die(esc_html__('You do not have sufficient permissions to view this page.', 'mxchat'));
1753 + }
3959 1754
3960 - // Process citation-style brackets [URL]
3961 - $text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
3962 - $url = esc_url($matches[1]);
3963 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$url}</a>";
3964 - }, $text);
3965 -
3966 - // Process standalone URLs (not already in links or img src)
3967 - $text = preg_replace_callback(
3968 - '/(?<!href="|src="|">)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
3969 - function($matches) {
3970 - $url = esc_url($matches[1]);
3971 - // Truncate display URL if too long
3972 - $display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
3973 - return "<a href=\"{$url}\" target=\"_blank\" rel=\"noopener\">{$display}</a>";
3974 - },
3975 - $text
1755 + // First get unique session IDs ordered by most recent message in each session
1756 + $session_ids = $wpdb->get_col(
1757 + $wpdb->prepare(
1758 + "SELECT DISTINCT session_id
1759 + FROM {$table_name}
1760 + GROUP BY session_id
1761 + ORDER BY MAX(timestamp) DESC"
1762 + )
3976 1763 );
3977 1764
3978 - // Process mailto links
3979 - $text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
3980 - $link_text = esc_html($matches[1]);
3981 - $mailto = esc_url($matches[2]);
3982 - return "<a href=\"{$mailto}\">{$link_text}</a>";
3983 - }, $text);
1765 + if (empty($session_ids)) {
1766 + wp_die(esc_html__('No chat history available.', 'mxchat'));
1767 + }
3984 1768
3985 - // Convert paragraphs: split by double newlines, wrap in <p> tags
3986 - // This creates proper paragraph structure instead of excessive <br> tags
3987 - $paragraphs = preg_split('/\n\n+/', $text);
1769 + ob_start();
1770 + echo '<div class="mxchat-transcript">';
3988 1771
3989 - // Filter out empty paragraphs but preserve content like "0"
3990 - $paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
3991 - return $p !== '';
3992 - }));
1772 + // Iterate through sessions from newest to oldest
1773 + foreach ($session_ids as $session_id) {
1774 + // Get the email associated with this session (if available)
1775 + $email = $wpdb->get_var(
1776 + $wpdb->prepare(
1777 + "SELECT user_email
1778 + FROM {$table_name}
1779 + WHERE session_id = %s AND user_email != ''
1780 + ORDER BY timestamp ASC
1781 + LIMIT 1",
1782 + $session_id
1783 + )
1784 + );
3993 1785
3994 - if (empty($paragraphs)) {
3995 - // No content after filtering
3996 - return '';
3997 - } elseif (count($paragraphs) > 1) {
3998 - // Multiple paragraphs - wrap each in <p> tags, convert single newlines to <br>
3999 - $formatted_paragraphs = array_map(function($p) {
4000 - return nl2br($p);
4001 - }, $paragraphs);
4002 - $text = '<p>' . implode('</p><p>', $formatted_paragraphs) . '</p>';
4003 - } else {
4004 - // Single paragraph - just convert newlines to <br>
4005 - $text = nl2br($paragraphs[0]);
4006 - }
1786 + // Debug: Check email retrieval
1787 + if (empty($email)) {
1788 + //error_log("No email found for session {$session_id}");
1789 + } else {
1790 + //error_log("Email for session {$session_id}: " . $email);
1791 + }
4007 1792
4008 - return $text;
4009 -}
1793 + // Get messages for this session ordered by timestamp
1794 + $messages = $wpdb->get_results(
1795 + $wpdb->prepare(
1796 + "SELECT * FROM {$table_name}
1797 + WHERE session_id = %s
1798 + ORDER BY timestamp ASC",
1799 + $session_id
1800 + )
1801 + );
4010 1802
4011 -/**
4012 - * AJAX handler to fetch RAG context for a specific message
4013 - * Used by the transcript viewer to show retrieved documents
4014 - */
4015 -public function mxchat_get_rag_context() {
4016 - // Check permissions
4017 - if (!current_user_can('manage_options')) {
4018 - wp_send_json_error(['message' => esc_html__('You do not have sufficient permissions.', 'mxchat')]);
4019 - wp_die();
4020 - }
1803 + // Start session block
1804 + echo '<div class="mxchat-session">';
1805 + echo '<div class="mxchat-session-header">';
1806 + // Wrap checkbox and session ID in one block
1807 + echo '<div class="mxchat-session-id">';
1808 + echo '<input type="checkbox" name="delete_session_ids[]" value="' . esc_attr($session_id) . '"> ';
1809 + echo '<strong>Session ID:</strong> ' . esc_html($session_id);
1810 + echo '</div>';
4021 1811
4022 - // Validate message ID
4023 - if (!isset($_POST['message_id']) || empty($_POST['message_id'])) {
4024 - wp_send_json_error(['message' => esc_html__('Message ID is required.', 'mxchat')]);
4025 - wp_die();
4026 - }
1812 + // Place email directly below the session ID block
1813 + if (!empty($email)) {
1814 + echo '<div class="mxchat-session-email">';
1815 + echo '<strong>Email:</strong> ' . esc_html($email);
1816 + echo '</div>';
1817 + }
1818 + echo '</div>';
4027 1819
4028 - $message_id = absint($_POST['message_id']);
1820 + echo '<div class="mxchat-messages">';
4029 1821
4030 - global $wpdb;
4031 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1822 + // Display messages for this session
1823 + foreach ($messages as $transcript) {
1824 + $formatted_timestamp = date_i18n('F j, Y g:i a', strtotime($transcript->timestamp));
4032 1825
4033 - // Fetch the RAG context for this message
4034 - $result = $wpdb->get_row($wpdb->prepare(
4035 - "SELECT rag_context FROM {$table_name} WHERE id = %d",
4036 - $message_id
4037 - ));
1826 + // Determine message styling
1827 + switch ($transcript->role) {
1828 + case 'assistant':
1829 + case 'bot':
1830 + $message_class = 'bot-message';
1831 + $display_role = esc_html__('Chatbot', 'mxchat');
1832 + break;
1833 + case 'user':
1834 + $message_class = 'user-message';
1835 + $display_role = !empty($transcript->user_identifier)
1836 + ? sanitize_text_field($transcript->user_identifier)
1837 + : esc_html__('User', 'mxchat');
1838 + break;
1839 + case 'agent':
1840 + $message_class = 'agent-message';
1841 + $display_role = esc_html__('Agent', 'mxchat');
1842 + break;
1843 + default:
1844 + $message_class = 'unknown-message';
1845 + $display_role = esc_html__('Unknown', 'mxchat');
1846 + }
4038 1847
4039 - if (!$result || empty($result->rag_context)) {
4040 - wp_send_json_error(['message' => esc_html__('No RAG context found for this message.', 'mxchat')]);
4041 - wp_die();
4042 - }
1848 + // Process message content
1849 + $message_content = wp_kses(
1850 + stripslashes($transcript->message),
1851 + [
1852 + 'b' => [], 'strong' => [], 'i' => [], 'em' => [], 'u' => [],
1853 + 'br' => [], 'p' => [], 'ul' => [], 'ol' => [], 'li' => [],
1854 + 'a' => ['href' => [], 'title' => []]
1855 + ]
1856 + );
1857 + $message_content = nl2br($message_content);
4043 1858
4044 - // Decode the JSON data
4045 - $rag_context = json_decode($result->rag_context, true);
1859 + // Render message
1860 + echo '<div class="mxchat-message ' . esc_attr($message_class) . '">';
1861 + echo '<div class="mxchat-message-header">' . esc_html($display_role) . '</div>';
1862 + echo '<div class="mxchat-message-content">' . $message_content . '</div>';
1863 + echo '<div class="mxchat-timestamp">' . esc_html($formatted_timestamp) . '</div>';
1864 + echo '</div>';
1865 + }
4046 1866
4047 - if (json_last_error() !== JSON_ERROR_NONE) {
4048 - wp_send_json_error(['message' => esc_html__('Invalid RAG context data.', 'mxchat')]);
4049 - wp_die();
1867 + // Close session block
1868 + echo '</div></div>';
4050 1869 }
4051 1870
4052 - wp_send_json_success($rag_context);
1871 + echo '</div>';
1872 + $output = ob_get_clean();
1873 + echo $output;
4053 1874 wp_die();
4054 1875 }
4055 1876
4056 -public function display_admin_notices() {
4057 - // Check if we're on a MXChat admin page
4058 - $screen = get_current_screen();
4059 - if (!$screen || strpos($screen->base, 'mxchat') === false) {
4060 - return;
4061 - }
4062 -
4063 - $dismiss_button = '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__('Dismiss this notice.', 'mxchat') . '</span></button>';
4064 -
4065 - // Check for error notices
4066 - $error_notice = get_transient('mxchat_admin_notice_error');
4067 - if ($error_notice) {
4068 - echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post($error_notice) . '</p>' . $dismiss_button . '</div>';
4069 - delete_transient('mxchat_admin_notice_error');
4070 - }
4071 -
4072 - // Check for success notices
4073 - $success_notice = get_transient('mxchat_admin_notice_success');
4074 - if ($success_notice) {
4075 - echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post($success_notice) . '</p>' . $dismiss_button . '</div>';
4076 - delete_transient('mxchat_admin_notice_success');
4077 - }
4078 -
4079 - // Check for info notices
4080 - $info_notice = get_transient('mxchat_admin_notice_info');
4081 - if ($info_notice) {
4082 - echo '<div class="notice notice-info is-dismissible"><p>' . wp_kses_post($info_notice) . '</p>' . $dismiss_button . '</div>';
4083 - delete_transient('mxchat_admin_notice_info');
4084 - }
4085 -}
4086 -
4087 -
4088 1877 public function mxchat_create_activation_page() {
4089 - // Include the new Pro & Extensions page template
4090 - require_once plugin_dir_path(__FILE__) . 'admin-pro-page.php';
1878 + $license_status = get_option('mxchat_license_status', 'inactive');
1879 + $license_error = get_option('mxchat_license_error', '');
1880 + ?>
1881 + <div class="wrap mxchat-admin">
1882 + <h2>MxChat Pro: Activation</h2>
1883 + <?php if ($license_status === 'inactive' && !empty($license_error)): ?>
1884 + <div class="error notice">
1885 + <p><?php echo esc_html($license_error); ?></p>
1886 + </div>
1887 + <?php endif; ?>
4091 1888
4092 - // Get addons configuration from the MxChat_Addons class
4093 - require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php';
4094 - $addons_instance = new MxChat_Addons();
4095 - $addons_config = $addons_instance->get_addons_config();
1889 + <form id="mxchat-activation-form" style="<?php echo $license_status === 'active' ? 'display: none;' : ''; ?>">
1890 + <table class="form-table">
1891 + <tr valign="top">
1892 + <th scope="row">Email Address</th>
1893 + <td>
1894 + <input type="email" id="mxchat_pro_email" name="mxchat_pro_email" value="<?php echo esc_attr(get_option('mxchat_pro_email')); ?>" class="regular-text" required />
1895 + </td>
1896 + </tr>
1897 + <tr valign="top">
1898 + <th scope="row">Activation Key</th>
1899 + <td>
1900 + <input type="text" id="mxchat_activation_key" name="mxchat_activation_key" value="<?php echo esc_attr(get_option('mxchat_activation_key')); ?>" class="regular-text" required />
1901 + </td>
1902 + </tr>
1903 + </table>
1904 + <?php if ($license_status !== 'active'): ?>
1905 + <button type="submit" id="activate_license_button" class="button button-primary"><?php esc_html_e('Activate License', 'mxchat'); ?></button>
1906 + <div id="mxchat-activation-spinner" class="mxchat-activation-spinner" style="display: none;"></div>
1907 + <?php endif; ?>
1908 + </form>
4096 1909
4097 - // Render the consolidated Pro & Extensions page
4098 - mxchat_render_pro_page($this, $addons_config);
1910 + <!-- License Status Display -->
1911 + <h3>License Status: <span id="mxchat-license-status"><?php echo $license_status === 'active' ? 'Active' : 'Inactive'; ?></span></h3>
1912 + </div>
1913 + <?php
4099 1914 }
4100 1915
4101 -/**
4102 - * Check if current activation is linked to a domain
4103 - * This checks YOUR website's database, not the user's local database
4104 - */
4105 -public function is_current_activation_linked($domain) {
4106 - $license_key = get_option('mxchat_activation_key');
4107 - $email = get_option('mxchat_pro_email');
4108 -
4109 - if (empty($license_key) || empty($email)) {
4110 - return false;
1916 +public function mxchat_intents_page_html() {
1917 + if ( ! current_user_can( 'manage_options' ) ) {
1918 + return;
4111 1919 }
4112 1920
4113 - // Check with YOUR website's API
4114 - $response = wp_remote_post('https://mxchat.ai/mxchat-api/check-domain', array(
4115 - 'body' => array(
4116 - 'license_key' => $license_key,
4117 - 'email' => $email,
4118 - 'domain' => $domain
4119 - ),
4120 - 'timeout' => 10,
4121 - 'sslverify' => false
4122 - ));
1921 + // Fetch existing intents with pagination and filtering
1922 + global $wpdb;
1923 + $table_name = $wpdb->prefix . 'mxchat_intents';
1924 + $page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
1925 + $per_page = 20;
1926 + $offset = ( $page - 1 ) * $per_page;
4123 1927
4124 - if (is_wp_error($response)) {
4125 - return false;
4126 - }
4127 1928
4128 - $body = json_decode(wp_remote_retrieve_body($response), true);
4129 - return isset($body['success']) && $body['success'] && isset($body['data']['linked']) && $body['data']['linked'];
1929 + // Add at the start of mxchat_intents_page_html()
1930 +if (isset($_GET['updated']) && $_GET['updated'] === 'true') {
1931 + echo '<div class="notice notice-success is-dismissible"><p>' .
1932 + esc_html__('Intent updated successfully.', 'mxchat') .
1933 + '</p></div>';
4130 1934 }
4131 1935
1936 + // Build the WHERE clause based on filters
1937 + $where = '1=1';
1938 + $search_term = isset( $_GET['s'] ) ? trim( $_GET['s'] ) : '';
1939 + $callback_filter = isset( $_GET['callback_filter'] ) ? sanitize_text_field( $_GET['callback_filter'] ) : '';
4132 1940
4133 -public function mxchat_actions_page_html() {
4134 - if (!current_user_can('manage_options')) {
4135 - return;
1941 + if ( $search_term ) {
1942 + $search_term_like = '%' . $wpdb->esc_like( $search_term ) . '%';
1943 + $where .= $wpdb->prepare( ' AND (intent_label LIKE %s OR phrases LIKE %s)', $search_term_like, $search_term_like );
4136 1944 }
4137 1945
4138 - global $wpdb;
4139 - $table_name = $wpdb->prefix . 'mxchat_intents';
1946 + if ( $callback_filter ) {
1947 + $where .= $wpdb->prepare( ' AND callback_function = %s', $callback_filter );
1948 + }
4140 1949
4141 - // Get stats for dashboard
4142 - $total_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
4143 - $enabled_actions = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
4144 - $disabled_actions = $total_actions - $enabled_actions;
1950 + // Get total count for pagination
1951 + $total_intents = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name WHERE $where" );
1952 + $total_pages = ceil( $total_intents / $per_page );
4145 1953
4146 - // Get unique action types count
4147 - $action_types_count = $wpdb->get_var("SELECT COUNT(DISTINCT callback_function) FROM $table_name");
1954 + // Fetch intents with pagination and filters
1955 + $intents = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE $where LIMIT %d OFFSET %d", $per_page, $offset ) );
4148 1956
4149 - // Get action type distribution
4150 - $type_distribution_raw = $wpdb->get_results("SELECT callback_function, COUNT(*) as count FROM $table_name GROUP BY callback_function ORDER BY count DESC LIMIT 10");
1957 + // Get available callback functions with 'pro_only' flag
4151 1958 $available_callbacks = $this->mxchat_get_available_callbacks();
4152 - $callback_groups = $this->mxchat_get_available_callbacks(true, true);
1959 + ?>
4153 1960
4154 - $action_type_distribution = array();
4155 - foreach ($type_distribution_raw as $row) {
4156 - $label = isset($available_callbacks[$row->callback_function]['label'])
4157 - ? $available_callbacks[$row->callback_function]['label']
4158 - : $row->callback_function;
4159 - $action_type_distribution[$label] = $row->count;
4160 - }
4161 -
4162 - // Prepare page data
4163 - $page_data = array(
4164 - 'total_actions' => $total_actions,
4165 - 'enabled_actions' => $enabled_actions,
4166 - 'disabled_actions' => $disabled_actions,
4167 - 'action_types_count' => $action_types_count,
4168 - 'action_type_distribution' => $action_type_distribution,
4169 - 'available_callbacks' => $available_callbacks,
4170 - 'callback_groups' => $callback_groups,
4171 - );
4172 -
4173 - // Include and render the new template
4174 - require_once plugin_dir_path(__FILE__) . 'admin-actions-page.php';
4175 - mxchat_render_actions_page($this, $page_data);
4176 -}
4177 -
4178 -/**
4179 - * LEGACY HTML - Preserved below for reference, to be removed in future update
4180 - */
4181 -function mxchat_actions_page_legacy_html() {
4182 - // This function is deprecated and no longer used
4183 - // The new template is in includes/admin-actions-page.php
4184 - ?>
4185 - <div class="wrap mxchat-wrapper">
4186 - <!-- Hero Section -->
4187 - <div class="mxchat-hero">
4188 - <h1 class="mxchat-main-title">
4189 - <span class="mxchat-gradient-text">Actions</span> Manager
4190 - </h1>
4191 - <p class="mxchat-hero-subtitle">
4192 - <?php esc_html_e('Create and manage custom actions to enhance your chatbot\'s capabilities.', 'mxchat'); ?>
1961 + <div class="wrap mxchat-admin">
1962 + <!-- Add Intent Form -->
1963 + <form id="mxchat-add-intent-form" method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
1964 + <input type="hidden" name="action" value="mxchat_add_intent">
1965 + <?php wp_nonce_field( 'mxchat_add_intent_nonce' ); ?>
1966 + <h2><?php esc_html_e( 'Add New Intent', 'mxchat' ); ?></h2>
1967 + <p class="description">
1968 + <?php esc_html_e( 'We highly encourage users to quickly read our ', 'mxchat' ); ?>
1969 + <a href="https://mxchat.ai/documentation/#intents" target="_blank" rel="noopener noreferrer">
1970 + <?php esc_html_e( 'documentation', 'mxchat' ); ?>
1971 + </a>
1972 + <?php esc_html_e( ' to better understand intents. Some intents require setup in the Integration tab. If your intent is not triggering lower similarity threshold test.', 'mxchat' ); ?>
4193 1973 </p>
4194 - </div>
4195 1974
4196 - <!-- Actions Header with Search and Filter -->
4197 - <div class="mxchat-actions-header">
4198 - <div class="mxchat-actions-filters">
4199 - <form method="get" class="mxchat-search-form">
4200 - <input type="hidden" name="page" value="mxchat-actions">
4201 - <div class="mxchat-search-group">
4202 - <span class="dashicons dashicons-search"></span>
4203 - <input type="text" name="s" class="mxchat-search-input"
4204 - placeholder="<?php esc_attr_e('Search Actions', 'mxchat'); ?>"
4205 - value="<?php echo esc_attr($search_term); ?>">
4206 - </div>
4207 - <select name="callback_filter" class="mxchat-action-filter">
4208 - <option value=""><?php esc_html_e('All Action Types', 'mxchat'); ?></option>
4209 - <?php foreach ($available_callbacks as $function => $callback_data) :
4210 - $label = $callback_data['label']; ?>
4211 - <option value="<?php echo esc_attr($function); ?>"
4212 - <?php selected($callback_filter, $function); ?>>
4213 - <?php echo esc_html($label); ?>
4214 - </option>
4215 - <?php endforeach; ?>
4216 - </select>
4217 - <button type="submit" class="mxchat-button-secondary">
4218 - <?php esc_html_e('Filter', 'mxchat'); ?>
4219 - </button>
4220 - </form>
1975 + <div class="mxchat-form-group">
1976 + <label for="intent_label"><?php esc_html_e( 'Intent Label (For your reference only)', 'mxchat' ); ?></label>
1977 + <input name="intent_label" type="text" id="intent_label" class="regular-text" required
1978 + placeholder="Example Email Capture: Newsletter Signup">
4221 1979 </div>
4222 - <div class="mxchat-actions-controls">
4223 - <button type="button" id="mxchat-add-action-btn" class="mxchat-button-primary">
4224 - <span class="dashicons dashicons-plus-alt"></span>
4225 - <?php esc_html_e('Add New Action', 'mxchat'); ?>
4226 - </button>
1980 + <div class="mxchat-form-group">
1981 + <label for="phrases"><?php esc_html_e( 'Phrases (comma-separated)', 'mxchat' ); ?></label>
1982 + <textarea name="phrases" id="phrases" rows="5" class="large-text" required
1983 + placeholder="Example Email Capture: sign me up, subscribe me, I want to join, add me to the newsletter, send me updates, keep me informed"></textarea>
4227 1984 </div>
4228 - </div>
1985 + <div class="mxchat-form-group">
1986 + <label for="callback_function"><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></label>
1987 +<select name="callback_function" id="callback_function" required>
1988 + <option value=""><?php esc_html_e('Select a Callback', 'mxchat'); ?></option>
1989 + <?php
1990 + $groups = $this->mxchat_get_available_callbacks(true); // Fetch grouped data
4229 1991
4230 - <!-- Actions Grid Layout - All actions in a single grid -->
4231 - <div class="mxchat-actions-grid">
4232 - <div class="mxchat-cards-container">
4233 - <?php if (!empty($actions)) : ?>
4234 - <?php foreach ($actions as $action) :
4235 - $callback_function = $action->callback_function;
4236 - $callback_label = isset($available_callbacks[$callback_function]['label'])
4237 - ? $available_callbacks[$callback_function]['label']
4238 - : $callback_function;
4239 - $threshold_value = isset($action->similarity_threshold)
4240 - ? round($action->similarity_threshold * 100)
4241 - : 85;
1992 + foreach ($groups as $group_label => $group_callbacks) :
1993 + echo '<optgroup label="' . esc_attr($group_label) . '">';
1994 + foreach ($group_callbacks as $function => $data) :
1995 + $label = $data['label'];
1996 + $pro_only = $data['pro_only'];
1997 + $disabled = (!$this->is_activated && $pro_only) ? 'disabled' : '';
1998 + $label_suffix = (!$this->is_activated && $pro_only) ? ' (Pro Only)' : '';
1999 + ?>
2000 + <option value="<?php echo esc_attr($function); ?>" <?php echo $disabled; ?>>
2001 + <?php echo esc_html($label . $label_suffix); ?>
2002 + </option>
2003 + <?php endforeach;
2004 + echo '</optgroup>';
2005 + endforeach;
2006 + ?>
2007 +</select>
4242 2008
4243 - // Check if this is a form action
4244 - $is_form_action = strpos($action->intent_label, 'Form ') === 0;
4245 2009
4246 - // Get action status (enabled/disabled) - default to true if column doesn't exist
4247 - $is_enabled = isset($action->enabled) ? (bool)$action->enabled : true;
4248 -
4249 - // Get enabled bots for display
4250 - $enabled_bots = [];
4251 - if (isset($action->enabled_bots) && !empty($action->enabled_bots)) {
4252 - $enabled_bots = json_decode($action->enabled_bots, true);
4253 - if (!is_array($enabled_bots)) {
4254 - $enabled_bots = ['default'];
4255 - }
4256 - } else {
4257 - $enabled_bots = ['default']; // Backward compatibility
4258 - }
4259 - ?>
4260 - <div class="mxchat-action-card <?php echo $is_form_action ? 'mxchat-form-action' : ''; ?>">
4261 - <div class="mxchat-card-header">
4262 - <div class="mxchat-card-title"><?php echo esc_html($action->intent_label); ?></div>
4263 - <div class="mxchat-card-toggle">
4264 - <label class="mxchat-switch">
4265 - <input type="checkbox" class="mxchat-action-toggle"
4266 - data-action-id="<?php echo esc_attr($action->id); ?>"
4267 - <?php checked($is_enabled); ?>>
4268 - <span class="mxchat-slider round"></span>
4269 - </label>
4270 - </div>
4271 - </div>
4272 2010
4273 - <div class="mxchat-card-body">
4274 - <div class="mxchat-card-description">
4275 - <strong><?php esc_html_e('Type:', 'mxchat'); ?></strong>
4276 - <?php echo esc_html($callback_label); ?>
4277 - </div>
4278 -
4279 - <div class="mxchat-card-phrases">
4280 - <strong><?php esc_html_e('Trigger phrases:', 'mxchat'); ?></strong>
4281 - <div class="mxchat-phrases-preview">
4282 - <?php
4283 - // Check if the helper function exists, otherwise use a simple substring
4284 - if (method_exists($this, 'get_trimmed_phrases')) {
4285 - echo esc_html($this->get_trimmed_phrases($action->phrases));
4286 - } else {
4287 - echo esc_html(strlen($action->phrases) > 100 ?
4288 - substr($action->phrases, 0, 97) . '...' :
4289 - $action->phrases);
4290 - }
4291 - ?>
4292 - </div>
4293 - </div>
4294 -
4295 - <div class="mxchat-threshold-control">
4296 - <div class="mxchat-threshold-label">
4297 - <?php esc_html_e('Similarity Threshold:', 'mxchat'); ?>
4298 - <span class="mxchat-threshold-value"><?php echo esc_html($threshold_value); ?>%</span>
4299 - </div>
4300 - </div>
4301 -
4302 - <!-- Bot Availability Display (Read-only) -->
4303 - <div class="mxchat-card-bots">
4304 - <strong><?php esc_html_e('Assigned bots:', 'mxchat'); ?></strong>
4305 - <div class="mxchat-bot-badges">
4306 - <?php
4307 - foreach ($enabled_bots as $bot_id) {
4308 - if ($bot_id === 'default') {
4309 - echo '<span class="mxchat-bot-badge">' . esc_html__('Default Bot', 'mxchat') . '</span>';
4310 - } else {
4311 - // Try to get bot name from multi-bot manager
4312 - if (class_exists('MxChat_Multi_Bot_Core_Manager')) {
4313 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4314 - $available_bots = $multi_bot_manager->get_available_bots();
4315 - $bot_name = isset($available_bots[$bot_id]) ? $available_bots[$bot_id] : $bot_id;
4316 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_name) . '</span>';
4317 - } else {
4318 - echo '<span class="mxchat-bot-badge">' . esc_html($bot_id) . '</span>';
4319 - }
4320 - }
4321 - }
4322 - ?>
4323 - </div>
4324 - </div>
4325 - </div>
4326 -
4327 - <div class="mxchat-card-footer">
4328 - <?php
4329 - // Check if it's a form action
4330 - $is_form_action = preg_match('/Form (\d+)/', $action->intent_label, $form_matches);
4331 -
4332 - // Check if it's a recommendation flow action
4333 - $is_flow_action = preg_match('/Recommendation Flow (\d+)/', $action->intent_label, $flow_matches);
4334 -
4335 - if ($is_form_action) {
4336 - $form_id = isset($form_matches[1]) ? $form_matches[1] : '';
4337 - ?>
4338 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-forms&action=edit&form_id=' . $form_id)); ?>"
4339 - class="mxchat-button-primary">
4340 - <span class="dashicons dashicons-feedback"></span>
4341 - <?php esc_html_e('Edit Form', 'mxchat'); ?>
4342 - </a>
4343 - <?php } elseif ($is_flow_action) {
4344 - ?>
4345 - <a href="<?php echo esc_url(admin_url('admin.php?page=mxchat-smart-recommender')); ?>"
4346 - class="mxchat-button-primary">
4347 - <span class="dashicons dashicons-list-view"></span>
4348 - <?php esc_html_e('Manage Flows', 'mxchat'); ?>
4349 - </a>
4350 - <?php } else { ?>
4351 - <button type="button"
4352 - class="mxchat-button-secondary mxchat-edit-button"
4353 - data-action-id="<?php echo esc_attr($action->id); ?>"
4354 - data-phrases="<?php echo esc_attr($action->phrases); ?>"
4355 - data-label="<?php echo esc_attr($action->intent_label); ?>"
4356 - data-threshold="<?php echo esc_attr(round($action->similarity_threshold * 100)); ?>"
4357 - data-callback-function="<?php echo esc_attr($action->callback_function); ?>"
4358 - data-enabled-bots="<?php echo esc_attr(json_encode($enabled_bots)); ?>">
4359 - <span class="dashicons dashicons-edit"></span>
4360 - <?php esc_html_e('Edit', 'mxchat'); ?>
4361 - </button>
4362 - <form method="post"
4363 - action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
4364 - class="mxchat-delete-form"
4365 - onsubmit="return confirm('<?php esc_attr_e('Are you sure you want to delete this action?', 'mxchat'); ?>');">
4366 - <?php wp_nonce_field('mxchat_delete_intent_nonce'); ?>
4367 - <input type="hidden" name="action" value="mxchat_delete_intent">
4368 - <input type="hidden" name="intent_id" value="<?php echo esc_attr($action->id); ?>">
4369 - <button type="submit" class="mxchat-button-text mxchat-delete-button">
4370 - <span class="dashicons dashicons-trash"></span>
4371 - <?php esc_html_e('Delete', 'mxchat'); ?>
4372 - </button>
4373 - </form>
4374 - <?php } ?>
4375 - </div>
4376 - </div>
4377 - <?php endforeach; ?>
4378 - <?php else : ?>
4379 - <!-- If no actions found -->
4380 - <div class="mxchat-no-actions">
4381 - <div class="mxchat-empty-state">
4382 - <span class="dashicons dashicons-format-chat"></span>
4383 - <h2><?php esc_html_e('No actions found', 'mxchat'); ?></h2>
4384 - <p><?php esc_html_e('Get started by creating your first action to enhance your chatbot.', 'mxchat'); ?></p>
4385 - <button type="button" id="mxchat-create-first-action" class="mxchat-button-primary">
4386 - <?php esc_html_e('Create Your First Action', 'mxchat'); ?>
4387 - </button>
4388 - </div>
4389 - </div>
4390 - <?php endif; ?>
4391 2011 </div>
2012 + <button type="submit" class="button button-primary submit-content-button">
2013 + <?php esc_html_e( 'Add Intent', 'mxchat' ); ?>
2014 + </button>
2015 + <div id="mxchat-intent-loading" style="display: none;"></div>
2016 + <div id="mxchat-intent-loading-text" style="display: none;">
2017 + <?php esc_html_e( 'Saving intent, please wait...', 'mxchat' ); ?>
4392 2018 </div>
4393 2019
4394 - <?php if ($total_pages > 1) : ?>
4395 - <div class="mxchat-pagination">
4396 - <?php
4397 - echo paginate_links(array(
4398 - 'base' => add_query_arg('paged', '%#%'),
4399 - 'format' => '',
4400 - 'prev_text' => __('&laquo; Previous', 'mxchat'),
4401 - 'next_text' => __('Next &raquo;', 'mxchat'),
4402 - 'total' => $total_pages,
4403 - 'current' => $page
4404 - ));
4405 - ?>
4406 - </div>
4407 - <?php endif; ?>
2020 + </form>
4408 2021
4409 -<!-- Add/Edit Action Modal with Step-Based Approach -->
4410 -<!-- Complete Modal HTML with Defined Groups Variable -->
4411 -<div id="mxchat-action-modal" class="mxchat-modal" style="display: none;">
4412 - <div class="mxchat-modal-content">
4413 - <span class="mxchat-modal-close">&times;</span>
4414 -
4415 - <form id="mxchat-action-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
4416 - <!-- Dynamic nonce field -->
4417 - <div id="action-nonce-container">
4418 - <?php wp_nonce_field('mxchat_add_intent_nonce', 'add_intent_nonce'); ?>
2022 + <!-- Filter Form -->
2023 + <form method="get" action="">
2024 + <input type="hidden" name="page" value="mxchat-intents">
2025 + <div class="mxchat-search-group">
2026 + <input type="text" name="s" id="mxchat-intent-search" placeholder="<?php esc_attr_e( 'Search Intents', 'mxchat' ); ?>" value="<?php echo esc_attr( $search_term ); ?>">
2027 + <select name="callback_filter" id="mxchat-callback-filter">
2028 + <option value=""><?php esc_html_e( 'All Callbacks', 'mxchat' ); ?></option>
2029 + <?php foreach ( $available_callbacks as $function => $callback_data ) : ?>
2030 + <?php $label = $callback_data['label']; ?>
2031 + <option value="<?php echo esc_attr( $function ); ?>" <?php selected( $callback_filter, $function ); ?>><?php echo esc_html( $label ); ?></option>
2032 + <?php endforeach; ?>
2033 + </select>
2034 + <button type="submit" class="button"><?php esc_html_e( 'Filter', 'mxchat' ); ?></button>
4419 2035 </div>
4420 - <input type="hidden" name="action" id="form_action_type" value="mxchat_add_intent">
4421 - <input type="hidden" name="intent_id" id="edit_action_id" value="">
4422 - <input type="hidden" name="callback_function" id="callback_function" value="">
2036 + </form>
4423 2037
4424 - <!-- Step 1: Action Type Selection -->
4425 - <div id="mxchat-action-step-1" class="mxchat-action-step active">
4426 - <div class="mxchat-step-indicator">
4427 - <div class="mxchat-step-number">1</div>
4428 - <div class="mxchat-step-title"><?php esc_html_e('Select Action Type', 'mxchat'); ?></div>
4429 - </div>
4430 -
4431 - <div id="mxchat-action-type-selector" class="mxchat-action-type-selector">
4432 - <div class="mxchat-action-type-search">
4433 - <span class="dashicons dashicons-search"></span>
4434 - <input type="text" id="action-type-search" placeholder="<?php esc_attr_e('Search action types...', 'mxchat'); ?>" class="mxchat-action-type-search-input">
4435 - </div>
4436 -
4437 - <?php
4438 - // Get the callbacks - IMPORTANT: Define the $groups variable here
4439 - $groups = $this->mxchat_get_available_callbacks(true, true);
4440 - ?>
4441 -
4442 - <div class="mxchat-action-type-categories">
4443 - <button type="button" class="mxchat-category-button active" data-category="all"><?php esc_html_e('All', 'mxchat'); ?></button>
2038 + <!-- Intents Table -->
2039 + <table class="wp-list-table mxchat-intents-table widefat fixed striped">
2040 + <thead>
2041 + <tr>
2042 + <th><?php esc_html_e( 'Intent Label', 'mxchat' ); ?></th>
2043 + <th><?php esc_html_e( 'Phrases', 'mxchat' ); ?></th>
2044 + <th><?php esc_html_e( 'Callback Function', 'mxchat' ); ?></th>
2045 + <th><?php esc_html_e( 'Similarity Threshold', 'mxchat' ); ?></th>
2046 + <th><?php esc_html_e( 'Actions', 'mxchat' ); ?></th>
2047 + </tr>
2048 + </thead>
2049 + <tbody>
2050 + <?php if ( $intents ) : ?>
2051 + <?php foreach ( $intents as $intent ) : ?>
4444 2052 <?php
4445 - // Get unique categories from the defined groups
4446 - foreach ($groups as $group_label => $group_callbacks) :
4447 - $category_slug = sanitize_title($group_label);
2053 + $callback_function = $intent->callback_function;
2054 + $callback_label = isset( $available_callbacks[ $callback_function ]['label'] ) ? $available_callbacks[ $callback_function ]['label'] : $callback_function;
2055 + $threshold_value = isset( $intent->similarity_threshold ) ? round( $intent->similarity_threshold * 100 ) : 85;
4448 2056 ?>
4449 - <button type="button" class="mxchat-category-button" data-category="<?php echo esc_attr($category_slug); ?>"><?php echo esc_html($group_label); ?></button>
4450 - <?php endforeach; ?>
4451 - </div>
2057 + <tr>
2058 + <td><?php echo esc_html( $intent->intent_label ); ?></td>
2059 + <td><?php echo esc_html( $intent->phrases ); ?></td>
2060 + <td><?php echo esc_html( $callback_label ); ?></td>
2061 + <!-- Similarity Threshold Column -->
2062 + <td>
2063 + <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
2064 + <?php wp_nonce_field( 'mxchat_update_intent_threshold_nonce' ); ?>
2065 + <input type="hidden" name="action" value="mxchat_update_intent_threshold">
2066 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
2067 + <input type="range" name="intent_threshold" id="intent_threshold_<?php echo esc_attr( $intent->id ); ?>" min="70" max="95" value="<?php echo esc_attr( $threshold_value ); ?>" oninput="document.getElementById('threshold_output_<?php echo esc_attr( $intent->id ); ?>').value = this.value + '%'">
2068 + <output id="threshold_output_<?php echo esc_attr( $intent->id ); ?>"><?php echo esc_html( $threshold_value ); ?>%</output>
2069 + </td>
2070 + <!-- Actions Column -->
2071 + <td>
2072 + <button type="submit" class="button button-primary mxchat-save-button">
2073 + <?php esc_html_e( 'Save', 'mxchat' ); ?>
2074 + </button>
2075 + </form>
4452 2076
4453 - <div class="mxchat-action-types-grid">
4454 - <?php
4455 - // Generate action cards from available callbacks
4456 - foreach ($groups as $group_label => $group_callbacks) :
4457 - $category_slug = sanitize_title($group_label);
4458 2077
4459 - foreach ($group_callbacks as $function => $data) :
4460 - $label = $data['label'];
4461 - $icon = isset($data['icon']) ? $data['icon'] : 'admin-generic';
4462 - $description = isset($data['description']) ? $data['description'] : '';
4463 - $is_addon = isset($data['addon']) && $data['addon'] !== false;
4464 - $addon_name = isset($data['addon_name']) ? $data['addon_name'] : '';
4465 - $is_installed = isset($data['installed']) ? $data['installed'] : true;
4466 - $is_promo = !empty($data['addon_promo']) && !$is_installed;
4467 2078
4468 - // Determine card status and styling
4469 - $card_class = 'mxchat-action-type-card';
4470 - $icon_class = 'mxchat-action-type-icon';
4471 - $status_badge = '';
4472 2079
4473 - if ($is_promo) {
4474 - // Promotional card — not selectable, just informational
4475 - $card_class .= ' not-installed mxchat-promo-card';
4476 - $status_badge = '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4477 - } elseif ($is_addon && !$is_installed) {
4478 - // Add-on not installed
4479 - $card_class .= ' not-installed';
4480 - $status_badge .= '<span class="mxchat-addon-badge">' . esc_html__('Add-on Required', 'mxchat') . '</span>';
4481 - }
2080 + <button type="button"
2081 + class="button button-secondary mxchat-edit-button"
2082 + data-intent-id="<?php echo esc_attr($intent->id); ?>"
2083 + data-phrases="<?php echo esc_attr($intent->phrases); ?>">
2084 + <?php esc_html_e('Edit', 'mxchat'); ?>
2085 + </button>
4482 2086
4483 - // Default description if none provided
4484 - if (empty($description)) {
4485 - $description = sprintf(
4486 - esc_html__('Use the %s action in your chatbot', 'mxchat'),
4487 - $label
4488 - );
4489 - }
4490 - ?>
4491 - <div class="<?php echo esc_attr($card_class); ?>"
4492 - data-category="<?php echo esc_attr($category_slug); ?>"
4493 - <?php if (!$is_promo) : ?>
4494 - data-value="<?php echo esc_attr($function); ?>"
4495 - data-label="<?php echo esc_attr($label); ?>"
4496 - <?php endif; ?>
4497 - data-pro="false"
4498 - data-addon="<?php echo esc_attr($is_addon ? $data['addon'] : ''); ?>"
4499 - data-installed="<?php echo $is_installed ? 'true' : 'false'; ?>"
4500 - <?php if ($is_promo) : ?>data-promo="true"<?php endif; ?>>
4501 - <div class="<?php echo esc_attr($icon_class); ?>">
4502 - <span class="dashicons dashicons-<?php echo esc_attr($icon); ?>"></span>
4503 - </div>
4504 - <div class="mxchat-action-type-info">
4505 - <h4><?php echo esc_html($label); ?></h4>
4506 - <p><?php echo esc_html($description); ?></p>
4507 - <?php if (!empty($status_badge)) : ?>
4508 - <?php echo $status_badge; ?>
4509 - <?php endif; ?>
4510 2087
4511 - <?php if ($is_promo || ($is_addon && !$is_installed)) : ?>
4512 - <div class="mxchat-addon-info">
4513 - <?php echo esc_html(sprintf(
4514 - __('Requires %s', 'mxchat'),
4515 - $addon_name
4516 - )); ?>
4517 - — <a href="https://mxchat.ai/" target="_blank"><?php esc_html_e('Get Add-on', 'mxchat'); ?></a>
4518 - </div>
4519 - <?php endif; ?>
4520 - </div>
4521 - </div>
4522 - <?php endforeach;
4523 - endforeach; ?>
4524 - </div>
4525 - </div>
4526 2088
4527 - <div class="mxchat-modal-actions">
4528 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4529 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4530 - </button>
4531 - </div>
4532 - </div>
4533 2089
4534 - <!-- Step 2: Action Configuration -->
4535 - <div id="mxchat-action-step-2" class="mxchat-action-step">
4536 - <div class="mxchat-step-indicator">
4537 - <div class="mxchat-step-number">2</div>
4538 - <div class="mxchat-step-title"><?php esc_html_e('Configure Action', 'mxchat'); ?></div>
4539 - </div>
2090 + <!-- Delete Form -->
2091 + <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" onsubmit="return confirm('<?php esc_attr_e( 'Are you sure you want to delete this intent?', 'mxchat' ); ?>');">
2092 + <?php wp_nonce_field( 'mxchat_delete_intent_nonce' ); ?>
2093 + <input type="hidden" name="action" value="mxchat_delete_intent">
2094 + <input type="hidden" name="intent_id" value="<?php echo esc_attr( $intent->id ); ?>">
2095 + <button type="submit" class="button mxchat-delete-all">
2096 + <?php esc_html_e( 'Delete', 'mxchat' ); ?>
2097 + </button>
2098 + </form>
2099 + </td>
2100 + </tr>
2101 + <?php endforeach; ?>
2102 + <?php else : ?>
2103 + <tr>
2104 + <td colspan="5"><?php esc_html_e( 'No intents found.', 'mxchat' ); ?></td>
2105 + </tr>
2106 + <?php endif; ?>
2107 + </tbody>
2108 + </table>
4540 2109
4541 - <div class="mxchat-selected-action">
4542 - <button type="button" class="mxchat-back-button" id="mxchat-back-to-step-1">
4543 - <span class="dashicons dashicons-arrow-left-alt"></span>
4544 - <?php esc_html_e('Back to Action Types', 'mxchat'); ?>
4545 - </button>
4546 - <div class="mxchat-selected-action-info">
4547 - <div id="selected-action-icon" class="mxchat-action-type-icon">
4548 - <span class="dashicons dashicons-admin-generic"></span>
4549 - </div>
4550 - <div class="mxchat-selected-action-details">
4551 - <h3 id="selected-action-title"><?php esc_html_e('Selected Action', 'mxchat'); ?></h3>
4552 - <p id="selected-action-description"><?php esc_html_e('Configure this action for your chatbot', 'mxchat'); ?></p>
4553 - </div>
4554 - </div>
4555 - </div>
4556 2110
4557 - <div class="mxchat-form-group">
4558 - <label for="intent_label">
4559 - <?php esc_html_e('Action Label (For your reference only)', 'mxchat'); ?>
4560 - </label>
4561 - <input name="intent_label" type="text" id="intent_label" required
4562 - class="mxchat-intent-input"
4563 - placeholder="<?php esc_attr_e('Example: Newsletter Signup', 'mxchat'); ?>">
4564 - </div>
4565 -
4566 - <div class="mxchat-form-group">
4567 - <label for="phrases">
4568 - <?php esc_html_e('Trigger Phrases (comma-separated)', 'mxchat'); ?>
4569 - </label>
4570 - <textarea name="phrases" id="action_phrases" rows="5" required
4571 - class="mxchat-intent-textarea"
4572 - placeholder="<?php esc_attr_e('Example: sign me up, subscribe me, I want to join, add me to the newsletter', 'mxchat'); ?>"></textarea>
4573 - </div>
4574 -
4575 - <div class="mxchat-form-group">
4576 - <label for="similarity_threshold">
4577 - <?php esc_html_e('Similarity Threshold', 'mxchat'); ?>
4578 - <span class="mxchat-threshold-value-display">85%</span>
4579 - </label>
4580 - <div class="mxchat-slider-group modal-slider">
4581 - <input type="range"
4582 - name="similarity_threshold"
4583 - id="similarity_threshold"
4584 - min="10"
4585 - max="95"
4586 - value="85"
4587 - class="mxchat-intent-slider"
4588 - oninput="document.querySelector('.mxchat-threshold-value-display').textContent = this.value + '%'">
4589 - </div>
4590 - <div class="mxchat-threshold-hint">
4591 - <?php esc_html_e('Lower values (10-30) make the action trigger more easily. Higher values (70-95) require more exact matches.', 'mxchat'); ?>
4592 - </div>
4593 - </div>
4594 -
4595 - <!-- Bot Selection Section -->
4596 - <div class="mxchat-form-group">
4597 - <label for="enabled_bots">
4598 - <?php esc_html_e('Which bots should we enable this action for?', 'mxchat'); ?>
4599 - </label>
4600 - <div class="mxchat-bot-selector">
4601 - <div class="mxchat-bot-option">
4602 - <label class="mxchat-checkbox-label">
4603 - <input type="checkbox"
4604 - name="enabled_bots[]"
4605 - value="default"
4606 - id="bot_default"
4607 - checked="checked">
4608 - <span class="mxchat-checkmark"></span>
4609 - <?php esc_html_e('Default Bot', 'mxchat'); ?>
4610 - </label>
4611 - </div>
4612 -
4613 - <?php if (class_exists('MxChat_Multi_Bot_Core_Manager')) :
4614 - $multi_bot_manager = MxChat_Multi_Bot_Core_Manager::get_instance();
4615 - $available_bots = $multi_bot_manager->get_available_bots();
4616 -
4617 - foreach ($available_bots as $bot_id => $bot_name) :
4618 - if ($bot_id === 'default') continue; // Skip default, already shown above
4619 - ?>
4620 - <div class="mxchat-bot-option">
4621 - <label class="mxchat-checkbox-label">
4622 - <input type="checkbox"
4623 - name="enabled_bots[]"
4624 - value="<?php echo esc_attr($bot_id); ?>"
4625 - id="bot_<?php echo esc_attr($bot_id); ?>">
4626 - <span class="mxchat-checkmark"></span>
4627 - <?php echo esc_html($bot_name); ?>
4628 - </label>
4629 - </div>
4630 - <?php
4631 - endforeach;
4632 - endif; ?>
4633 - </div>
4634 - </div>
4635 -
4636 - <div class="mxchat-modal-actions">
4637 - <button type="button" class="mxchat-button-secondary mxchat-modal-cancel">
4638 - <?php esc_html_e('Cancel', 'mxchat'); ?>
4639 - </button>
4640 - <button type="submit" class="mxchat-button-primary" id="mxchat-save-action-btn">
4641 - <?php esc_html_e('Save Action', 'mxchat'); ?>
4642 - </button>
4643 - </div>
2111 + <div id="mxchat-edit-modal" class="mxchat-modal" style="display: none;">
2112 + <div class="mxchat-modal-content">
2113 + <span class="mxchat-modal-close">&times;</span>
2114 + <h2><?php esc_html_e('Edit Intent Phrases', 'mxchat'); ?></h2>
2115 + <form id="mxchat-edit-intent-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
2116 + <?php wp_nonce_field('mxchat_edit_intent_nonce'); ?>
2117 + <input type="hidden" name="action" value="mxchat_edit_intent">
2118 + <input type="hidden" name="intent_id" id="edit_intent_id">
2119 + <div class="mxchat-form-group">
2120 + <label for="edit_phrases"><?php esc_html_e('Phrases (comma-separated)', 'mxchat'); ?></label>
2121 + <textarea name="phrases" id="edit_phrases" rows="5" class="large-text" required></textarea>
4644 2122 </div>
2123 + <button type="submit" class="button button-primary">
2124 + <?php esc_html_e('Update Phrases', 'mxchat'); ?>
2125 + </button>
4645 2126 </form>
4646 2127 </div>
4647 2128 </div>
4648 2129
4649 -<div id="mxchat-action-loading" class="mxchat-action-loading" style="display: none;">
4650 - <div class="mxchat-action-loading-spinner"></div>
4651 - <div class="mxchat-action-loading-text">
4652 - <?php esc_html_e('Saving action, please wait...', 'mxchat'); ?>
4653 - </div>
4654 -</div>
4655 - </div><!-- .mxchat-wrapper -->
4656 - <?php
4657 -}
4658 -private function get_trimmed_phrases($phrases, $max_length = 100) {
4659 - if (strlen($phrases) <= $max_length) {
4660 - return $phrases;
4661 - }
4662 2130
4663 - $trimmed = substr($phrases, 0, $max_length);
4664 - $last_comma = strrpos($trimmed, ',');
4665 2131
4666 - if ($last_comma !== false) {
4667 - $trimmed = substr($trimmed, 0, $last_comma);
4668 - }
4669 2132
4670 - return $trimmed . '...';
2133 + </div>
2134 + <?php
4671 2135 }
4672 -public function mxchat_add_enabled_column_to_intents() {
4673 - global $wpdb;
4674 - $table_name = $wpdb->prefix . 'mxchat_intents';
4675 2136
4676 - // Check if the column already exists
4677 - $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name LIKE 'enabled'");
4678 2137
4679 - if (empty($columns)) {
4680 - // Add the column with default value of 1 (enabled)
4681 - $wpdb->query("ALTER TABLE $table_name ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
4682 - }
4683 -}
4684 2138
4685 -public function mxchat_handle_delete_intent() {
4686 - if ( ! current_user_can( 'manage_options' ) ) {
4687 - wp_die( esc_html__('Unauthorized user', 'mxchat') );
2139 +/**
2140 + * Handle editing of intent phrases
2141 + *
2142 + * @since 1.0.0
2143 + * @return void
2144 + */
2145 +public function handle_edit_intent() {
2146 + // Verify nonce and user capabilities
2147 + if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'mxchat_edit_intent_nonce')) {
2148 + wp_die(esc_html__('Security check failed.', 'mxchat'));
4688 2149 }
4689 2150
4690 - check_admin_referer('mxchat_delete_intent_nonce');
4691 -
4692 - if (isset($_POST['intent_id'])) {
4693 - global $wpdb;
4694 - $table_name = $wpdb->prefix . 'mxchat_intents';
4695 - $intent_id = intval($_POST['intent_id']);
4696 -
4697 - $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
4698 - }
4699 -
4700 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
4701 - exit;
4702 -}
4703 -public function mxchat_handle_edit_intent() {
4704 - // Security checks (nonce and permissions)
4705 2151 if (!current_user_can('manage_options')) {
4706 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
2152 + wp_die(esc_html__('You do not have permission to perform this action.', 'mxchat'));
4707 2153 }
4708 - check_admin_referer('mxchat_edit_intent');
4709 2154
4710 - // Get POST data
2155 + // Validate and sanitize input
4711 2156 $intent_id = isset($_POST['intent_id']) ? absint($_POST['intent_id']) : 0;
4712 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
4713 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
4714 - $threshold_percentage = isset($_POST['similarity_threshold']) ? intval($_POST['similarity_threshold']) : 85;
4715 - $similarity_threshold = min(95, max(10, $threshold_percentage)) / 100; // Convert to 0.10–0.95
4716 -
4717 - // Handle enabled_bots
4718 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
4719 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
4720 -
4721 - // Ensure default is always included for backward compatibility
4722 - if (!in_array('default', $enabled_bots)) {
4723 - $enabled_bots[] = 'default';
2157 + if (!$intent_id) {
2158 + wp_die(esc_html__('Invalid intent ID.', 'mxchat'));
4724 2159 }
4725 -
4726 - $enabled_bots_json = json_encode($enabled_bots);
4727 2160
4728 - // Validate inputs
4729 - if (!$intent_id || empty($intent_label) || empty($phrases_input)) {
4730 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
4731 - return;
2161 + $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
2162 + if (empty($phrases_input)) {
2163 + wp_die(esc_html__('Phrases cannot be empty.', 'mxchat'));
4732 2164 }
4733 2165
2166 + // Process phrases the same way as in intent creation
4734 2167 $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
2168 +
4735 2169 if (empty($phrases_array)) {
4736 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
4737 - return;
2170 + wp_die(esc_html__('Please enter at least one valid phrase.', 'mxchat'));
4738 2171 }
4739 2172
4740 - // Generate embeddings with improved error handling
2173 + // Generate embeddings and combine them
4741 2174 $vectors = [];
4742 - $failed_phrases = [];
4743 -
4744 2175 foreach ($phrases_array as $phrase) {
4745 2176 $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
4746 2177 if (is_array($embedding_vector)) {
4747 2178 $vectors[] = $embedding_vector;
4748 2179 } else {
4749 - $failed_phrases[] = $phrase;
2180 + wp_die(esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase));
4750 2181 }
4751 2182 }
4752 2183
4753 - if (!empty($failed_phrases)) {
4754 - $this->handle_embedding_error(
4755 - sprintf(
4756 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
4757 - implode(', ', $failed_phrases)
4758 - )
4759 - );
4760 - return;
4761 - }
4762 -
4763 2184 if (empty($vectors)) {
4764 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4765 - return;
2185 + wp_die(esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4766 2186 }
4767 2187
2188 + // Create combined vector just like in intent creation
4768 2189 $combined_vector = $this->mxchat_average_vectors($vectors);
4769 2190 $serialized_vector = maybe_serialize($combined_vector);
4770 2191
4771 - // Update the database
4772 2192 global $wpdb;
4773 2193 $table_name = $wpdb->prefix . 'mxchat_intents';
4774 2194
2195 + // Update the intent with both new phrases and the combined vector
4775 2196 $result = $wpdb->update(
4776 2197 $table_name,
4777 2198 array(
4778 - 'intent_label' => $intent_label,
4779 2199 'phrases' => implode(', ', $phrases_array),
4780 - 'embedding_vector' => $serialized_vector,
4781 - 'similarity_threshold' => $similarity_threshold,
4782 - 'enabled_bots' => $enabled_bots_json, // Include enabled_bots in update
2200 + 'embedding_vector' => $serialized_vector
4783 2201 ),
4784 2202 array('id' => $intent_id),
4785 - array('%s', '%s', '%s', '%f', '%s'), // Format: string, string, string, float, string
4786 - array('%d') // Where format: integer
2203 + array('%s', '%s'),
2204 + array('%d')
4787 2205 );
4788 2206
4789 2207 if (false === $result) {
4790 - $this->handle_embedding_error(__('Failed to update action in database.', 'mxchat'));
4791 - return;
2208 + wp_die(esc_html__('Failed to update intent.', 'mxchat'));
4792 2209 }
4793 2210
4794 - // Set success message and redirect
4795 - set_transient('mxchat_admin_notice_success', __('Intent updated successfully!', 'mxchat'), 60);
4796 -
2211 + // Redirect back to the intents page with a success message
4797 2212 $redirect_url = add_query_arg(
4798 2213 array(
4799 - 'page' => 'mxchat-actions'
2214 + 'page' => 'mxchat-intents',
2215 + 'updated' => 'true'
4800 2216 ),
4801 2217 admin_url('admin.php')
4802 2218 );
2219 +
4803 2220 wp_safe_redirect($redirect_url);
4804 2221 exit;
4805 2222 }
4806 -public function mxchat_handle_add_intent() {
4807 - if (!current_user_can('manage_options')) {
4808 - wp_die(esc_html__('Unauthorized user', 'mxchat'));
2223 +public function mxchat_handle_update_intent_threshold() {
2224 + if ( ! current_user_can( 'manage_options' ) ) {
2225 + wp_die( esc_html__('Unauthorized user', 'mxchat') );
4809 2226 }
4810 - check_admin_referer('mxchat_add_intent_nonce');
4811 - global $wpdb;
4812 - $table_name = $wpdb->prefix . 'mxchat_intents';
4813 -
4814 - // Sanitize and get form data
4815 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
4816 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
4817 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
4818 -
4819 - // Get similarity threshold from form (convert percentage to decimal)
4820 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
4821 -
4822 - // Handle enabled_bots
4823 - $enabled_bots = isset($_POST['enabled_bots']) ? $_POST['enabled_bots'] : array('default');
4824 - $enabled_bots = array_map('sanitize_text_field', $enabled_bots);
4825 -
4826 - // Ensure default is always included for backward compatibility with existing actions
4827 - if (!in_array('default', $enabled_bots)) {
4828 - $enabled_bots[] = 'default';
4829 - }
4830 -
4831 - $enabled_bots_json = json_encode($enabled_bots);
4832 -
4833 - // Validate required fields
4834 - if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
4835 - $this->handle_embedding_error(__('Invalid input. Please ensure all fields are filled out.', 'mxchat'));
4836 - return;
4837 - }
4838 -
4839 - // Validate callback function
4840 - $available_callbacks = $this->mxchat_get_available_callbacks();
4841 - if (!array_key_exists($callback_function, $available_callbacks)) {
4842 - $this->handle_embedding_error(__('Invalid callback function selected.', 'mxchat'));
4843 - return;
4844 - }
4845 -
4846 - // Check if this is an add-on promotional placeholder (not a real action)
4847 - if (!empty($available_callbacks[$callback_function]['addon_promo'])) {
4848 - $addon_name = isset($available_callbacks[$callback_function]['addon_name']) ? $available_callbacks[$callback_function]['addon_name'] : __('an add-on', 'mxchat');
4849 - $this->handle_embedding_error(sprintf(
4850 - __('This action requires the %s to be installed and activated.', 'mxchat'),
4851 - $addon_name
4852 - ));
4853 - return;
4854 - }
4855 -
4856 - // Process phrases
4857 - $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
4858 - if (empty($phrases_array)) {
4859 - $this->handle_embedding_error(__('Please enter at least one valid phrase.', 'mxchat'));
4860 - return;
4861 - }
4862 -
4863 - // Generate embeddings with improved error handling
4864 - $vectors = [];
4865 - $failed_phrases = [];
4866 - foreach ($phrases_array as $phrase) {
4867 - $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
4868 - if (is_array($embedding_vector)) {
4869 - $vectors[] = $embedding_vector;
4870 - } else {
4871 - $failed_phrases[] = $phrase;
4872 - }
4873 - }
4874 -
4875 - // Check for embedding failures
4876 - if (!empty($failed_phrases)) {
4877 - $this->handle_embedding_error(
4878 - sprintf(
4879 - __('Error generating embeddings for phrases: %s. Check your embedding API.', 'mxchat'),
4880 - implode(', ', $failed_phrases)
4881 - )
4882 - );
4883 - return;
4884 - }
4885 -
4886 - if (empty($vectors)) {
4887 - $this->handle_embedding_error(__('No valid embeddings generated. Please check your phrases.', 'mxchat'));
4888 - return;
4889 - }
4890 -
4891 - // Create combined vector and insert into database
4892 - $combined_vector = $this->mxchat_average_vectors($vectors);
4893 - $serialized_vector = maybe_serialize($combined_vector);
4894 -
4895 - $result = $wpdb->insert($table_name, [
4896 - 'intent_label' => $intent_label,
4897 - 'phrases' => implode(', ', $phrases_array),
4898 - 'embedding_vector' => $serialized_vector,
4899 - 'callback_function' => $callback_function,
4900 - 'similarity_threshold' => $similarity_threshold,
4901 - 'enabled_bots' => $enabled_bots_json, // NEW field
4902 - ]);
4903 -
4904 - if ($result === false) {
4905 - $this->handle_embedding_error(__('Database error: ', 'mxchat') . $wpdb->last_error);
4906 - return;
4907 - }
4908 -
4909 - // Set success message and redirect
4910 - set_transient('mxchat_admin_notice_success', __('New intent added successfully!', 'mxchat'), 60);
4911 - wp_safe_redirect(admin_url('admin.php?page=mxchat-actions'));
4912 - exit;
4913 -}
4914 2227
2228 + check_admin_referer('mxchat_update_intent_threshold_nonce');
4915 2229
2230 + if (isset($_POST['intent_id'], $_POST['intent_threshold'])) {
2231 + global $wpdb;
2232 + $table_name = $wpdb->prefix . 'mxchat_intents';
2233 + $intent_id = intval($_POST['intent_id']);
2234 + $threshold_percentage = max(70, min(95, intval($_POST['intent_threshold'])));
2235 + $similarity_threshold = $threshold_percentage / 100;
4916 2236
4917 -
4918 -private function handle_embedding_error($message, $redirect = true) {
4919 - // Store the error message in the existing transient
4920 - set_transient('mxchat_admin_notice_error', $message, 60);
4921 -
4922 - if ($redirect) {
4923 - // Redirect back to the actions page
4924 - $redirect_url = add_query_arg(
4925 - array(
4926 - 'page' => 'mxchat-actions'
4927 - ),
4928 - admin_url('admin.php')
2237 + $wpdb->update(
2238 + $table_name,
2239 + ['similarity_threshold' => $similarity_threshold],
2240 + ['id' => $intent_id],
2241 + ['%f'],
2242 + ['%d']
4929 2243 );
4930 - wp_safe_redirect($redirect_url);
4931 - exit;
4932 2244 }
4933 -}
4934 2245
4935 -/**
4936 - * AJAX handler to fetch actions list for the new split-panel UI
4937 - */
4938 -public function mxchat_fetch_actions_list() {
4939 - check_ajax_referer('mxchat_actions_nonce', 'security');
4940 -
4941 - if (!current_user_can('manage_options')) {
4942 - wp_send_json_error(__('Unauthorized', 'mxchat'));
4943 - }
4944 -
4945 - global $wpdb;
4946 - $table_name = $wpdb->prefix . 'mxchat_intents';
4947 -
4948 - $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
4949 - $per_page = isset($_POST['per_page']) ? min(100, max(1, intval($_POST['per_page']))) : 50;
4950 - $offset = ($page - 1) * $per_page;
4951 - $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
4952 - $callback_filter = isset($_POST['callback_filter']) ? sanitize_text_field($_POST['callback_filter']) : '';
4953 - $sort_order = isset($_POST['sort_order']) && $_POST['sort_order'] === 'asc' ? 'ASC' : 'DESC';
4954 -
4955 - // Build WHERE clause
4956 - $where = '1=1';
4957 - $params = array();
4958 -
4959 - if ($search) {
4960 - $search_like = '%' . $wpdb->esc_like($search) . '%';
4961 - $where .= ' AND (intent_label LIKE %s OR phrases LIKE %s)';
4962 - $params[] = $search_like;
4963 - $params[] = $search_like;
4964 - }
4965 -
4966 - if ($callback_filter) {
4967 - $where .= ' AND callback_function = %s';
4968 - $params[] = $callback_filter;
4969 - }
4970 -
4971 - // Get total count
4972 - $count_query = "SELECT COUNT(*) FROM $table_name WHERE $where";
4973 - if (!empty($params)) {
4974 - $count_query = $wpdb->prepare($count_query, $params);
4975 - }
4976 - $total_actions = $wpdb->get_var($count_query);
4977 -
4978 - // Get actions
4979 - $query = "SELECT * FROM $table_name WHERE $where ORDER BY id $sort_order LIMIT %d OFFSET %d";
4980 - $all_params = array_merge($params, array($per_page, $offset));
4981 - $actions = $wpdb->get_results($wpdb->prepare($query, $all_params));
4982 -
4983 - // Get available callbacks for labels/icons
4984 - $available_callbacks = $this->mxchat_get_available_callbacks();
4985 -
4986 - // Prefetch individual phrase counts for all fetched actions
4987 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
4988 - $phrase_counts = array();
4989 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
4990 - $action_ids = wp_list_pluck($actions, 'id');
4991 - if (!empty($action_ids)) {
4992 - $id_placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
4993 - $count_results = $wpdb->get_results($wpdb->prepare(
4994 - "SELECT intent_id, COUNT(*) as cnt FROM $phrases_table WHERE intent_id IN ($id_placeholders) GROUP BY intent_id",
4995 - $action_ids
4996 - ));
4997 - foreach ($count_results as $row) {
4998 - $phrase_counts[$row->intent_id] = intval($row->cnt);
4999 - }
5000 - }
5001 - }
5002 -
5003 - // Format actions for response
5004 - $formatted_actions = array();
5005 - foreach ($actions as $action) {
5006 - $callback_data = isset($available_callbacks[$action->callback_function])
5007 - ? $available_callbacks[$action->callback_function]
5008 - : array('label' => $action->callback_function, 'icon' => 'admin-generic');
5009 -
5010 - $enabled_bots = json_decode($action->enabled_bots, true);
5011 - if (!is_array($enabled_bots)) {
5012 - $enabled_bots = array('default');
5013 - }
5014 -
5015 - $formatted_actions[] = array(
5016 - 'id' => intval($action->id),
5017 - 'label' => $action->intent_label,
5018 - 'phrases' => $action->phrases,
5019 - 'callback_function' => $action->callback_function,
5020 - 'callback_label' => $callback_data['label'],
5021 - 'icon' => isset($callback_data['icon']) ? $callback_data['icon'] : 'admin-generic',
5022 - 'threshold' => round($action->similarity_threshold * 100),
5023 - 'enabled' => (bool) $action->enabled,
5024 - 'enabled_bots' => $enabled_bots,
5025 - 'has_legacy_vector' => !empty($action->embedding_vector),
5026 - 'individual_phrase_count' => isset($phrase_counts[$action->id]) ? $phrase_counts[$action->id] : 0,
5027 - );
5028 - }
5029 -
5030 - $total_pages = ceil($total_actions / $per_page);
5031 - $showing_start = $total_actions > 0 ? $offset + 1 : 0;
5032 - $showing_end = min($offset + $per_page, $total_actions);
5033 -
5034 - wp_send_json_success(array(
5035 - 'actions' => $formatted_actions,
5036 - 'page' => $page,
5037 - 'per_page' => $per_page,
5038 - 'total_actions' => intval($total_actions),
5039 - 'total_pages' => $total_pages,
5040 - 'showing_start' => $showing_start,
5041 - 'showing_end' => $showing_end,
5042 - ));
2246 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
2247 + exit;
5043 2248 }
5044 2249
5045 -/**
5046 - * AJAX handler to toggle action enabled status
5047 - */
5048 -public function mxchat_toggle_action_status() {
5049 - check_ajax_referer('mxchat_actions_nonce', 'security');
5050 -
5051 - if (!current_user_can('manage_options')) {
5052 - wp_send_json_error(__('Unauthorized', 'mxchat'));
2250 +public function mxchat_handle_add_intent() {
2251 + if ( ! current_user_can( 'manage_options' ) ) {
2252 + wp_die( esc_html__('Unauthorized user', 'mxchat') );
5053 2253 }
5054 2254
5055 - $action_id = isset($_POST['action_id']) ? intval($_POST['action_id']) : 0;
5056 - $enabled = isset($_POST['enabled']) ? intval($_POST['enabled']) : 0;
2255 + check_admin_referer('mxchat_add_intent_nonce');
5057 2256
5058 - if (!$action_id) {
5059 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5060 - }
5061 -
5062 2257 global $wpdb;
5063 2258 $table_name = $wpdb->prefix . 'mxchat_intents';
5064 2259
5065 - $result = $wpdb->update(
5066 - $table_name,
5067 - array('enabled' => $enabled ? 1 : 0),
5068 - array('id' => $action_id),
5069 - array('%d'),
5070 - array('%d')
5071 - );
5072 -
5073 - if ($result === false) {
5074 - wp_send_json_error(__('Failed to update action status', 'mxchat'));
5075 - }
5076 -
5077 - wp_send_json_success(array('enabled' => (bool) $enabled));
5078 -}
5079 -
5080 -/**
5081 - * AJAX handler to bulk delete actions
5082 - */
5083 -public function mxchat_bulk_delete_actions() {
5084 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5085 -
5086 - if (!current_user_can('manage_options')) {
5087 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5088 - }
5089 -
5090 - $action_ids = isset($_POST['action_ids']) ? array_map('intval', (array) $_POST['action_ids']) : array();
5091 -
5092 - if (empty($action_ids)) {
5093 - wp_send_json_error(__('No actions selected', 'mxchat'));
5094 - }
5095 -
5096 - global $wpdb;
5097 - $table_name = $wpdb->prefix . 'mxchat_intents';
5098 -
5099 - $placeholders = implode(',', array_fill(0, count($action_ids), '%d'));
5100 - $query = $wpdb->prepare("DELETE FROM $table_name WHERE id IN ($placeholders)", $action_ids);
5101 - $result = $wpdb->query($query);
5102 -
5103 - if ($result === false) {
5104 - wp_send_json_error(__('Failed to delete actions', 'mxchat'));
5105 - }
5106 -
5107 - // Also delete individual phrases for these intents
5108 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5109 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5110 - $wpdb->query($wpdb->prepare("DELETE FROM $phrases_table WHERE intent_id IN ($placeholders)", $action_ids));
5111 - }
5112 -
5113 - wp_send_json_success(array('deleted' => $result));
5114 -}
5115 -
5116 -/**
5117 - * AJAX handler to add a new intent/action
5118 - */
5119 -public function mxchat_add_intent_ajax() {
5120 - check_ajax_referer('mxchat_add_intent_nonce', 'security');
5121 -
5122 - if (!current_user_can('manage_options')) {
5123 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5124 - }
5125 -
5126 - global $wpdb;
5127 - $table_name = $wpdb->prefix . 'mxchat_intents';
5128 -
5129 - // Sanitize input
5130 2260 $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5131 2261 $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5132 2262 $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5133 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5134 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
2263 + $default_threshold = 0.85;
5135 2264
5136 - // Validate
5137 - // Check if using new individual phrases mode or legacy mode
5138 - $individual_phrases = isset($_POST['individual_phrases']) ? array_filter(array_map('sanitize_text_field', (array) $_POST['individual_phrases'])) : array();
5139 - $use_individual = !empty($individual_phrases);
5140 -
5141 - // Validate required fields (phrases not required when using individual mode)
5142 - if (empty($intent_label) || empty($callback_function)) {
5143 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
2265 + if (empty($intent_label) || empty($callback_function) || empty($phrases_input)) {
2266 + wp_die( esc_html__('Invalid input. Please ensure all fields are filled out.', 'mxchat') );
5144 2267 }
5145 - if (!$use_individual && empty($phrases_input)) {
5146 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
5147 - }
5148 2268
5149 - // Ensure default bot is included
5150 - if (!in_array('default', $enabled_bots)) {
5151 - $enabled_bots[] = 'default';
5152 - }
5153 - $enabled_bots_json = json_encode($enabled_bots);
2269 + $available_callbacks = $this->mxchat_get_available_callbacks();
5154 2270
5155 - if ($use_individual) {
5156 - // New mode: individual phrases each get their own vector
5157 - // Insert the intent row with empty legacy fields
5158 - $result = $wpdb->insert(
5159 - $table_name,
5160 - array(
5161 - 'intent_label' => $intent_label,
5162 - 'phrases' => '',
5163 - 'embedding_vector' => '',
5164 - 'similarity_threshold' => $similarity_threshold,
5165 - 'callback_function' => $callback_function,
5166 - 'enabled' => 1,
5167 - 'enabled_bots' => $enabled_bots_json,
5168 - )
5169 - );
5170 -
5171 - if ($result === false) {
5172 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5173 - }
5174 -
5175 - $intent_id = $wpdb->insert_id;
5176 -
5177 - // Insert each phrase individually with its own embedding
5178 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5179 - $failed_phrases = array();
5180 - foreach ($individual_phrases as $phrase) {
5181 - $phrase = trim($phrase);
5182 - if (empty($phrase)) continue;
5183 -
5184 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5185 - if (is_wp_error($embedding_vector)) {
5186 - $failed_phrases[] = $phrase;
5187 - continue;
5188 - }
5189 -
5190 - $wpdb->insert(
5191 - $phrases_table,
5192 - array(
5193 - 'intent_id' => $intent_id,
5194 - 'phrase' => $phrase,
5195 - 'embedding_vector' => maybe_serialize($embedding_vector),
5196 - )
5197 - );
5198 - }
5199 -
5200 - $response = array('id' => $intent_id);
5201 - if (!empty($failed_phrases)) {
5202 - $response['failed_phrases'] = $failed_phrases;
5203 - }
5204 - wp_send_json_success($response);
5205 -
5206 - } else {
5207 - // Legacy mode: combine all phrases into one embedding (backwards compatible)
5208 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5209 - if (empty($phrases_array)) {
5210 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5211 - }
5212 -
5213 - // Generate embedding (combine phrases into single string for embedding)
5214 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5215 - if (is_wp_error($embedding_vector)) {
5216 - // Fallback: store without embedding
5217 - $serialized_vector = null;
5218 - } else {
5219 - $serialized_vector = maybe_serialize($embedding_vector);
5220 - }
5221 -
5222 - // Insert
5223 - $result = $wpdb->insert(
5224 - $table_name,
5225 - array(
5226 - 'intent_label' => $intent_label,
5227 - 'phrases' => implode(', ', $phrases_array),
5228 - 'embedding_vector' => $serialized_vector,
5229 - 'similarity_threshold' => $similarity_threshold,
5230 - 'callback_function' => $callback_function,
5231 - 'enabled' => 1,
5232 - 'enabled_bots' => $enabled_bots_json,
5233 - )
5234 - );
5235 -
5236 - if ($result === false) {
5237 - wp_send_json_error(__('Failed to add action to database.', 'mxchat'));
5238 - }
5239 -
5240 - wp_send_json_success(array('id' => $wpdb->insert_id));
2271 + if (!array_key_exists($callback_function, $available_callbacks)) {
2272 + wp_die( esc_html__('Invalid callback function selected.', 'mxchat') );
5241 2273 }
5242 -}
5243 2274
5244 -/**
5245 - * AJAX handler to edit an existing intent/action
5246 - */
5247 -public function mxchat_edit_intent_ajax() {
5248 - check_ajax_referer('mxchat_edit_intent', 'security');
5249 -
5250 - if (!current_user_can('manage_options')) {
5251 - wp_send_json_error(__('Unauthorized', 'mxchat'));
2275 + $is_pro_only = $available_callbacks[$callback_function]['pro_only'];
2276 + if ($is_pro_only && !$this->is_activated) {
2277 + wp_die( esc_html__('This callback function is available in the Pro version only.', 'mxchat') );
5252 2278 }
5253 2279
5254 - global $wpdb;
5255 - $table_name = $wpdb->prefix . 'mxchat_intents';
2280 + $phrases_array = array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', $phrases_input))));
5256 2281
5257 - // Sanitize input
5258 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5259 - $intent_label = isset($_POST['intent_label']) ? sanitize_text_field($_POST['intent_label']) : '';
5260 - $phrases_input = isset($_POST['phrases']) ? sanitize_textarea_field($_POST['phrases']) : '';
5261 - $callback_function = isset($_POST['callback_function']) ? sanitize_text_field($_POST['callback_function']) : '';
5262 - $similarity_threshold = isset($_POST['similarity_threshold']) ? floatval($_POST['similarity_threshold']) / 100 : 0.85;
5263 - $enabled_bots = isset($_POST['enabled_bots']) ? array_map('sanitize_text_field', (array) $_POST['enabled_bots']) : array('default');
5264 -
5265 - // Validate
5266 - if (!$intent_id || empty($intent_label)) {
5267 - wp_send_json_error(__('Please fill in all required fields.', 'mxchat'));
2282 + if (empty($phrases_array)) {
2283 + wp_die( esc_html__('Please enter at least one valid phrase.', 'mxchat') );
5268 2284 }
5269 2285
5270 - // Check if phrases are managed individually (empty phrases_input means individual mode)
5271 - $uses_individual_phrases = empty($phrases_input);
5272 -
5273 - if ($uses_individual_phrases) {
5274 - // Individual phrase mode: only update non-phrase fields, skip embedding regeneration
5275 - $update_data = array(
5276 - 'intent_label' => $intent_label,
5277 - 'similarity_threshold' => $similarity_threshold,
5278 - 'callback_function' => $callback_function,
5279 - 'enabled_bots' => json_encode($enabled_bots),
5280 - );
5281 - } else {
5282 - // Legacy mode: process phrases and regenerate embedding (backwards compatible for add-ons)
5283 - $phrases_array = array_filter(array_map('trim', preg_split('/[\n,]+/', $phrases_input)));
5284 - if (empty($phrases_array)) {
5285 - wp_send_json_error(__('Please provide at least one trigger phrase.', 'mxchat'));
5286 - }
5287 -
5288 - // Generate new embedding (combine phrases into single string for embedding)
5289 - $embedding_vector = $this->mxchat_generate_embedding(implode(' ', $phrases_array));
5290 - if (is_wp_error($embedding_vector)) {
5291 - // Keep existing embedding
5292 - $update_data = array(
5293 - 'intent_label' => $intent_label,
5294 - 'phrases' => implode(', ', $phrases_array),
5295 - 'similarity_threshold' => $similarity_threshold,
5296 - 'callback_function' => $callback_function,
5297 - 'enabled_bots' => json_encode($enabled_bots),
5298 - );
2286 + $vectors = [];
2287 + foreach ($phrases_array as $phrase) {
2288 + $embedding_vector = $this->mxchat_generate_embedding($phrase, $this->options['api_key']);
2289 + if (is_array($embedding_vector)) {
2290 + $vectors[] = $embedding_vector;
5299 2291 } else {
5300 - $serialized_vector = maybe_serialize($embedding_vector);
5301 - $update_data = array(
5302 - 'intent_label' => $intent_label,
5303 - 'phrases' => implode(', ', $phrases_array),
5304 - 'embedding_vector' => $serialized_vector,
5305 - 'similarity_threshold' => $similarity_threshold,
5306 - 'callback_function' => $callback_function,
5307 - 'enabled_bots' => json_encode($enabled_bots),
5308 - );
2292 + wp_die( esc_html__('Error generating embedding for phrase: ', 'mxchat') . esc_html($phrase) );
5309 2293 }
5310 2294 }
5311 2295
5312 - // Ensure default bot is included
5313 - if (!in_array('default', $enabled_bots)) {
5314 - $enabled_bots[] = 'default';
5315 - }
5316 - $update_data['enabled_bots'] = json_encode($enabled_bots);
2296 + if (!empty($vectors)) {
2297 + $combined_vector = $this->mxchat_average_vectors($vectors);
2298 + $serialized_vector = maybe_serialize($combined_vector);
5317 2299
5318 - $result = $wpdb->update(
5319 - $table_name,
5320 - $update_data,
5321 - array('id' => $intent_id),
5322 - null,
5323 - array('%d')
5324 - );
2300 + $result = $wpdb->insert($table_name, [
2301 + 'intent_label' => $intent_label,
2302 + 'phrases' => implode(', ', $phrases_array),
2303 + 'embedding_vector' => $serialized_vector,
2304 + 'callback_function' => $callback_function,
2305 + 'similarity_threshold' => $default_threshold,
2306 + ]);
5325 2307
5326 - if ($result === false) {
5327 - wp_send_json_error(__('Failed to update action.', 'mxchat'));
2308 + if ($result === false) {
2309 + wp_die( esc_html__('Database error: ', 'mxchat') . esc_html($wpdb->last_error) );
2310 + }
2311 + } else {
2312 + wp_die( esc_html__('No valid embeddings generated. Please check your phrases.', 'mxchat') );
5328 2313 }
5329 2314
5330 - wp_send_json_success(array('updated' => true));
2315 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
2316 + exit;
5331 2317 }
5332 2318
5333 -/**
5334 - * AJAX handler to delete a single intent/action
5335 - */
5336 -public function mxchat_delete_intent_ajax() {
5337 - check_ajax_referer('mxchat_delete_intent_nonce', 'security');
5338 2319
5339 - if (!current_user_can('manage_options')) {
5340 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5341 - }
5342 2320
5343 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5344 2321
5345 - if (!$intent_id) {
5346 - wp_send_json_error(__('Invalid action ID', 'mxchat'));
5347 - }
5348 2322
5349 - global $wpdb;
5350 - $table_name = $wpdb->prefix . 'mxchat_intents';
5351 2323
5352 - $result = $wpdb->delete($table_name, array('id' => $intent_id), array('%d'));
2324 +private function mxchat_get_available_callbacks($grouped = false) {
2325 + $callbacks = [
2326 + 'mxchat_handle_email_capture' => [
2327 + 'label' => 'Email Capture',
2328 + 'pro_only' => false,
2329 + 'group' => 'Customer Engagement',
2330 + ],
2331 + 'mxchat_handle_product_inquiry' => [
2332 + 'label' => 'Show Product Card',
2333 + 'pro_only' => true,
2334 + 'group' => 'WooCommerce Features',
2335 + ],
2336 + 'mxchat_handle_order_history' => [
2337 + 'label' => 'Order History',
2338 + 'pro_only' => true,
2339 + 'group' => 'WooCommerce Features',
2340 + ],
2341 + 'mxchat_generate_image' => [
2342 + 'label' => 'Generate Image',
2343 + 'pro_only' => true,
2344 + 'group' => 'Other Features',
2345 + ],
2346 + 'mxchat_handle_search_request' => [
2347 + 'label' => 'Brave Web Search',
2348 + 'pro_only' => false,
2349 + 'group' => 'Search Features',
2350 + ],
2351 + 'mxchat_handle_image_search_request' => [
2352 + 'label' => 'Brave Image Search',
2353 + 'pro_only' => false,
2354 + 'group' => 'Search Features',
2355 + ],
2356 + 'mxchat_handle_add_to_cart_intent' => [
2357 + 'label' => 'Add to Cart',
2358 + 'pro_only' => true,
2359 + 'group' => 'WooCommerce Features',
2360 + ],
2361 + 'mxchat_handle_checkout_intent' => [
2362 + 'label' => 'Proceed to Checkout',
2363 + 'pro_only' => true,
2364 + 'group' => 'WooCommerce Features',
2365 + ],
2366 + 'mxchat_handle_pdf_discussion' => [
2367 + 'label' => 'Chat with PDF',
2368 + 'pro_only' => true,
2369 + 'group' => 'Other Features',
2370 + ],
2371 + 'mxchat_handle_product_recommendations' => [
2372 + 'label' => 'Product Recommendations',
2373 + 'pro_only' => true,
2374 + 'group' => 'WooCommerce Features',
2375 + ],
2376 + 'mxchat_live_agent_handover' => [
2377 + 'label' => 'Live Agent',
2378 + 'pro_only' => true,
2379 + 'group' => 'Customer Engagement',
2380 + ],
2381 + 'mxchat_handle_switch_to_chatbot_intent' => [
2382 + 'label' => 'Back to Chatbot',
2383 + 'pro_only' => true,
2384 + 'group' => 'Customer Engagement',
2385 + ],
2386 + ];
5353 2387
5354 - if ($result === false) {
5355 - wp_send_json_error(__('Failed to delete action', 'mxchat'));
2388 + // Return grouped structure if requested
2389 + if ($grouped) {
2390 + $grouped_callbacks = [];
2391 + foreach ($callbacks as $key => $data) {
2392 + $group_label = $data['group'] ?? 'Other Features';
2393 + $grouped_callbacks[$group_label][$key] = [
2394 + 'label' => $data['label'],
2395 + 'pro_only' => $data['pro_only'],
2396 + ];
2397 + }
2398 + return $grouped_callbacks;
5356 2399 }
5357 2400
5358 - // Also delete individual phrases for this intent
5359 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5360 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5361 - $wpdb->delete($phrases_table, array('intent_id' => $intent_id), array('%d'));
5362 - }
5363 -
5364 - wp_send_json_success(array('deleted' => true));
2401 + return $callbacks;
5365 2402 }
5366 2403
5367 -/**
5368 - * AJAX handler to add a single phrase with its own embedding to an intent
5369 - */
5370 -public function mxchat_add_phrase_ajax() {
5371 - check_ajax_referer('mxchat_add_phrase_nonce', 'security');
5372 2404
5373 - if (!current_user_can('manage_options')) {
5374 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5375 - }
5376 2405
5377 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5378 - $phrase = isset($_POST['phrase']) ? sanitize_text_field($_POST['phrase']) : '';
2406 +private function mxchat_average_vectors($vectors) {
2407 + $vector_length = count($vectors[0]);
2408 + $sum_vector = array_fill(0, $vector_length, 0);
5379 2409
5380 - if (!$intent_id || empty($phrase)) {
5381 - wp_send_json_error(__('Please provide an intent ID and phrase.', 'mxchat'));
2410 + foreach ($vectors as $vector) {
2411 + for ($i = 0; $i < $vector_length; $i++) {
2412 + $sum_vector[$i] += $vector[$i];
2413 + }
5382 2414 }
5383 2415
5384 - // Verify the intent exists
5385 - global $wpdb;
5386 - $intents_table = $wpdb->prefix . 'mxchat_intents';
5387 - $intent = $wpdb->get_row($wpdb->prepare("SELECT id FROM $intents_table WHERE id = %d", $intent_id));
5388 - if (!$intent) {
5389 - wp_send_json_error(__('Action not found.', 'mxchat'));
2416 + // Divide each component by the number of vectors to get the average
2417 + $num_vectors = count($vectors);
2418 + for ($i = 0; $i < $vector_length; $i++) {
2419 + $sum_vector[$i] /= $num_vectors;
5390 2420 }
5391 2421
5392 - // Generate embedding for this single phrase
5393 - $embedding_vector = $this->mxchat_generate_embedding($phrase);
5394 - if (is_wp_error($embedding_vector)) {
5395 - wp_send_json_error(__('Failed to generate embedding: ', 'mxchat') . $embedding_vector->get_error_message());
5396 - }
5397 -
5398 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5399 - $result = $wpdb->insert(
5400 - $phrases_table,
5401 - array(
5402 - 'intent_id' => $intent_id,
5403 - 'phrase' => $phrase,
5404 - 'embedding_vector' => maybe_serialize($embedding_vector),
5405 - )
5406 - );
5407 -
5408 - if ($result === false) {
5409 - wp_send_json_error(__('Failed to add phrase.', 'mxchat'));
5410 - }
5411 -
5412 - wp_send_json_success(array('id' => $wpdb->insert_id, 'phrase' => $phrase));
2422 + return $sum_vector;
5413 2423 }
5414 2424
5415 -/**
5416 - * AJAX handler to delete a single phrase from wp_mxchat_intent_phrases
5417 - */
5418 -public function mxchat_delete_phrase_ajax() {
5419 - check_ajax_referer('mxchat_delete_phrase_nonce', 'security');
5420 -
5421 - if (!current_user_can('manage_options')) {
5422 - wp_send_json_error(__('Unauthorized', 'mxchat'));
2425 +public function mxchat_handle_delete_intent() {
2426 + if ( ! current_user_can( 'manage_options' ) ) {
2427 + wp_die( esc_html__('Unauthorized user', 'mxchat') );
5423 2428 }
5424 2429
5425 - $phrase_id = isset($_POST['phrase_id']) ? intval($_POST['phrase_id']) : 0;
5426 - if (!$phrase_id) {
5427 - wp_send_json_error(__('Invalid phrase ID.', 'mxchat'));
5428 - }
2430 + check_admin_referer('mxchat_delete_intent_nonce');
5429 2431
5430 - global $wpdb;
5431 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5432 - $result = $wpdb->delete($phrases_table, array('id' => $phrase_id), array('%d'));
2432 + if (isset($_POST['intent_id'])) {
2433 + global $wpdb;
2434 + $table_name = $wpdb->prefix . 'mxchat_intents';
2435 + $intent_id = intval($_POST['intent_id']);
5433 2436
5434 - if ($result === false) {
5435 - wp_send_json_error(__('Failed to delete phrase.', 'mxchat'));
2437 + $wpdb->delete($table_name, ['id' => $intent_id], ['%d']);
5436 2438 }
5437 2439
5438 - wp_send_json_success(array('deleted' => true));
2440 + wp_safe_redirect(admin_url('admin.php?page=mxchat-intents'));
2441 + exit;
5439 2442 }
5440 2443
5441 -/**
5442 - * AJAX handler to fetch individual phrases for an intent
5443 - */
5444 -public function mxchat_get_phrases_ajax() {
5445 - check_ajax_referer('mxchat_get_phrases_nonce', 'security');
5446 2444
5447 - if (!current_user_can('manage_options')) {
5448 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5449 - }
5450 -
5451 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5452 - if (!$intent_id) {
5453 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5454 - }
5455 -
5456 - global $wpdb;
5457 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
5458 -
5459 - $phrases = array();
5460 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
5461 - $phrases = $wpdb->get_results($wpdb->prepare(
5462 - "SELECT id, phrase, created_at FROM $phrases_table WHERE intent_id = %d ORDER BY created_at ASC",
5463 - $intent_id
5464 - ));
5465 - }
5466 -
5467 - wp_send_json_success(array('phrases' => $phrases));
5468 -}
5469 -
5470 -/**
5471 - * AJAX handler to clear legacy phrases and embedding from the main intents table
5472 - */
5473 -public function mxchat_delete_legacy_phrases_ajax() {
5474 - check_ajax_referer('mxchat_delete_legacy_nonce', 'security');
5475 -
5476 - if (!current_user_can('manage_options')) {
5477 - wp_send_json_error(__('Unauthorized', 'mxchat'));
5478 - }
5479 -
5480 - $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
5481 - if (!$intent_id) {
5482 - wp_send_json_error(__('Invalid intent ID.', 'mxchat'));
5483 - }
5484 -
5485 - global $wpdb;
5486 - $table_name = $wpdb->prefix . 'mxchat_intents';
5487 -
5488 - $result = $wpdb->update(
5489 - $table_name,
5490 - array('phrases' => '', 'embedding_vector' => ''),
5491 - array('id' => $intent_id),
5492 - array('%s', '%s'),
5493 - array('%d')
5494 - );
5495 -
5496 - if ($result === false) {
5497 - wp_send_json_error(__('Failed to clear legacy phrases.', 'mxchat'));
5498 - }
5499 -
5500 - wp_send_json_success(array('cleared' => true));
5501 -}
5502 -
5503 -/**
5504 - * Enhanced get_available_callbacks function with form action exclusion
5505 - *
5506 - * @param bool $grouped Whether to return callbacks grouped by category
5507 - * @param bool $include_all Whether to include all potential actions (even if add-on not installed)
5508 - * @return array Callbacks data with icons, descriptions and availability status
5509 - */
5510 -private function mxchat_get_available_callbacks($grouped = false, $include_all = true) {
5511 - // Load WordPress plugin functions if needed
5512 - if (!function_exists('get_plugins')) {
5513 - require_once ABSPATH . 'wp-admin/includes/plugin.php';
5514 - }
5515 -
5516 - // Get active plugins
5517 - $active_plugins = get_option('active_plugins', array());
5518 -
5519 - // Functions to exclude from the action selector only if Pro is activated
5520 - // If user doesn't have Pro, show these so they can see what they're missing
5521 - $excluded_when_pro_active_functions = array(
5522 - 'mxchat_handle_form_collection' // Forms add-on action
5523 - );
5524 -
5525 - // Always excluded functions (regardless of Pro status)
5526 - $always_excluded_functions = array();
5527 -
5528 - // Combine exclusion lists based on Pro activation status
5529 - $excluded_functions = $always_excluded_functions;
5530 - if ($this->is_activated) {
5531 - // Only exclude add-on managed functions if Pro is active
5532 - $excluded_functions = array_merge($excluded_functions, $excluded_when_pro_active_functions);
5533 - }
5534 -
5535 - // Define add-on plugin files and their corresponding action functions
5536 - $addon_plugins = array(
5537 - 'mxchat-woo/mxchat-woo.php' => array(
5538 - 'functions' => array(
5539 - 'mxchat_handle_product_recommendations',
5540 - 'mxchat_handle_order_history',
5541 - 'mxchat_show_product_card',
5542 - 'mxchat_add_to_cart',
5543 - 'mxchat_checkout_redirect',
5544 - 'mxchat_handle_featured_products'
5545 - ),
5546 - 'name' => __('WooCommerce Add-on', 'mxchat'),
5547 - 'pro_required' => true
5548 - ),
5549 - 'mxchat-perplexity/mxchat-perplexity.php' => array(
5550 - 'functions' => array('mxchat_perplexity_research'),
5551 - 'name' => __('Perplexity Add-on', 'mxchat'),
5552 - 'pro_required' => true
5553 - ),
5554 - 'mxchat-forms/mxchat-forms.php' => array(
5555 - 'functions' => array('mxchat_handle_form_collection'),
5556 - 'name' => __('Forms Add-on', 'mxchat'),
5557 - 'pro_required' => true
5558 - ),
5559 - // Add other add-ons and their functions here
5560 - );
5561 -
5562 - // Get the functions that are provided by active add-ons
5563 - $addon_provided_functions = array();
5564 - $addon_function_mapping = array(); // Maps functions to their add-on info
5565 -
5566 - // Check which add-ons are active
5567 - foreach ($addon_plugins as $plugin_file => $addon_info) {
5568 - $is_active = in_array($plugin_file, $active_plugins);
5569 -
5570 - // For each function in this addon
5571 - foreach ($addon_info['functions'] as $function) {
5572 - // Consider a function installed only if:
5573 - // 1. The add-on is active AND
5574 - // 2. Either it doesn't require Pro OR Pro is activated
5575 - $is_installed = $is_active && (!$addon_info['pro_required'] || $this->is_activated);
5576 -
5577 - // If the add-on is installed, mark this function as provided by an add-on
5578 - if ($is_installed) {
5579 - $addon_provided_functions[] = $function;
5580 - }
5581 -
5582 - // Store addon info for this function regardless of installation status
5583 - $addon_function_mapping[$function] = array(
5584 - 'addon' => basename(dirname($plugin_file)),
5585 - 'addon_name' => $addon_info['name'],
5586 - 'pro_required' => $addon_info['pro_required'],
5587 - 'is_active' => $is_active,
5588 - 'is_installed' => $is_installed
5589 - );
5590 - }
5591 - }
5592 -
5593 - // Core callbacks - always available in the base plugin
5594 - $core_callbacks = array(
5595 - 'mxchat_handle_email_capture' => array(
5596 - 'label' => __('Loops Email Capture', 'mxchat'),
5597 - 'pro_only' => false,
5598 - 'group' => __('Customer Engagement', 'mxchat'),
5599 - 'icon' => 'email-alt',
5600 - 'description' => __('Collect visitor emails for your mailing list in Loops', 'mxchat'),
5601 - 'addon' => false, // Not from an add-on
5602 - 'installed' => true // Always installed with base plugin
5603 - ),
5604 - 'mxchat_handle_search_request' => array(
5605 - 'label' => __('Brave Web Search', 'mxchat'),
5606 - 'pro_only' => false,
5607 - 'group' => __('Search Features', 'mxchat'),
5608 - 'icon' => 'search',
5609 - 'description' => __('Let users search the web directly from the chat', 'mxchat'),
5610 - 'addon' => false,
5611 - 'installed' => true
5612 - ),
5613 - 'mxchat_handle_image_search_request' => array(
5614 - 'label' => __('Brave Image Search', 'mxchat'),
5615 - 'pro_only' => false,
5616 - 'group' => __('Search Features', 'mxchat'),
5617 - 'icon' => 'format-image',
5618 - 'description' => __('Search and display images in the chat conversation', 'mxchat'),
5619 - 'addon' => false,
5620 - 'installed' => true
5621 - ),
5622 - // Pro core features - check is_activated property
5623 - 'mxchat_generate_image' => array(
5624 - 'label' => __('Generate Image (OpenAI)', 'mxchat'),
5625 - 'pro_only' => false,
5626 - 'group' => __('Other Features', 'mxchat'),
5627 - 'icon' => 'art',
5628 - 'description' => __('Create images with GPT Image from OpenAI (requires OpenAI API key)', 'mxchat'),
5629 - 'addon' => false,
5630 - 'installed' => true
5631 - ),
5632 - 'mxchat_generate_gemini_image' => array(
5633 - 'label' => __('Generate Image (Gemini)', 'mxchat'),
5634 - 'pro_only' => false,
5635 - 'group' => __('Other Features', 'mxchat'),
5636 - 'icon' => 'art',
5637 - 'description' => __('Create images with Imagen from Google (requires Gemini API key)', 'mxchat'),
5638 - 'addon' => false,
5639 - 'installed' => true
5640 - ),
5641 - 'mxchat_handle_pdf_discussion' => array(
5642 - 'label' => __('Chat with PDF', 'mxchat'),
5643 - 'pro_only' => false,
5644 - 'group' => __('Other Features', 'mxchat'),
5645 - 'icon' => 'media-document',
5646 - 'description' => __('Answer questions about uploaded PDF documents', 'mxchat'),
5647 - 'addon' => false,
5648 - 'installed' => true
5649 - ),
5650 - 'mxchat_live_agent_handover' => array(
5651 - 'label' => __('Slack Live Agent', 'mxchat'),
5652 - 'pro_only' => false,
5653 - 'group' => __('Customer Engagement', 'mxchat'),
5654 - 'icon' => 'admin-users',
5655 - 'description' => __('Transfer conversation to a human support agent on Slack', 'mxchat'),
5656 - 'addon' => false,
5657 - 'installed' => true
5658 - ),
5659 - 'mxchat_telegram_live_agent_handover' => array(
5660 - 'label' => __('Telegram Live Agent', 'mxchat'),
5661 - 'pro_only' => false,
5662 - 'group' => __('Customer Engagement', 'mxchat'),
5663 - 'icon' => 'format-chat',
5664 - 'description' => __('Transfer conversation to a human support agent on Telegram', 'mxchat'),
5665 - 'addon' => false,
5666 - 'installed' => true
5667 - ),
5668 - 'mxchat_handle_switch_to_chatbot_intent' => array(
5669 - 'label' => __('Back to Chatbot', 'mxchat'),
5670 - 'pro_only' => false,
5671 - 'group' => __('Customer Engagement', 'mxchat'),
5672 - 'icon' => 'backup',
5673 - 'description' => __('Return from live agent mode to AI chatbot', 'mxchat'),
5674 - 'addon' => false,
5675 - 'installed' => true
5676 - ),
5677 - );
5678 -
5679 - // Add-on callbacks with placeholders - only include if the add-on is NOT active
5680 - // These are promotional/informational only — not selectable as real actions
5681 - $addon_callbacks = array(
5682 - // WooCommerce Add-on
5683 - 'mxchat_handle_product_recommendations' => array(
5684 - 'label' => __('Product Recommendations', 'mxchat'),
5685 - 'pro_only' => false,
5686 - 'addon_promo' => true,
5687 - 'group' => __('WooCommerce Features', 'mxchat'),
5688 - 'icon' => 'cart',
5689 - 'description' => __('Suggest products based on customer preferences', 'mxchat'),
5690 - ),
5691 - 'mxchat_handle_order_history' => array(
5692 - 'label' => __('Order History', 'mxchat'),
5693 - 'pro_only' => false,
5694 - 'addon_promo' => true,
5695 - 'group' => __('WooCommerce Features', 'mxchat'),
5696 - 'icon' => 'clipboard',
5697 - 'description' => __('Allow customers to check their order status', 'mxchat'),
5698 - ),
5699 - 'mxchat_show_product_card' => array(
5700 - 'label' => __('Show Product Card', 'mxchat'),
5701 - 'pro_only' => false,
5702 - 'addon_promo' => true,
5703 - 'group' => __('WooCommerce Features', 'mxchat'),
5704 - 'icon' => 'products',
5705 - 'description' => __('Display product information in the chat', 'mxchat'),
5706 - ),
5707 - 'mxchat_add_to_cart' => array(
5708 - 'label' => __('Add to Cart', 'mxchat'),
5709 - 'pro_only' => false,
5710 - 'addon_promo' => true,
5711 - 'group' => __('WooCommerce Features', 'mxchat'),
5712 - 'icon' => 'plus-alt',
5713 - 'description' => __('Add products to cart directly from chat', 'mxchat'),
5714 - ),
5715 - 'mxchat_checkout_redirect' => array(
5716 - 'label' => __('Proceed to Checkout', 'mxchat'),
5717 - 'pro_only' => false,
5718 - 'addon_promo' => true,
5719 - 'group' => __('WooCommerce Features', 'mxchat'),
5720 - 'icon' => 'arrow-right-alt',
5721 - 'description' => __('Redirect customer to checkout page', 'mxchat'),
5722 - ),
5723 - 'mxchat_handle_featured_products' => array(
5724 - 'label' => __('Featured Products Showcase', 'mxchat'),
5725 - 'pro_only' => false,
5726 - 'addon_promo' => true,
5727 - 'group' => __('WooCommerce Features', 'mxchat'),
5728 - 'icon' => 'star-filled',
5729 - 'description' => __('Display a curated selection of products with an AI-generated message', 'mxchat'),
5730 - ),
5731 -
5732 - // Perplexity Add-on
5733 - 'mxchat_perplexity_research' => array(
5734 - 'label' => __('Perplexity Research', 'mxchat'),
5735 - 'pro_only' => false,
5736 - 'addon_promo' => true,
5737 - 'group' => __('Search Features', 'mxchat'),
5738 - 'icon' => 'book-alt',
5739 - 'description' => __('Allows the chatbot to search the web for accurate, up-to-date answers', 'mxchat'),
5740 - ),
5741 -
5742 - // Forms Add-on
5743 - 'mxchat_handle_form_collection' => array(
5744 - 'label' => __('Form Collection', 'mxchat'),
5745 - 'pro_only' => false,
5746 - 'addon_promo' => true,
5747 - 'group' => __('Form Features', 'mxchat'),
5748 - 'icon' => 'feedback',
5749 - 'description' => __('Collect user information through custom forms in chat', 'mxchat'),
5750 - ),
5751 - );
5752 -
5753 - // Enhance add-on callbacks with installation status and addon info
5754 - foreach ($addon_callbacks as $function => $data) {
5755 - if (isset($addon_function_mapping[$function])) {
5756 - $addon_info = $addon_function_mapping[$function];
5757 -
5758 - $addon_callbacks[$function]['addon'] = $addon_info['addon'];
5759 - $addon_callbacks[$function]['addon_name'] = $addon_info['addon_name'];
5760 - $addon_callbacks[$function]['installed'] = $addon_info['is_installed'];
5761 -
5762 - // Set pro_only based on add-on configuration
5763 - $addon_callbacks[$function]['pro_only'] = $addon_info['pro_required'];
5764 - } else {
5765 - $addon_callbacks[$function]['addon'] = 'unknown';
5766 - $addon_callbacks[$function]['addon_name'] = __('Unknown Add-on', 'mxchat');
5767 - $addon_callbacks[$function]['installed'] = false;
5768 - }
5769 - }
5770 -
5771 - // Initialize callbacks with core features
5772 - $callbacks = $core_callbacks;
5773 -
5774 - // Get callbacks from active add-ons
5775 - $active_addon_callbacks = apply_filters('mxchat_available_callbacks', array());
5776 -
5777 - // Add placeholder callbacks only for add-ons that aren't active
5778 - if ($include_all) {
5779 - foreach ($addon_callbacks as $function => $data) {
5780 - // Skip placeholders for functions provided by active add-ons
5781 - if (in_array($function, $addon_provided_functions)) {
5782 - continue;
5783 - }
5784 -
5785 - // Skip excluded functions
5786 - if (in_array($function, $excluded_functions)) {
5787 - continue;
5788 - }
5789 -
5790 - // Add the placeholder
5791 - $callbacks[$function] = $data;
5792 - }
5793 - }
5794 -
5795 - // Add callbacks from active add-ons (will override placeholders)
5796 - foreach ($active_addon_callbacks as $function => $data) {
5797 - // Skip excluded functions
5798 - if (in_array($function, $excluded_functions)) {
5799 - continue;
5800 - }
5801 -
5802 - // Always include callbacks from add-ons
5803 - $callbacks[$function] = $data;
5804 -
5805 - // Ensure they have the proper add-on info
5806 - if (isset($addon_function_mapping[$function])) {
5807 - $addon_info = $addon_function_mapping[$function];
5808 - $callbacks[$function]['addon'] = $addon_info['addon'];
5809 - $callbacks[$function]['addon_name'] = $addon_info['addon_name'];
5810 - $callbacks[$function]['installed'] = $addon_info['is_installed'];
5811 - $callbacks[$function]['pro_only'] = $addon_info['pro_required'];
5812 - }
5813 - }
5814 -
5815 - // Just before returning callbacks, sort them to prioritize free features
5816 - if (!$grouped) {
5817 - // Create temporary arrays for sorting
5818 - $free_callbacks = array();
5819 - $pro_callbacks = array();
5820 -
5821 - // Split callbacks into free and pro
5822 - foreach ($callbacks as $key => $data) {
5823 - if (isset($data['pro_only']) && $data['pro_only']) {
5824 - $pro_callbacks[$key] = $data;
5825 - } else {
5826 - $free_callbacks[$key] = $data;
5827 - }
5828 - }
5829 -
5830 - // Merge with free callbacks first
5831 - $callbacks = array_merge($free_callbacks, $pro_callbacks);
5832 - }
5833 -
5834 - // Return grouped structure if requested
5835 - if ($grouped) {
5836 - $grouped_callbacks = array();
5837 - foreach ($callbacks as $key => $data) {
5838 - $group_label = isset($data['group']) ? $data['group'] : __('Other Features', 'mxchat');
5839 -
5840 - // Ensure we carry forward all the new fields in grouped mode
5841 - $callback_data = array(
5842 - 'label' => $data['label'],
5843 - 'pro_only' => isset($data['pro_only']) ? $data['pro_only'] : false,
5844 - 'icon' => isset($data['icon']) ? $data['icon'] : 'admin-generic',
5845 - 'description' => isset($data['description']) ? $data['description'] : __('Custom action for your chatbot', 'mxchat'),
5846 - 'addon' => isset($data['addon']) ? $data['addon'] : false,
5847 - 'addon_name' => isset($data['addon_name']) ? $data['addon_name'] : '',
5848 - 'installed' => isset($data['installed']) ? $data['installed'] : true
5849 - );
5850 -
5851 - $grouped_callbacks[$group_label][$key] = $callback_data;
5852 - }
5853 -
5854 - // Sort within each group to prioritize free features
5855 - foreach ($grouped_callbacks as $group => $items) {
5856 - $free_items = array();
5857 - $pro_items = array();
5858 -
5859 - foreach ($items as $key => $data) {
5860 - if (isset($data['pro_only']) && $data['pro_only']) {
5861 - $pro_items[$key] = $data;
5862 - } else {
5863 - $free_items[$key] = $data;
5864 - }
5865 - }
5866 -
5867 - $grouped_callbacks[$group] = array_merge($free_items, $pro_items);
5868 - }
5869 -
5870 - return $grouped_callbacks;
5871 - }
5872 -
5873 - return $callbacks;
5874 -}
5875 -
5876 2445 public function mxchat_page_init() {
2446 + // Register settings
5877 2447 register_setting(
5878 2448 'mxchat_option_group',
5879 2449 'mxchat_options',
5880 2450 array($this, 'mxchat_sanitize')
@@ -5885,201 +2455,70 @@
5885 2455 'mxchat_similarity_threshold',
5886 2456 array(
5887 2457 'type' => 'number',
5888 2458 'sanitize_callback' => function($value) {
5889 - $value = absint($value);
5890 - return min(max($value, 20), 95);
2459 + $value = absint($value); // Ensure it's an integer
2460 + return min(max($value, 70), 85); // Enforce range
5891 2461 },
5892 2462 'default' => 80,
5893 2463 )
5894 2464 );
5895 2465
2466 +
5896 2467 // Chatbot Settings Section
5897 2468 add_settings_section(
5898 2469 'mxchat_chatbot_section',
5899 - esc_html__('Chatbot Settings', 'mxchat'),
2470 + 'Chatbot Settings',
5900 2471 null,
5901 2472 'mxchat-chatbot'
5902 2473 );
5903 2474
5904 - // API Keys Settings Section
5905 - add_settings_section(
5906 - 'mxchat_api_keys_section',
5907 - esc_html__('API Keys', 'mxchat'),
5908 - array($this, 'mxchat_api_keys_section_callback'),
5909 - 'mxchat-api-keys'
5910 - );
5911 -
5912 - // OpenAI API Key
5913 - add_settings_field(
5914 - 'api_key',
5915 - esc_html__('OpenAI API Key', 'mxchat'),
5916 - array($this, 'api_key_callback'),
5917 - 'mxchat-api-keys',
5918 - 'mxchat_api_keys_section'
5919 - );
5920 -
5921 - // X.AI API Key
5922 - add_settings_field(
5923 - 'xai_api_key',
5924 - esc_html__('X.AI API Key', 'mxchat'),
5925 - array($this, 'xai_api_key_callback'),
5926 - 'mxchat-api-keys',
5927 - 'mxchat_api_keys_section'
5928 - );
5929 -
5930 - // Claude API Key
5931 - add_settings_field(
5932 - 'claude_api_key',
5933 - esc_html__('Claude API Key', 'mxchat'),
5934 - array($this, 'claude_api_key_callback'),
5935 - 'mxchat-api-keys',
5936 - 'mxchat_api_keys_section'
5937 - );
5938 -
5939 - // DeepSeek API Key
5940 - add_settings_field(
5941 - 'deepseek_api_key',
5942 - esc_html__('DeepSeek API Key', 'mxchat'),
5943 - array($this, 'deepseek_api_key_callback'),
5944 - 'mxchat-api-keys',
5945 - 'mxchat_api_keys_section'
5946 - );
5947 -
5948 - // Google Gemini API Key
5949 - add_settings_field(
5950 - 'gemini_api_key',
5951 - esc_html__('Google Gemini API Key', 'mxchat'),
5952 - array($this, 'gemini_api_key_callback'),
5953 - 'mxchat-api-keys',
5954 - 'mxchat_api_keys_section'
5955 - );
5956 -
5957 - // Voyage AI API Key
5958 - add_settings_field(
5959 - 'voyage_api_key',
5960 - esc_html__('Voyage AI API Key', 'mxchat'),
5961 - array($this, 'voyage_api_key_callback'),
5962 - 'mxchat-api-keys',
5963 - 'mxchat_api_keys_section'
5964 - );
5965 -
5966 - // OpenRouter API Key
5967 - add_settings_field(
5968 - 'openrouter_api_key',
5969 - esc_html__('OpenRouter API Key', 'mxchat'),
5970 - array($this, 'openrouter_api_key_callback'),
5971 - 'mxchat-api-keys',
5972 - 'mxchat_api_keys_section'
5973 - );
5974 -
5975 - // Custom (OpenAI-compatible) Provider — for Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
5976 - add_settings_field(
5977 - 'custom_provider',
5978 - esc_html__('Custom Provider (OpenAI-compatible)', 'mxchat'),
5979 - array($this, 'custom_provider_callback'),
5980 - 'mxchat-api-keys',
5981 - 'mxchat_api_keys_section'
5982 - );
5983 -
5984 - // Loops API Key
5985 - add_settings_field(
5986 - 'loops_api_key',
5987 - esc_html__('Loops API Key', 'mxchat'),
5988 - array($this, 'mxchat_loops_api_key_callback'),
5989 - 'mxchat-api-keys',
5990 - 'mxchat_api_keys_section'
5991 - );
5992 -
5993 - // Brave Search API Key
5994 - add_settings_field(
5995 - 'brave_api_key',
5996 - __('Brave API Key', 'mxchat'),
5997 - array($this, 'mxchat_brave_api_key_callback'),
5998 - 'mxchat-api-keys',
5999 - 'mxchat_api_keys_section'
6000 - );
6001 -
6002 2475 // Similarity Threshold Slider
6003 2476 add_settings_field(
6004 2477 'similarity_threshold', // Field ID
6005 - esc_html__('Similarity Threshold', 'mxchat'), // Field title
2478 + 'Similarity Threshold', // Field title
6006 2479 array($this, 'mxchat_similarity_threshold_callback'), // Callback function
6007 2480 'mxchat-chatbot', // Page
6008 2481 'mxchat_chatbot_section' // Section
6009 2482 );
6010 2483
6011 - // RAG Sources Limit Slider
2484 + // Existing fields...
6012 2485 add_settings_field(
6013 - 'rag_sources_limit', // Field ID
6014 - esc_html__('RAG Sources Limit', 'mxchat'), // Field title
6015 - array($this, 'mxchat_rag_sources_limit_callback'), // Callback function
6016 - 'mxchat-chatbot', // Page
6017 - 'mxchat_chatbot_section' // Section
6018 - );
6019 -
6020 - // RAG Chunks Limit Slider
6021 - add_settings_field(
6022 - 'rag_chunks_limit', // Field ID
6023 - esc_html__('RAG Chunks Limit', 'mxchat'), // Field title
6024 - array($this, 'mxchat_rag_chunks_limit_callback'), // Callback function
6025 - 'mxchat-chatbot', // Page
6026 - 'mxchat_chatbot_section' // Section
6027 - );
6028 -
6029 - add_settings_field(
6030 - 'append_to_body',
6031 - esc_html__('Auto-Display Chatbot', 'mxchat'),
6032 - array($this, 'mxchat_append_to_body_callback'),
2486 + 'api_key',
2487 + 'OpenAI API Key',
2488 + array($this, 'api_key_callback'),
6033 2489 'mxchat-chatbot',
6034 2490 'mxchat_chatbot_section'
6035 2491 );
6036 2492
6037 2493 add_settings_field(
6038 - 'contextual_awareness_toggle',
6039 - esc_html__('Contextual Awareness', 'mxchat'),
6040 - array($this, 'mxchat_contextual_awareness_callback'),
6041 - 'mxchat-chatbot',
6042 - 'mxchat_chatbot_section'
2494 + 'xai_api_key',
2495 + 'X.AI API Key',
2496 + array($this, 'xai_api_key_callback'),
2497 + 'mxchat-chatbot',
2498 + 'mxchat_chatbot_section'
6043 2499 );
6044 2500
6045 2501 add_settings_field(
6046 - 'citation_links_toggle',
6047 - esc_html__('Citation Links', 'mxchat'),
6048 - array($this, 'mxchat_citation_links_toggle_callback'),
2502 + 'claude_api_key',
2503 + 'Claude API Key',
2504 + array($this, 'claude_api_key_callback'),
6049 2505 'mxchat-chatbot',
6050 2506 'mxchat_chatbot_section'
6051 2507 );
6052 2508
6053 - // Satisfaction rating toggle (plan-a5b006).
2509 +
6054 2510 add_settings_field(
6055 - 'satisfaction_rating_enabled',
6056 - esc_html__('Satisfaction Rating Prompt', 'mxchat'),
6057 - array($this, 'mxchat_satisfaction_rating_toggle_callback'),
2511 + 'system_prompt_instructions',
2512 + 'AI Instructions (Behavior)',
2513 + array($this, 'system_prompt_instructions_callback'),
6058 2514 'mxchat-chatbot',
6059 2515 'mxchat_chatbot_section'
6060 2516 );
6061 2517
6062 - // Satisfaction rating customization (plan-141a12, plan-29caac):
6063 - // the 5 customization fields are now inline-rendered inside
6064 - // mxchat_satisfaction_rating_toggle_callback's sub-options wrapper.
6065 -
6066 2518 add_settings_field(
6067 - 'enable_streaming_toggle',
6068 - esc_html__('Enable Streaming', 'mxchat'),
6069 - array($this, 'enable_streaming_toggle_callback'),
6070 - 'mxchat-chatbot',
6071 - 'mxchat_chatbot_section', // Same section as your working toggle
6072 - array(
6073 - 'class' => 'mxchat-setting-row streaming-setting',
6074 - 'style' => 'display: none;' // Hidden by default, shown when OpenAI/Claude selected
6075 - )
6076 - );
6077 -
6078 -
6079 - add_settings_field(
6080 2519 'model',
6081 - esc_html__('Chat Model', 'mxchat'),
2520 + 'Model',
6082 2521 array($this, 'mxchat_model_callback'),
6083 2522 'mxchat-chatbot',
6084 2523 'mxchat_chatbot_section'
6085 2524 );
@@ -6084,43 +2523,18 @@
6084 2523 'mxchat_chatbot_section'
6085 2524 );
6086 2525
6087 2526 add_settings_field(
6088 - 'embedding_model',
6089 - esc_html__('Embedding Model', 'mxchat'),
6090 - array($this, 'embedding_model_callback'),
6091 - 'mxchat-chatbot',
6092 - 'mxchat_chatbot_section'
6093 - );
6094 -
6095 - add_settings_field(
6096 - 'system_prompt_instructions',
6097 - esc_html__('AI Instructions (Behavior)', 'mxchat'),
6098 - array($this, 'system_prompt_instructions_callback'),
6099 - 'mxchat-chatbot',
6100 - 'mxchat_chatbot_section'
6101 - );
6102 -
6103 -
6104 - add_settings_field(
6105 2527 'top_bar_title',
6106 - esc_html__('Top Bar Title', 'mxchat'),
2528 + 'Top Bar Title',
6107 2529 array($this, 'mxchat_top_bar_title_callback'),
6108 2530 'mxchat-chatbot',
6109 2531 'mxchat_chatbot_section'
6110 2532 );
6111 2533
6112 - add_settings_field(
6113 - 'ai_agent_text',
6114 - esc_html__('AI Agent Text', 'mxchat'),
6115 - array($this, 'mxchat_ai_agent_text_callback'),
6116 - 'mxchat-chatbot',
6117 - 'mxchat_chatbot_section'
6118 - );
6119 -
6120 - add_settings_field(
2534 + add_settings_field(
6121 2535 'enable_email_block',
6122 - esc_html__('Require Email To Chat', 'mxchat'),
2536 + 'Require Email Before Chat',
6123 2537 array($this, 'enable_email_block_callback'),
6124 2538 'mxchat-chatbot',
6125 2539 'mxchat_chatbot_section'
6126 2540 );
@@ -6126,9 +2540,9 @@
6126 2540 );
6127 2541
6128 2542 add_settings_field(
6129 2543 'email_blocker_header_content',
6130 - esc_html__('Require Email Chat Content', 'mxchat'),
2544 + 'Require Email Chat Content',
6131 2545 array($this, 'email_blocker_header_content_callback'),
6132 2546 'mxchat-chatbot',
6133 2547 'mxchat_chatbot_section'
6134 2548 );
@@ -6134,9 +2548,9 @@
6134 2548 );
6135 2549
6136 2550 add_settings_field(
6137 2551 'email_blocker_button_text',
6138 - esc_html__('Require Email Chat Button Text', 'mxchat'),
2552 + 'Require Email Chat Button Text',
6139 2553 [$this, 'email_blocker_button_text_callback'],
6140 2554 'mxchat-chatbot',
6141 2555 'mxchat_chatbot_section'
6142 2556 );
@@ -6141,50 +2555,66 @@
6141 2555 'mxchat_chatbot_section'
6142 2556 );
6143 2557
6144 2558 add_settings_field(
6145 - 'enable_name_field',
6146 - esc_html__('Require Name Field', 'mxchat'),
6147 - array($this, 'enable_name_field_callback'),
2559 + 'intro_message',
2560 + 'Introductory Message',
2561 + array($this, 'mxchat_intro_message_callback'),
6148 2562 'mxchat-chatbot',
6149 2563 'mxchat_chatbot_section'
6150 2564 );
6151 2565
6152 2566 add_settings_field(
6153 - 'name_field_placeholder',
6154 - esc_html__('Name Field Placeholder', 'mxchat'),
6155 - array($this, 'name_field_placeholder_callback'),
2567 + 'input_copy',
2568 + 'Input Copy',
2569 + array($this, 'mxchat_input_copy_callback'),
6156 2570 'mxchat-chatbot',
6157 2571 'mxchat_chatbot_section'
6158 2572 );
6159 2573
6160 2574 add_settings_field(
6161 - 'intro_message',
6162 - esc_html__('Introductory Message', 'mxchat'),
6163 - array($this, 'mxchat_intro_message_callback'),
2575 + 'rate_limit_logged_in',
2576 + __('Rate Limit for Logged-in Users', 'mxchat'),
2577 + array($this, 'mxchat_rate_limit_logged_in_callback'),
6164 2578 'mxchat-chatbot',
6165 2579 'mxchat_chatbot_section'
6166 2580 );
6167 2581
6168 2582 add_settings_field(
6169 - 'input_copy',
6170 - esc_html__('Input Copy', 'mxchat'),
6171 - array($this, 'mxchat_input_copy_callback'),
2583 + 'rate_limit_logged_out',
2584 + __('Rate Limit for Logged-out Users', 'mxchat'),
2585 + array($this, 'mxchat_rate_limit_logged_out_callback'),
6172 2586 'mxchat-chatbot',
6173 2587 'mxchat_chatbot_section'
6174 2588 );
6175 2589
6176 2590 add_settings_field(
2591 + 'rate_limit_message',
2592 + 'Rate Limit Message',
2593 + array($this, 'mxchat_rate_limit_message_callback'),
2594 + 'mxchat-chatbot',
2595 + 'mxchat_chatbot_section'
2596 + );
2597 +
2598 + add_settings_field(
6177 2599 'pre_chat_message',
6178 - esc_html__('Chat Teaser Pop-up', 'mxchat'),
2600 + 'Chat Teaser Pop-up',
6179 2601 array($this, 'mxchat_pre_chat_message_callback'),
6180 2602 'mxchat-chatbot',
6181 2603 'mxchat_chatbot_section'
6182 2604 );
6183 2605
6184 - add_settings_field(
2606 + add_settings_field(
2607 + 'append_to_body',
2608 + 'Append Chat Widget to Body',
2609 + array($this, 'mxchat_append_to_body_callback'),
2610 + 'mxchat-chatbot',
2611 + 'mxchat_chatbot_section'
2612 + );
2613 +
2614 + add_settings_field(
6185 2615 'privacy_toggle',
6186 - esc_html__('Toggle Privacy Notice', 'mxchat'),
2616 + 'Toggle Privacy Notice',
6187 2617 array($this, 'mxchat_privacy_toggle_callback'),
6188 2618 'mxchat-chatbot',
6189 2619 'mxchat_chatbot_section'
6190 2620 );
@@ -6190,9 +2620,9 @@
6190 2620 );
6191 2621
6192 2622 add_settings_field(
6193 2623 'complianz_toggle',
6194 - esc_html__('Enable Complianz', 'mxchat'),
2624 + 'Enable Complianz',
6195 2625 array($this, 'mxchat_complianz_toggle_callback'),
6196 2626 'mxchat-chatbot',
6197 2627 'mxchat_chatbot_section'
6198 2628 );
@@ -6198,9 +2628,9 @@
6198 2628 );
6199 2629
6200 2630 add_settings_field(
6201 2631 'link_target_toggle',
6202 - esc_html__('Open Links in a New Tab', 'mxchat'),
2632 + 'Open Links in a New Tab',
6203 2633 array($this, 'mxchat_link_target_toggle_callback'),
6204 2634 'mxchat-chatbot',
6205 2635 'mxchat_chatbot_section'
6206 2636 );
@@ -6205,90 +2635,125 @@
6205 2635 'mxchat_chatbot_section'
6206 2636 );
6207 2637
6208 2638 add_settings_field(
6209 - 'chat_persistence_toggle',
6210 - esc_html__('Enable Chat Persistence', 'mxchat'),
6211 - array($this, 'mxchat_chat_persistence_toggle_callback'),
6212 - 'mxchat-chatbot',
6213 - 'mxchat_chatbot_section'
2639 + 'chat_persistence_toggle',
2640 + 'Enable Chat Persistence',
2641 + array($this, 'mxchat_chat_persistence_toggle_callback'),
2642 + 'mxchat-chatbot',
2643 + 'mxchat_chatbot_section'
6214 2644 );
6215 2645
6216 2646 add_settings_field(
6217 - 'popular_question_1',
6218 - esc_html__('Quick Question 1', 'mxchat'),
6219 - array($this, 'mxchat_popular_question_1_callback'),
6220 - 'mxchat-chatbot',
6221 - 'mxchat_chatbot_section'
6222 - );
2647 + 'popular_question_1',
2648 + 'Popular Question 1',
2649 + array($this, 'mxchat_popular_question_1_callback'),
2650 + 'mxchat-chatbot',
2651 + 'mxchat_chatbot_section'
2652 +);
6223 2653
6224 - add_settings_field(
6225 - 'popular_question_2',
6226 - esc_html__('Quick Question 2', 'mxchat'),
6227 - array($this, 'mxchat_popular_question_2_callback'),
6228 - 'mxchat-chatbot',
6229 - 'mxchat_chatbot_section'
6230 - );
2654 +add_settings_field(
2655 + 'popular_question_2',
2656 + 'Popular Question 2',
2657 + array($this, 'mxchat_popular_question_2_callback'),
2658 + 'mxchat-chatbot',
2659 + 'mxchat_chatbot_section'
2660 +);
6231 2661
6232 - add_settings_field(
6233 - 'popular_question_3',
6234 - esc_html__('Quick Question 3', 'mxchat'),
6235 - array($this, 'mxchat_popular_question_3_callback'),
6236 - 'mxchat-chatbot',
6237 - 'mxchat_chatbot_section'
6238 - );
2662 +add_settings_field(
2663 + 'popular_question_3',
2664 + 'Popular Question 3',
2665 + array($this, 'mxchat_popular_question_3_callback'),
2666 + 'mxchat-chatbot',
2667 + 'mxchat_chatbot_section'
2668 +);
6239 2669
6240 - add_settings_field(
6241 - 'additional_popular_questions',
6242 - esc_html__('Additional Quick Questions', 'mxchat'),
6243 - array($this, 'mxchat_additional_popular_questions_callback'),
6244 - 'mxchat-chatbot',
6245 - 'mxchat_chatbot_section'
6246 - );
2670 +add_settings_field(
2671 + 'additional_popular_questions',
2672 + 'Additional Popular Questions',
2673 + array($this, 'mxchat_additional_popular_questions_callback'),
2674 + 'mxchat-chatbot',
2675 + 'mxchat_chatbot_section'
2676 +);
6247 2677
6248 2678
6249 - add_settings_field(
6250 - 'rate_limits',
6251 - __('Rate Limits Settings', 'mxchat'),
6252 - array($this, 'mxchat_rate_limits_callback'),
6253 - 'mxchat-chatbot',
6254 - 'mxchat_chatbot_section'
6255 - );
2679 +// WooCommerce Settings Section
2680 +add_settings_section(
2681 + 'mxchat_woocommerce_section',
2682 + 'WooCommerce Settings',
2683 + null,
2684 + 'mxchat-embed'
2685 +);
6256 2686
6257 - // Loops Settings Section
6258 - add_settings_section(
6259 - 'mxchat_loops_section',
6260 - esc_html__('Loops Settings', 'mxchat'),
6261 - null,
6262 - 'mxchat-embed'
6263 - );
2687 +// Loops Settings Section
2688 +add_settings_section(
2689 + 'mxchat_loops_section',
2690 + 'Loops Settings',
2691 + null,
2692 + 'mxchat-embed'
2693 +);
6264 2694
6265 - // Loops Settings Fields (API Key moved to API Keys tab)
6266 - add_settings_field(
6267 - 'loops_mailing_list',
6268 - esc_html__('Loops Mailing List', 'mxchat'),
6269 - array($this, 'mxchat_loops_mailing_list_callback'),
6270 - 'mxchat-embed',
6271 - 'mxchat_loops_section'
6272 - );
2695 +// WooCommerce Settings Fields
2696 +add_settings_field(
2697 + 'enable_woocommerce_integration',
2698 + 'Automatically Embed Products',
2699 + array($this, 'mxchat_enable_woocommerce_integration_callback'),
2700 + 'mxchat-embed',
2701 + 'mxchat_woocommerce_section'
2702 +);
6273 2703
6274 - add_settings_field(
6275 - 'triggered_phrase_response',
6276 - esc_html__('Triggered Phrase Response', 'mxchat'),
6277 - array($this, 'mxchat_triggered_phrase_response_callback'),
6278 - 'mxchat-embed',
6279 - 'mxchat_loops_section'
6280 - );
6281 2704
6282 - add_settings_field(
6283 - 'email_capture_response',
6284 - esc_html__('Email Capture Response', 'mxchat'),
6285 - array($this, 'mxchat_email_capture_response_callback'),
6286 - 'mxchat-embed',
6287 - 'mxchat_loops_section'
6288 - );
2705 +add_settings_field(
2706 + 'woocommerce_consumer_key',
2707 + 'WooCommerce Consumer Key',
2708 + array($this, 'mxchat_woocommerce_consumer_key_callback'),
2709 + 'mxchat-embed',
2710 + 'mxchat_woocommerce_section'
2711 +);
6289 2712
6290 - // Brave Search Settings Fields
2713 +add_settings_field(
2714 + 'woocommerce_consumer_secret',
2715 + 'WooCommerce Consumer Secret',
2716 + array($this, 'mxchat_woocommerce_consumer_secret_callback'),
2717 + 'mxchat-embed',
2718 + 'mxchat_woocommerce_section'
2719 +);
2720 +
2721 +// Loops Settings Fields
2722 +add_settings_field(
2723 + 'loops_api_key',
2724 + 'Loops API Key',
2725 + array($this, 'mxchat_loops_api_key_callback'),
2726 + 'mxchat-embed',
2727 + 'mxchat_loops_section'
2728 +);
2729 +
2730 +add_settings_field(
2731 + 'loops_mailing_list',
2732 + 'Loops Mailing List',
2733 + array($this, 'mxchat_loops_mailing_list_callback'),
2734 + 'mxchat-embed',
2735 + 'mxchat_loops_section'
2736 +);
2737 +
2738 +add_settings_field(
2739 + 'triggered_phrase_response',
2740 + 'Triggered Phrase Response',
2741 + array($this, 'mxchat_triggered_phrase_response_callback'),
2742 + 'mxchat-embed',
2743 + 'mxchat_loops_section'
2744 +);
2745 +
2746 +add_settings_field(
2747 + 'email_capture_response',
2748 + 'Email Capture Response',
2749 + array($this, 'mxchat_email_capture_response_callback'),
2750 + 'mxchat-embed',
2751 + 'mxchat_loops_section'
2752 +);
2753 +
2754 +
2755 + // Brave Search Settings Fields
6291 2756 add_settings_section(
6292 2757 'mxchat_brave_section',
6293 2758 __('Brave Search Settings', 'mxchat'),
6294 2759 array($this, 'mxchat_brave_section_callback'),
@@ -6294,10 +2759,17 @@
6294 2759 array($this, 'mxchat_brave_section_callback'),
6295 2760 'mxchat-embed'
6296 2761 );
6297 2762
6298 - // Brave API Key moved to API Keys tab
6299 2763 add_settings_field(
2764 + 'brave_api_key',
2765 + __('Brave API Key', 'mxchat'),
2766 + array($this, 'mxchat_brave_api_key_callback'),
2767 + 'mxchat-embed',
2768 + 'mxchat_brave_section'
2769 + );
2770 +
2771 + add_settings_field(
6300 2772 'brave_image_count',
6301 2773 __('Number of Images to Return', 'mxchat'),
6302 2774 array($this, 'mxchat_brave_image_count_callback'),
6303 2775 'mxchat-embed',
@@ -6335,354 +2807,320 @@
6335 2807 'mxchat-embed',
6336 2808 'mxchat_brave_section'
6337 2809 );
6338 2810
2811 +
6339 2812 // Chat with PDF Intent Settings Fields
2813 +add_settings_section(
2814 + 'mxchat_pdf_intent_section',
2815 + __('Toolbar Settings & Intents', 'mxchat'),
2816 + array($this, 'mxchat_pdf_intent_section_callback'),
2817 + 'mxchat-embed'
2818 +);
2819 +
2820 +add_settings_field(
2821 + 'chat_toolbar_toggle',
2822 + __('Show Chat Toolbar', 'mxchat'),
2823 + array($this, 'mxchat_chat_toolbar_toggle_callback'),
2824 + 'mxchat-embed',
2825 + 'mxchat_pdf_intent_section'
2826 +);
2827 +
2828 +
2829 +add_settings_field(
2830 + 'pdf_intent_trigger_text',
2831 + __('Intent Trigger Text', 'mxchat'),
2832 + array($this, 'mxchat_pdf_intent_trigger_text_callback'),
2833 + 'mxchat-embed',
2834 + 'mxchat_pdf_intent_section'
2835 +);
2836 +
2837 +add_settings_field(
2838 + 'pdf_intent_success_text',
2839 + __('Success Text', 'mxchat'),
2840 + array($this, 'mxchat_pdf_intent_success_text_callback'),
2841 + 'mxchat-embed',
2842 + 'mxchat_pdf_intent_section'
2843 +);
2844 +
2845 +add_settings_field(
2846 + 'pdf_intent_error_text',
2847 + __('Error Text', 'mxchat'),
2848 + array($this, 'mxchat_pdf_intent_error_text_callback'),
2849 + 'mxchat-embed',
2850 + 'mxchat_pdf_intent_section'
2851 +);
2852 +
2853 +// Add PDF Maximum Pages Field
2854 +add_settings_field(
2855 + 'pdf_max_pages',
2856 + __('Maximum Document Pages', 'mxchat'),
2857 + array($this, 'mxchat_pdf_max_pages_callback'),
2858 + 'mxchat-embed',
2859 + 'mxchat_pdf_intent_section'
2860 +);
2861 +
2862 +
2863 +
2864 +
2865 +// Live Agent Settings Fields
2866 +add_settings_section(
2867 + 'mxchat_live_agent_section',
2868 + __('Live Agent Settings', 'mxchat'),
2869 + array($this, 'mxchat_live_agent_section_callback'),
2870 + 'mxchat-embed'
2871 +);
2872 +
2873 +// Live Agent Status Fields (add at top of live agent settings)
2874 +add_settings_field(
2875 + 'live_agent_status',
2876 + __('Live Agent Status', 'mxchat'),
2877 + array($this, 'mxchat_live_agent_status_callback'),
2878 + 'mxchat-embed',
2879 + 'mxchat_live_agent_section'
2880 +);
2881 +
2882 +add_settings_field(
2883 + 'live_agent_notification_message',
2884 + __('Notification Message', 'mxchat'),
2885 + array($this, 'mxchat_live_agent_notification_message_callback'),
2886 + 'mxchat-embed',
2887 + 'mxchat_live_agent_section'
2888 +);
2889 +
2890 +add_settings_field(
2891 + 'live_agent_away_message',
2892 + __('Away Message', 'mxchat'),
2893 + array($this, 'mxchat_live_agent_away_message_callback'),
2894 + 'mxchat-embed',
2895 + 'mxchat_live_agent_section'
2896 +);
2897 +
2898 +add_settings_field(
2899 + 'live_agent_webhook_url',
2900 + __('Slack Webhook URL', 'mxchat'),
2901 + array($this, 'mxchat_live_agent_webhook_url_callback'),
2902 + 'mxchat-embed',
2903 + 'mxchat_live_agent_section'
2904 +);
2905 +
2906 +add_settings_field(
2907 + 'live_agent_secret_key',
2908 + __('Slack Secret Key', 'mxchat'),
2909 + array($this, 'mxchat_live_agent_secret_key_callback'),
2910 + 'mxchat-embed',
2911 + 'mxchat_live_agent_section'
2912 +);
2913 +
2914 +// Live Agent Integration Fields
2915 +add_settings_field(
2916 + 'live_agent_bot_token',
2917 + __('Slack Bot OAuth Token', 'mxchat'),
2918 + array($this, 'mxchat_live_agent_bot_token_callback'),
2919 + 'mxchat-embed',
2920 + 'mxchat_live_agent_section'
2921 +);
2922 +
2923 +
2924 + // Theme Settings Section
6340 2925 add_settings_section(
6341 - 'mxchat_pdf_intent_section',
6342 - __('Toolbar Settings & Intents', 'mxchat'),
6343 - array($this, 'mxchat_pdf_intent_section_callback'),
6344 - 'mxchat-embed'
2926 + 'mxchat_theme_section',
2927 + 'Theme Settings',
2928 + null,
2929 + 'mxchat-theme'
6345 2930 );
6346 2931
6347 2932 add_settings_field(
6348 - 'chat_toolbar_toggle',
6349 - __('Show Chat Toolbar', 'mxchat'),
6350 - array($this, 'mxchat_chat_toolbar_toggle_callback'),
6351 - 'mxchat-embed',
6352 - 'mxchat_pdf_intent_section'
2933 + 'close_button_color',
2934 + 'Close Button & Title Color',
2935 + array($this, 'mxchat_close_button_color_callback'),
2936 + 'mxchat-theme',
2937 + 'mxchat_theme_section'
6353 2938 );
6354 2939
6355 - // PDF Upload Button Toggle
6356 2940 add_settings_field(
6357 - 'show_pdf_upload_button',
6358 - __('Show PDF Upload Button', 'mxchat'),
6359 - array($this, 'mxchat_show_pdf_upload_button_callback'),
6360 - 'mxchat-embed',
6361 - 'mxchat_pdf_intent_section'
2941 + 'chatbot_bg_color',
2942 + 'Chatbot Background Color',
2943 + array($this, 'mxchat_chatbot_bg_color_callback'),
2944 + 'mxchat-theme',
2945 + 'mxchat_theme_section'
6362 2946 );
6363 2947
6364 - // Word Upload Button Toggle
6365 2948 add_settings_field(
6366 - 'show_word_upload_button',
6367 - __('Show Word Upload Button', 'mxchat'),
6368 - array($this, 'mxchat_show_word_upload_button_callback'),
6369 - 'mxchat-embed',
6370 - 'mxchat_pdf_intent_section'
2949 + 'user_message_bg_color',
2950 + 'User Message Background Color',
2951 + array($this, 'mxchat_user_message_bg_color_callback'),
2952 + 'mxchat-theme',
2953 + 'mxchat_theme_section'
6371 2954 );
6372 2955
6373 2956 add_settings_field(
6374 - 'pdf_intent_trigger_text',
6375 - __('Intent Trigger Text', 'mxchat'),
6376 - array($this, 'mxchat_pdf_intent_trigger_text_callback'),
6377 - 'mxchat-embed',
6378 - 'mxchat_pdf_intent_section'
2957 + 'user_message_font_color',
2958 + 'User Message Font Color',
2959 + array($this, 'mxchat_user_message_font_color_callback'),
2960 + 'mxchat-theme',
2961 + 'mxchat_theme_section'
6379 2962 );
6380 2963
6381 2964 add_settings_field(
6382 - 'pdf_intent_success_text',
6383 - __('Success Text', 'mxchat'),
6384 - array($this, 'mxchat_pdf_intent_success_text_callback'),
6385 - 'mxchat-embed',
6386 - 'mxchat_pdf_intent_section'
2965 + 'bot_message_bg_color',
2966 + 'Bot Message Background Color',
2967 + array($this, 'mxchat_bot_message_bg_color_callback'),
2968 + 'mxchat-theme',
2969 + 'mxchat_theme_section'
6387 2970 );
6388 2971
6389 2972 add_settings_field(
6390 - 'pdf_intent_error_text',
6391 - __('Error Text', 'mxchat'),
6392 - array($this, 'mxchat_pdf_intent_error_text_callback'),
6393 - 'mxchat-embed',
6394 - 'mxchat_pdf_intent_section'
2973 + 'bot_message_font_color',
2974 + 'Bot Message Font Color',
2975 + array($this, 'mxchat_bot_message_font_color_callback'),
2976 + 'mxchat-theme',
2977 + 'mxchat_theme_section'
6395 2978 );
6396 2979
6397 - // Add PDF Maximum Pages Field
6398 2980 add_settings_field(
6399 - 'pdf_max_pages',
6400 - __('Maximum Document Pages', 'mxchat'),
6401 - array($this, 'mxchat_pdf_max_pages_callback'),
6402 - 'mxchat-embed',
6403 - 'mxchat_pdf_intent_section'
2981 + 'top_bar_bg_color',
2982 + 'Top Bar Background Color',
2983 + array($this, 'mxchat_top_bar_bg_color_callback'),
2984 + 'mxchat-theme',
2985 + 'mxchat_theme_section'
6404 2986 );
6405 2987
6406 - // Live Agent Settings Fields
6407 - add_settings_section(
6408 - 'mxchat_live_agent_section',
6409 - __('Live Agent Settings', 'mxchat'),
6410 - array($this, 'mxchat_live_agent_section_callback'),
6411 - 'mxchat-embed'
6412 - );
6413 -
6414 - // Live Agent Status Fields (add at top of live agent settings)
6415 2988 add_settings_field(
6416 - 'live_agent_status',
6417 - __('Live Agent Status', 'mxchat'),
6418 - array($this, 'mxchat_live_agent_status_callback'),
6419 - 'mxchat-embed',
6420 - 'mxchat_live_agent_section'
2989 + 'send_button_font_color',
2990 + 'Send Button Color',
2991 + array($this, 'mxchat_send_button_font_color_callback'),
2992 + 'mxchat-theme',
2993 + 'mxchat_theme_section'
6421 2994 );
6422 2995
6423 2996 add_settings_field(
6424 - 'live_agent_notification_message',
6425 - __('Notification Message', 'mxchat'),
6426 - array($this, 'mxchat_live_agent_notification_message_callback'),
6427 - 'mxchat-embed',
6428 - 'mxchat_live_agent_section'
2997 + 'chat_input_font_color',
2998 + 'Chat Input Font Color',
2999 + array($this, 'mxchat_chat_input_font_color_callback'),
3000 + 'mxchat-theme',
3001 + 'mxchat_theme_section'
6429 3002 );
6430 3003
6431 3004 add_settings_field(
6432 - 'live_agent_away_message',
6433 - __('Away Message', 'mxchat'),
6434 - array($this, 'mxchat_live_agent_away_message_callback'),
6435 - 'mxchat-embed',
6436 - 'mxchat_live_agent_section'
3005 + 'chatbot_background_color',
3006 + 'Floating Widget Background Color',
3007 + array($this, 'mxchat_chatbot_background_color_callback'),
3008 + 'mxchat-theme',
3009 + 'mxchat_theme_section'
6437 3010 );
6438 3011
6439 3012 add_settings_field(
6440 - 'live_agent_user_ids',
6441 - __('Slack Agent User IDs', 'mxchat'),
6442 - array($this, 'mxchat_live_agent_user_ids_callback'),
6443 - 'mxchat-embed',
6444 - 'mxchat_live_agent_section'
3013 + 'icon_color',
3014 + 'Chatbot Icon Color',
3015 + array($this, 'mxchat_icon_color_callback'),
3016 + 'mxchat-theme',
3017 + 'mxchat_theme_section'
6445 3018 );
6446 3019
6447 3020 add_settings_field(
6448 - 'live_agent_webhook_url',
6449 - __('Slack Webhook URL', 'mxchat'),
6450 - array($this, 'mxchat_live_agent_webhook_url_callback'),
6451 - 'mxchat-embed',
6452 - 'mxchat_live_agent_section'
3021 + 'custom_icon',
3022 + 'Custom Chatbot Icon (PNG)',
3023 + array($this, 'mxchat_custom_icon_callback'),
3024 + 'mxchat-theme',
3025 + 'mxchat_theme_section'
6453 3026 );
6454 3027
6455 3028 add_settings_field(
6456 - 'live_agent_secret_key',
6457 - __('Slack Secret Key', 'mxchat'),
6458 - array($this, 'mxchat_live_agent_secret_key_callback'),
6459 - 'mxchat-embed',
6460 - 'mxchat_live_agent_section'
3029 + 'title_icon',
3030 + 'Title Bar Icon (PNG)',
3031 + array($this, 'mxchat_title_icon_callback'),
3032 + 'mxchat-theme',
3033 + 'mxchat_theme_section'
6461 3034 );
6462 3035
6463 - // Live Agent Integration Fields
6464 - add_settings_field(
6465 - 'live_agent_bot_token',
6466 - __('Slack Bot OAuth Token', 'mxchat'),
6467 - array($this, 'mxchat_live_agent_bot_token_callback'),
6468 - 'mxchat-embed',
6469 - 'mxchat_live_agent_section'
6470 - );
6471 3036
6472 - // Telegram Integration Section
6473 - add_settings_section(
6474 - 'mxchat_telegram_section',
6475 - __('Telegram Settings', 'mxchat'),
6476 - array($this, 'mxchat_telegram_section_callback'),
6477 - 'mxchat-embed'
6478 - );
6479 -
6480 3037 add_settings_field(
6481 - 'telegram_status',
6482 - __('Live Agent Status', 'mxchat'),
6483 - array($this, 'mxchat_telegram_status_callback'),
6484 - 'mxchat-embed',
6485 - 'mxchat_telegram_section'
3038 + 'live_agent_message_bg_color',
3039 + 'Live Agent Background Color',
3040 + array($this, 'mxchat_live_agent_message_bg_color_callback'),
3041 + 'mxchat-theme',
3042 + 'mxchat_theme_section'
6486 3043 );
6487 3044
6488 3045 add_settings_field(
6489 - 'telegram_notification_message',
6490 - __('Notification Message', 'mxchat'),
6491 - array($this, 'mxchat_telegram_notification_message_callback'),
6492 - 'mxchat-embed',
6493 - 'mxchat_telegram_section'
3046 + 'live_agent_message_font_color',
3047 + 'Live Agent Font Color',
3048 + array($this, 'mxchat_live_agent_message_font_color_callback'),
3049 + 'mxchat-theme',
3050 + 'mxchat_theme_section'
6494 3051 );
6495 3052
3053 + // Mode Indicator Background Color
6496 3054 add_settings_field(
6497 - 'telegram_away_message',
6498 - __('Away Message', 'mxchat'),
6499 - array($this, 'mxchat_telegram_away_message_callback'),
6500 - 'mxchat-embed',
6501 - 'mxchat_telegram_section'
3055 + 'mode_indicator_bg_color',
3056 + 'Mode Indicator Background Color',
3057 + array($this, 'mxchat_mode_indicator_bg_color_callback'),
3058 + 'mxchat-theme',
3059 + 'mxchat_theme_section'
6502 3060 );
6503 3061
3062 + // Mode Indicator Font Color
6504 3063 add_settings_field(
6505 - 'telegram_bot_token',
6506 - __('Telegram Bot Token', 'mxchat'),
6507 - array($this, 'mxchat_telegram_bot_token_callback'),
6508 - 'mxchat-embed',
6509 - 'mxchat_telegram_section'
3064 + 'mode_indicator_font_color',
3065 + 'Mode Indicator Font Color',
3066 + array($this, 'mxchat_mode_indicator_font_color_callback'),
3067 + 'mxchat-theme',
3068 + 'mxchat_theme_section'
6510 3069 );
6511 3070
6512 3071 add_settings_field(
6513 - 'telegram_group_id',
6514 - __('Telegram Group ID', 'mxchat'),
6515 - array($this, 'mxchat_telegram_group_id_callback'),
6516 - 'mxchat-embed',
6517 - 'mxchat_telegram_section'
3072 + 'toolbar_icon_color',
3073 + 'Toolbar Icon Color',
3074 + array($this, 'mxchat_toolbar_icon_color_callback'),
3075 + 'mxchat-theme',
3076 + 'mxchat_theme_section'
6518 3077 );
6519 3078
6520 - add_settings_field(
6521 - 'telegram_webhook_secret',
6522 - __('Webhook Secret Token', 'mxchat'),
6523 - array($this, 'mxchat_telegram_webhook_secret_callback'),
6524 - 'mxchat-embed',
6525 - 'mxchat_telegram_section'
6526 - );
6527 -
6528 3079 // General Settings Section
6529 3080 add_settings_section(
6530 3081 'mxchat_general_section',
6531 - esc_html__('YouTube Tutorials', 'mxchat'),
3082 + 'Frequently Asked Questions (FAQ)',
6532 3083 null,
6533 3084 'mxchat-general'
6534 3085 );
6535 -}
6536 3086
6537 -public function mxchat_prompts_page_init() {
6538 - register_setting(
6539 - 'mxchat_prompts_options',
6540 - 'mxchat_prompts_options',
6541 - array(
6542 - 'type' => 'array',
6543 - 'description' => __('MXChat Knowledge Base Settings', 'mxchat'),
6544 - 'default' => array(
6545 - 'mxchat_auto_sync_posts' => 0,
6546 - 'mxchat_auto_sync_pages' => 0,
6547 - 'mxchat_use_pinecone' => 0,
6548 - 'mxchat_pinecone_api_key' => '',
6549 - 'mxchat_pinecone_environment' => '',
6550 - 'mxchat_pinecone_index' => '',
6551 - 'mxchat_pinecone_host' => '',
6552 - ),
6553 - 'sanitize_callback' => array($this, 'sanitize_prompts_options'),
6554 - )
6555 - );
6556 3087
6557 - add_action('admin_notices', array($this, 'sync_settings_notice'));
3088 +
3089 +
3090 +
3091 +
6558 3092 }
6559 3093
6560 -public function mxchat_transcripts_page_init() {
3094 +public function mxchat_prompts_page_init() {
3095 + // Register settings for the prompts/knowledge base page
6561 3096 register_setting(
6562 - 'mxchat_transcripts_options',
6563 - 'mxchat_transcripts_options',
3097 + 'mxchat_prompts_options',
3098 + 'mxchat_auto_sync_posts',
6564 3099 array(
6565 - 'type' => 'array',
6566 - 'description' => __('MXChat Transcripts Notification Settings', 'mxchat'),
6567 - 'default' => array(
6568 - 'mxchat_enable_notifications' => 0,
6569 - 'mxchat_notification_email' => get_option('admin_email'),
6570 - 'mxchat_auto_delete_transcripts' => 'never',
6571 - ),
6572 - 'sanitize_callback' => array($this, 'sanitize_transcripts_options'),
3100 + 'type' => 'boolean',
3101 + 'description' => 'Automatically sync posts to knowledge base',
3102 + 'sanitize_callback' => array($this, 'sanitize_sync_setting'),
3103 + 'default' => 0,
3104 + 'show_in_rest' => false,
6573 3105 )
6574 3106 );
6575 -
6576 - add_settings_section(
6577 - 'mxchat_transcripts_notification_section',
6578 - esc_html__('Chat Notification Settings', 'mxchat'),
6579 - array($this, 'mxchat_transcripts_notification_section_callback'),
6580 - 'mxchat-transcripts'
3107 + register_setting(
3108 + 'mxchat_prompts_options',
3109 + 'mxchat_auto_sync_pages',
3110 + array(
3111 + 'type' => 'boolean',
3112 + 'description' => 'Automatically sync pages to knowledge base',
3113 + 'sanitize_callback' => array($this, 'sanitize_sync_setting'),
3114 + 'default' => 0,
3115 + 'show_in_rest' => false,
3116 + )
6581 3117 );
6582 3118
6583 - add_settings_field(
6584 - 'mxchat_enable_notifications',
6585 - esc_html__('Enable Chat Notifications', 'mxchat'),
6586 - array($this, 'mxchat_enable_notifications_callback'),
6587 - 'mxchat-transcripts',
6588 - 'mxchat_transcripts_notification_section'
6589 - );
6590 -
6591 - add_settings_field(
6592 - 'mxchat_notification_email',
6593 - esc_html__('Notification Email Address', 'mxchat'),
6594 - array($this, 'mxchat_notification_email_callback'),
6595 - 'mxchat-transcripts',
6596 - 'mxchat_transcripts_notification_section'
6597 - );
6598 -
6599 - add_settings_field(
6600 - 'mxchat_auto_delete_transcripts',
6601 - esc_html__('Auto-Delete Old Transcripts', 'mxchat'),
6602 - array($this, 'mxchat_auto_delete_transcripts_callback'),
6603 - 'mxchat-transcripts',
6604 - 'mxchat_transcripts_notification_section'
6605 - );
6606 -
6607 - add_settings_field(
6608 - 'mxchat_retention_days',
6609 - esc_html__('Custom Retention (Days)', 'mxchat'),
6610 - array($this, 'mxchat_retention_days_callback'),
6611 - 'mxchat-transcripts',
6612 - 'mxchat_transcripts_notification_section'
6613 - );
6614 -
6615 - add_settings_field(
6616 - 'mxchat_auto_email_transcript',
6617 - esc_html__('Auto-Email Full Transcript', 'mxchat'),
6618 - array($this, 'mxchat_auto_email_transcript_callback'),
6619 - 'mxchat-transcripts',
6620 - 'mxchat_transcripts_notification_section'
6621 - );
3119 + // Add settings saved message
3120 + add_action('admin_notices', array($this, 'sync_settings_notice'));
6622 3121 }
6623 3122
6624 -
6625 -/**
6626 - * Sanitize all prompts options
6627 - *
6628 - * @param array $input The unsanitized options array
6629 - * @return array The sanitized options array
6630 - */
6631 -public function sanitize_prompts_options($input) {
6632 - // Log the incoming input.
6633 - //error_log('Sanitizing inputs: ' . print_r($input, true));
6634 -
6635 - $sanitized = array();
6636 -
6637 - // Boolean options
6638 - $sanitized['mxchat_auto_sync_posts'] = isset($input['mxchat_auto_sync_posts']) ? 1 : 0;
6639 - $sanitized['mxchat_auto_sync_pages'] = isset($input['mxchat_auto_sync_pages']) ? 1 : 0;
6640 -$sanitized['mxchat_use_pinecone'] = !empty($input['mxchat_use_pinecone']) ? 1 : 0;
6641 -
6642 - // API Key: if less than 32 characters, flag as invalid.
6643 - $api_key = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? '');
6644 - if (!empty($api_key) && strlen($api_key) < 32) {
6645 - add_settings_error(
6646 - 'mxchat_prompts_options',
6647 - 'invalid_api_key',
6648 - __('The Pinecone API key appears to be invalid. Please check your API key.', 'mxchat')
6649 - );
6650 - $existing_options = get_option('mxchat_prompts_options', array());
6651 - $sanitized['mxchat_pinecone_api_key'] = $existing_options['mxchat_pinecone_api_key'] ?? '';
6652 - } else {
6653 - $sanitized['mxchat_pinecone_api_key'] = $api_key;
6654 - }
6655 -
6656 - // Environment and Index Name
6657 - $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? '');
6658 - $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? '');
6659 -
6660 - // Host: Remove protocol and validate format.
6661 - $host = sanitize_text_field($input['mxchat_pinecone_host'] ?? '');
6662 - $host = preg_replace('#^https?://#', '', $host);
6663 - //error_log('Host after removing protocol: ' . $host);
6664 - if (!empty($host)) {
6665 - if (!preg_match('/^[\w-]+\.svc\.[\w-]+\.pinecone\.io$/', $host)) {
6666 - add_settings_error(
6667 - 'mxchat_prompts_options',
6668 - 'invalid_host',
6669 - __('The Pinecone host appears to be invalid. It should look like "mxchat-vectors-zrmsquq.svc.aped-4627-b74a.pinecone.io"', 'mxchat')
6670 - );
6671 - $existing_options = get_option('mxchat_prompts_options', array());
6672 - $sanitized['mxchat_pinecone_host'] = $existing_options['mxchat_pinecone_host'] ?? '';
6673 - } else {
6674 - $sanitized['mxchat_pinecone_host'] = $host;
6675 - }
6676 - } else {
6677 - $sanitized['mxchat_pinecone_host'] = '';
6678 - }
6679 -
6680 - //error_log('Final sanitized array: ' . print_r($sanitized, true));
6681 -
6682 - return $sanitized;
6683 -}
6684 -
6685 3123 public function sync_settings_notice() {
6686 3124 // Only show notice on our plugin page
6687 3125 if (!isset($_GET['page']) || $_GET['page'] !== 'mxchat-prompts') {
6688 3126 return;
@@ -6689,148 +3127,191 @@
6689 3127 }
6690 3128
6691 3129 // Check if settings were updated
6692 3130 if (isset($_GET['settings-updated'])) {
6693 -
6694 3131 ?>
6695 3132 <div class="notice notice-success is-dismissible">
6696 3133 <p><?php esc_html_e('Sync settings updated successfully.', 'mxchat'); ?></p>
6697 - <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php esc_html_e('Dismiss this notice.', 'mxchat'); ?></span></button>
6698 3134 </div>
6699 3135 <?php
6700 -
6701 3136 }
6702 3137 }
6703 3138 // Add this sanitization function to your class
6704 3139 public function sanitize_sync_setting($input) {
6705 - return (bool)$input ? __('1', 'mxchat') : __('', 'mxchat');
3140 + return (bool)$input ? '1' : '';
6706 3141 }
6707 3142
6708 -public function mxchat_rate_limits_callback() {
3143 +
3144 +
3145 +public function mxchat_handle_activate_license() {
3146 + // Check nonce
3147 + if (!check_ajax_referer('mxchat_activate_license_nonce', 'security', false)) {
3148 + wp_send_json_error('Invalid security token');
3149 + return;
3150 + }
3151 +
3152 + // Verify user capabilities
3153 + if (!current_user_can('manage_options')) {
3154 + wp_send_json_error('Unauthorized access');
3155 + return;
3156 + }
3157 +
3158 + $license_key = isset($_POST['mxchat_activation_key']) ? sanitize_text_field($_POST['mxchat_activation_key']) : '';
3159 + $customer_email = isset($_POST['mxchat_pro_email']) ? sanitize_email($_POST['mxchat_pro_email']) : '';
3160 +
3161 + if (empty($license_key) || empty($customer_email)) {
3162 + wp_send_json_error('Email or License Key is missing');
3163 + return;
3164 + }
3165 +
3166 + $product_id = 'MxChatPRO';
3167 + $response = wp_remote_get(
3168 + add_query_arg(
3169 + array(
3170 + 'wc-api' => 'software-api',
3171 + 'request' => 'activation',
3172 + 'email' => $customer_email,
3173 + 'license_key' => $license_key,
3174 + 'product_id' => $product_id
3175 + ),
3176 + 'http://mxchat.ai/'
3177 + )
3178 + );
3179 +
3180 + if (is_wp_error($response)) {
3181 + wp_send_json_error('Activation failed due to a server error: ' . $response->get_error_message());
3182 + return;
3183 + }
3184 +
3185 + $body = wp_remote_retrieve_body($response);
3186 + $data = json_decode($body);
3187 +
3188 + if ($data && isset($data->activated) && $data->activated) {
3189 + update_option('mxchat_license_status', 'active');
3190 + update_option('mxchat_pro_email', $customer_email);
3191 + update_option('mxchat_activation_key', $license_key);
3192 + wp_send_json_success(array('message' => 'License activated successfully'));
3193 + } else {
3194 + $error_message = isset($data->error) ? $data->error : 'Activation failed';
3195 + update_option('mxchat_license_status', 'inactive');
3196 + update_option('mxchat_license_error', $error_message);
3197 + wp_send_json_error($error_message);
3198 + }
3199 +}
3200 +
3201 +public function mxchat_rate_limit_logged_in_callback() {
3202 + // Load the entire 'mxchat_options' array
6709 3203 $all_options = get_option('mxchat_options', []);
6710 3204
3205 + // Retrieve the saved rate limit or use the default value
3206 + $default_rate_limit = '100';
3207 + $selected_rate_limit = isset($all_options['rate_limit_logged_in']) ? $all_options['rate_limit_logged_in'] : $default_rate_limit;
3208 +
6711 3209 // Define available rate limits
6712 - $rate_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
3210 + $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited');
6713 3211
6714 - // Define available timeframes
6715 - $timeframes = array(
6716 - 'hourly' => __('Per Hour', 'mxchat'),
6717 - 'daily' => __('Per Day', 'mxchat'),
6718 - 'weekly' => __('Per Week', 'mxchat'),
6719 - 'monthly' => __('Per Month', 'mxchat')
6720 - );
3212 + // Output the dropdown
3213 + echo '<div class="pro-feature-wrapper active">';
3214 + echo '<select id="rate_limit_logged_in" name="rate_limit_logged_in">';
3215 + foreach ($rate_limits as $limit) {
3216 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
3217 + }
3218 + echo '</select>';
3219 + echo '<p class="description">Set the maximum number of messages a logged-in user can send within a 24-hour period.</p>';
3220 + echo '</div>';
3221 +}
6721 3222
6722 - // Get all roles plus a "logged_out" pseudo-role
6723 - $roles = wp_roles()->get_names();
6724 - $roles['logged_out'] = __('Logged Out Users', 'mxchat');
6725 3223
6726 - // Start the wrapper
6727 - echo '<div class="pro-feature-wrapper active">';
6728 - echo '<div class="mxchat-rate-limits-container">';
6729 3224
6730 - echo '<p class="description" style="margin-bottom: 20px;">' .
6731 - esc_html__('Set message limits for each user role and customize the experience when users reach those limits. You can use {limit}, {timeframe}, {count}, and {remaining} as placeholders.', 'mxchat') .
6732 - '</p>';
3225 +public function mxchat_rate_limit_logged_out_callback() {
3226 + // Load the entire 'mxchat_options' array
3227 + $all_options = get_option('mxchat_options', []);
6733 3228
6734 - // Add markdown link documentation
6735 - echo '<div class="notice notice-info inline" style="margin-bottom: 20px; padding: 10px;">';
6736 - echo '<p><strong>' . esc_html__('Markdown Links Supported:', 'mxchat') . '</strong></p>';
6737 - echo '<p>' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '</p>';
6738 - echo '<ul style="margin-left: 20px;">';
6739 - echo '<li><code>[Link text](https://example.com)</code> - Creates a clickable link</li>';
6740 - echo '<li><code>[Visit our pricing](https://example.com/pricing)</code> - Link with custom text</li>';
6741 - echo '<li><code>Plain URLs like https://example.com will also become clickable</code></li>';
6742 - echo '</ul>';
3229 + // Retrieve the saved rate limit or use the default value
3230 + $default_rate_limit = '10';
3231 + $selected_rate_limit = isset($all_options['rate_limit_logged_out']) ? $all_options['rate_limit_logged_out'] : $default_rate_limit;
3232 +
3233 + // Define available rate limits
3234 + $rate_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited');
3235 +
3236 + // Output the dropdown
3237 + echo '<div class="pro-feature-wrapper active">';
3238 + echo '<select id="rate_limit_logged_out" name="rate_limit_logged_out">';
3239 + foreach ($rate_limits as $limit) {
3240 + echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_rate_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
3241 + }
3242 + echo '</select>';
3243 + echo '<p class="description">Set the maximum number of messages a logged-out user can send within a 24-hour period.</p>';
6743 3244 echo '</div>';
3245 +}
6744 3246
6745 - // Output the controls for each role
6746 - foreach ($roles as $role_id => $role_name) {
6747 - // Get saved options or defaults
6748 - $default_limit = ($role_id === 'logged_out') ? '10' : '100';
6749 - $default_timeframe = 'daily';
6750 - $default_message = __('Rate limit exceeded. Please try again later.', 'mxchat');
3247 +public function mxchat_rate_limit_message_callback() {
3248 + // Load the entire 'mxchat_options' array
3249 + $all_options = get_option('mxchat_options', []);
6751 3250
6752 - $selected_limit = isset($all_options['rate_limits'][$role_id]['limit'])
6753 - ? $all_options['rate_limits'][$role_id]['limit']
6754 - : $default_limit;
3251 + // Retrieve the saved message or use the default value
3252 + $default_message = 'Rate limit exceeded. Please try again later.';
3253 + $rate_limit_message = isset($all_options['rate_limit_message']) ? $all_options['rate_limit_message'] : $default_message;
6755 3254
6756 - $selected_timeframe = isset($all_options['rate_limits'][$role_id]['timeframe'])
6757 - ? $all_options['rate_limits'][$role_id]['timeframe']
6758 - : $default_timeframe;
3255 + // Output the textarea
3256 + echo '<div class="pro-feature-wrapper active">';
3257 + printf(
3258 + '<textarea id="rate_limit_message" name="rate_limit_message" rows="3" cols="50">%s</textarea>',
3259 + esc_textarea($rate_limit_message)
3260 + );
3261 + echo '<p class="description">This message will be displayed when a user exceeds the rate limit.</p>';
3262 + echo '</div>';
3263 +}
6759 3264
6760 - $custom_message = isset($all_options['rate_limits'][$role_id]['message'])
6761 - ? $all_options['rate_limits'][$role_id]['message']
6762 - : $default_message;
6763 3265
6764 - // Output the row
6765 - echo '<div class="mxchat-rate-limit-row mxchat-autosave-section">';
3266 +public function mxchat_enable_woocommerce_integration_callback() {
3267 + // Load from mxchat_options array
3268 + $options = get_option('mxchat_options', []);
6766 3269
6767 - // Role label
6768 - echo '<div class="mxchat-rate-limit-role">' . esc_html($role_name) . '</div>';
3270 + // Get WooCommerce integration status with backwards compatibility
3271 + $woo_integration = isset($options['enable_woocommerce_integration'])
3272 + ? $options['enable_woocommerce_integration']
3273 + : '';
6769 3274
6770 - // Controls section
6771 - echo '<div class="mxchat-rate-limit-controls-wrapper">';
3275 + // Support both old ('1') and new ('on') values
3276 + $checked = ($woo_integration === 'on' || $woo_integration === '1') ? 'checked' : '';
6772 3277
6773 - // Rate limit and timeframe controls
6774 - echo '<div class="mxchat-rate-limit-controls">';
3278 + // Check if the feature is activated (paid feature)
3279 + $disabled = $this->is_activated ? '' : 'disabled';
3280 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
6775 3281
6776 - // Limit dropdown
6777 - echo '<div>';
6778 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_limit">' . esc_html__('Limit:', 'mxchat') . '</label>';
6779 - echo '<select
6780 - id="rate_limits_' . esc_attr($role_id) . '_limit"
6781 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][limit]"
6782 - class="mxchat-autosave-field">';
6783 - foreach ($rate_limits as $limit) {
6784 - echo '<option value="' . esc_attr($limit) . '" ' . selected($selected_limit, $limit, false) . '>' . esc_html($limit) . '</option>';
6785 - }
6786 - echo '</select>';
6787 - echo '</div>';
3282 + echo '<div class="' . esc_attr($class) . '">';
6788 3283
6789 - // Timeframe dropdown
6790 - echo '<div>';
6791 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_timeframe">' . esc_html__('Timeframe:', 'mxchat') . '</label>';
6792 - echo '<select
6793 - id="rate_limits_' . esc_attr($role_id) . '_timeframe"
6794 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][timeframe]"
6795 - class="mxchat-autosave-field">';
6796 - foreach ($timeframes as $value => $label) {
6797 - echo '<option value="' . esc_attr($value) . '" ' . selected($selected_timeframe, $value, false) . '>' . esc_html($label) . '</option>';
6798 - }
6799 - echo '</select>';
6800 - echo '</div>';
3284 + echo '<label class="toggle-switch">';
3285 + echo sprintf(
3286 + '<input type="checkbox" id="enable_woocommerce_integration" name="enable_woocommerce_integration" value="on" %s %s />',
3287 + esc_attr($checked),
3288 + esc_attr($disabled)
3289 + );
3290 + echo '<span class="slider"></span>';
3291 + echo '</label>';
6801 3292
6802 - echo '</div>'; // End controls
3293 + echo '<p class="description">Automatically syncs new product additions, updates, and removals to the knowledge base. For existing products, submit your product sitemap in the Knowledge Base section to add them initially.</p>';
6803 3294
6804 - // Custom message textarea
6805 - echo '<div class="mxchat-rate-limit-message">';
6806 - echo '<label for="rate_limits_' . esc_attr($role_id) . '_message">' . esc_html__('Custom Message:', 'mxchat') . '</label>';
6807 - echo '<textarea
6808 - id="rate_limits_' . esc_attr($role_id) . '_message"
6809 - name="mxchat_options[rate_limits][' . esc_attr($role_id) . '][message]"
6810 - class="mxchat-autosave-field"
6811 - placeholder="' . esc_attr__('Enter custom message when rate limit is exceeded', 'mxchat') . '">' .
6812 - esc_textarea($custom_message) .
6813 - '</textarea>';
6814 - echo '<p class="description">' .
6815 - esc_html__('Example: Rate limit reached! [Visit our pricing page](https://example.com/pricing) to upgrade.', 'mxchat') .
6816 - '</p>';
6817 - echo '</div>'; // End message
3295 + // Pro feature overlay for non-activated users
3296 + if (!$this->is_activated) {
3297 + echo '<div class="pro-feature-overlay">';
3298 + echo '<a href="https://mxchat.ai/" target="_blank">';
3299 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3300 + echo '</a>';
3301 + echo '</div>';
3302 + }
6818 3303
6819 - echo '</div>'; // End controls wrapper
3304 + echo '</div>';
3305 +}
6820 3306
6821 - echo '</div>'; // End row
6822 - }
6823 3307
6824 - echo '</div>'; // End container
6825 3308
6826 - echo '</div>'; // End pro-feature-wrapper
6827 -}
6828 3309
6829 -private function mxchat_add_option_field($id, $title, $callback = '') {
3310 + private function mxchat_add_option_field($id, $title, $callback = '') {
6830 3311 add_settings_field(
6831 3312 $id,
6832 - __($title, 'mxchat'),
3313 + $title,
6833 3314 $callback ? array($this, $callback) : array($this, $id . '_callback'),
6834 3315 'mxchat-max',
6835 3316 'mxchat_setting_section_id',
6836 3317 $id === 'model' ? ['label_for' => 'model'] : []
@@ -6836,228 +3317,166 @@
6836 3317 $id === 'model' ? ['label_for' => 'model'] : []
6837 3318 );
6838 3319 }
6839 3320
6840 -// API Keys Section Callback
6841 -public function mxchat_api_keys_section_callback() {
6842 - echo '<p>' . esc_html__('Manage all your API keys in one place. Add the API keys for the services you want to use with your chatbot.', 'mxchat') . '</p>';
6843 -}
6844 -
6845 -// OpenAI API Key
6846 3321 public function api_key_callback() {
3322 + // Retrieve from your stored 'api_key' in the mxchat_options array
6847 3323 $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : '';
6848 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
6849 3324
6850 - echo '<div class="api-key-wrapper">';
6851 - echo '<input type="text" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6852 - echo '<button type="button" id="toggleApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6853 - echo '<p class="description">' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '</p>';
6854 - echo '</div>';
3325 + // Notice we changed the name to "api_key" (no array notation).
3326 + echo '<input type="password" id="api_key" name="api_key" value="' . $apiKey . '" class="regular-text" />';
3327 + echo '<button type="button" id="toggleApiKeyVisibility">Show</button>';
3328 + echo '<p class="description">The OpenAI API key is required even when using other models as it is used for vector embedding functionality.</p>';
6855 3329 }
6856 3330
6857 -// X.AI API Key
3331 +
3332 +
3333 +
6858 3334 public function xai_api_key_callback() {
3335 + // Check if the feature is activated (paid feature)
3336 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
3337 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
3338 +
3339 + // Retrieve the X.AI API key value
6859 3340 $xaiApiKey = isset($this->options['xai_api_key']) ? esc_attr($this->options['xai_api_key']) : '';
6860 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
6861 3341
6862 - echo '<div class="api-key-wrapper">';
6863 - echo '<input type="text" id="xai_api_key" name="xai_api_key" value="' . $xaiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6864 - echo '<button type="button" id="toggleXaiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6865 - echo '<p class="description">' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '</p>';
6866 - echo '</div>';
6867 -}
6868 -// Claude API Key
6869 -public function claude_api_key_callback() {
6870 - $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
6871 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3342 + // Render the input field for the X.AI API key
3343 + echo '<div class="' . esc_attr($class) . '">';
3344 + printf(
3345 + '<input type="password" id="xai_api_key" name="xai_api_key" value="%s" class="regular-text" %s />',
3346 + $xaiApiKey,
3347 + $disabled
3348 + );
3349 + echo '<button type="button" id="toggleXaiApiKeyVisibility">Show</button>';
6872 3350
6873 - echo '<div class="api-key-wrapper">';
6874 - echo '<input type="text" id="claude_api_key" name="claude_api_key" value="' . $claudeApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6875 - echo '<button type="button" id="toggleClaudeApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6876 - echo '<p class="description">' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '</p>';
3351 + // If the feature is not activated, show the overlay with a "Pro Only" message
3352 + if (!$this->is_activated) {
3353 + echo '<div class="pro-feature-overlay">';
3354 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3355 + echo '</div>';
3356 + }
3357 +
6877 3358 echo '</div>';
6878 3359 }
6879 3360
6880 -// DeepSeek API Key
6881 -public function deepseek_api_key_callback() {
6882 - $apiKey = isset($this->options['deepseek_api_key']) ? esc_attr($this->options['deepseek_api_key']) : '';
6883 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
6884 3361
6885 - echo '<div class="api-key-wrapper">';
6886 - echo '<input type="text" id="deepseek_api_key" name="deepseek_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6887 - echo '<button type="button" id="toggleDeepSeekApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6888 - echo '<p class="description">' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '</p>';
6889 - echo '</div>';
6890 -}
3362 +public function claude_api_key_callback() {
3363 + // Check if the feature is activated (paid feature)
3364 + $disabled = $this->is_activated ? '' : 'disabled'; // Disable input if not activated
3365 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive'; // CSS class to style the wrapper based on activation status
6891 3366
6892 -// Gemini API Key
6893 -public function gemini_api_key_callback() {
6894 - $geminiApiKey = isset($this->options['gemini_api_key']) ? esc_attr($this->options['gemini_api_key']) : '';
6895 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3367 + // Retrieve the Claude API key value
3368 + $claudeApiKey = isset($this->options['claude_api_key']) ? esc_attr($this->options['claude_api_key']) : '';
6896 3369
6897 - echo '<div class="api-key-wrapper">';
6898 - echo '<input type="text" id="gemini_api_key" name="gemini_api_key" value="' . $geminiApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6899 - echo '<button type="button" id="toggleGeminiApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6900 - echo '<p class="description">' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '</p>';
6901 - echo '</div>';
6902 -}
3370 + // Render the input field for the Claude API key
3371 + echo '<div class="' . esc_attr($class) . '">';
3372 + printf(
3373 + '<input type="password" id="claude_api_key" name="claude_api_key" value="%s" class="regular-text" %s />',
3374 + $claudeApiKey,
3375 + $disabled
3376 + );
3377 + echo '<button type="button" id="toggleClaudeApiKeyVisibility">Show</button>';
6903 3378
3379 + // If the feature is not activated, show the overlay with a "Pro Only" message
3380 + if (!$this->is_activated) {
3381 + echo '<div class="pro-feature-overlay">';
3382 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3383 + echo '</div>';
3384 + }
6904 3385
6905 -// OpenRouter API Key
6906 -public function openrouter_api_key_callback() {
6907 - $openrouterApiKey = isset($this->options['openrouter_api_key']) ? esc_attr($this->options['openrouter_api_key']) : '';
6908 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
6909 -
6910 - echo '<div class="api-key-wrapper">';
6911 - echo '<input type="text" id="openrouter_api_key" name="openrouter_api_key" value="' . $openrouterApiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6912 - echo '<button type="button" id="toggleOpenRouterApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
6913 - echo '<p class="description">' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '</p>';
6914 3386 echo '</div>';
6915 3387 }
6916 3388
6917 -// Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.
6918 -public function custom_provider_callback() {
6919 - $base_url = isset($this->options['custom_provider_base_url']) ? esc_attr($this->options['custom_provider_base_url']) : '';
6920 - $api_key = isset($this->options['custom_provider_api_key']) ? esc_attr($this->options['custom_provider_api_key']) : '';
6921 - $model_name = isset($this->options['custom_provider_model']) ? esc_attr($this->options['custom_provider_model']) : '';
6922 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? esc_attr($this->options['custom_provider_auth_scheme']) : 'bearer';
6923 - $api_version = isset($this->options['custom_provider_api_version']) ? esc_attr($this->options['custom_provider_api_version']) : '';
6924 - $use_embed = !empty($this->options['custom_provider_for_embeddings']) && $this->options['custom_provider_for_embeddings'] === 'on';
6925 - $use_images = !empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on';
6926 - $embed_model = isset($this->options['custom_provider_embedding_model']) ? esc_attr($this->options['custom_provider_embedding_model']) : '';
6927 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
6928 - $test_nonce = wp_create_nonce('mxchat_test_custom_provider');
3389 +public function mxchat_woocommerce_consumer_key_callback() {
3390 + // Load the entire 'mxchat_options' array
3391 + $all_options = get_option('mxchat_options', []);
6929 3392
6930 - echo '<style>
6931 - .mxchat-cp { max-width: 680px; }
6932 - .mxchat-cp .mxchat-cp-intro { margin: 0 0 16px; color: #50575e; font-size: 13px; line-height: 1.5; }
6933 - .mxchat-cp .mxchat-cp-row { display: block; margin: 0 0 18px; }
6934 - .mxchat-cp .mxchat-cp-row > label { display: block; font-weight: 600; margin: 0 0 6px; color: #1d2327; font-size: 13px; }
6935 - .mxchat-cp .mxchat-cp-row > input[type="text"],
6936 - .mxchat-cp .mxchat-cp-row > input[type="password"],
6937 - .mxchat-cp .mxchat-cp-row > select { display: block; width: 100%; max-width: 480px; margin: 0; }
6938 - .mxchat-cp .mxchat-cp-row > .description { display: block; margin: 6px 0 0; color: #646970; font-size: 12px; line-height: 1.5; max-width: 480px; }
6939 - .mxchat-cp .mxchat-cp-test { margin-top: 4px; padding-top: 14px; border-top: 1px solid #e5e7eb; }
6940 - .mxchat-cp .mxchat-cp-test .mxchat-cp-test-status { display: inline-block; margin-left: 10px; vertical-align: middle; font-size: 13px; }
6941 - </style>';
3393 + // Retrieve the WooCommerce consumer key or set a default
3394 + $consumer_key = isset($all_options['woocommerce_consumer_key']) ? $all_options['woocommerce_consumer_key'] : '';
6942 3395
6943 - echo '<div class="api-key-wrapper mxchat-cp">';
6944 - echo '<p class="mxchat-cp-intro">' . esc_html__('Point MxChat at any OpenAI-compatible /v1/chat/completions endpoint: Ollama, LM Studio, vLLM, llama.cpp, LocalAI, Azure OpenAI, etc. Then select "Custom (OpenAI-compatible)" in the model picker.', 'mxchat') . '</p>';
3396 + // Check if the feature is activated (paid feature)
3397 + $disabled = $this->is_activated ? '' : 'disabled';
3398 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
6945 3399
6946 - echo '<div class="mxchat-cp-row">';
6947 - echo '<label for="custom_provider_base_url">' . esc_html__('Base URL', 'mxchat') . '</label>';
6948 - echo '<input type="text" id="custom_provider_base_url" name="custom_provider_base_url" value="' . $base_url . '" class="regular-text mxchat-autosave-field" placeholder="http://localhost:11434/v1" autocomplete="off" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6949 - echo '<p class="description">' . esc_html__('Examples: Ollama http://localhost:11434/v1 · LM Studio http://localhost:1234/v1 · vLLM http://gpu:8000/v1 · Azure https://<resource>.openai.azure.com/openai/deployments/<deployment>', 'mxchat') . '</p>';
6950 - echo '</div>';
3400 + echo '<div class="' . esc_attr($class) . '">';
6951 3401
6952 - echo '<div class="mxchat-cp-row">';
6953 - echo '<label for="custom_provider_api_key">' . esc_html__('API Key (optional)', 'mxchat') . '</label>';
6954 - echo '<input type="password" id="custom_provider_api_key" name="custom_provider_api_key" value="' . $api_key . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
6955 - echo '<p class="description">' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '</p>';
6956 - echo '</div>';
3402 + // Render the input field
3403 + printf(
3404 + '<input type="text" id="woocommerce_consumer_key" name="woocommerce_consumer_key" value="%s" class="regular-text" %s />',
3405 + esc_attr($consumer_key),
3406 + esc_attr($disabled)
3407 + );
6957 3408
6958 - echo '<div class="mxchat-cp-row">';
6959 - echo '<label for="custom_provider_model">' . esc_html__('Model Name', 'mxchat') . '</label>';
6960 - echo '<input type="text" id="custom_provider_model" name="custom_provider_model" value="' . $model_name . '" class="regular-text mxchat-autosave-field" placeholder="llama3.2" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
6961 - echo '<p class="description">' . esc_html__('The model identifier the upstream server expects (e.g. llama3.2, mistral, gpt-oss). For Azure this is the deployment ID — leave empty if the Base URL already includes /deployments/<deployment>.', 'mxchat') . '</p>';
6962 - echo '</div>';
3409 + // Description for the input field
3410 + echo '<p class="description">Enter your WooCommerce consumer key for integration.</p>';
6963 3411
6964 - echo '<div class="mxchat-cp-row">';
6965 - echo '<label for="custom_provider_auth_scheme">' . esc_html__('Auth Scheme', 'mxchat') . '</label>';
6966 - echo '<select id="custom_provider_auth_scheme" name="custom_provider_auth_scheme" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
6967 - echo '<option value="bearer"' . selected($auth_scheme, 'bearer', false) . '>' . esc_html__('Authorization: Bearer (OpenAI / Ollama / vLLM / LM Studio)', 'mxchat') . '</option>';
6968 - echo '<option value="api-key"' . selected($auth_scheme, 'api-key', false) . '>' . esc_html__('api-key header (Azure OpenAI)', 'mxchat') . '</option>';
6969 - echo '</select>';
6970 - echo '<p class="description">' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '</p>';
3412 + // Pro feature overlay for non-activated users
3413 + if (!$this->is_activated) {
3414 + echo '<div class="pro-feature-overlay">';
3415 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
3416 + echo '</div>';
3417 + }
3418 +
6971 3419 echo '</div>';
3420 +}
6972 3421
6973 - echo '<div class="mxchat-cp-row">';
6974 - echo '<label for="custom_provider_api_version">' . esc_html__('API Version (Azure only)', 'mxchat') . '</label>';
6975 - echo '<input type="text" id="custom_provider_api_version" name="custom_provider_api_version" value="' . $api_version . '" class="regular-text mxchat-autosave-field" placeholder="2024-08-01-preview" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
6976 - echo '<p class="description">' . esc_html__('Appended as ?api-version=... on the request URL. Leave empty for non-Azure providers.', 'mxchat') . '</p>';
6977 - echo '</div>';
6978 3422
6979 - // Extended-use checkboxes — opt-in routing of other dispatcher paths through the custom provider.
6980 - echo '<div class="mxchat-cp-row">';
6981 - echo '<label style="font-weight:600; display:block; margin:0 0 6px; color:#1d2327; font-size:13px;">' . esc_html__('Extended routing (opt-in)', 'mxchat') . '</label>';
6982 - echo '<label style="display:block; margin:0 0 6px; font-weight:400;"><input type="checkbox" id="custom_provider_for_embeddings" name="custom_provider_for_embeddings" value="on"' . checked($use_embed, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for embeddings', 'mxchat') . '</label>';
6983 - echo '<label style="display:block; margin:0 0 0; font-weight:400;"><input type="checkbox" id="custom_provider_for_images" name="custom_provider_for_images" value="on"' . checked($use_images, true, false) . ' class="mxchat-autosave-field" data-nonce="' . $nonce . '" /> ' . esc_html__('Use custom provider for image generation', 'mxchat') . '</label>';
6984 - echo '<p class="description">' . esc_html__('When off, embeddings and image generation continue to use OpenAI (current behavior). Turn on only if your endpoint exposes OpenAI-compatible /embeddings or /images/generations routes (e.g. Ollama, vLLM, LocalAI).', 'mxchat') . '</p>';
6985 - echo '</div>';
3423 +public function mxchat_woocommerce_consumer_secret_callback() {
3424 + // Get value with fallback
3425 + $consumer_secret = isset($this->options['woocommerce_consumer_secret'])
3426 + ? esc_attr($this->options['woocommerce_consumer_secret'])
3427 + : '';
6986 3428
6987 - echo '<div class="mxchat-cp-row">';
6988 - echo '<label for="custom_provider_embedding_model">' . esc_html__('Custom Embedding Model', 'mxchat') . '</label>';
6989 - echo '<input type="text" id="custom_provider_embedding_model" name="custom_provider_embedding_model" value="' . $embed_model . '" class="regular-text mxchat-autosave-field" placeholder="nomic-embed-text" autocomplete="off" data-lpignore="true" data-nonce="' . $nonce . '" />';
6990 - echo '<p class="description">' . esc_html__('Only used when "Use custom provider for embeddings" is on. The embedding model name is separate from the chat model name above (e.g. Ollama embedding models: nomic-embed-text, mxbai-embed-large). Leave blank to fall back to the chat model name.', 'mxchat') . '</p>';
6991 - echo '</div>';
3429 + // Check if the feature is activated (paid feature)
3430 + $disabled = $this->is_activated ? '' : 'disabled';
3431 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
6992 3432
6993 - echo '<div class="mxchat-cp-test">';
6994 - echo '<button type="button" class="button" id="mxchat-test-custom-provider" data-nonce="' . $test_nonce . '">' . esc_html__('Test Connection', 'mxchat') . '</button>';
6995 - echo '<span id="mxchat-test-custom-provider-result" class="mxchat-cp-test-status"></span>';
6996 - echo '</div>';
3433 + echo '<div class="' . esc_attr($class) . '">';
6997 3434
6998 - echo '<script>(function(){
6999 - var btn = document.getElementById("mxchat-test-custom-provider");
7000 - if (!btn || btn._wired) { return; } btn._wired = true;
7001 - btn.addEventListener("click", function(){
7002 - var out = document.getElementById("mxchat-test-custom-provider-result");
7003 - out.textContent = "' . esc_js(__('Testing...', 'mxchat')) . '";
7004 - out.style.color = "#646970";
7005 - var fd = new FormData();
7006 - fd.append("action", "mxchat_test_custom_provider");
7007 - fd.append("_wpnonce", btn.getAttribute("data-nonce"));
7008 - fetch(ajaxurl, { method:"POST", credentials:"same-origin", body: fd })
7009 - .then(function(r){ return r.json(); })
7010 - .then(function(j){
7011 - if (j && j.success) {
7012 - out.textContent = "✓ " + (j.data && j.data.message ? j.data.message : "' . esc_js(__('OK', 'mxchat')) . '");
7013 - out.style.color = "#00a32a";
7014 - } else {
7015 - out.textContent = "⚠ " + (j && j.data && j.data.message ? j.data.message : "' . esc_js(__('Failed', 'mxchat')) . '");
7016 - out.style.color = "#d63638";
7017 - }
7018 - })
7019 - .catch(function(){
7020 - out.textContent = "⚠ ' . esc_js(__('Request failed', 'mxchat')) . '";
7021 - out.style.color = "#d63638";
7022 - });
7023 - });
7024 - })();</script>';
3435 + // Output the password input
3436 + echo sprintf(
3437 + '<input type="password"
3438 + id="woocommerce_consumer_secret"
3439 + name="woocommerce_consumer_secret"
3440 + value="%s"
3441 + class="regular-text"
3442 + %s />',
3443 + $consumer_secret,
3444 + esc_attr($disabled)
3445 + );
7025 3446
7026 - echo '</div>';
7027 -}
3447 + // Add show/hide button
3448 + echo '<button type="button" id="toggleWooCommerceSecretVisibility">Show</button>';
7028 3449
7029 -// Voyage API Key
7030 -public function voyage_api_key_callback() {
7031 - $apiKey = isset($this->options['voyage_api_key']) ? esc_attr($this->options['voyage_api_key']) : '';
7032 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
3450 + // Pro feature overlay
3451 + if (!$this->is_activated) {
3452 + echo '<div class="pro-feature-overlay">';
3453 + echo '<a href="https://mxchat.ai/" target="_blank">';
3454 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3455 + echo '</a>';
3456 + echo '</div>';
3457 + }
7033 3458
7034 - echo '<div class="api-key-wrapper">';
7035 - echo '<input type="text" id="voyage_api_key" name="voyage_api_key" value="' . $apiKey . '" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="' . $nonce . '" />';
7036 - echo '<button type="button" id="toggleVoyageAPIKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
7037 - echo '<p class="description">' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '</p>';
7038 3459 echo '</div>';
7039 3460 }
7040 -
7041 3461 public function mxchat_loops_api_key_callback() {
3462 + // Support both old and new format
7042 3463 $loops_api_key = isset($this->options['loops_api_key']) ? esc_attr($this->options['loops_api_key']) : '';
7043 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7044 3464
7045 3465 echo '<div class="api-key-wrapper">';
7046 3466 echo sprintf(
7047 - '<input type="text" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
7048 - $loops_api_key,
7049 - $nonce
3467 + '<input type="password" id="loops_api_key" name="loops_api_key" value="%s" class="regular-text" />',
3468 + $loops_api_key
7050 3469 );
7051 - echo '<button type="button" id="toggleLoopsApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
3470 + echo '<button type="button" id="toggleLoopsApiKeyVisibility">Show</button>';
7052 3471 echo '</div>';
7053 - echo '<p class="description">' . esc_html__('Required for Loops email integration. Get your API key from Loops.so', 'mxchat') . '</p>';
3472 + echo '<p class="description">Enter your Loops API Key here. (See FAQ for details)</p>';
7054 3473 }
3474 +
7055 3475 public function mxchat_loops_mailing_list_callback() {
7056 3476 // Add error handling and type checking
7057 3477 $loops_api_key = '';
7058 3478 $selected_list = '';
7059 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7060 3479
7061 3480 // Safely get the API key
7062 3481 if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) {
7063 3482 $loops_api_key = $this->options['loops_api_key'];
@@ -7070,14 +3489,9 @@
7070 3489
7071 3490 if (!empty($loops_api_key)) {
7072 3491 $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key);
7073 3492 if (is_array($lists) && !empty($lists)) {
7074 - echo '<div class="mxchat-field-wrapper">';
7075 - echo '<select id="loops_mailing_list" name="loops_mailing_list" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
7076 -
7077 - // Add a default "Select a list" option
7078 - echo '<option value="" ' . selected($selected_list, '', false) . '>' . esc_html__('Select a list', 'mxchat') . '</option>';
7079 -
3493 + echo '<select id="loops_mailing_list" name="loops_mailing_list">';
7080 3494 foreach ($lists as $list) {
7081 3495 if (is_array($list) && isset($list['id']) && isset($list['name'])) {
7082 3496 echo sprintf(
7083 3497 '<option value="%s" %s>%s</option>',
@@ -7087,56 +3501,47 @@
7087 3501 );
7088 3502 }
7089 3503 }
7090 3504 echo '</select>';
7091 - echo '</div>';
7092 - echo '<p class="description">' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '</p>';
7093 3505 } else {
7094 - echo '<p class="description">' . esc_html__('No lists found. Please verify your API Key.', 'mxchat') . '</p>';
3506 + echo '<p class="description">No lists found. Please verify your API Key.</p>';
7095 3507 }
7096 3508 } else {
7097 - echo '<p class="description">' . esc_html__('Enter a valid Loops API Key to load mailing lists.', 'mxchat') . '</p>';
3509 + echo '<p class="description">Enter a valid Loops API Key to load mailing lists.</p>';
7098 3510 }
7099 3511 }
7100 3512 public function mxchat_triggered_phrase_response_callback() {
7101 - $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat');
3513 + $default_response = 'Would you like to join our mailing list? Please provide your email below.';
7102 3514 $triggered_response = isset($this->options['triggered_phrase_response'])
7103 3515 ? $this->options['triggered_phrase_response']
7104 3516 : $default_response;
7105 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7106 3517
7107 - echo '<div class="mxchat-field-wrapper">';
7108 3518 echo sprintf(
7109 - '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7110 - $nonce,
3519 + '<textarea id="triggered_phrase_response" name="triggered_phrase_response" rows="3" cols="50">%s</textarea>',
7111 3520 esc_textarea($triggered_response)
7112 3521 );
7113 - echo '</div>';
7114 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '</p>';
3522 + echo '<p class="description">Enter the chatbot response when a trigger keyword is detected, prompting the user to share their email.</p>';
7115 3523 }
7116 3524
7117 3525 public function mxchat_email_capture_response_callback() {
7118 - $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
3526 + $default_response = 'Thank you for providing your email! You\'ve been added to our list.';
7119 3527 $email_capture_response = isset($this->options['email_capture_response'])
7120 3528 ? $this->options['email_capture_response']
7121 3529 : $default_response;
7122 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
7123 3530
7124 - echo '<div class="mxchat-field-wrapper">';
7125 3531 echo sprintf(
7126 - '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50" class="mxchat-autosave-field" data-nonce="%s">%s</textarea>',
7127 - $nonce,
3532 + '<textarea id="email_capture_response" name="email_capture_response" rows="3" cols="50">%s</textarea>',
7128 3533 esc_textarea($email_capture_response)
7129 3534 );
7130 - echo '</div>';
7131 - echo '<p class="description">' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '</p>';
3535 + echo '<p class="description">Enter the message to send when a user provides their email.</p>';
7132 3536 }
3537 +
7133 3538 public function mxchat_pre_chat_message_callback() {
7134 3539 // Load the entire 'mxchat_options' array
7135 3540 $all_options = get_option('mxchat_options', []);
7136 3541
7137 3542 // Retrieve the saved message or use the default value
7138 - $default_message = __('Hey there! Ask me anything!', 'mxchat');
3543 + $default_message = 'Hey there! Ask me anything!';
7139 3544 $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message;
7140 3545
7141 3546 // Output the textarea
7142 3547 printf(
@@ -7142,164 +3547,56 @@
7142 3547 printf(
7143 3548 '<textarea id="pre_chat_message" name="pre_chat_message" rows="5" cols="50">%s</textarea>',
7144 3549 esc_textarea($pre_chat_message)
7145 3550 );
3551 + echo '<p class="description">Set the message displayed to users before they start a chat. Use this to provide a friendly greeting or instructions.</p>';
7146 3552 }
7147 3553
3554 +
3555 +
7148 3556 // Callback for AI Instructions textarea
7149 3557 public function system_prompt_instructions_callback() {
7150 3558 // Retrieve the current value of the system prompt instructions
7151 3559 $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : '';
3560 +
7152 3561 // Render the textarea field
7153 3562 printf(
7154 3563 '<textarea id="system_prompt_instructions" name="system_prompt_instructions" rows="5" cols="50">%s</textarea>',
7155 3564 $instructions
7156 3565 );
7157 - // Personalization hint
7158 - echo '<p class="description" style="margin-top: 8px;">';
7159 - echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '<br>';
7160 - echo '<code style="font-size: 12px;">' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '</code>';
7161 - echo '</p>';
7162 - // Sample instructions button
7163 - echo '<div class="mxchat-instructions-container">';
7164 - echo '<button type="button" class="mxchat-instructions-btn" id="mxchatViewSampleBtn">';
7165 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7166 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7167 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7168 - echo '</svg>';
7169 - echo esc_html__('View Sample Instructions', 'mxchat');
7170 - echo '</button>';
7171 - echo '</div>';
7172 3566
7173 - // Add modal to WordPress admin footer instead of inline
7174 - add_action('admin_footer', array($this, 'render_sample_instructions_modal'));
3567 + // Provide a helpful description
3568 + echo '<p class="description">Provide system-level instructions for the AI to guide its behavior. Be clear and concise for better results.</p>';
7175 3569 }
7176 3570
7177 -// New method to render modal in admin footer
7178 -public function render_sample_instructions_modal() {
7179 - static $modal_rendered = false;
7180 - if ($modal_rendered) return; // Prevent duplicate modals
7181 - $modal_rendered = true;
7182 3571
7183 - echo '<div class="mxchat-instructions-modal-overlay" id="mxchatSampleModal">';
7184 - echo '<div class="mxchat-instructions-modal-content">';
7185 - echo '<div class="mxchat-instructions-modal-header">';
7186 - echo '<h3 class="mxchat-instructions-modal-title">';
7187 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7188 - echo '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>';
7189 - echo '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>';
7190 - echo '</svg>';
7191 - echo esc_html__('Sample AI Instructions', 'mxchat');
7192 - echo '</h3>';
7193 - echo '<button type="button" class="mxchat-instructions-modal-close" id="mxchatModalClose">';
7194 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7195 - echo '<line x1="18" y1="6" x2="6" y2="18"/>';
7196 - echo '<line x1="6" y1="6" x2="18" y2="18"/>';
7197 - echo '</svg>';
7198 - echo '</button>';
7199 - echo '</div>';
7200 - echo '<div class="mxchat-instructions-modal-body">';
7201 - echo '<div class="mxchat-instructions-content">';
7202 - echo esc_html('You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines:
7203 -
7204 -# Response Style - CRITICALLY IMPORTANT
7205 -- MAXIMUM LENGTH: 1-3 short sentences per response
7206 -- Ultra-concise: Get straight to the answer with no filler
7207 -- No introductions like "Sure!" or "I\'d be happy to help"
7208 -- No phrases like "based on my knowledge" or "according to information"
7209 -- No explanatory text before giving the answer
7210 -- No summaries or repetition
7211 -- Hyperlink all URLs
7212 -- Respond in user\'s language
7213 -- Minor chit chat or conversation is okay, but try to keep it focused on [insert topic]
7214 -
7215 -# Knowledge Base Requirements - PREVENT HALLUCINATIONS
7216 -- ONLY answer using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters
7217 -- If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately."
7218 -- NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information
7219 -- When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing
7220 -- Better to admit insufficient information than provide inaccurate answers');
7221 - echo '</div>';
7222 - echo '<button type="button" class="mxchat-instructions-copy-btn" id="mxchatCopyBtn">';
7223 - echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">';
7224 - echo '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>';
7225 - echo '<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>';
7226 - echo '</svg>';
7227 - echo esc_html__('Copy Instructions', 'mxchat');
7228 - echo '</button>';
7229 - echo '</div>';
7230 - echo '<div class="mxchat-instructions-modal-footer">';
7231 - echo '<button type="button" class="mxchat-instructions-btn-secondary" id="mxchatCloseBtn">' . esc_html__('Close', 'mxchat') . '</button>';
7232 - echo '</div>';
7233 - echo '</div>';
7234 - echo '</div>';
7235 -}
7236 -
7237 -
7238 3572 public function mxchat_model_callback() {
7239 3573 // Define available models grouped by provider
7240 3574 $models = array(
7241 - esc_html__('OpenRouter (100+ Models)', 'mxchat') => array(
7242 - 'openrouter' => esc_html__('OpenRouter - Select after entering API key', 'mxchat'),
3575 + 'X.AI Models' => array(
3576 + 'grok-beta' => 'grok-beta (Early Beta)',
3577 + 'grok-2' => 'Grok 2'
7243 3578 ),
7244 - esc_html__('Google Gemini Models', 'mxchat') => array(
7245 - 'gemini-3-pro-preview' => esc_html__('Gemini 3 Pro (Most Intelligent, Multimodal)', 'mxchat'),
7246 - 'gemini-3-flash-preview' => esc_html__('Gemini 3 Flash (Balanced Speed & Scale)', 'mxchat'),
7247 - 'gemini-2.5-pro' => esc_html__('Gemini 2.5 Pro (Advanced Thinking)', 'mxchat'),
7248 - 'gemini-2.5-flash' => esc_html__('Gemini 2.5 Flash (Best Price-Performance)', 'mxchat'),
7249 - 'gemini-2.5-flash-lite' => esc_html__('Gemini 2.5 Flash-Lite (Ultra Fast)', 'mxchat'),
7250 - 'gemini-2.0-flash' => esc_html__('Gemini 2.0 Flash (Deprecated Mar 2026)', 'mxchat'),
7251 - 'gemini-2.0-flash-lite' => esc_html__('Gemini 2.0 Flash-Lite (Deprecated Mar 2026)', 'mxchat'),
7252 - 'gemini-1.5-pro' => esc_html__('Gemini 1.5 Pro (Deprecated Sep 2025)', 'mxchat'),
7253 - 'gemini-1.5-flash' => esc_html__('Gemini 1.5 Flash (Deprecated Sep 2025)', 'mxchat'),
3579 + 'Claude Models' => array(
3580 + 'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet (Most Intelligent)',
3581 + 'claude-3-opus-20240229' => 'Claude 3 Opus (Highly Complex Tasks)',
3582 + 'claude-3-sonnet-20240229' => 'Claude 3 Sonnet (Balanced)',
3583 + 'claude-3-haiku-20240307' => 'Claude 3 Haiku (Fastest)'
7254 3584 ),
7255 - esc_html__('X.AI Models', 'mxchat') => array(
7256 - 'grok-3-beta' => esc_html__('Grok-3 (Powerful)', 'mxchat'),
7257 - 'grok-3-fast-beta' => esc_html__('Grok-3 Fast (High Performance)', 'mxchat'),
7258 - 'grok-3-mini-beta' => esc_html__('Grok-3 Mini (Affordable)', 'mxchat'),
7259 - 'grok-3-mini-fast-beta' => esc_html__('Grok-3 Mini Fast (Quick Response)', 'mxchat'),
7260 - 'grok-2' => esc_html__('Grok 2', 'mxchat'),
7261 - 'grok-4-0709' => esc_html__('Grok 4 (Latest Flagship)', 'mxchat'),
7262 - 'grok-4-1-fast-reasoning' => esc_html__('Grok 4.1 Fast (Reasoning)', 'mxchat'),
7263 - 'grok-4-1-fast-non-reasoning' => esc_html__('Grok 4.1 Fast (Non-Reasoning)', 'mxchat'),
7264 - ),
7265 - esc_html__('DeepSeek Models', 'mxchat') => array(
7266 - 'deepseek-chat' => esc_html__('DeepSeek-V3', 'mxchat'),
7267 - ),
7268 - esc_html__('Claude Models', 'mxchat') => array(
7269 - 'claude-opus-4-7' => esc_html__('Claude Opus 4.7 (Latest Flagship)', 'mxchat'),
7270 - 'claude-opus-4-6' => esc_html__('Claude Opus 4.6 (Most Capable - Recommended)', 'mxchat'),
7271 - 'claude-sonnet-4-6' => esc_html__('Claude Sonnet 4.6 (Latest Sonnet - Fast & Capable)', 'mxchat'),
7272 - 'claude-opus-4-5' => esc_html__('Claude Opus 4.5 (Highly Capable)', 'mxchat'),
7273 - 'claude-sonnet-4-5-20250929' => esc_html__('Claude Sonnet 4.5 (Best for Agents & Coding)', 'mxchat'),
7274 - 'claude-opus-4-1-20250805' => esc_html__('Claude Opus 4.1 (Exceptional for Complex Tasks)', 'mxchat'),
7275 - 'claude-haiku-4-5-20251001' => esc_html__('Claude Haiku 4.5 (Fastest & Most Intelligent)', 'mxchat'),
7276 - 'claude-opus-4-20250514' => esc_html__('Claude 4 Opus (Complex Tasks)', 'mxchat'),
7277 - 'claude-sonnet-4-20250514' => esc_html__('Claude 4 Sonnet (High Performance)', 'mxchat'),
7278 - ),
7279 - esc_html__('Custom (OpenAI-compatible)', 'mxchat') => array(
7280 - 'custom-provider' => esc_html__('Custom Provider (configure in API Keys tab)', 'mxchat'),
7281 - ),
7282 - esc_html__('OpenAI Models', 'mxchat') => array(
7283 - 'gpt-5.5' => esc_html__('GPT-5.5 (Latest Flagship)', 'mxchat'),
7284 - 'gpt-5.4' => esc_html__('GPT-5.4 (Flagship Reasoning & Coding)', 'mxchat'),
7285 - 'gpt-5.4-mini' => esc_html__('GPT-5.4 Mini (Fast, 400K Context)', 'mxchat'),
7286 - 'gpt-5.4-nano' => esc_html__('GPT-5.4 Nano (Fastest & Cheapest)', 'mxchat'),
7287 - 'gpt-5.3-chat-latest' => esc_html__('GPT-5.3 Chat (Conversational)', 'mxchat'),
7288 - 'gpt-5.2' => esc_html__('GPT-5.2 (Best General-Purpose & Agentic Model)', 'mxchat'),
7289 - 'gpt-5.1-chat-latest' => esc_html__('GPT-5.1 Chat Latest (Recommended)', 'mxchat'),
7290 - 'gpt-5.1-2025-11-13' => esc_html__('GPT-5.1 (Flagship for Coding & Agentic Tasks)', 'mxchat'),
7291 - 'gpt-5' => esc_html__('GPT-5 (Flagship for Coding, Reasoning & Agents)', 'mxchat'),
7292 - 'gpt-5-mini' => esc_html__('GPT-5 Mini (Fast and Lightweight)', 'mxchat'),
7293 - 'gpt-5-nano' => esc_html__('GPT-5 Nano (Fastest & Cheapest for Summarization/Classification)', 'mxchat'),
7294 - ),
3585 + 'OpenAI Models' => array(
3586 + 'gpt-4o' => 'GPT-4o (Recommended)',
3587 + 'gpt-4o-mini' => 'GPT-4o Mini (Fast and Lightweight)',
3588 + 'gpt-4-turbo' => 'GPT-4 Turbo (High-Performance)',
3589 + 'gpt-4' => 'GPT-4 (High Intelligence)',
3590 + 'gpt-3.5-turbo' => 'GPT-3.5 Turbo (Affordable and Fast)'
3591 + )
7295 3592 );
7296 3593
7297 3594 // Retrieve the currently selected model from saved options
7298 - $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-5.1-chat-latest';
3595 + $selected_model = isset($this->options['model']) ? esc_attr($this->options['model']) : 'gpt-3.5-turbo';
7299 3596
7300 3597 // Begin the select dropdown
7301 - echo '<select id="model" name="model">';
3598 + echo '<select id="model" name="model">'; // No array notation in name attribute
7302 3599
7303 3600 // Iterate over groups of models
7304 3601 foreach ($models as $group_label => $group_models) {
7305 3602 echo '<optgroup label="' . esc_attr($group_label) . '">';
@@ -7304,265 +3601,28 @@
7304 3601 foreach ($models as $group_label => $group_models) {
7305 3602 echo '<optgroup label="' . esc_attr($group_label) . '">';
7306 3603
7307 3604 foreach ($group_models as $model_value => $model_label) {
7308 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
3605 + // Disable Pro-only models for non-activated users
3606 + $disabled = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? 'disabled' : '';
3607 + $label_suffix = (!$this->is_activated && ($group_label === 'X.AI Models' || $group_label === 'Claude Models')) ? ' (Pro Only)' : '';
3608 +
3609 + // Output the option element
3610 + echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . ' ' . $disabled . '>' . esc_html($model_label . $label_suffix) . '</option>';
7309 3611 }
7310 3612
7311 3613 echo '</optgroup>';
7312 3614 }
7313 3615
3616 + // Close the select dropdown
7314 3617 echo '</select>';
7315 3618
7316 - // Add a note for OpenRouter
7317 - echo '<p class="description" id="openrouter-model-note" style="display:none; color: #d63638; font-weight: 500;">';
7318 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle;"></span> ';
7319 - echo esc_html__('After entering your OpenRouter API key above, click the button below to load available models.', 'mxchat');
7320 - echo '</p>';
7321 -
7322 - // API Key Status Messages (hidden by default, shown by JS based on selected model)
7323 - $has_openai_key = !empty($this->options['api_key']);
7324 - $has_claude_key = !empty($this->options['claude_api_key']);
7325 - $has_xai_key = !empty($this->options['xai_api_key']);
7326 - $has_deepseek_key = !empty($this->options['deepseek_api_key']);
7327 - $has_gemini_key = !empty($this->options['gemini_api_key']);
7328 - $has_openrouter_key = !empty($this->options['openrouter_api_key']);
7329 -
7330 - // OpenAI/GPT models
7331 - echo '<p class="mxchat-api-status" data-provider="openai" style="display:none;">';
7332 - if ($has_openai_key) {
7333 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
7334 - } else {
7335 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7336 - }
7337 - echo '</p>';
7338 -
7339 - // Claude models
7340 - echo '<p class="mxchat-api-status" data-provider="claude" style="display:none;">';
7341 - if ($has_claude_key) {
7342 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Anthropic (Claude) detected', 'mxchat') . '</span>';
7343 - } else {
7344 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Anthropic (Claude) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7345 - }
7346 - echo '</p>';
7347 -
7348 - // X.AI models
7349 - echo '<p class="mxchat-api-status" data-provider="xai" style="display:none;">';
7350 - if ($has_xai_key) {
7351 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for X.AI (Grok) detected', 'mxchat') . '</span>';
7352 - } else {
7353 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for X.AI (Grok) detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7354 - }
7355 - echo '</p>';
7356 -
7357 - // DeepSeek models
7358 - echo '<p class="mxchat-api-status" data-provider="deepseek" style="display:none;">';
7359 - if ($has_deepseek_key) {
7360 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for DeepSeek detected', 'mxchat') . '</span>';
7361 - } else {
7362 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for DeepSeek detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7363 - }
7364 - echo '</p>';
7365 -
7366 - // Gemini models
7367 - echo '<p class="mxchat-api-status" data-provider="gemini" style="display:none;">';
7368 - if ($has_gemini_key) {
7369 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
7370 - } else {
7371 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7372 - }
7373 - echo '</p>';
7374 -
7375 - // OpenRouter models
7376 - echo '<p class="mxchat-api-status" data-provider="openrouter" style="display:none;">';
7377 - if ($has_openrouter_key) {
7378 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenRouter detected', 'mxchat') . '</span>';
7379 - } else {
7380 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenRouter detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7381 - }
7382 - echo '</p>';
7383 -
7384 - // ADD THESE HIDDEN FIELDS RIGHT HERE:
7385 - $openrouter_model = isset($this->options['openrouter_selected_model']) ? esc_attr($this->options['openrouter_selected_model']) : '';
7386 - $openrouter_model_name = isset($this->options['openrouter_selected_model_name']) ? esc_attr($this->options['openrouter_selected_model_name']) : '';
7387 -
7388 - echo '<input type="hidden" id="openrouter_selected_model" name="openrouter_selected_model" value="' . $openrouter_model . '" />';
7389 - echo '<input type="hidden" id="openrouter_selected_model_name" name="openrouter_selected_model_name" value="' . $openrouter_model_name . '" />';
3619 + // Add a description below the dropdown
3620 + echo '<p class="description">Select the AI model to use for your chatbot. Pro-only models are marked accordingly.</p>';
7390 3621 }
7391 3622
7392 -// Update your existing callback method
7393 -public function enable_streaming_toggle_callback() {
7394 - // Get value from options array, default to 'on'
7395 - $enabled = isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on';
7396 - $checked = ($enabled === 'on') ? 'checked' : '';
7397 3623
7398 - echo '<label class="toggle-switch">';
7399 - echo sprintf(
7400 - '<input type="checkbox" id="enable_streaming_toggle" name="enable_streaming_toggle" value="on" %s />',
7401 - esc_attr($checked)
7402 - );
7403 - echo '<span class="slider"></span>';
7404 - echo '</label>';
7405 3624
7406 - // Test button with better styling
7407 - echo '<div style="margin-top: 15px;">';
7408 - echo '<button type="button" id="mxchat-test-streaming-btn" class="button button-secondary">';
7409 - echo '<span class="dashicons dashicons-admin-tools" style="vertical-align: middle; margin-right: 5px;"></span>';
7410 - echo esc_html__('Test Streaming Compatibility', 'mxchat');
7411 - echo '</button>';
7412 - echo '<p id="mxchat-test-streaming-result" style="margin-top:10px; font-weight: bold;"></p>';
7413 - echo '</div>';
7414 -}
7415 -
7416 -// Web Search toggle callback
7417 -public function enable_web_search_toggle_callback() {
7418 - // Get value from options array, default to 'off'
7419 - $enabled = isset($this->options['enable_web_search']) ? $this->options['enable_web_search'] : 'off';
7420 - $checked = ($enabled === 'on') ? 'checked' : '';
7421 -
7422 - // Get current model to determine if we should show/enable the toggle
7423 - $current_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.1-chat-latest';
7424 -
7425 - // Models that DON'T support web search (per OpenAI docs)
7426 - // gpt-5 with minimal reasoning is handled at API level, gpt-4.1-nano doesn't support it
7427 - $unsupported_models = array('gpt-4.1-nano');
7428 -
7429 - // Check if current model is an OpenAI model that supports web search
7430 - $openai_models = array(
7431 - 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-nano', 'gpt-5.3-chat-latest',
7432 - 'gpt-5.2', 'gpt-5.1-chat-latest', 'gpt-5.1-2025-11-13', 'gpt-5', 'gpt-5-mini', 'gpt-5-nano'
7433 - );
7434 -
7435 - $is_openai = in_array($current_model, $openai_models);
7436 - $is_supported = $is_openai && !in_array($current_model, $unsupported_models);
7437 -
7438 - // Wrapper div with data attributes for JS to show/hide
7439 - echo '<div id="web-search-toggle-wrapper" data-openai-models="' . esc_attr(implode(',', $openai_models)) . '" data-unsupported-models="' . esc_attr(implode(',', $unsupported_models)) . '"' . (!$is_supported ? ' style="display:none;"' : '') . '>';
7440 -
7441 - echo '<label class="toggle-switch">';
7442 - echo sprintf(
7443 - '<input type="checkbox" id="enable_web_search" name="enable_web_search" value="on" %s />',
7444 - esc_attr($checked)
7445 - );
7446 - echo '<span class="slider"></span>';
7447 - echo '</label>';
7448 -
7449 - echo '</div>';
7450 -
7451 - // Message shown when non-OpenAI model is selected
7452 - echo '<p id="web-search-unavailable-message" class="description" style="color: #666;' . ($is_supported ? ' display:none;' : '') . '">';
7453 - echo '<span class="dashicons dashicons-info" style="font-size: 16px; vertical-align: middle; margin-right: 4px;"></span>';
7454 - echo esc_html__('Web search is only available for OpenAI models.', 'mxchat');
7455 - echo '</p>';
7456 -}
7457 -
7458 -// AJAX handler to fetch OpenRouter models
7459 -public function fetch_openrouter_models() {
7460 - check_ajax_referer('mxchat_fetch_openrouter_models', 'nonce');
7461 -
7462 - $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
7463 -
7464 - if (empty($api_key)) {
7465 - wp_send_json_error(array('message' => 'API key is required'));
7466 - }
7467 -
7468 - $response = wp_remote_get('https://openrouter.ai/api/v1/models', array(
7469 - 'headers' => array(
7470 - 'Authorization' => 'Bearer ' . $api_key,
7471 - 'Content-Type' => 'application/json',
7472 - ),
7473 - 'timeout' => 15,
7474 - ));
7475 -
7476 - if (is_wp_error($response)) {
7477 - wp_send_json_error(array('message' => $response->get_error_message()));
7478 - }
7479 -
7480 - $body = wp_remote_retrieve_body($response);
7481 - $data = json_decode($body, true);
7482 -
7483 - if (isset($data['data']) && is_array($data['data'])) {
7484 - // Format the models for the frontend
7485 - $models = array_map(function($model) {
7486 - return array(
7487 - 'id' => $model['id'],
7488 - 'name' => $model['name'] ?? $model['id'],
7489 - 'description' => $model['description'] ?? '',
7490 - 'context_length' => $model['context_length'] ?? 0,
7491 - 'pricing' => array(
7492 - 'prompt' => $model['pricing']['prompt'] ?? 0,
7493 - 'completion' => $model['pricing']['completion'] ?? 0,
7494 - ),
7495 - );
7496 - }, $data['data']);
7497 -
7498 - wp_send_json_success(array('models' => $models));
7499 - } else {
7500 - wp_send_json_error(array('message' => 'Invalid response from OpenRouter'));
7501 - }
7502 -}
7503 -
7504 -// Callback function for embedding model selection
7505 -public function embedding_model_callback() {
7506 - $models = array(
7507 - esc_html__('OpenAI Embeddings', 'mxchat') => array(
7508 - 'text-embedding-3-small' => esc_html__('TE3 Small (1536, Efficient)', 'mxchat'),
7509 - 'text-embedding-ada-002' => esc_html__('Ada 2 (1536, Recommended)', 'mxchat'),
7510 - 'text-embedding-3-large' => esc_html__('TE3 Large (3072, Powerful)', 'mxchat'),
7511 - ),
7512 - esc_html__('Voyage AI Embeddings', 'mxchat') => array(
7513 - 'voyage-3-large' => esc_html__('Voyage-3 Large (2048, Most Capable)', 'mxchat'),
7514 - ),
7515 - esc_html__('Google Gemini Embeddings', 'mxchat') => array(
7516 - 'gemini-embedding-001' => esc_html__('Gemini Embedding (1536, Stable)', 'mxchat'),
7517 - )
7518 - );
7519 - $selected_model = isset($this->options['embedding_model']) ? esc_attr($this->options['embedding_model']) : 'text-embedding-ada-002';
7520 - echo '<select id="embedding_model" name="embedding_model">';
7521 - foreach ($models as $group_label => $group_models) {
7522 - echo '<optgroup label="' . esc_attr($group_label) . '">';
7523 - foreach ($group_models as $model_value => $model_label) {
7524 - echo '<option value="' . esc_attr($model_value) . '" ' . selected($selected_model, $model_value, false) . '>' . esc_html($model_label) . '</option>';
7525 - }
7526 - echo '</optgroup>';
7527 - }
7528 - echo '</select>';
7529 -
7530 - // API Key Status Messages for Embedding Models
7531 - $has_openai_key = !empty($this->options['api_key']);
7532 - $has_voyage_key = !empty($this->options['voyage_api_key']);
7533 - $has_gemini_key = !empty($this->options['gemini_api_key']);
7534 -
7535 - // OpenAI Embeddings
7536 - echo '<p class="mxchat-embedding-api-status" data-provider="openai" style="display:none;">';
7537 - if ($has_openai_key) {
7538 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for OpenAI detected', 'mxchat') . '</span>';
7539 - } else {
7540 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for OpenAI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7541 - }
7542 - echo '</p>';
7543 -
7544 - // Voyage AI Embeddings
7545 - echo '<p class="mxchat-embedding-api-status" data-provider="voyage" style="display:none;">';
7546 - if ($has_voyage_key) {
7547 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Voyage AI detected', 'mxchat') . '</span>';
7548 - } else {
7549 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Voyage AI detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7550 - }
7551 - echo '</p>';
7552 -
7553 - // Gemini Embeddings
7554 - echo '<p class="mxchat-embedding-api-status" data-provider="gemini" style="display:none;">';
7555 - if ($has_gemini_key) {
7556 - echo '<span style="color: #00a32a;">✓ ' . esc_html__('API key for Google Gemini detected', 'mxchat') . '</span>';
7557 - } else {
7558 - echo '<span style="color: #d63638;">⚠ ' . esc_html__('No API key for Google Gemini detected. Please enter API key in API Keys tab.', 'mxchat') . '</span>';
7559 - }
7560 - echo '</p>';
7561 -
7562 -}
7563 -
7564 -
7565 3625 public function mxchat_top_bar_title_callback() {
7566 3626 // Retrieve the current value of the top bar title from saved options
7567 3627 $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
7568 3628
@@ -7567,17 +3627,13 @@
7567 3627 $top_bar_title = isset($this->options['top_bar_title']) ? esc_attr($this->options['top_bar_title']) : '';
7568 3628
7569 3629 // Render the input field
7570 3630 echo '<input type="text" id="top_bar_title" name="top_bar_title" value="' . $top_bar_title . '" />';
3631 +
3632 + // Add a description
3633 + echo '<p class="description">Enter the title text that will appear on the top bar of the chatbot.</p>';
7571 3634 }
7572 -public function mxchat_ai_agent_text_callback() {
7573 - // Retrieve the current value of the AI agent text from saved options
7574 - $ai_agent_text = isset($this->options['ai_agent_text']) ? esc_attr($this->options['ai_agent_text']) : '';
7575 - // Render the input field
7576 - echo '<input type="text" id="ai_agent_text" name="ai_agent_text" value="' . $ai_agent_text . '" />';
7577 -}
7578 3635
7579 -
7580 3636 public function enable_email_block_callback() {
7581 3637 // Load full plugin options array
7582 3638 $all_options = get_option('mxchat_options', []);
7583 3639
@@ -7593,10 +3649,13 @@
7593 3649 esc_attr($checked)
7594 3650 );
7595 3651 echo '<span class="slider"></span>';
7596 3652 echo '</label>';
3653 + echo '<p class="description">Enable to require email before a user chats. Their email will appear at the top of the transcript.</p>';
7597 3654 }
7598 3655
3656 +
3657 +
7599 3658 public function email_blocker_header_content_callback() {
7600 3659 // Load the entire 'mxchat_options' array
7601 3660 $all_options = get_option('mxchat_options', []);
7602 3661
@@ -7604,18 +3663,23 @@
7604 3663 $content = isset($all_options['email_blocker_header_content'])
7605 3664 ? $all_options['email_blocker_header_content']
7606 3665 : '';
7607 3666
7608 - // Render the textarea - IMPORTANT: name should be just "email_blocker_header_content"
3667 + // Render the textarea
7609 3668 echo '<textarea
7610 3669 id="email_blocker_header_content"
7611 3670 name="email_blocker_header_content"
7612 3671 rows="5"
7613 3672 cols="70"
7614 - data-setting="email_blocker_header_content"
7615 3673 >' . esc_textarea($content) . '</textarea>';
3674 +
3675 + echo '<p class="description">';
3676 + echo 'You may enter HTML here, such as &lt;h2&gt;Welcome&lt;/h2&gt; or &lt;p&gt;Let\'s get started&lt;/p&gt;.';
3677 + echo ' Email form will show for users who are not logged in or have not provided an email within 24h.';
3678 + echo '</p>';
7616 3679 }
7617 3680
3681 +
7618 3682 public function email_blocker_button_text_callback() {
7619 3683 // Load the entire 'mxchat_options' array
7620 3684 $all_options = get_option('mxchat_options', []);
7621 3685
@@ -7625,294 +3689,580 @@
7625 3689 : '';
7626 3690
7627 3691 // Use esc_attr to safely render the existing text
7628 3692 echo '<input type="text" id="email_blocker_button_text" name="email_blocker_button_text" value="' . esc_attr($button_text) . '" style="width: 300px;" />';
7629 -}
7630 3693
7631 -//Enable name field callback
7632 -public function enable_name_field_callback() {
7633 - // Load full plugin options array
7634 - $all_options = get_option('mxchat_options', []);
7635 - // Get the value, default to 'off'
7636 - $enable_name_field = isset($all_options['enable_name_field']) ? $all_options['enable_name_field'] : 'off';
7637 - // Check if it's 'on'
7638 - $checked = ($enable_name_field === 'on') ? 'checked' : '';
7639 - echo '<label class="toggle-switch">';
7640 - echo sprintf(
7641 - '<input type="checkbox" id="enable_name_field" name="enable_name_field" value="on" %s />',
7642 - esc_attr($checked)
7643 - );
7644 - echo '<span class="slider"></span>';
7645 - echo '</label>';
3694 + echo '<p class="description">';
3695 + echo 'Enter the text you want on the submit button, e.g. "Start Chat".';
3696 + echo '</p>';
7646 3697 }
7647 -//Name field placeholder callback
7648 -public function name_field_placeholder_callback() {
7649 - $all_options = get_option('mxchat_options', []);
7650 - $placeholder = isset($all_options['name_field_placeholder'])
7651 - ? $all_options['name_field_placeholder']
7652 - : esc_html__('Enter your name', 'mxchat');
7653 3698
7654 - echo '<input type="text" id="name_field_placeholder" name="name_field_placeholder" value="' . esc_attr($placeholder) . '" style="width: 300px;" />';
7655 -}
7656 3699
7657 3700
7658 -
7659 3701 public function mxchat_intro_message_callback() {
7660 3702 // Load the entire 'mxchat_options' array
7661 3703 $all_options = get_option('mxchat_options', []);
3704 +
7662 3705 // Retrieve the saved intro message or use the default
7663 - $default_message = __('Hello! How can I assist you today?', 'mxchat');
3706 + $default_message = 'Hello! How can I assist you today?';
7664 3707 $saved_message = isset($all_options['intro_message']) ? $all_options['intro_message'] : $default_message;
7665 - // Output the textarea with the saved value without escaping HTML
3708 +
3709 + // Output the textarea with the saved value
7666 3710 ?>
7667 - <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo $saved_message; ?></textarea>
7668 - <p class="description" style="margin-top: 8px;">
7669 - <?php esc_html_e('Use {visitor_name} to personalize greetings when lead capture is enabled.', 'mxchat'); ?><br>
7670 - <code style="font-size: 12px;"><?php esc_html_e('Example: Hello {visitor_name}! How can I help you today?', 'mxchat'); ?></code>
3711 + <textarea id="intro_message" name="intro_message" rows="5" cols="50"><?php echo esc_textarea($saved_message); ?></textarea>
3712 + <p class="description">
3713 + <?php esc_html_e('Enter your message. Line breaks will be preserved.', 'mxchat'); ?>
7671 3714 </p>
7672 3715 <?php
7673 3716 }
7674 3717
3718 +
7675 3719 public function mxchat_input_copy_callback() {
7676 3720 // Load the entire 'mxchat_options' array
7677 3721 $all_options = get_option('mxchat_options', []);
7678 3722
7679 3723 // Retrieve the saved input copy or use the default value
7680 - $default_copy = __('How can I assist?', 'mxchat');
3724 + $default_copy = 'How can I assist?';
7681 3725 $input_copy = isset($all_options['input_copy']) ? $all_options['input_copy'] : $default_copy;
7682 3726
7683 3727 // Output the input field with the saved value
7684 3728 printf(
7685 - '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="%s" />',
7686 - esc_attr($input_copy),
7687 - esc_attr__('How can I assist?', 'mxchat')
3729 + '<input type="text" id="input_copy" name="input_copy" value="%s" placeholder="How can I assist?" />',
3730 + esc_attr($input_copy)
7688 3731 );
3732 +
3733 + // Output the description
3734 + echo '<p class="description">This is the placeholder text for the chat input field.</p>';
7689 3735 }
7690 3736
7691 3737
7692 -public function mxchat_append_to_body_callback() {
7693 - // Fetch fresh options to ensure we have the latest saved values
7694 - $options = get_option('mxchat_options', array());
7695 3738
7696 - // Get value from options array, default to 'off'
7697 - $append_to_body = isset($options['append_to_body']) ? $options['append_to_body'] : 'off';
7698 - $checked = ($append_to_body === 'on') ? 'checked' : '';
7699 3739
7700 - // Get post type visibility settings
7701 - $visibility_mode = isset($options['post_type_visibility_mode']) ? $options['post_type_visibility_mode'] : 'all';
7702 - $visibility_list = isset($options['post_type_visibility_list']) ? $options['post_type_visibility_list'] : array();
7703 - if (!is_array($visibility_list)) {
7704 - $visibility_list = array();
7705 - }
7706 3740
7707 - echo '<div class="mxchat-autosave-section">';
3741 +public function mxchat_close_button_color_callback() {
3742 + $disabled = $this->is_activated ? '' : 'disabled';
3743 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7708 3744
7709 - // Main toggle
7710 - echo '<label class="toggle-switch">';
3745 + echo '<div class="' . esc_attr($class) . '">';
7711 3746 echo sprintf(
7712 - '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
7713 - esc_attr($checked)
3747 + '<input type="text"
3748 + id="close_button_color"
3749 + name="close_button_color"
3750 + value="%s"
3751 + class="my-color-field"
3752 + data-default-color="#4a4a4a"
3753 + %s />',
3754 + isset($this->options['close_button_color']) ? esc_attr($this->options['close_button_color']) : '#4a4a4a',
3755 + esc_attr($disabled)
7714 3756 );
7715 - echo '<span class="slider"></span>';
7716 - echo '</label>';
7717 3757
7718 - // Post Type Visibility Options (only visible when auto-display is ON)
7719 - $display_style = ($append_to_body === 'on') ? '' : 'display: none;';
7720 - echo '<div id="post-type-visibility-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
3758 + if (!$this->is_activated) {
3759 + echo '<div class="pro-feature-overlay">';
3760 + echo '<a href="https://mxchat.ai/" target="_blank">';
3761 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3762 + echo '</a>';
3763 + echo '</div>';
3764 + }
3765 + echo '</div>';
3766 +}
7721 3767
7722 - echo '<div class="mxchat-post-type-visibility-header">';
7723 - echo '<h4>' . esc_html__('Post Type Visibility', 'mxchat') . '</h4>';
7724 - echo '</div>';
3768 +public function mxchat_chatbot_bg_color_callback() {
3769 + $disabled = $this->is_activated ? '' : 'disabled';
3770 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7725 3771
7726 - // Mode selector (radio buttons)
7727 - echo '<div class="mxchat-visibility-mode">';
3772 + echo '<div class="' . esc_attr($class) . '">';
3773 + echo sprintf(
3774 + '<input type="text"
3775 + id="chatbot_bg_color"
3776 + name="chatbot_bg_color"
3777 + value="%s"
3778 + class="my-color-field"
3779 + data-default-color="#f9f9f9"
3780 + %s />',
3781 + isset($this->options['chatbot_bg_color']) ? esc_attr($this->options['chatbot_bg_color']) : '#f9f9f9',
3782 + esc_attr($disabled)
3783 + );
7728 3784
7729 - echo '<label class="mxchat-radio-label">';
7730 - echo '<input type="radio" name="post_type_visibility_mode" value="all" ' . checked($visibility_mode, 'all', false) . ' />';
7731 - echo '<span>' . esc_html__('Show on all post types', 'mxchat') . '</span>';
7732 - echo '</label>';
3785 + if (!$this->is_activated) {
3786 + echo '<div class="pro-feature-overlay">';
3787 + echo '<a href="https://mxchat.ai/" target="_blank">';
3788 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3789 + echo '</a>';
3790 + echo '</div>';
3791 + }
3792 + echo '</div>';
3793 +}
7733 3794
7734 - echo '<label class="mxchat-radio-label">';
7735 - echo '<input type="radio" name="post_type_visibility_mode" value="include" ' . checked($visibility_mode, 'include', false) . ' />';
7736 - echo '<span>' . esc_html__('Only show on selected post types', 'mxchat') . '</span>';
7737 - echo '</label>';
3795 +public function mxchat_user_message_bg_color_callback() {
3796 + $disabled = $this->is_activated ? '' : 'disabled';
3797 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7738 3798
7739 - echo '<label class="mxchat-radio-label">';
7740 - echo '<input type="radio" name="post_type_visibility_mode" value="exclude" ' . checked($visibility_mode, 'exclude', false) . ' />';
7741 - echo '<span>' . esc_html__('Hide on selected post types', 'mxchat') . '</span>';
7742 - echo '</label>';
3799 + echo '<div class="' . esc_attr($class) . '">';
3800 + echo sprintf(
3801 + '<input type="text"
3802 + id="user_message_bg_color"
3803 + name="user_message_bg_color"
3804 + value="%s"
3805 + class="my-color-field"
3806 + data-default-color="#0078d7"
3807 + %s />',
3808 + isset($this->options['user_message_bg_color']) ? esc_attr($this->options['user_message_bg_color']) : '#0078d7',
3809 + esc_attr($disabled)
3810 + );
7743 3811
3812 + if (!$this->is_activated) {
3813 + echo '<div class="pro-feature-overlay">';
3814 + echo '<a href="https://mxchat.ai/" target="_blank">';
3815 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3816 + echo '</a>';
3817 + echo '</div>';
3818 + }
7744 3819 echo '</div>';
3820 +}
7745 3821
7746 - // Post type checkboxes (only visible when mode is include or exclude)
7747 - $list_display = ($visibility_mode !== 'all') ? '' : 'display: none;';
7748 - echo '<div id="post-type-list" class="mxchat-post-type-list" style="' . esc_attr($list_display) . '">';
3822 +public function mxchat_user_message_font_color_callback() {
3823 + $disabled = $this->is_activated ? '' : 'disabled';
3824 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7749 3825
7750 - // Get all public post types
7751 - $post_types = get_post_types(array('public' => true), 'objects');
3826 + echo '<div class="' . esc_attr($class) . '">';
3827 + echo sprintf(
3828 + '<input type="text"
3829 + id="user_message_font_color"
3830 + name="user_message_font_color"
3831 + value="%s"
3832 + class="my-color-field"
3833 + data-default-color="#ffffff"
3834 + %s />',
3835 + isset($this->options['user_message_font_color']) ? esc_attr($this->options['user_message_font_color']) : '#ffffff',
3836 + esc_attr($disabled)
3837 + );
7752 3838
7753 - foreach ($post_types as $post_type) {
7754 - // Skip attachments
7755 - if ($post_type->name === 'attachment') {
7756 - continue;
7757 - }
3839 + if (!$this->is_activated) {
3840 + echo '<div class="pro-feature-overlay">';
3841 + echo '<a href="https://mxchat.ai/" target="_blank">';
3842 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3843 + echo '</a>';
3844 + echo '</div>';
3845 + }
3846 + echo '</div>';
3847 +}
7758 3848
7759 - $is_checked = in_array($post_type->name, $visibility_list) ? 'checked' : '';
3849 +public function mxchat_bot_message_bg_color_callback() {
3850 + $disabled = $this->is_activated ? '' : 'disabled';
3851 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7760 3852
7761 - echo '<label class="mxchat-checkbox-label">';
7762 - echo '<input type="checkbox" name="post_type_visibility_list[]" value="' . esc_attr($post_type->name) . '" ' . $is_checked . ' />';
7763 - echo '<span>' . esc_html($post_type->label) . '</span>';
7764 - echo '</label>';
3853 + echo '<div class="' . esc_attr($class) . '">';
3854 + echo sprintf(
3855 + '<input type="text"
3856 + id="bot_message_bg_color"
3857 + name="bot_message_bg_color"
3858 + value="%s"
3859 + class="my-color-field"
3860 + data-default-color="#e1e1e1"
3861 + %s />',
3862 + isset($this->options['bot_message_bg_color']) ? esc_attr($this->options['bot_message_bg_color']) : '#e1e1e1',
3863 + esc_attr($disabled)
3864 + );
3865 +
3866 + if (!$this->is_activated) {
3867 + echo '<div class="pro-feature-overlay">';
3868 + echo '<a href="https://mxchat.ai/" target="_blank">';
3869 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3870 + echo '</a>';
3871 + echo '</div>';
7765 3872 }
3873 + echo '</div>';
3874 +}
7766 3875
7767 - echo '</div>'; // End post-type-list
7768 - echo '</div>'; // End post-type-visibility-options
7769 - echo '</div>'; // End mxchat-autosave-section
7770 -}
3876 +public function mxchat_bot_message_font_color_callback() {
3877 + $disabled = $this->is_activated ? '' : 'disabled';
3878 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7771 3879
7772 -public function mxchat_contextual_awareness_callback() {
7773 - // Get value from options array, default to 'off'
7774 - $contextual_awareness = isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off';
7775 - $checked = ($contextual_awareness === 'on') ? 'checked' : '';
7776 - echo '<label class="toggle-switch">';
3880 + echo '<div class="' . esc_attr($class) . '">';
7777 3881 echo sprintf(
7778 - '<input type="checkbox" id="contextual_awareness_toggle" name="contextual_awareness_toggle" value="on" %s />',
7779 - esc_attr($checked)
3882 + '<input type="text"
3883 + id="bot_message_font_color"
3884 + name="bot_message_font_color"
3885 + value="%s"
3886 + class="my-color-field"
3887 + data-default-color="#333333"
3888 + %s />',
3889 + isset($this->options['bot_message_font_color']) ? esc_attr($this->options['bot_message_font_color']) : '#333333',
3890 + esc_attr($disabled)
7780 3891 );
7781 - echo '<span class="slider"></span>';
7782 - echo '</label>';
3892 +
3893 + if (!$this->is_activated) {
3894 + echo '<div class="pro-feature-overlay">';
3895 + echo '<a href="https://mxchat.ai/" target="_blank">';
3896 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3897 + echo '</a>';
3898 + echo '</div>';
3899 + }
3900 + echo '</div>';
7783 3901 }
7784 3902
7785 -public function mxchat_citation_links_toggle_callback() {
7786 - // Get value from options array, default to 'on' (enabled by default)
7787 - $citation_links = isset($this->options['citation_links_toggle']) ? $this->options['citation_links_toggle'] : 'on';
7788 - $checked = ($citation_links === 'on') ? 'checked' : '';
7789 - echo '<label class="toggle-switch">';
3903 +public function mxchat_live_agent_message_bg_color_callback() {
3904 + $disabled = $this->is_activated ? '' : 'disabled';
3905 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
3906 +
3907 + echo '<div class="' . esc_attr($class) . '">';
7790 3908 echo sprintf(
7791 - '<input type="checkbox" id="citation_links_toggle" name="citation_links_toggle" value="on" %s />',
7792 - esc_attr($checked)
3909 + '<input type="text"
3910 + id="live_agent_message_bg_color"
3911 + name="live_agent_message_bg_color"
3912 + value="%s"
3913 + class="my-color-field"
3914 + data-default-color="#ffffff"
3915 + %s />',
3916 + isset($this->options['live_agent_message_bg_color']) ? esc_attr($this->options['live_agent_message_bg_color']) : '#ffffff',
3917 + esc_attr($disabled)
7793 3918 );
7794 - echo '<span class="slider"></span>';
7795 - echo '</label>';
3919 +
3920 + if (!$this->is_activated) {
3921 + echo '<div class="pro-feature-overlay">';
3922 + echo '<a href="https://mxchat.ai/" target="_blank">';
3923 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3924 + echo '</a>';
3925 + echo '</div>';
3926 + }
3927 + echo '</div>';
7796 3928 }
7797 3929
7798 -/**
7799 - * Toggle for the end-of-session satisfaction rating prompt (plan-a5b006).
7800 - * Default ON. The widget reads this through the localized object; the
7801 - * mxchat_satisfaction_rating_enabled filter still lets developers force
7802 - * the value site-wide.
7803 - *
7804 - * The 5 customization fields (idle/question/thanks/placeholder/saved) are
7805 - * rendered inline here inside a single wrapper div whose initial display
7806 - * is set server-side from the toggle value (plan-29caac). Mirrors the
7807 - * auto-display chatbot pattern at mxchat_append_to_body_callback — no
7808 - * DOMContentLoaded race because rows exist as direct children of this
7809 - * callback's output, and the wrapper's display: none is inline at render
7810 - * time so refresh shows the correct state with no flash.
7811 - */
7812 -public function mxchat_satisfaction_rating_toggle_callback() {
7813 - $options = $this->options;
7814 - $value = isset($options['satisfaction_rating_enabled']) ? $options['satisfaction_rating_enabled'] : 'off';
7815 - $checked = ($value === 'on') ? 'checked' : '';
3930 +public function mxchat_live_agent_message_font_color_callback() {
3931 + $disabled = $this->is_activated ? '' : 'disabled';
3932 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7816 3933
7817 - $idle = isset($options['satisfaction_rating_idle_seconds']) ? intval($options['satisfaction_rating_idle_seconds']) : 60;
7818 - $idle = max(5, min(600, $idle));
7819 - $question = isset($options['satisfaction_rating_question']) ? $options['satisfaction_rating_question'] : '';
7820 - $thanks = isset($options['satisfaction_rating_thanks']) ? $options['satisfaction_rating_thanks'] : '';
7821 - $placeholder = isset($options['satisfaction_rating_placeholder']) ? $options['satisfaction_rating_placeholder'] : '';
7822 - $saved = isset($options['satisfaction_rating_saved']) ? $options['satisfaction_rating_saved'] : '';
3934 + echo '<div class="' . esc_attr($class) . '">';
3935 + echo sprintf(
3936 + '<input type="text"
3937 + id="live_agent_message_font_color"
3938 + name="live_agent_message_font_color"
3939 + value="%s"
3940 + class="my-color-field"
3941 + data-default-color="#333333"
3942 + %s />',
3943 + isset($this->options['live_agent_message_font_color']) ? esc_attr($this->options['live_agent_message_font_color']) : '#333333',
3944 + esc_attr($disabled)
3945 + );
7823 3946
7824 - echo '<div class="mxchat-autosave-section">';
3947 + if (!$this->is_activated) {
3948 + echo '<div class="pro-feature-overlay">';
3949 + echo '<a href="https://mxchat.ai/" target="_blank">';
3950 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3951 + echo '</a>';
3952 + echo '</div>';
3953 + }
3954 + echo '</div>';
3955 +}
7825 3956
7826 - echo '<label class="toggle-switch">';
3957 +public function mxchat_mode_indicator_bg_color_callback() {
3958 + $disabled = $this->is_activated ? '' : 'disabled';
3959 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
3960 +
3961 + echo '<div class="' . esc_attr($class) . '">';
7827 3962 echo sprintf(
7828 - '<input type="checkbox" id="satisfaction_rating_enabled" name="satisfaction_rating_enabled" value="on" %s />',
7829 - esc_attr($checked)
3963 + '<input type="text"
3964 + id="mode_indicator_bg_color"
3965 + name="mode_indicator_bg_color"
3966 + value="%s"
3967 + class="my-color-field"
3968 + data-default-color="#767676"
3969 + %s />',
3970 + isset($this->options['mode_indicator_bg_color']) ? esc_attr($this->options['mode_indicator_bg_color']) : '#767676',
3971 + esc_attr($disabled)
7830 3972 );
7831 - echo '<span class="slider"></span>';
7832 - echo '</label>';
7833 3973
7834 - ?>
7835 - <style>
7836 - .mxchat-sub-options-field { margin: 12px 0; }
7837 - .mxchat-sub-options-field label { display: inline-block; margin-bottom: 4px; }
7838 - #satisfaction-rating-sub-options h4 { margin: 16px 0 8px; }
7839 - </style>
7840 - <?php
3974 + if (!$this->is_activated) {
3975 + echo '<div class="pro-feature-overlay">';
3976 + echo '<a href="https://mxchat.ai/" target="_blank">';
3977 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
3978 + echo '</a>';
3979 + echo '</div>';
3980 + }
3981 + echo '</div>';
3982 +}
7841 3983
7842 - $display_style = ($value === 'on') ? '' : 'display: none;';
7843 - echo '<div id="satisfaction-rating-sub-options" class="mxchat-sub-options" style="' . esc_attr($display_style) . '">';
3984 +public function mxchat_mode_indicator_font_color_callback() {
3985 + $disabled = $this->is_activated ? '' : 'disabled';
3986 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7844 3987
7845 - echo '<h4>' . esc_html__('Customize the prompt (optional)', 'mxchat') . '</h4>';
3988 + echo '<div class="' . esc_attr($class) . '">';
3989 + echo sprintf(
3990 + '<input type="text"
3991 + id="mode_indicator_font_color"
3992 + name="mode_indicator_font_color"
3993 + value="%s"
3994 + class="my-color-field"
3995 + data-default-color="#ffffff"
3996 + %s />',
3997 + isset($this->options['mode_indicator_font_color']) ? esc_attr($this->options['mode_indicator_font_color']) : '#ffffff',
3998 + esc_attr($disabled)
3999 + );
7846 4000
7847 - echo '<div class="mxchat-sub-options-field">';
7848 - echo '<label for="satisfaction_rating_idle_seconds"><strong>' . esc_html__('Idle Timeout', 'mxchat') . '</strong></label><br />';
7849 - printf(
7850 - '<input type="number" id="satisfaction_rating_idle_seconds" name="satisfaction_rating_idle_seconds" value="%d" min="5" max="600" step="1" class="small-text" /> <span class="description">%s</span>',
7851 - (int) $idle,
7852 - esc_html__('seconds of user inactivity before the prompt appears (5-600)', 'mxchat')
7853 - );
4001 + if (!$this->is_activated) {
4002 + echo '<div class="pro-feature-overlay">';
4003 + echo '<a href="https://mxchat.ai/" target="_blank">';
4004 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4005 + echo '</a>';
4006 + echo '</div>';
4007 + }
7854 4008 echo '</div>';
4009 +}
7855 4010
7856 - echo '<div class="mxchat-sub-options-field">';
7857 - echo '<label for="satisfaction_rating_question"><strong>' . esc_html__('Prompt Question', 'mxchat') . '</strong></label><br />';
7858 - printf(
7859 - '<input type="text" id="satisfaction_rating_question" name="satisfaction_rating_question" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
7860 - esc_attr($question),
7861 - esc_attr__('Was this helpful?', 'mxchat')
4011 +public function mxchat_toolbar_icon_color_callback() {
4012 + $disabled = $this->is_activated ? '' : 'disabled';
4013 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4014 +
4015 + echo '<div class="' . esc_attr($class) . '">';
4016 + echo sprintf(
4017 + '<input type="text"
4018 + id="toolbar_icon_color"
4019 + name="toolbar_icon_color"
4020 + value="%s"
4021 + class="my-color-field"
4022 + data-default-color="#212121"
4023 + %s />',
4024 + isset($this->options['toolbar_icon_color']) ? esc_attr($this->options['toolbar_icon_color']) : '#212121',
4025 + esc_attr($disabled)
7862 4026 );
7863 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown above the thumbs up/down.', 'mxchat') . '</p>';
4027 +
4028 + if (!$this->is_activated) {
4029 + echo '<div class="pro-feature-overlay">';
4030 + echo '<a href="https://mxchat.ai/" target="_blank">';
4031 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4032 + echo '</a>';
4033 + echo '</div>';
4034 + }
7864 4035 echo '</div>';
4036 +}
7865 4037
7866 - echo '<div class="mxchat-sub-options-field">';
7867 - echo '<label for="satisfaction_rating_thanks"><strong>' . esc_html__('Thank-You Message', 'mxchat') . '</strong></label><br />';
7868 - printf(
7869 - '<input type="text" id="satisfaction_rating_thanks" name="satisfaction_rating_thanks" value="%s" maxlength="300" class="regular-text" placeholder="%s" />',
7870 - esc_attr($thanks),
7871 - esc_attr__('Thanks! Anything we should improve? (optional)', 'mxchat')
4038 +public function mxchat_top_bar_bg_color_callback() {
4039 + $disabled = $this->is_activated ? '' : 'disabled';
4040 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4041 +
4042 + echo '<div class="' . esc_attr($class) . '">';
4043 + echo sprintf(
4044 + '<input type="text"
4045 + id="top_bar_bg_color"
4046 + name="top_bar_bg_color"
4047 + value="%s"
4048 + class="my-color-field"
4049 + data-default-color="#00b294"
4050 + %s />',
4051 + isset($this->options['top_bar_bg_color']) ? esc_attr($this->options['top_bar_bg_color']) : '#00b294',
4052 + esc_attr($disabled)
7872 4053 );
7873 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the user clicks a thumb.', 'mxchat') . '</p>';
4054 +
4055 + if (!$this->is_activated) {
4056 + echo '<div class="pro-feature-overlay">';
4057 + echo '<a href="https://mxchat.ai/" target="_blank">';
4058 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4059 + echo '</a>';
4060 + echo '</div>';
4061 + }
7874 4062 echo '</div>';
4063 +}
7875 4064
7876 - echo '<div class="mxchat-sub-options-field">';
7877 - echo '<label for="satisfaction_rating_placeholder"><strong>' . esc_html__('Feedback Placeholder', 'mxchat') . '</strong></label><br />';
7878 - printf(
7879 - '<input type="text" id="satisfaction_rating_placeholder" name="satisfaction_rating_placeholder" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
7880 - esc_attr($placeholder),
7881 - esc_attr__('Tell us what could be better…', 'mxchat')
4065 +public function mxchat_send_button_font_color_callback() {
4066 + $disabled = $this->is_activated ? '' : 'disabled';
4067 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4068 +
4069 + echo '<div class="' . esc_attr($class) . '">';
4070 + echo sprintf(
4071 + '<input type="text"
4072 + id="send_button_font_color"
4073 + name="send_button_font_color"
4074 + value="%s"
4075 + class="my-color-field"
4076 + data-default-color="#ffffff"
4077 + %s />',
4078 + isset($this->options['send_button_font_color']) ? esc_attr($this->options['send_button_font_color']) : '#ffffff',
4079 + esc_attr($disabled)
7882 4080 );
7883 - echo '<p class="description">' . esc_html__('Leave blank for the default. Placeholder text inside the feedback textarea.', 'mxchat') . '</p>';
4081 +
4082 + if (!$this->is_activated) {
4083 + echo '<div class="pro-feature-overlay">';
4084 + echo '<a href="https://mxchat.ai/" target="_blank">';
4085 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4086 + echo '</a>';
4087 + echo '</div>';
4088 + }
7884 4089 echo '</div>';
4090 +}
7885 4091
7886 - echo '<div class="mxchat-sub-options-field">';
7887 - echo '<label for="satisfaction_rating_saved"><strong>' . esc_html__('Saved Confirmation', 'mxchat') . '</strong></label><br />';
7888 - printf(
7889 - '<input type="text" id="satisfaction_rating_saved" name="satisfaction_rating_saved" value="%s" maxlength="200" class="regular-text" placeholder="%s" />',
7890 - esc_attr($saved),
7891 - esc_attr__('Thanks for the feedback.', 'mxchat')
4092 +public function mxchat_chatbot_background_color_callback() {
4093 + $disabled = $this->is_activated ? '' : 'disabled';
4094 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4095 +
4096 + echo '<div class="' . esc_attr($class) . '">';
4097 + echo sprintf(
4098 + '<input type="text"
4099 + id="chatbot_background_color"
4100 + name="chatbot_background_color"
4101 + value="%s"
4102 + class="my-color-field"
4103 + data-default-color="#000000"
4104 + %s />',
4105 + isset($this->options['chatbot_background_color']) ? esc_attr($this->options['chatbot_background_color']) : '#000000',
4106 + esc_attr($disabled)
7892 4107 );
7893 - echo '<p class="description">' . esc_html__('Leave blank for the default. Shown after the feedback is sent.', 'mxchat') . '</p>';
4108 +
4109 + if (!$this->is_activated) {
4110 + echo '<div class="pro-feature-overlay">';
4111 + echo '<a href="https://mxchat.ai/" target="_blank">';
4112 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4113 + echo '</a>';
4114 + echo '</div>';
4115 + }
7894 4116 echo '</div>';
4117 +}
7895 4118
7896 - echo '</div>'; // #satisfaction-rating-sub-options
7897 - echo '</div>'; // .mxchat-autosave-section
4119 +public function mxchat_icon_color_callback() {
4120 + $disabled = $this->is_activated ? '' : 'disabled';
4121 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
7898 4122
7899 - ?>
7900 - <script>
7901 - (function() {
7902 - document.addEventListener('DOMContentLoaded', function() {
7903 - var toggle = document.getElementById('satisfaction_rating_enabled');
7904 - var subOptions = document.getElementById('satisfaction-rating-sub-options');
7905 - if (!toggle || !subOptions) return;
7906 - toggle.addEventListener('change', function() {
7907 - subOptions.style.display = toggle.checked ? '' : 'none';
7908 - });
7909 - });
7910 - })();
7911 - </script>
7912 - <?php
4123 + echo '<div class="' . esc_attr($class) . '">';
4124 + echo sprintf(
4125 + '<input type="text"
4126 + id="icon_color"
4127 + name="icon_color"
4128 + value="%s"
4129 + class="my-color-field"
4130 + data-default-color="#ffffff"
4131 + %s />',
4132 + isset($this->options['icon_color']) ? esc_attr($this->options['icon_color']) : '#ffffff',
4133 + esc_attr($disabled)
4134 + );
4135 +
4136 + if (!$this->is_activated) {
4137 + echo '<div class="pro-feature-overlay">';
4138 + echo '<a href="https://mxchat.ai/" target="_blank">';
4139 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4140 + echo '</a>';
4141 + echo '</div>';
4142 + }
4143 + echo '</div>';
7913 4144 }
7914 4145
4146 +public function mxchat_custom_icon_callback() {
4147 + $disabled = $this->is_activated ? '' : 'disabled';
4148 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4149 + $custom_icon_url = isset($this->options['custom_icon']) ? esc_url($this->options['custom_icon']) : '';
4150 +
4151 + echo '<div class="' . esc_attr($class) . '">';
4152 + echo sprintf(
4153 + '<input type="url"
4154 + id="custom_icon"
4155 + name="custom_icon"
4156 + value="%s"
4157 + placeholder="Enter PNG URL"
4158 + class="regular-text"
4159 + %s />',
4160 + $custom_icon_url,
4161 + esc_attr($disabled)
4162 + );
4163 +
4164 + // Preview container for the icon
4165 + if (!empty($custom_icon_url)) {
4166 + echo '<div class="icon-preview" style="margin-top: 10px;">';
4167 + echo '<img src="' . esc_url($custom_icon_url) . '" alt="Custom Icon Preview" style="max-width: 48px; height: auto;" />';
4168 + echo '</div>';
4169 + }
4170 +
4171 + echo '<p class="description">Upload your PNG icon and paste the URL here. Recommended size: 48x48 pixels.</p>';
4172 +
4173 + if (!$this->is_activated) {
4174 + echo '<div class="pro-feature-overlay">';
4175 + echo '<a href="https://mxchat.ai/" target="_blank">';
4176 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4177 + echo '</a>';
4178 + echo '</div>';
4179 + }
4180 + echo '</div>';
4181 +}
4182 +
4183 +public function mxchat_title_icon_callback() {
4184 + $disabled = $this->is_activated ? '' : 'disabled';
4185 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4186 + // Fixed the variable reference - it was using custom_icon instead of title_icon
4187 + $title_icon_url = isset($this->options['title_icon']) ? esc_url($this->options['title_icon']) : '';
4188 +
4189 + echo '<div class="' . esc_attr($class) . '">';
4190 + echo sprintf(
4191 + '<input type="url"
4192 + id="title_icon"
4193 + name="title_icon"
4194 + value="%s"
4195 + placeholder="Enter PNG URL"
4196 + class="regular-text"
4197 + %s />',
4198 + $title_icon_url,
4199 + esc_attr($disabled)
4200 + );
4201 +
4202 + // Preview container for the icon
4203 + if (!empty($title_icon_url)) {
4204 + echo '<div class="icon-preview" style="margin-top: 10px;">';
4205 + echo '<img src="' . esc_url($title_icon_url) . '" alt="Title Icon Preview" style="max-width: 48px; height: auto;" />';
4206 + echo '</div>';
4207 + }
4208 +
4209 + echo '<p class="description">Upload your PNG icon and paste the URL here. Recommended size: 48x48 pixels.</p>';
4210 +
4211 + if (!$this->is_activated) {
4212 + echo '<div class="pro-feature-overlay">';
4213 + echo '<a href="https://mxchat.ai/" target="_blank">';
4214 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4215 + echo '</a>';
4216 + echo '</div>';
4217 + }
4218 + echo '</div>';
4219 +}
4220 +
4221 +public function mxchat_chat_input_font_color_callback() {
4222 + $disabled = $this->is_activated ? '' : 'disabled';
4223 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4224 +
4225 + echo '<div class="' . esc_attr($class) . '">';
4226 + echo sprintf(
4227 + '<input type="text"
4228 + id="chat_input_font_color"
4229 + name="chat_input_font_color"
4230 + value="%s"
4231 + class="my-color-field"
4232 + data-default-color="#555555"
4233 + %s />',
4234 + isset($this->options['chat_input_font_color']) ? esc_attr($this->options['chat_input_font_color']) : '#555555',
4235 + esc_attr($disabled)
4236 + );
4237 +
4238 + if (!$this->is_activated) {
4239 + echo '<div class="pro-feature-overlay">';
4240 + echo '<a href="https://mxchat.ai/" target="_blank">';
4241 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4242 + echo '</a>';
4243 + echo '</div>';
4244 + }
4245 + echo '</div>';
4246 +}
4247 +
4248 +public function mxchat_append_to_body_callback() {
4249 + // Get value from options array, default to 'off'
4250 + $append_to_body = isset($this->options['append_to_body']) ? $this->options['append_to_body'] : 'off';
4251 + $checked = ($append_to_body === 'on') ? 'checked' : '';
4252 +
4253 + echo '<label class="toggle-switch">';
4254 + echo sprintf(
4255 + '<input type="checkbox" id="append_to_body" name="append_to_body" value="on" %s />',
4256 + esc_attr($checked)
4257 + );
4258 + echo '<span class="slider"></span>';
4259 + echo '</label>';
4260 + echo '<p class="description">Enable this option to automatically append the chat widget to the body of every page (recommended). No need to manually use the shortcode [mxchat_chatbot floating="yes"].</p>';
4261 +}
4262 +
4263 +
4264 +
7915 4265 public function mxchat_privacy_toggle_callback() {
7916 4266 // Load from mxchat_options array
7917 4267 $options = get_option('mxchat_options', []);
7918 4268
@@ -7922,9 +4272,9 @@
7922 4272
7923 4273 // Get privacy text with fallback
7924 4274 $privacy_text = isset($options['privacy_text'])
7925 4275 ? $options['privacy_text']
7926 - : __('By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.', 'mxchat');
4276 + : 'By chatting, you agree to our <a href="https://example.com/privacy-policy" target="_blank">privacy policy</a>.';
7927 4277
7928 4278 // Output the toggle switch
7929 4279 echo '<label class="toggle-switch">';
7930 4280 echo sprintf(
@@ -7932,8 +4282,9 @@
7932 4282 esc_attr($checked)
7933 4283 );
7934 4284 echo '<span class="slider"></span>';
7935 4285 echo '</label>';
4286 + echo '<p class="description">Enable this option to display a privacy notice below the chat widget.</p>';
7936 4287
7937 4288 // Output the custom text input field
7938 4289 echo sprintf(
7939 4290 '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
@@ -7938,8 +4289,9 @@
7938 4289 echo sprintf(
7939 4290 '<textarea id="privacy_text" name="privacy_text" rows="5" cols="50" class="regular-text">%s</textarea>',
7940 4291 esc_textarea($privacy_text)
7941 4292 );
4293 + echo '<p class="description">Enter the privacy policy text. You can include HTML links.</p>';
7942 4294 }
7943 4295
7944 4296
7945 4297 public function mxchat_complianz_toggle_callback() {
@@ -7949,18 +4301,39 @@
7949 4301 // Get complianz toggle value with fallback
7950 4302 $complianz_toggle = isset($options['complianz_toggle']) ? $options['complianz_toggle'] : 'off';
7951 4303 $checked = ($complianz_toggle === 'on') ? 'checked' : '';
7952 4304
4305 + // Check if the plugin is activated (paid feature)
4306 + $disabled = $this->is_activated ? '' : 'disabled';
4307 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4308 +
4309 + echo '<div class="' . esc_attr($class) . '">';
4310 +
7953 4311 // Output the toggle switch
7954 4312 echo '<label class="toggle-switch">';
7955 4313 echo sprintf(
7956 - '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s />',
7957 - esc_attr($checked)
4314 + '<input type="checkbox" id="complianz_toggle" name="complianz_toggle" value="on" %s %s />',
4315 + esc_attr($checked),
4316 + esc_attr($disabled)
7958 4317 );
7959 4318 echo '<span class="slider"></span>';
7960 4319 echo '</label>';
4320 +
4321 + echo '<p class="description">Enable this option to apply Complianz consent logic to the chatbot (must have Complianz Plugin).</p>';
4322 +
4323 + // If the feature is not activated, show the Pro feature overlay
4324 + if (!$this->is_activated) {
4325 + echo '<div class="pro-feature-overlay">';
4326 + echo '<a href="https://mxchat.ai/" target="_blank">';
4327 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4328 + echo '</a>';
4329 + echo '</div>';
4330 + }
4331 +
4332 + echo '</div>';
7961 4333 }
7962 4334
4335 +
7963 4336 public function mxchat_link_target_toggle_callback() {
7964 4337 // Load from mxchat_options array
7965 4338 $options = get_option('mxchat_options', []);
7966 4339
@@ -7975,8 +4348,9 @@
7975 4348 esc_attr($checked)
7976 4349 );
7977 4350 echo '<span class="slider"></span>';
7978 4351 echo '</label>';
4352 + echo '<p class="description">Enable to open links in a new tab (default is to open in the same tab).</p>';
7979 4353 }
7980 4354
7981 4355 public function mxchat_chat_persistence_toggle_callback() {
7982 4356 // Load from mxchat_options array
@@ -7985,18 +4359,39 @@
7985 4359 // Get chat persistence toggle value with fallback
7986 4360 $chat_persistence_toggle = isset($options['chat_persistence_toggle']) ? $options['chat_persistence_toggle'] : 'off';
7987 4361 $checked = ($chat_persistence_toggle === 'on') ? 'checked' : '';
7988 4362
4363 + // Check if the plugin is activated (paid feature)
4364 + $disabled = $this->is_activated ? '' : 'disabled';
4365 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4366 +
4367 + echo '<div class="' . esc_attr($class) . '">';
4368 +
7989 4369 // Output the toggle switch
7990 4370 echo '<label class="toggle-switch">';
7991 4371 echo sprintf(
7992 - '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s />',
7993 - esc_attr($checked)
4372 + '<input type="checkbox" id="chat_persistence_toggle" name="chat_persistence_toggle" value="on" %s %s />',
4373 + esc_attr($checked),
4374 + esc_attr($disabled)
7994 4375 );
7995 4376 echo '<span class="slider"></span>';
7996 4377 echo '</label>';
4378 +
4379 + echo '<p class="description">Enable to keep chat history when users navigate tabs or return to the site within 24 hours.</p>';
4380 +
4381 + // If not activated, show Pro feature overlay
4382 + if (!$this->is_activated) {
4383 + echo '<div class="pro-feature-overlay">';
4384 + echo '<a href="https://mxchat.ai/" target="_blank">';
4385 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4386 + echo '</a>';
4387 + echo '</div>';
4388 + }
4389 +
4390 + echo '</div>';
7997 4391 }
7998 4392
4393 +
7999 4394 public function mxchat_popular_question_1_callback() {
8000 4395 // Load the full plugin options array
8001 4396 $all_options = get_option('mxchat_options', []);
8002 4397
@@ -8004,12 +4399,14 @@
8004 4399 $popular_question_1 = isset($all_options['popular_question_1']) ? $all_options['popular_question_1'] : '';
8005 4400
8006 4401 // Render the input field
8007 4402 printf(
8008 - '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="%s" class="regular-text" />',
8009 - esc_attr($popular_question_1),
8010 - esc_attr__('Enter Quick Question 1', 'mxchat')
4403 + '<input type="text" id="popular_question_1" name="popular_question_1" value="%s" placeholder="Enter Popular Question 1" class="regular-text" />',
4404 + esc_attr($popular_question_1)
8011 4405 );
4406 +
4407 + // Add a description for the field
4408 + echo '<p class="description">This will be the first popular question in the chatbot.</p>';
8012 4409 }
8013 4410
8014 4411
8015 4412 public function mxchat_popular_question_2_callback() {
@@ -8018,39 +4415,84 @@
8018 4415
8019 4416 // Retrieve the specific option for popular_question_2
8020 4417 $popular_question_2 = isset($all_options['popular_question_2']) ? $all_options['popular_question_2'] : '';
8021 4418
4419 + // Check if the plugin is activated (paid feature)
4420 + $disabled = $this->is_activated ? '' : 'disabled';
4421 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4422 +
4423 + echo '<div class="' . esc_attr($class) . '">';
4424 +
8022 4425 // Render the input field
8023 4426 printf(
8024 - '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="%s" class="regular-text" />',
4427 + '<input type="text" id="popular_question_2" name="popular_question_2" value="%s" placeholder="Enter Popular Question 2" class="regular-text" %s />',
8025 4428 esc_attr($popular_question_2),
8026 - esc_attr__('Enter Quick Question 2', 'mxchat')
4429 + esc_attr($disabled)
8027 4430 );
4431 +
4432 + // Add a description for the field
4433 + echo '<p class="description">This will be the second popular question in the chatbot.</p>';
4434 +
4435 + // If not activated, show Pro feature overlay
4436 + if (!$this->is_activated) {
4437 + echo '<div class="pro-feature-overlay">';
4438 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4439 + echo '</div>';
4440 + }
4441 +
4442 + echo '</div>';
8028 4443 }
8029 4444
8030 4445
4446 +
8031 4447 public function mxchat_popular_question_3_callback() {
8032 - // Load the full plugin options array
8033 - $all_options = get_option('mxchat_options', []);
4448 + // Load the full plugin options array
4449 + $all_options = get_option('mxchat_options', []);
8034 4450
8035 - // Retrieve the specific option for popular_question_3
8036 - $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
4451 + // Retrieve the specific option for popular_question_3
4452 + $popular_question_3 = isset($all_options['popular_question_3']) ? $all_options['popular_question_3'] : '';
8037 4453
8038 - // Render the input field
8039 - printf(
8040 - '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="%s" class="regular-text" />',
8041 - esc_attr($popular_question_3),
8042 - esc_attr(__('Enter Quick Question 3', 'mxchat'))
8043 - );
4454 + // Check if the plugin is activated (paid feature)
4455 + $disabled = $this->is_activated ? '' : 'disabled';
4456 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4457 +
4458 + echo '<div class="' . esc_attr($class) . '">';
4459 +
4460 + // Render the input field
4461 + printf(
4462 + '<input type="text" id="popular_question_3" name="popular_question_3" value="%s" placeholder="Enter Popular Question 3" class="regular-text" %s />',
4463 + esc_attr($popular_question_3),
4464 + esc_attr($disabled)
4465 + );
4466 +
4467 + // Add a description for the field
4468 + echo '<p class="description">This will be the third popular question in the chatbot.</p>';
4469 +
4470 + // If not activated, show Pro feature overlay
4471 + if (!$this->is_activated) {
4472 + echo '<div class="pro-feature-overlay">';
4473 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4474 + echo '</div>';
4475 + }
4476 +
4477 + echo '</div>';
8044 4478 }
8045 4479
4480 +
8046 4481 public function mxchat_additional_popular_questions_callback() {
4482 + // Load from both possible sources for backwards compatibility
8047 4483 $options = get_option('mxchat_options', []);
8048 4484 $additional_questions = isset($options['additional_popular_questions'])
8049 4485 ? $options['additional_popular_questions']
8050 4486 : get_option('additional_popular_questions', array());
8051 4487
4488 + // Check if the feature is activated (paid feature)
4489 + $disabled = $this->is_activated ? '' : 'disabled';
4490 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4491 +
4492 + echo '<div class="' . esc_attr($class) . '">';
8052 4493 echo '<div id="mxchat-additional-questions-container">';
4494 +
8053 4495 if (!empty($additional_questions)) {
8054 4496 foreach ($additional_questions as $index => $question) {
8055 4497 printf(
8056 4498 '<div class="mxchat-question-row">
@@ -8055,19 +4497,20 @@
8055 4497 printf(
8056 4498 '<div class="mxchat-question-row">
8057 4499 <input type="text" name="additional_popular_questions[]"
8058 4500 value="%s"
8059 - placeholder="%s"
4501 + placeholder="Enter Additional Popular Question %d"
8060 4502 class="regular-text mxchat-question-input"
8061 - data-question-index="%d" />
4503 + data-question-index="%d"
4504 + %s />
8062 4505 <button type="button" class="button mxchat-remove-question"
8063 - aria-label="%s">%s</button>
4506 + aria-label="Remove question" %s>Remove</button>
8064 4507 </div>',
8065 4508 esc_attr($question),
8066 - esc_attr(sprintf(__('Enter Additional Quick Question %d', 'mxchat'), $index + 4)),
4509 + $index + 4,
8067 4510 $index,
8068 - esc_attr(__('Remove question', 'mxchat')),
8069 - esc_html__('Remove', 'mxchat')
4511 + esc_attr($disabled),
4512 + esc_attr($disabled)
8070 4513 );
8071 4514 }
8072 4515 } else {
8073 4516 printf(
@@ -8073,40 +4516,52 @@
8073 4516 printf(
8074 4517 '<div class="mxchat-question-row">
8075 4518 <input type="text" name="additional_popular_questions[]"
8076 4519 value=""
8077 - placeholder="%s"
4520 + placeholder="Enter Additional Popular Question 4"
8078 4521 class="regular-text mxchat-question-input"
8079 - data-question-index="0" />
4522 + data-question-index="0"
4523 + %s />
8080 4524 <button type="button" class="button mxchat-remove-question"
8081 - aria-label="%s">%s</button>
4525 + aria-label="Remove question" %s>Remove</button>
8082 4526 </div>',
8083 - esc_attr(__('Enter Additional Quick Question 4', 'mxchat')),
8084 - esc_attr(__('Remove question', 'mxchat')),
8085 - esc_html__('Remove', 'mxchat')
4527 + esc_attr($disabled),
4528 + esc_attr($disabled)
8086 4529 );
8087 4530 }
4531 +
8088 4532 echo '</div>';
4533 +
8089 4534 printf(
8090 - '<button type="button" class="button mxchat-add-question" aria-label="%s">%s</button>',
8091 - esc_attr(__('Add question', 'mxchat')),
8092 - esc_html__('Add Question', 'mxchat')
4535 + '<button type="button" class="button mxchat-add-question" aria-label="Add question" %s>Add Question</button>',
4536 + esc_attr($disabled)
8093 4537 );
4538 +
4539 + echo '<p class="description">You can add more popular questions beyond the default three here.</p>';
4540 +
4541 + if (!$this->is_activated) {
4542 + echo '<div class="pro-feature-overlay">';
4543 + echo '<a href="https://mxchat.ai/" target="_blank">';
4544 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4545 + echo '</a>';
4546 + echo '</div>';
4547 + }
4548 +
4549 + echo '</div>';
8094 4550 }
8095 4551
4552 +
8096 4553 public function mxchat_brave_api_key_callback() {
8097 4554 $brave_api_key = isset($this->options['brave_api_key']) ? esc_attr($this->options['brave_api_key']) : '';
8098 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8099 4555
8100 4556 echo '<div class="api-key-wrapper">';
8101 4557 echo sprintf(
8102 - '<input type="text" id="brave_api_key" name="brave_api_key" value="%s" class="regular-text mxchat-autosave-field mxchat-api-key-field" autocomplete="new-password" data-lpignore="true" data-form-type="other" data-nonce="%s" />',
8103 - $brave_api_key,
8104 - $nonce
4558 + '<input type="password" id="brave_api_key" name="brave_api_key" value="%s" class="regular-text" />',
4559 + $brave_api_key
8105 4560 );
8106 - echo '<button type="button" id="toggleBraveApiKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
4561 + echo '<button type="button" id="toggleBraveApiKeyVisibility">Show</button>';
8107 4562 echo '</div>';
8108 - echo '<p class="description">' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '</p>';
4563 + echo '<p class="description">' . __('Enter your Brave Search API Key here. (See FAQ for details)', 'mxchat') . '</p>';
8109 4564 }
8110 4565
8111 4566 public function mxchat_brave_image_count_callback() {
8112 4567 $brave_image_count = isset($this->options['brave_image_count'])
@@ -8111,18 +4566,14 @@
8111 4566 public function mxchat_brave_image_count_callback() {
8112 4567 $brave_image_count = isset($this->options['brave_image_count'])
8113 4568 ? intval($this->options['brave_image_count'])
8114 4569 : 4;
8115 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8116 4570
8117 - echo '<div class="mxchat-field-wrapper">';
8118 4571 echo sprintf(
8119 4572 '<input type="number" id="brave_image_count" name="brave_image_count"
8120 - value="%d" min="1" max="6" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8121 - $brave_image_count,
8122 - $nonce
4573 + value="%d" min="1" max="6" class="small-text" />',
4574 + $brave_image_count
8123 4575 );
8124 - echo '</div>';
8125 4576 echo '<p class="description">' . __('Select the number of images to return (1-6).', 'mxchat') . '</p>';
8126 4577 }
8127 4578
8128 4579 public function mxchat_brave_safe_search_callback() {
@@ -8128,12 +4579,10 @@
8128 4579 public function mxchat_brave_safe_search_callback() {
8129 4580 $brave_safe_search = isset($this->options['brave_safe_search'])
8130 4581 ? esc_attr($this->options['brave_safe_search'])
8131 4582 : 'strict';
8132 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8133 4583
8134 - echo '<div class="mxchat-field-wrapper">';
8135 - echo '<select id="brave_safe_search" name="brave_safe_search" class="mxchat-autosave-field" data-nonce="' . $nonce . '">';
4584 + echo '<select id="brave_safe_search" name="brave_safe_search">';
8136 4585 echo sprintf(
8137 4586 '<option value="strict" %s>%s</option>',
8138 4587 selected($brave_safe_search, 'strict', false),
8139 4588 __('Strict', 'mxchat')
@@ -8143,11 +4592,10 @@
8143 4592 selected($brave_safe_search, 'off', false),
8144 4593 __('Off', 'mxchat')
8145 4594 );
8146 4595 echo '</select>';
8147 - echo '</div>';
8148 4596 echo '<p class="description">' .
8149 - esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
4597 + __('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') .
8150 4598 '</p>';
8151 4599 }
8152 4600
8153 4601 public function mxchat_brave_news_count_callback() {
@@ -8153,19 +4601,15 @@
8153 4601 public function mxchat_brave_news_count_callback() {
8154 4602 $brave_news_count = isset($this->options['brave_news_count'])
8155 4603 ? intval($this->options['brave_news_count'])
8156 4604 : 3;
8157 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8158 4605
8159 - echo '<div class="mxchat-field-wrapper">';
8160 4606 echo sprintf(
8161 4607 '<input type="number" id="brave_news_count" name="brave_news_count"
8162 - value="%d" min="1" max="10" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8163 - $brave_news_count,
8164 - $nonce
4608 + value="%d" min="1" max="10" class="small-text" />',
4609 + $brave_news_count
8165 4610 );
8166 - echo '</div>';
8167 - echo '<p class="description">' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
4611 + echo '<p class="description">' . __('Select the number of news articles to retrieve (1-10).', 'mxchat') . '</p>';
8168 4612 }
8169 4613
8170 4614 public function mxchat_brave_country_callback() {
8171 4615 $brave_country = isset($this->options['brave_country'])
@@ -8170,19 +4614,15 @@
8170 4614 public function mxchat_brave_country_callback() {
8171 4615 $brave_country = isset($this->options['brave_country'])
8172 4616 ? esc_attr($this->options['brave_country'])
8173 4617 : 'us';
8174 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8175 4618
8176 - echo '<div class="mxchat-field-wrapper">';
8177 4619 echo sprintf(
8178 4620 '<input type="text" id="brave_country" name="brave_country"
8179 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8180 - $brave_country,
8181 - $nonce
4621 + value="%s" maxlength="2" class="small-text" />',
4622 + $brave_country
8182 4623 );
8183 - echo '</div>';
8184 - echo '<p class="description">' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
4624 + echo '<p class="description">' . __('Enter the country code (e.g., "us" for United States).', 'mxchat') . '</p>';
8185 4625 }
8186 4626
8187 4627 public function mxchat_brave_language_callback() {
8188 4628 $brave_language = isset($this->options['brave_language'])
@@ -8187,19 +4627,15 @@
8187 4627 public function mxchat_brave_language_callback() {
8188 4628 $brave_language = isset($this->options['brave_language'])
8189 4629 ? esc_attr($this->options['brave_language'])
8190 4630 : 'en';
8191 - $nonce = wp_create_nonce('mxchat_autosave_nonce');
8192 4631
8193 - echo '<div class="mxchat-field-wrapper">';
8194 4632 echo sprintf(
8195 4633 '<input type="text" id="brave_language" name="brave_language"
8196 - value="%s" maxlength="2" class="small-text mxchat-autosave-field" data-nonce="%s" />',
8197 - $brave_language,
8198 - $nonce
4634 + value="%s" maxlength="2" class="small-text" />',
4635 + $brave_language
8199 4636 );
8200 - echo '</div>';
8201 - echo '<p class="description">' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
4637 + echo '<p class="description">' . __('Enter the language code (e.g., "en" for English).', 'mxchat') . '</p>';
8202 4638 }
8203 4639
8204 4640
8205 4641
@@ -8210,118 +4646,138 @@
8210 4646 echo '<p>' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '</p>';
8211 4647 }
8212 4648
8213 4649 public function mxchat_chat_toolbar_toggle_callback() {
8214 - // Get chat toolbar toggle value with fallback
8215 - $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
8216 - $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
4650 + // Get chat toolbar toggle value with fallback
4651 + $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off';
4652 + $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : '';
8217 4653
8218 - // Output the toggle switch
8219 - echo '<label class="toggle-switch">';
8220 - echo sprintf(
8221 - '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s />',
8222 - esc_attr($checked)
8223 - );
8224 - echo '<span class="slider"></span>';
8225 - echo '</label>';
4654 + // Check if the plugin is activated (paid feature)
4655 + $disabled = $this->is_activated ? '' : 'disabled';
4656 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8226 4657
8227 - echo '<p class="description">' . esc_html__('Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).', 'mxchat') . '</p>';
8228 -}
4658 + echo '<div class="' . esc_attr($class) . '">';
8229 4659
8230 -/**
8231 - * Callback for PDF upload button toggle setting
8232 - */
8233 -public function mxchat_show_pdf_upload_button_callback() {
8234 - // Get toggle value with fallback
8235 - $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on';
8236 - $checked = ($show_pdf_button === 'on') ? 'checked' : '';
4660 + // Output the toggle switch
4661 + echo '<label class="toggle-switch">';
4662 + echo sprintf(
4663 + '<input type="checkbox" id="chat_toolbar_toggle" name="chat_toolbar_toggle" value="on" %s %s />',
4664 + esc_attr($checked),
4665 + esc_attr($disabled)
4666 + );
4667 + echo '<span class="slider"></span>';
4668 + echo '</label>';
8237 4669
8238 - // Output the toggle switch
8239 - echo '<label class="toggle-switch">';
8240 - echo sprintf(
8241 - '<input type="checkbox" id="show_pdf_upload_button" name="show_pdf_upload_button" value="on" %s />',
8242 - esc_attr($checked)
8243 - );
8244 - echo '<span class="slider"></span>';
8245 - echo '</label>';
4670 + // Pro feature overlay
4671 + if (!$this->is_activated) {
4672 + echo '<div class="pro-feature-overlay">';
4673 + echo '<a href="https://mxchat.ai/" target="_blank">';
4674 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4675 + echo '</a>';
4676 + echo '</div>';
4677 + }
8246 4678
8247 - echo '<p class="description">' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
4679 + echo '</div>';
4680 + echo '<p class="description">Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).</p>';
8248 4681 }
8249 4682
8250 -/**
8251 - * Callback for Word upload button toggle setting
8252 - */
8253 -public function mxchat_show_word_upload_button_callback() {
8254 - // Get toggle value with fallback
8255 - $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on';
8256 - $checked = ($show_word_button === 'on') ? 'checked' : '';
8257 4683
8258 - // Output the toggle switch
8259 - echo '<label class="toggle-switch">';
8260 - echo sprintf(
8261 - '<input type="checkbox" id="show_word_upload_button" name="show_word_upload_button" value="on" %s />',
8262 - esc_attr($checked)
8263 - );
8264 - echo '<span class="slider"></span>';
8265 - echo '</label>';
8266 -
8267 - echo '<p class="description">' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '</p>';
8268 -}
8269 -
8270 4684 public function mxchat_pdf_intent_trigger_text_callback() {
8271 - $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
4685 + $disabled = $this->is_activated ? '' : 'disabled';
4686 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4687 + $default_text = "Please provide the URL to the PDF you'd like to discuss.";
8272 4688
4689 + echo '<div class="' . esc_attr($class) . '">';
8273 4690 echo sprintf(
8274 4691 '<textarea id="pdf_intent_trigger_text"
8275 4692 name="pdf_intent_trigger_text"
8276 4693 rows="3"
8277 4694 cols="50"
8278 - placeholder="%s">%s</textarea>',
8279 - esc_attr__('Enter trigger text', 'mxchat'),
4695 + placeholder="Enter trigger text"
4696 + %s>%s</textarea>',
4697 + esc_attr($disabled),
8280 4698 isset($this->options['pdf_intent_trigger_text'])
8281 4699 ? esc_textarea($this->options['pdf_intent_trigger_text'])
8282 4700 : esc_textarea($default_text)
8283 4701 );
8284 - echo '<p class="description">' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '</p>';
4702 + echo '<p class="description">Text displayed when the intent is triggered.</p>';
4703 +
4704 + if (!$this->is_activated) {
4705 + echo '<div class="pro-feature-overlay">';
4706 + echo '<a href="https://mxchat.ai/" target="_blank">';
4707 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4708 + echo '</a>';
4709 + echo '</div>';
4710 + }
4711 + echo '</div>';
8285 4712 }
8286 4713
8287 4714 public function mxchat_pdf_intent_success_text_callback() {
8288 - $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat');
4715 + $disabled = $this->is_activated ? '' : 'disabled';
4716 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4717 + $default_text = "I've processed the PDF. What questions do you have about it?";
8289 4718
4719 + echo '<div class="' . esc_attr($class) . '">';
8290 4720 echo sprintf(
8291 4721 '<textarea id="pdf_intent_success_text"
8292 4722 name="pdf_intent_success_text"
8293 4723 rows="3"
8294 4724 cols="50"
8295 - placeholder="%s">%s</textarea>',
8296 - esc_attr__('Enter success text', 'mxchat'),
4725 + placeholder="Enter success text"
4726 + %s>%s</textarea>',
4727 + esc_attr($disabled),
8297 4728 isset($this->options['pdf_intent_success_text'])
8298 4729 ? esc_textarea($this->options['pdf_intent_success_text'])
8299 4730 : esc_textarea($default_text)
8300 4731 );
8301 - echo '<p class="description">' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '</p>';
4732 + echo '<p class="description">Text displayed when the intent is successful.</p>';
4733 +
4734 + if (!$this->is_activated) {
4735 + echo '<div class="pro-feature-overlay">';
4736 + echo '<a href="https://mxchat.ai/" target="_blank">';
4737 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4738 + echo '</a>';
4739 + echo '</div>';
4740 + }
4741 + echo '</div>';
8302 4742 }
8303 4743
8304 4744 public function mxchat_pdf_intent_error_text_callback() {
8305 - $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
4745 + $disabled = $this->is_activated ? '' : 'disabled';
4746 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4747 + $default_text = "Sorry, I couldn't process the PDF. Please ensure it's a valid file.";
8306 4748
4749 + echo '<div class="' . esc_attr($class) . '">';
8307 4750 echo sprintf(
8308 4751 '<textarea id="pdf_intent_error_text"
8309 4752 name="pdf_intent_error_text"
8310 4753 rows="3"
8311 4754 cols="50"
8312 - placeholder="%s">%s</textarea>',
8313 - esc_attr__('Enter error text', 'mxchat'),
4755 + placeholder="Enter error text"
4756 + %s>%s</textarea>',
4757 + esc_attr($disabled),
8314 4758 isset($this->options['pdf_intent_error_text'])
8315 4759 ? esc_textarea($this->options['pdf_intent_error_text'])
8316 4760 : esc_textarea($default_text)
8317 4761 );
8318 - echo '<p class="description">' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '</p>';
4762 + echo '<p class="description">Text displayed when an error occurs during the intent.</p>';
4763 +
4764 + if (!$this->is_activated) {
4765 + echo '<div class="pro-feature-overlay">';
4766 + echo '<a href="https://mxchat.ai/" target="_blank">';
4767 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4768 + echo '</a>';
4769 + echo '</div>';
4770 + }
4771 + echo '</div>';
8319 4772 }
8320 4773
8321 4774 public function mxchat_pdf_max_pages_callback() {
4775 + $disabled = $this->is_activated ? '' : 'disabled';
4776 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8322 4777 $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
8323 4778
4779 + echo '<div class="' . esc_attr($class) . '">';
8324 4780 echo sprintf(
8325 4781 '<input type="range"
8326 4782 id="pdf_max_pages"
8327 4783 name="pdf_max_pages"
@@ -8327,24 +4783,37 @@
8327 4783 name="pdf_max_pages"
8328 4784 min="1"
8329 4785 max="69"
8330 4786 value="%d"
4787 + %s
8331 4788 class="range-slider" />',
8332 - esc_attr($max_pages)
4789 + esc_attr($max_pages),
4790 + esc_attr($disabled)
8333 4791 );
8334 4792 echo '<span id="pdf_max_pages_output">' . esc_html($max_pages) . '</span>';
8335 - echo '<p class="description">' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '</p>';
4793 + echo '<p class="description">Set the maximum number of document pages users can upload for processing. (1-69 pages)</p>';
4794 +
4795 + if (!$this->is_activated) {
4796 + echo '<div class="pro-feature-overlay">';
4797 + echo '<a href="https://mxchat.ai/" target="_blank">';
4798 + echo '<img src="' . esc_url(plugin_dir_url(__FILE__) . '../images/pro-only-dark.png') . '" alt="Pro Only" />';
4799 + echo '</a>';
4800 + echo '</div>';
4801 + }
4802 + echo '</div>';
8336 4803 }
8337 4804
8338 4805 public function mxchat_live_agent_status_callback() {
8339 - // Always get fresh options instead of using cached $this->options
8340 - $fresh_options = get_option('mxchat_options');
8341 - $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off';
4806 + $disabled = $this->is_activated ? '' : 'disabled';
4807 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4808 + $status = isset($this->options['live_agent_status']) ? $this->options['live_agent_status'] : 'off';
8342 4809
4810 + echo '<div class="' . esc_attr($class) . '">';
8343 4811 echo '<label class="toggle-switch">';
8344 4812 echo sprintf(
8345 - '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s />',
8346 - checked($status, 'on', false)
4813 + '<input type="checkbox" id="live_agent_status" name="live_agent_status" value="on" %s %s />',
4814 + checked($status, 'on', false),
4815 + esc_attr($disabled)
8347 4816 );
8348 4817 echo '<span class="slider"></span>';
8349 4818 echo '</label>';
8350 4819 echo '<label for="live_agent_status" class="mxchat-status-label">';
@@ -8349,167 +4818,98 @@
8349 4818 echo '</label>';
8350 4819 echo '<label for="live_agent_status" class="mxchat-status-label">';
8351 4820 echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
8352 4821 echo '</label>';
4822 +
4823 + if (!$this->is_activated) {
4824 + echo '<div class="pro-feature-overlay">';
4825 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4826 + echo '</div>';
4827 + }
4828 + echo '</div>';
8353 4829 }
8354 4830
4831 +
4832 +// Away Message Callback
8355 4833 public function mxchat_live_agent_away_message_callback() {
4834 + $disabled = $this->is_activated ? '' : 'disabled';
4835 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8356 4836 $message = isset($this->options['live_agent_away_message'])
8357 4837 ? $this->options['live_agent_away_message']
8358 4838 : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
8359 4839
4840 + echo '<div class="' . esc_attr($class) . '">';
8360 4841 printf(
8361 - '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50">%s</textarea>',
4842 + '<textarea id="live_agent_away_message" name="live_agent_away_message" rows="3" cols="50" %s>%s</textarea>',
4843 + esc_attr($disabled),
8362 4844 esc_textarea($message)
8363 4845 );
8364 4846 echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
4847 +
4848 + if (!$this->is_activated) {
4849 + echo '<div class="pro-feature-overlay">';
4850 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4851 + echo '</div>';
4852 + }
4853 + echo '</div>';
8365 4854 }
8366 4855
8367 4856 public function mxchat_live_agent_notification_message_callback() {
4857 + $disabled = $this->is_activated ? '' : 'disabled';
4858 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8368 4859 $message = isset($this->options['live_agent_notification_message'])
8369 4860 ? $this->options['live_agent_notification_message']
8370 4861 : __('Live agent has been notified.', 'mxchat');
8371 4862
4863 + echo '<div class="' . esc_attr($class) . '">';
8372 4864 printf(
8373 - '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50">%s</textarea>',
4865 + '<textarea id="live_agent_notification_message" name="live_agent_notification_message" rows="3" cols="50" %s>%s</textarea>',
4866 + esc_attr($disabled),
8374 4867 esc_textarea($message)
8375 4868 );
8376 4869 echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
4870 +
4871 + if (!$this->is_activated) {
4872 + echo '<div class="pro-feature-overlay">';
4873 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4874 + echo '</div>';
4875 + }
4876 + echo '</div>';
8377 4877 }
8378 4878
8379 4879 public function mxchat_live_agent_webhook_url_callback() {
4880 + $disabled = $this->is_activated ? '' : 'disabled';
4881 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8380 4882 $webhook_url = isset($this->options['live_agent_webhook_url'])
8381 4883 ? esc_url($this->options['live_agent_webhook_url'])
8382 4884 : esc_url(get_option('live_agent_webhook_url', ''));
8383 4885
4886 + echo '<div class="' . esc_attr($class) . '">';
8384 4887 printf(
8385 - '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" />',
8386 - $webhook_url
4888 + '<input type="password" id="live_agent_webhook_url" name="live_agent_webhook_url" value="%s" class="regular-text" %s />',
4889 + $webhook_url,
4890 + esc_attr($disabled)
8387 4891 );
8388 - echo '<button type="button" id="toggleWebhookUrlVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8389 - echo '<p class="description">' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '</p>';
8390 -}
4892 + echo '<button type="button" id="toggleWebhookUrlVisibility">Show</button>';
4893 + echo '<p class="description">Enter your Slack webhook URL for live agent notifications.</p>';
8391 4894
8392 -public function mxchat_live_agent_secret_key_callback() {
8393 - printf(
8394 - '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" />',
8395 - isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : ''
8396 - );
8397 - echo '<button type="button" id="toggleSecretKeyVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8398 - echo '<p class="description">' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '</p>';
4895 + if (!$this->is_activated) {
4896 + echo '<div class="pro-feature-overlay">';
4897 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4898 + echo '</div>';
4899 + }
4900 + echo '</div>';
8399 4901 }
8400 4902
8401 -public function mxchat_live_agent_bot_token_callback() {
8402 - printf(
8403 - '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" />',
8404 - isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : ''
8405 - );
8406 - echo '<button type="button" id="toggleBotTokenVisibility">' . esc_html__('Show', 'mxchat') . '</button>';
8407 - echo '<p class="description">' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '</p>';
8408 -}
8409 4903
8410 -public function mxchat_live_agent_user_ids_callback() {
8411 - $user_ids = isset($this->options['live_agent_user_ids'])
8412 - ? esc_textarea($this->options['live_agent_user_ids'])
8413 - : '';
8414 -
8415 - printf(
8416 - '<textarea id="live_agent_user_ids" name="live_agent_user_ids" rows="4" class="large-text">%s</textarea>',
8417 - $user_ids
8418 - );
8419 - echo '<p class="description">' . esc_html__('Enter Slack User IDs of agents who should be automatically invited to chat channels (one per line). Find user IDs in Slack profiles under "More" → "Copy member ID". Example: U1234567890', 'mxchat') . '</p>';
8420 -}
8421 -
8422 -/**
8423 - * Telegram Integration Callbacks
8424 - */
8425 -public function mxchat_telegram_section_callback() {
8426 - echo '<p>' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '</p>';
8427 -}
8428 -
8429 -public function mxchat_telegram_status_callback() {
8430 - $fresh_options = get_option('mxchat_options');
8431 - $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off';
8432 -
8433 - echo '<label class="toggle-switch">';
8434 - echo sprintf(
8435 - '<input type="checkbox" id="telegram_status" name="telegram_status" value="on" %s />',
8436 - checked($status, 'on', false)
8437 - );
8438 - echo '<span class="slider"></span>';
8439 - echo '</label>';
8440 - echo '<label for="telegram_status" class="mxchat-status-label">';
8441 - echo '<span class="status-text">' . ($status === 'on' ? esc_html__('Online', 'mxchat') : esc_html__('Offline', 'mxchat')) . '</span>';
8442 - echo '</label>';
8443 -}
8444 -
8445 -public function mxchat_telegram_notification_message_callback() {
8446 - $message = isset($this->options['telegram_notification_message'])
8447 - ? $this->options['telegram_notification_message']
8448 - : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat');
8449 -
8450 - printf(
8451 - '<textarea id="telegram_notification_message" name="telegram_notification_message" rows="3" cols="50">%s</textarea>',
8452 - esc_textarea($message)
8453 - );
8454 - echo '<p class="description">' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '</p>';
8455 -}
8456 -
8457 -public function mxchat_telegram_away_message_callback() {
8458 - $message = isset($this->options['telegram_away_message'])
8459 - ? $this->options['telegram_away_message']
8460 - : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat');
8461 -
8462 - printf(
8463 - '<textarea id="telegram_away_message" name="telegram_away_message" rows="3" cols="50">%s</textarea>',
8464 - esc_textarea($message)
8465 - );
8466 - echo '<p class="description">' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '</p>';
8467 -}
8468 -
8469 -public function mxchat_telegram_bot_token_callback() {
8470 - printf(
8471 - '<input type="password" id="telegram_bot_token" name="telegram_bot_token" value="%s" class="regular-text" />',
8472 - isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : ''
8473 - );
8474 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_bot_token\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
8475 - echo '<p class="description">' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '</p>';
8476 -}
8477 -
8478 -public function mxchat_telegram_group_id_callback() {
8479 - printf(
8480 - '<input type="text" id="telegram_group_id" name="telegram_group_id" value="%s" class="regular-text" />',
8481 - isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : ''
8482 - );
8483 - echo '<p class="description">' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '</p>';
8484 -}
8485 -
8486 -public function mxchat_telegram_webhook_secret_callback() {
8487 - $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : '';
8488 -
8489 - // Auto-generate secret if empty
8490 - if (empty($secret)) {
8491 - $secret = wp_generate_password(64, false, false);
8492 - $options = get_option('mxchat_options', []);
8493 - $options['telegram_webhook_secret'] = $secret;
8494 - update_option('mxchat_options', $options);
8495 - $this->options['telegram_webhook_secret'] = $secret;
8496 - }
8497 -
8498 - printf(
8499 - '<input type="password" id="telegram_webhook_secret" name="telegram_webhook_secret" value="%s" class="regular-text" />',
8500 - esc_attr($secret)
8501 - );
8502 - echo '<button type="button" class="button button-secondary" onclick="var f=document.getElementById(\'telegram_webhook_secret\'); if(f.type===\'password\'){f.type=\'text\';this.textContent=\'' . esc_js(__('Hide', 'mxchat')) . '\';}else{f.type=\'password\';this.textContent=\'' . esc_js(__('Show', 'mxchat')) . '\';}">' . esc_html__('Show', 'mxchat') . '</button>';
8503 - echo '<p class="description">' . esc_html__('Secret token for webhook verification. Use this when setting up your Telegram webhook with the secret_token parameter.', 'mxchat') . '</p>';
8504 -}
8505 -
8506 4904 public function mxchat_similarity_threshold_callback() {
8507 4905 // Load from mxchat_options array
8508 4906 $options = get_option('mxchat_options', []);
8509 4907
8510 - // Get value from options array with default of 35
8511 - $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35;
4908 + // Get value with backwards compatibility
4909 + $threshold = isset($options['similarity_threshold'])
4910 + ? $options['similarity_threshold']
4911 + : get_option('mxchat_similarity_threshold', 80);
8512 4912
8513 4913 echo '<div class="slider-container">';
8514 4914 echo sprintf(
8515 4915 '<input type="range"
@@ -8514,9 +4914,9 @@
8514 4914 echo sprintf(
8515 4915 '<input type="range"
8516 4916 id="similarity_threshold"
8517 4917 name="similarity_threshold"
8518 - min="20"
4918 + min="70"
8519 4919 max="85"
8520 4920 step="1"
8521 4921 value="%s"
8522 4922 class="range-slider" />',
@@ -8526,789 +4926,376 @@
8526 4926 '<span id="threshold_value" class="range-value">%s</span>',
8527 4927 esc_html($threshold)
8528 4928 );
8529 4929 echo '</div>';
4930 +
4931 + echo '<p class="description">';
4932 + echo 'Set the similarity threshold (recommended: 75) to balance accuracy; too high might limit your bot\'s ability to find relevant knowledge.';
4933 + echo '</p>';
8530 4934 }
8531 4935
8532 -public function mxchat_rag_sources_limit_callback() {
8533 - // Load from mxchat_options array
8534 - $options = get_option('mxchat_options', []);
8535 4936
8536 - // Get value from options array with default of 3
8537 - $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3;
8538 4937
8539 - echo '<div class="slider-container">';
8540 - echo sprintf(
8541 - '<input type="range"
8542 - id="rag_sources_limit"
8543 - name="rag_sources_limit"
8544 - min="3"
8545 - max="10"
8546 - step="1"
8547 - value="%s"
8548 - class="range-slider" />',
8549 - esc_attr($rag_sources_limit)
4938 +public function mxchat_live_agent_secret_key_callback() {
4939 + $disabled = $this->is_activated ? '' : 'disabled';
4940 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
4941 +
4942 + echo '<div class="' . esc_attr($class) . '">';
4943 + printf(
4944 + '<input type="password" id="live_agent_secret_key" name="live_agent_secret_key" value="%s" class="regular-text" %s />',
4945 + isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : '',
4946 + esc_attr($disabled)
8550 4947 );
8551 - echo sprintf(
8552 - '<span id="rag_sources_limit_value" class="range-value">%s</span>',
8553 - esc_html($rag_sources_limit)
8554 - );
4948 + echo '<button type="button" id="toggleSecretKeyVisibility">Show</button>';
4949 + echo '<p class="description">Secret key for validating Slack requests. Keep this secure.</p>';
4950 +
4951 + if (!$this->is_activated) {
4952 + echo '<div class="pro-feature-overlay">';
4953 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4954 + echo '</div>';
4955 + }
8555 4956 echo '</div>';
8556 4957 }
8557 4958
8558 -public function mxchat_rag_chunks_limit_callback() {
8559 - // Load from mxchat_options array
8560 - $options = get_option('mxchat_options', []);
4959 +public function mxchat_live_agent_bot_token_callback() {
4960 + $disabled = $this->is_activated ? '' : 'disabled';
4961 + $class = $this->is_activated ? 'pro-feature-wrapper active' : 'pro-feature-wrapper inactive';
8561 4962
8562 - // Get value from options array with default of 15
8563 - $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15;
4963 + echo '<div class="' . esc_attr($class) . '">';
4964 + printf(
4965 + '<input type="password" id="live_agent_bot_token" name="live_agent_bot_token" value="%s" class="regular-text" %s />',
4966 + isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : '',
4967 + esc_attr($disabled)
4968 + );
4969 + echo '<button type="button" id="toggleBotTokenVisibility">Show</button>';
4970 + echo '<p class="description">Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.</p>';
8564 4971
8565 - echo '<div class="slider-container">';
8566 - echo sprintf(
8567 - '<input type="range"
8568 - id="rag_chunks_limit"
8569 - name="rag_chunks_limit"
8570 - min="8"
8571 - max="20"
8572 - step="1"
8573 - value="%s"
8574 - class="range-slider" />',
8575 - esc_attr($rag_chunks_limit)
8576 - );
8577 - echo sprintf(
8578 - '<span id="rag_chunks_limit_value" class="range-value">%s</span>',
8579 - esc_html($rag_chunks_limit)
8580 - );
4972 + if (!$this->is_activated) {
4973 + echo '<div class="pro-feature-overlay">';
4974 + echo '<a href="https://mxchat.ai/" target="_blank"><img src="' . plugin_dir_url(__FILE__) . '../images/pro-only-dark.png" alt="Pro Only" /></a>';
4975 + echo '</div>';
4976 + }
8581 4977 echo '</div>';
8582 4978 }
8583 4979
8584 4980 public function mxchat_enqueue_admin_assets() {
8585 - // Get plugin version
8586 - $version = MXCHAT_VERSION;
4981 + wp_enqueue_style('wp-color-picker');
8587 4982
8588 - // Use file modification time for development (remove in production)
8589 - if (defined('WP_DEBUG') && WP_DEBUG) {
8590 - $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php');
8591 - }
4983 + // Get the plugin version or file modification time for cache busting
4984 + $plugin_version = '1.6.1'; // Replace this with your plugin's version
8592 4985
8593 - $current_page = isset($_GET['page']) ? $_GET['page'] : '';
8594 - $plugin_url = plugin_dir_url(__FILE__) . '../';
4986 + // File paths
4987 + $color_picker_js_path = plugin_dir_path(__FILE__) . '../js/my-color-picker.js';
4988 + $embedding_check_js_path = plugin_dir_path(__FILE__) . '../js/embedding-check.js';
4989 + $admin_css_path = plugin_dir_path(__FILE__) . '../css/admin-style.css';
4990 + $transcripts_js_path = plugin_dir_path(__FILE__) . '../js/mxchat_transcripts.js';
8595 4991
8596 - // Only load on MxChat pages
8597 - if (strpos($current_page, 'mxchat') === false) {
8598 - return;
8599 - }
4992 + // Check if files exist and get modification times
4993 + $color_picker_version = file_exists($color_picker_js_path) ? filemtime($color_picker_js_path) : $plugin_version;
4994 + $embedding_check_version = file_exists($embedding_check_js_path) ? filemtime($embedding_check_js_path) : $plugin_version;
4995 + $admin_css_version = file_exists($admin_css_path) ? filemtime($admin_css_path) : $plugin_version;
4996 + $transcripts_js_version = file_exists($transcripts_js_path) ? filemtime($transcripts_js_path) : $plugin_version;
8600 4997
8601 - // Always load these on all MxChat pages
8602 - $this->enqueue_core_admin_assets($plugin_url, $version);
8603 - $this->enqueue_page_specific_assets($current_page, $plugin_url, $version);
8604 - $this->localize_admin_scripts($current_page);
8605 -}
8606 -private function enqueue_core_admin_assets($plugin_url, $version) {
8607 - // Core admin styles
8608 - wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version);
8609 - wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version);
4998 + // Enqueue scripts and styles with corrected paths
4999 + wp_enqueue_script(
5000 + 'mxchat-color-picker',
5001 + plugin_dir_url(__FILE__) . '../js/my-color-picker.js',
5002 + array('wp-color-picker'),
5003 + $color_picker_version,
5004 + true
5005 + );
8610 5006
8611 - // New sidebar navigation styles (for main settings page)
8612 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
5007 + wp_enqueue_script(
5008 + 'mxchat-embedding-check',
5009 + plugin_dir_url(__FILE__) . '../js/embedding-check.js',
5010 + array(),
5011 + $embedding_check_version,
5012 + true
5013 + );
8613 5014
8614 - // Core admin scripts
8615 - wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true);
8616 -}
8617 -private function enqueue_page_specific_assets($current_page, $plugin_url, $version) {
8618 - switch ($current_page) {
8619 - case 'mxchat-prompts':
8620 - // Knowledge processing page assets
8621 - wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version);
8622 - wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true);
8623 - // Add the knowledge processing script (common script needed for WordPress dismiss functionality)
8624 - wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true);
8625 - break;
5015 + wp_enqueue_script(
5016 + 'mxchat-transcripts-js',
5017 + plugin_dir_url(__FILE__) . '../js/mxchat_transcripts.js',
5018 + array('jquery'),
5019 + $transcripts_js_version,
5020 + true
5021 + );
8626 5022
8627 - case 'mxchat-transcripts':
8628 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
8629 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
8630 - // Load transcripts-specific styles
8631 - wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version);
8632 - wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true);
8633 - break;
5023 + wp_enqueue_script(
5024 + 'mxchat-admin-js',
5025 + plugin_dir_url(__FILE__) . '../js/mxchat-admin.js',
5026 + array('jquery'),
5027 + $plugin_version,
5028 + true
5029 + );
8634 5030
8635 - case 'mxchat-actions':
8636 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
8637 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
8638 - // Load actions-specific styles
8639 - wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version);
8640 - wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true);
8641 5031
8642 - // Localize script data for actions page
8643 - $is_activated = get_option('mxchat_pro_license_status') === 'active';
8644 - wp_localize_script('mxchat-actions-js', 'mxchActionsData', array(
8645 - 'ajaxUrl' => admin_url('admin-ajax.php'),
8646 - 'nonce' => wp_create_nonce('mxchat_actions_nonce'),
8647 - 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'),
8648 - 'editNonce' => wp_create_nonce('mxchat_edit_intent'),
8649 - 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'),
8650 - 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'),
8651 - 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
8652 - 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
8653 - 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
8654 - 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
8655 - 'isActivated' => $is_activated,
8656 - 'i18n' => array(
8657 - 'confirmDelete' => __('Are you sure you want to delete this action?', 'mxchat'),
8658 - 'confirmBulkDelete' => __('Are you sure you want to delete the selected actions?', 'mxchat'),
8659 - 'saving' => __('Saving...', 'mxchat'),
8660 - 'saved' => __('Saved successfully!', 'mxchat'),
8661 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
8662 - 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'),
8663 - 'addonRequired' => __('This feature requires an add-on.', 'mxchat')
8664 - )
8665 - ));
8666 - break;
8667 -
8668 - case 'mxchat-activation':
8669 - // Load admin sidebar CSS first (shared styles for sidebar navigation)
8670 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
8671 - // Load pro page-specific styles
8672 - wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version);
8673 - // Load pro page JavaScript
8674 - wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true);
8675 - // Load activation script for license activation/deactivation
8676 - wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true);
8677 - break;
8678 -
8679 - case 'mxchat-content':
8680 - // Load admin sidebar CSS (shared styles for sidebar navigation)
8681 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
8682 - // Load content page-specific styles
8683 - wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version);
8684 - // Load content page JavaScript
8685 - wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true);
8686 - break;
8687 -
8688 - case 'mxchat-api-access':
8689 - // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons).
8690 - wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version);
8691 - wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true);
8692 - wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array(
8693 - 'copied' => __('Copied', 'mxchat'),
8694 - ));
8695 - break;
8696 - default:
8697 - wp_enqueue_script(
8698 - 'mxchat-test-streaming-js',
8699 - $plugin_url . 'js/mxchat-test-streaming.js',
8700 - ['jquery'],
8701 - $version,
8702 - true
8703 - );
8704 -
8705 - wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [
8706 - 'ajax_url' => admin_url('admin-ajax.php'),
8707 - 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'),
8708 - 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce')
8709 - ]);
8710 -
8711 - // Testing Tab: Load chatbot assets for the embedded testing chatbot
8712 - wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version);
8713 - wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version);
8714 -
8715 - wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true);
8716 - wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true);
8717 -
8718 - // Allow add-ons to enqueue their public CSS/JS for the testing chatbot
8719 - do_action('mxchat_enqueue_testing_tab_assets');
8720 -
8721 - // Localize mxchatChat for the chatbot JS (same settings as frontend)
8722 - $options = get_option('mxchat_options', array());
8723 - $prompts_options = get_option('mxchat_prompts_options', array());
8724 - $theme_options = get_option('mxchat_theme_options', array());
8725 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
8726 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
8727 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
8728 -
8729 - wp_localize_script('mxchat-chat-js', 'mxchatChat', array(
8730 - 'ajax_url' => admin_url('admin-ajax.php'),
8731 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
8732 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.1-chat-latest',
8733 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
8734 - 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off',
8735 - 'link_target_toggle' => $options['link_target_toggle'] ?? 'off',
8736 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
8737 - 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on',
8738 - 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff',
8739 - 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121',
8740 - 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121',
8741 - 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff',
8742 - 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121',
8743 - 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121',
8744 - 'close_button_color' => $options['close_button_color'] ?? '#fff',
8745 - 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121',
8746 - 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff',
8747 - 'icon_color' => $options['icon_color'] ?? '#fff',
8748 - 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121',
8749 - 'chat_persistence_toggle' => 'off', // Always off for testing chatbot
8750 - 'appendWidgetToBody' => 'off',
8751 - 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff',
8752 - 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333',
8753 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
8754 - 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676',
8755 - 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff',
8756 - 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121',
8757 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
8758 - 'email_collection_enabled' => 'off', // No email collection in testing
8759 - 'initial_email_state' => null,
8760 - 'skip_email_check' => true,
8761 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
8762 - 'skip_inline_colors' => $skip_inline_colors,
8763 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array()
8764 - ));
8765 -
8766 - // Localize testing tab script data
8767 - wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array(
8768 - 'ajaxUrl' => admin_url('admin-ajax.php'),
8769 - 'nonce' => wp_create_nonce('mxchat_test_nonce'),
8770 - 'isAdmin' => true,
8771 - 'testingEnabled' => true
8772 - ));
8773 -
8774 - // Add testing enabled flag for the chatbot to return debug data
8775 - add_action('admin_footer', function() {
8776 - echo '<script>window.mxchatTestingEnabled = true;</script>';
8777 - });
8778 -
8779 - break;
8780 - }
8781 -}
8782 -private function localize_admin_scripts($current_page) {
8783 - // Base localization data for main admin script
8784 - $base_data = array(
8785 - 'ajax_url' => admin_url('admin-ajax.php'),
8786 - 'nonce' => wp_create_nonce('mxchat_admin_nonce'),
8787 - 'admin_url' => admin_url(),
8788 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
8789 - 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
8790 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
8791 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
8792 - 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'),
8793 - 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'),
8794 - 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'),
8795 - 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'),
8796 - 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'),
8797 - 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'),
8798 - 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'),
8799 - 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'),
8800 - 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'),
8801 - 'is_activated' => $this->is_activated ? '1' : '0',
8802 - 'status_refresh_interval' => 5000,
8803 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
8804 - 'ajaxurl' => admin_url('admin-ajax.php')
5032 +wp_localize_script('mxchat-admin-js', 'mxchatAdmin', array(
5033 + 'ajax_url' => admin_url('admin-ajax.php'),
5034 + 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'),
5035 + 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'),
5036 + 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
5037 +));
5038 + // Enqueue the admin CSS
5039 + wp_enqueue_style(
5040 + 'mxchat-admin-css',
5041 + plugin_dir_url(__FILE__) . '../css/admin-style.css',
5042 + array(),
5043 + $admin_css_version
8805 5044 );
8806 5045
8807 - // Localize main admin script with base data
8808 - wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data);
8809 -
8810 - // Page-specific localizations
8811 - $this->localize_page_specific_scripts($current_page);
8812 -}
8813 -private function localize_page_specific_scripts($current_page) {
8814 - switch ($current_page) {
8815 - case 'mxchat-prompts':
8816 - // Status updater localization
8817 - wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array(
8818 - 'ajax_url' => admin_url('admin-ajax.php'),
8819 - 'nonce' => wp_create_nonce('mxchat_status_nonce')
8820 - ));
8821 -
8822 - // Content selector localization
8823 - $mxchat_options_for_selector = get_option('mxchat_options', array());
8824 - $acf_pdf_extract_default = !empty($mxchat_options_for_selector['acf_pdf_extract_default']);
8825 - wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array(
8826 - 'ajaxurl' => admin_url('admin-ajax.php'),
8827 - 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'),
8828 - 'acfPdfExtractDefault' => $acf_pdf_extract_default ? 1 : 0,
8829 - 'i18n' => array(
8830 - 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'),
8831 - 'selectAll' => __('Select All', 'mxchat'),
8832 - 'process' => __('Process Selected', 'mxchat'),
8833 - 'cancel' => __('Cancel', 'mxchat'),
8834 - 'noResults' => __('No content found.', 'mxchat'),
8835 - 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'),
8836 - 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat')
8837 - )
8838 - ));
8839 -
8840 - wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array(
8841 - 'ajax_url' => admin_url('admin-ajax.php'),
8842 - 'status_nonce' => wp_create_nonce('mxchat_status_nonce'),
8843 - 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'),
8844 - 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'),
8845 - 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
8846 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
8847 - 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'),
8848 - 'admin_url' => admin_url(),
8849 - 'ajaxurl' => admin_url('admin-ajax.php'),
8850 - 'status_refresh_interval' => 2000,
8851 - 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'
8852 - ));
8853 - break;
8854 -
8855 - case 'mxchat-activation':
8856 - wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array(
8857 - 'ajax_url' => admin_url('admin-ajax.php'),
8858 - 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce')
8859 - ));
8860 - break;
8861 -
8862 - case 'mxchat-content':
8863 - wp_localize_script('mxchat-content-js', 'mxchatContent', array(
8864 - 'ajaxUrl' => admin_url('admin-ajax.php'),
8865 - 'nonce' => wp_create_nonce('mxchat_content_nonce'),
8866 - 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'),
8867 - 'previewUrl' => home_url('/?p='),
8868 - 'isActivated' => $this->is_activated(),
8869 - 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'),
8870 - 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'),
8871 - 'seoOptimize' => array(
8872 - 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on',
8873 - 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on',
8874 - 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on',
8875 - 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on',
8876 - 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on',
8877 - 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on',
8878 - 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on',
8879 - ),
8880 - 'i18n' => array(
8881 - 'generating' => __('Generating...', 'mxchat'),
8882 - 'planning' => __('Planning content structure...', 'mxchat'),
8883 - 'images' => __('Generating images...', 'mxchat'),
8884 - 'writing' => __('Writing full content...', 'mxchat'),
8885 - 'creating' => __('Creating WordPress post...', 'mxchat'),
8886 - 'done' => __('Content generated successfully!', 'mxchat'),
8887 - 'error' => __('An error occurred. Please try again.', 'mxchat'),
8888 - 'editSuccess' => __('Content updated successfully.', 'mxchat'),
8889 - 'promptEmpty' => __('Please enter a prompt.', 'mxchat'),
8890 - )
8891 - ));
8892 - break;
8893 -
8894 - case 'mxchat-transcripts':
8895 - // Get chart data for localization
8896 - $chart_data = $this->get_transcripts_chart_data();
8897 -
8898 - wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array(
8899 - 'ajax_url' => admin_url('admin-ajax.php'),
8900 - 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'),
8901 - 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'),
8902 - 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'),
8903 - 'translate_nonce' => wp_create_nonce('mxchat_translate_messages')
8904 - ));
8905 -
8906 - // Localize chart data separately - use array_values to ensure proper JSON array encoding
8907 - wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array(
8908 - 'labels' => array_values($chart_data['labels']),
8909 - 'chats' => array_values($chart_data['chats']),
8910 - 'messages' => array_values($chart_data['messages'])
8911 - ));
8912 - break;
8913 -
8914 - case 'mxchat-settings':
8915 - default:
8916 - // Color picker and settings localization
8917 - wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
8918 - 'ajax_url' => admin_url('admin-ajax.php'),
8919 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
8920 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
8921 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
8922 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
8923 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
8924 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
8925 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
8926 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
8927 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
8928 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
8929 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
8930 - 'pre_chat_message' => $this->options['pre_chat_message'] ?? esc_html__('Hey there! Ask me anything!', 'mxchat'),
8931 - 'rate_limit_message' => $this->options['rate_limit_message'] ?? esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'),
8932 - 'loops_api_key' => $this->options['loops_api_key'] ?? '',
8933 - 'loops_mailing_list' => $this->options['loops_mailing_list'] ?? '',
8934 - 'triggered_phrase_response' => $this->options['triggered_phrase_response'] ?? esc_html__('Would you like to join our mailing list? Please provide your email below.', 'mxchat'),
8935 - 'email_capture_response' => $this->options['email_capture_response'] ?? esc_html__('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'),
8936 - 'pdf_intent_trigger_text' => $this->options['pdf_intent_trigger_text'] ?? esc_html__("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'),
8937 - 'pdf_intent_success_text' => $this->options['pdf_intent_success_text'] ?? esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat'),
8938 - 'pdf_intent_error_text' => $this->options['pdf_intent_error_text'] ?? esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'),
8939 - 'pdf_max_pages' => $this->options['pdf_max_pages'] ?? 69,
8940 - 'live_agent_webhook_url' => $this->options['live_agent_webhook_url'] ?? '',
8941 - 'live_agent_secret_key' => $this->options['live_agent_secret_key'] ?? '',
8942 - 'live_agent_bot_token' => $this->options['live_agent_bot_token'] ?? '',
8943 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
8944 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
8945 - 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
8946 - 'show_pdf_upload_button' => $this->options['show_pdf_upload_button'] ?? 'on',
8947 - 'show_word_upload_button' => $this->options['show_word_upload_button'] ?? 'on',
8948 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
8949 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
8950 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
8951 - ));
8952 - break;
8953 - }
8954 -
8955 - // Additional localization that was in the original code
8956 - wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array(
5046 + // Localize the script for color picker and settings
5047 + wp_localize_script('mxchat-color-picker', 'mxchatStyleSettings', array(
8957 5048 'ajax_url' => admin_url('admin-ajax.php'),
8958 - 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'),
5049 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
5050 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
5051 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
5052 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
5053 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
5054 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
5055 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
5056 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
5057 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
5058 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
5059 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
5060 + 'pre_chat_message' => $this->options['pre_chat_message'] ?? 'Hey there! Ask me anything!',
5061 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
5062 + 'loops_api_key' => $this->options['loops_api_key'] ?? '',
5063 + 'loops_mailing_list' => $this->options['loops_mailing_list'] ?? '',
5064 + 'triggered_phrase_response' => $this->options['triggered_phrase_response'] ?? 'Would you like to join our mailing list? Please provide your email below.',
5065 + 'email_capture_response' => $this->options['email_capture_response'] ?? 'Thank you for providing your email! You\'ve been added to our list.',
5066 + 'pdf_intent_trigger_text' => $this->options['pdf_intent_trigger_text'] ?? "Please provide the URL to the PDF you'd like to discuss.",
5067 + 'pdf_intent_success_text' => $this->options['pdf_intent_success_text'] ?? "I've processed the PDF. What questions do you have about it?",
5068 + 'pdf_intent_error_text' => $this->options['pdf_intent_error_text'] ?? "Sorry, I couldn't process the PDF. Please ensure it's a valid file.",
5069 + 'pdf_max_pages' => $this->options['pdf_max_pages'] ?? 69,
5070 + 'live_agent_webhook_url' => $this->options['live_agent_webhook_url'] ?? '',
5071 + 'live_agent_secret_key' => $this->options['live_agent_secret_key'] ?? '',
5072 + 'live_agent_bot_token' => $this->options['live_agent_bot_token'] ?? '',
5073 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
5074 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
5075 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
5076 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
5077 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
5078 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
8959 5079 ));
8960 5080 }
8961 5081
8962 -public function mxchat_sanitize($input) {
8963 - $new_input = array();
5082 + public function mxchat_sanitize($input) {
5083 + $new_input = array();
8964 5084
8965 - if (isset($input['api_key'])) {
8966 - $new_input['api_key'] = sanitize_text_field($input['api_key']);
8967 - }
5085 + if (isset($input['api_key'])) {
5086 + $new_input['api_key'] = sanitize_text_field($input['api_key']);
5087 + }
8968 5088
8969 - if (isset($input['similarity_threshold'])) {
8970 - $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
8971 - $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range
8972 - }
5089 + if (isset($input['similarity_threshold'])) {
5090 + $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer
5091 + $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 70), 85); // Enforce range
5092 + }
8973 5093
8974 - if (isset($input['rag_sources_limit'])) {
8975 - $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer
8976 - $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10
8977 - }
5094 + if (isset($input['xai_api_key'])) {
5095 + $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
5096 + }
8978 5097
8979 - if (isset($input['rag_chunks_limit'])) {
8980 - $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer
8981 - $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20
8982 - }
5098 + if (isset($input['claude_api_key'])) {
5099 + $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
5100 + }
8983 5101
8984 - if (isset($input['xai_api_key'])) {
8985 - $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']);
8986 - }
5102 + if (isset($input['enable_woocommerce_integration'])) {
5103 + $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
5104 + }
8987 5105
8988 - if (isset($input['claude_api_key'])) {
8989 - $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']);
8990 - }
5106 + if (isset($input['privacy_toggle'])) {
5107 + $new_input['privacy_toggle'] = $input['privacy_toggle'];
5108 + }
8991 5109
8992 - if (isset($input['enable_streaming_toggle'])) {
8993 - $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off';
8994 - } else {
8995 - // If checkbox not checked, it won't be in $input, so set to 'off'
8996 - $new_input['enable_streaming_toggle'] = 'off';
8997 - }
5110 + if (isset($input['complianz_toggle'])) {
5111 + $new_input['complianz_toggle'] = $input['complianz_toggle'];
5112 + }
8998 5113
8999 - if (isset($input['enable_web_search'])) {
9000 - $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off';
9001 - } else {
9002 - // If checkbox not checked, it won't be in $input, so set to 'off'
9003 - $new_input['enable_web_search'] = 'off';
9004 - }
5114 + // Handle custom privacy text input
5115 + if (isset($input['privacy_text'])) {
5116 + // Allow basic HTML for links
5117 + $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
5118 + }
9005 5119
9006 - if (isset($input['deepseek_api_key'])) {
9007 - $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']);
9008 - }
5120 + if (isset($input['system_prompt_instructions'])) {
5121 + $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
5122 + }
9009 5123
9010 - if (isset($input['gemini_api_key'])) {
9011 - $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']);
9012 - }
5124 + if (isset($input['mxchat_pro_email'])) {
5125 + $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
5126 + }
9013 5127
9014 - if (isset($input['enable_woocommerce_integration'])) {
9015 - $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off';
9016 - }
5128 + if (isset($input['mxchat_activation_key'])) {
5129 + $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
5130 + }
9017 5131
9018 - if (isset($input['privacy_toggle'])) {
9019 - $new_input['privacy_toggle'] = $input['privacy_toggle'];
9020 - }
5132 + if (isset($input['append_to_body'])) {
5133 + $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
5134 + }
9021 5135
9022 - if (isset($input['complianz_toggle'])) {
9023 - $new_input['complianz_toggle'] = $input['complianz_toggle'];
9024 - }
5136 + if (isset($input['top_bar_title'])) {
5137 + $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
5138 + }
9025 5139
9026 - // Handle custom privacy text input
9027 - if (isset($input['privacy_text'])) {
9028 - // Allow basic HTML for links
9029 - $new_input['privacy_text'] = wp_kses_post($input['privacy_text']);
9030 - }
5140 + if (isset($input['enable_email_block'])) {
5141 + $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
5142 + }
9031 5143
9032 - if (isset($input['system_prompt_instructions'])) {
9033 - $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']);
9034 - }
5144 + if (isset($input['email_blocker_header_content'])) {
5145 + // wp_kses_post() allows standard HTML tags permitted by WordPress
5146 + $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
5147 + }
5148 + if (isset($input['email_blocker_button_text'])) {
5149 + $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
5150 + }
9035 5151
9036 - if (isset($input['mxchat_pro_email'])) {
9037 - $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']);
9038 - }
5152 + if (isset($input['intro_message'])) {
5153 + $new_input['intro_message'] = sanitize_textarea_field($input['intro_message']); // Changed from sanitize_text_field
5154 + }
9039 5155
9040 - if (isset($input['mxchat_activation_key'])) {
9041 - $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']);
9042 - }
5156 + if (isset($input['input_copy'])) {
5157 + $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
5158 + }
9043 5159
9044 - if (isset($input['append_to_body'])) {
9045 - $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off';
9046 - }
9047 5160
9048 - // Post type visibility settings
9049 - if (isset($input['post_type_visibility_mode'])) {
9050 - $allowed_modes = array('all', 'include', 'exclude');
9051 - $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes)
9052 - ? $input['post_type_visibility_mode']
9053 - : 'all';
9054 - }
9055 -
9056 - if (isset($input['post_type_visibility_list'])) {
9057 - if (is_array($input['post_type_visibility_list'])) {
9058 - $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']);
9059 - } else {
9060 - $new_input['post_type_visibility_list'] = array();
5161 + if (isset($input['rate_limit_message'])) {
5162 + $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
9061 5163 }
9062 - }
9063 5164
9064 - if (isset($input['contextual_awareness_toggle'])) {
9065 - $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off';
9066 -}
5165 + if (isset($input['rate_limit_logged_in'])) {
5166 + $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
5167 + $rate_limit = sanitize_text_field($input['rate_limit_logged_in']);
9067 5168
9068 - if (isset($input['citation_links_toggle'])) {
9069 - $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off';
9070 -}
5169 + if (in_array($rate_limit, $allowed_limits, true)) {
5170 + $new_input['rate_limit_logged_in'] = $rate_limit;
5171 + } else {
5172 + $new_input['rate_limit_logged_in'] = '100'; // Default for logged-in users
5173 + }
5174 + }
9071 5175
9072 - // Satisfaction rating prompt — defaults ON when unchecked (so first save
9073 - // doesn't accidentally disable it). The form posts 'on' when checked;
9074 - // unchecked checkboxes don't post a value at all, so we infer 'off' only
9075 - // when the autosave/PHP request explicitly clears it via empty string.
9076 - if (array_key_exists('satisfaction_rating_enabled', $input)) {
9077 - $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off';
9078 - }
5176 + if (isset($input['rate_limit_logged_out'])) {
5177 + $allowed_limits = array('1', '3', '5', '10', '15', '20', '100', 'unlimited'); // Add 'unlimited' to allowed values
5178 + $rate_limit = sanitize_text_field($input['rate_limit_logged_out']);
9079 5179
9080 - // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600;
9081 - // the 4 text strings are sanitized + capped server-side. Blank values are
9082 - // preserved so the integrator falls back to translated defaults.
9083 - if (array_key_exists('satisfaction_rating_idle_seconds', $input)) {
9084 - $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds'])));
9085 - }
9086 - if (array_key_exists('satisfaction_rating_question', $input)) {
9087 - $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200);
9088 - }
9089 - if (array_key_exists('satisfaction_rating_thanks', $input)) {
9090 - $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300);
9091 - }
9092 - if (array_key_exists('satisfaction_rating_placeholder', $input)) {
9093 - $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200);
9094 - }
9095 - if (array_key_exists('satisfaction_rating_saved', $input)) {
9096 - $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200);
9097 - }
5180 + if (in_array($rate_limit, $allowed_limits, true)) {
5181 + $new_input['rate_limit_logged_out'] = $rate_limit;
5182 + } else {
5183 + $new_input['rate_limit_logged_out'] = '10'; // Default for logged-out users
5184 + }
5185 + }
9098 5186
9099 - if (isset($input['top_bar_title'])) {
9100 - $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']);
9101 - }
5187 + if (isset($input['pre_chat_message'])) {
5188 + $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
5189 + }
9102 5190
9103 - if (isset($input['ai_agent_text'])) {
9104 - $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']);
5191 + if (isset($input['model'])) {
5192 + $allowed_models = array(
5193 + 'grok-beta',
5194 + 'grok-2',
5195 + 'claude-3-5-sonnet-20241022',
5196 + 'claude-3-opus-20240229',
5197 + 'claude-3-sonnet-20240229',
5198 + 'claude-3-haiku-20240307',
5199 + 'gpt-4o',
5200 + 'gpt-4o-mini',
5201 + 'gpt-4-turbo',
5202 + 'gpt-4',
5203 + 'gpt-3.5-turbo',
5204 + );
5205 + if (in_array($input['model'], $allowed_models)) {
5206 + $new_input['model'] = sanitize_text_field($input['model']);
5207 + }
9105 5208 }
9106 5209
9107 - if (isset($input['enable_email_block'])) {
9108 - $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']);
9109 - }
5210 + // Sanitize new pro features
5211 + if (isset($input['close_button_color'])) {
5212 + $new_input['close_button_color'] = sanitize_hex_color($input['close_button_color']);
5213 + }
9110 5214
9111 - if (isset($input['email_blocker_header_content'])) {
9112 - // wp_kses_post() allows standard HTML tags permitted by WordPress
9113 - $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']);
9114 - }
9115 - if (isset($input['email_blocker_button_text'])) {
9116 - $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']);
9117 - }
9118 - // Sanitize name field toggle
9119 - if (isset($input['enable_name_field'])) {
9120 - $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off';
9121 - } else {
9122 - $new_input['enable_name_field'] = 'off';
9123 - }
9124 - // Sanitize name field placeholder
9125 - if (isset($input['name_field_placeholder'])) {
9126 - $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']);
9127 - }
9128 - if (isset($input['intro_message'])) {
9129 - $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead
9130 - }
5215 + if (isset($input['chatbot_bg_color'])) {
5216 + $new_input['chatbot_bg_color'] = sanitize_hex_color($input['chatbot_bg_color']);
5217 + }
9131 5218
9132 - if (isset($input['input_copy'])) {
9133 - $new_input['input_copy'] = sanitize_text_field($input['input_copy']);
9134 - }
5219 + if (isset($input['woocommerce_consumer_key'])) {
5220 + $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
5221 + }
9135 5222
9136 - if (isset($input['rate_limit_message'])) {
9137 - $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']);
9138 - }
5223 + if (isset($input['woocommerce_consumer_secret'])) {
5224 + $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
5225 + }
9139 5226
9140 -// Handle the new rate limits format
9141 -if (isset($input['rate_limits']) && is_array($input['rate_limits'])) {
9142 - $new_input['rate_limits'] = array();
9143 - $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited');
9144 - $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly');
5227 + if (isset($input['user_message_bg_color'])) {
5228 + $new_input['user_message_bg_color'] = sanitize_hex_color($input['user_message_bg_color']);
5229 + }
9145 5230
9146 - foreach ($input['rate_limits'] as $role_id => $settings) {
9147 - $new_input['rate_limits'][$role_id] = array();
5231 + if (isset($input['user_message_font_color'])) {
5232 + $new_input['user_message_font_color'] = sanitize_hex_color($input['user_message_font_color']);
5233 + }
9148 5234
9149 - // Sanitize limit
9150 - if (isset($settings['limit'])) {
9151 - $limit = sanitize_text_field($settings['limit']);
9152 - if (in_array($limit, $allowed_limits, true)) {
9153 - $new_input['rate_limits'][$role_id]['limit'] = $limit;
9154 - } else {
9155 - $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default
9156 - }
5235 + if (isset($input['bot_message_bg_color'])) {
5236 + $new_input['bot_message_bg_color'] = sanitize_hex_color($input['bot_message_bg_color']);
9157 5237 }
9158 5238
9159 - // Sanitize timeframe
9160 - if (isset($settings['timeframe'])) {
9161 - $timeframe = sanitize_text_field($settings['timeframe']);
9162 - if (in_array($timeframe, $allowed_timeframes, true)) {
9163 - $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe;
9164 - } else {
9165 - $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default
9166 - }
5239 + if (isset($input['bot_message_font_color'])) {
5240 + $new_input['bot_message_font_color'] = sanitize_hex_color($input['bot_message_font_color']);
9167 5241 }
9168 5242
9169 - // Sanitize message
9170 - if (isset($settings['message'])) {
9171 - $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']);
5243 + if (isset($input['live_agent_message_bg_color'])) {
5244 + $new_input['live_agent_message_bg_color'] = sanitize_hex_color($input['live_agent_message_bg_color']);
9172 5245 }
9173 - }
9174 -}
9175 5246
9176 - if (isset($input['pre_chat_message'])) {
9177 - $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']);
9178 - }
5247 + if (isset($input['live_agent_message_font_color'])) {
5248 + $new_input['live_agent_message_font_color'] = sanitize_hex_color($input['live_agent_message_font_color']);
5249 + }
9179 5250
9180 - if (isset($input['voyage_api_key'])) {
9181 - $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']);
9182 - }
5251 + if (isset($input['mode_indicator_bg_color'])) {
5252 + $new_input['mode_indicator_bg_color'] = sanitize_hex_color($input['mode_indicator_bg_color']);
5253 + }
9183 5254
9184 - // Add to your sanitize function
9185 - if (isset($input['embedding_model'])) {
9186 - $allowed_models = array(
9187 - 'text-embedding-ada-002',
9188 - 'text-embedding-3-small',
9189 - 'text-embedding-3-large',
9190 - 'voyage-3-large',
9191 - 'gemini-embedding-001'
9192 - );
9193 - if (in_array($input['embedding_model'], $allowed_models)) {
9194 - $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']);
5255 + if (isset($input['mode_indicator_font_color'])) {
5256 + $new_input['mode_indicator_font_color'] = sanitize_hex_color($input['mode_indicator_font_color']);
9195 5257 }
9196 - }
9197 5258
9198 -if (isset($input['model'])) {
9199 - if ($input['model'] === 'openrouter') {
9200 - $new_input['model'] = 'openrouter';
9201 - } else {
9202 - $allowed_models = array(
9203 - 'gemini-3-pro-preview',
9204 - 'gemini-3-flash-preview',
9205 - 'gemini-2.5-pro',
9206 - 'gemini-2.5-flash',
9207 - 'gemini-2.5-flash-lite',
9208 - 'gemini-2.0-flash',
9209 - 'gemini-2.0-flash-lite',
9210 - 'gemini-1.5-pro',
9211 - 'gemini-1.5-flash',
9212 - 'grok-4-0709',
9213 - 'grok-4-1-fast-reasoning',
9214 - 'grok-4-1-fast-non-reasoning',
9215 - 'grok-3-beta',
9216 - 'grok-3-fast-beta',
9217 - 'grok-3-mini-beta',
9218 - 'grok-3-mini-fast-beta',
9219 - 'grok-2',
9220 - 'deepseek-chat',
9221 - 'claude-opus-4-7',
9222 - 'claude-opus-4-6',
9223 - 'claude-sonnet-4-6',
9224 - 'claude-opus-4-5',
9225 - 'claude-sonnet-4-5-20250929',
9226 - 'claude-opus-4-1-20250805',
9227 - 'claude-haiku-4-5-20251001',
9228 - 'claude-opus-4-20250514',
9229 - 'claude-sonnet-4-20250514',
9230 - 'gpt-5.2',
9231 - 'gpt-5.1-chat-latest',
9232 - 'gpt-5.1-2025-11-13',
9233 - 'gpt-5',
9234 - 'gpt-5-mini',
9235 - 'gpt-5-nano',
9236 - 'gpt-5.5',
9237 - 'gpt-5.4',
9238 - 'gpt-5.4-mini',
9239 - 'gpt-5.4-nano',
9240 - 'gpt-5.3-chat-latest',
9241 - 'custom-provider',
9242 - );
5259 + if (isset($input['toolbar_icon_color'])) {
5260 + $new_input['toolbar_icon_color'] = sanitize_hex_color($input['toolbar_icon_color']);
5261 + }
9243 5262
9244 - if (in_array($input['model'], $allowed_models)) {
9245 - $new_input['model'] = sanitize_text_field($input['model']);
9246 - } else {
9247 - // Fallback for any deprecated model
9248 - $new_input['model'] = 'gpt-5.1-chat-latest';
5263 + if (isset($input['top_bar_bg_color'])) {
5264 + $new_input['top_bar_bg_color'] = sanitize_hex_color($input['top_bar_bg_color']);
9249 5265 }
9250 - }
9251 -}
9252 -
9253 -if (isset($input['openrouter_selected_model'])) {
9254 - // Just sanitize it, don't validate against a whitelist
9255 - $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']);
9256 -}
9257 5266
9258 -// ADD THIS:
9259 -if (isset($input['openrouter_selected_model_name'])) {
9260 - $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']);
9261 -}
9262 -
9263 - if (isset($input['openrouter_api_key'])) {
9264 - $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']);
9265 - }
5267 + if (isset($input['send_button_font_color'])) {
5268 + $new_input['send_button_font_color'] = sanitize_hex_color($input['send_button_font_color']);
5269 + }
9266 5270
9267 - // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc.
9268 - if (isset($input['custom_provider_base_url'])) {
9269 - $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/'));
9270 - }
9271 - if (isset($input['custom_provider_api_key'])) {
9272 - $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']);
9273 - }
9274 - if (isset($input['custom_provider_model'])) {
9275 - $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']);
9276 - }
9277 - if (isset($input['custom_provider_auth_scheme'])) {
9278 - $scheme = sanitize_text_field($input['custom_provider_auth_scheme']);
9279 - $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer';
9280 - }
9281 - if (isset($input['custom_provider_for_embeddings'])) {
9282 - $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off';
9283 - }
9284 - if (isset($input['custom_provider_for_images'])) {
9285 - $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off';
9286 - }
9287 - if (isset($input['custom_provider_embedding_model'])) {
9288 - $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']);
9289 - }
9290 - if (isset($input['custom_provider_api_version'])) {
9291 - $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']);
9292 - }
5271 + if (isset($input['chatbot_background_color'])) {
5272 + $new_input['chatbot_background_color'] = sanitize_hex_color($input['chatbot_background_color']);
5273 + }
9293 5274
5275 + if (isset($input['icon_color'])) {
5276 + $new_input['icon_color'] = sanitize_hex_color($input['icon_color']);
5277 + }
9294 5278
5279 + if (isset($input['custom_icon'])) {
5280 + $new_input['custom_icon'] = esc_url_raw($input['custom_icon']);
5281 + }
9295 5282
9296 - if (isset($input['woocommerce_consumer_key'])) {
9297 - $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']);
9298 - }
9299 5283
9300 - if (isset($input['woocommerce_consumer_secret'])) {
9301 - $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']);
9302 - }
5284 + if (isset($input['title_icon'])) {
5285 + $new_input['title_icon'] = esc_url_raw($input['title_icon']);
5286 + }
9303 5287
5288 + if (isset($input['chat_input_font_color'])) {
5289 + $new_input['chat_input_font_color'] = sanitize_hex_color($input['chat_input_font_color']);
5290 + }
9304 5291
9305 - // Sanitize link_target_toggle
9306 - if (isset($input['link_target_toggle'])) {
9307 - $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
9308 - }
5292 + // Sanitize link_target_toggle
5293 + if (isset($input['link_target_toggle'])) {
5294 + $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off';
5295 + }
9309 5296
9310 - // Sanitize Loops API Key
5297 + // Sanitize Loops API Key
9311 5298 if (isset($input['loops_api_key'])) {
9312 5299 $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']);
9313 5300 }
9314 5301
@@ -9315,8 +5302,10 @@
9315 5302 if (isset($input['chat_persistence_toggle'])) {
9316 5303 $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off';
9317 5304 }
9318 5305
5306 +
5307 +
9319 5308 if (isset($input['popular_question_1'])) {
9320 5309 $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']);
9321 5310 }
9322 5311
@@ -9336,17 +5325,19 @@
9336 5325 if (isset($input['loops_mailing_list'])) {
9337 5326 $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']);
9338 5327 }
9339 5328
9340 -// Sanitize Triggered Phrase Response
5329 + // Sanitize Triggered Phrase Response
9341 5330 if (isset($input['triggered_phrase_response'])) {
9342 5331 $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']);
9343 5332 }
5333 +
9344 5334 if (isset($input['email_capture_response'])) {
9345 - $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']);
5335 + $new_input['email_capture_response'] = sanitize_textarea_field($input['email_capture_response']);
9346 5336 }
9347 5337
9348 - // Sanitize Brave Search Settings
5338 +
5339 + // Sanitize Brave Search Settings
9349 5340 if (isset($input['brave_api_key'])) {
9350 5341 $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']);
9351 5342 }
9352 5343
@@ -9361,9 +5352,9 @@
9361 5352 }
9362 5353
9363 5354 if (isset($input['brave_news_count'])) {
9364 5355 $news_count = intval($input['brave_news_count']);
9365 - $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
5356 + $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3;
9366 5357 }
9367 5358
9368 5359 if (isset($input['brave_country'])) {
9369 5360 $new_input['brave_country'] = sanitize_text_field($input['brave_country']);
@@ -9372,26 +5363,14 @@
9372 5363 if (isset($input['brave_language'])) {
9373 5364 $new_input['brave_language'] = sanitize_text_field($input['brave_language']);
9374 5365 }
9375 5366
5367 +
9376 5368 if (isset($input['chat_toolbar_toggle'])) {
9377 5369 $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off';
9378 5370 }
9379 5371
9380 - // Sanitize PDF upload button toggle
9381 - if (isset($input['show_pdf_upload_button'])) {
9382 - $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off';
9383 - } else {
9384 - $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked
9385 - }
9386 5372
9387 - // Sanitize Word upload button toggle
9388 - if (isset($input['show_word_upload_button'])) {
9389 - $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off';
9390 - } else {
9391 - $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked
9392 - }
9393 -
9394 5373 if (isset($input['pdf_intent_trigger_text'])) {
9395 5374 $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']);
9396 5375 }
9397 5376
@@ -9409,268 +5388,77 @@
9409 5388 $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range
9410 5389 }
9411 5390 }
9412 5391
9413 - if (isset($input['live_agent_webhook_url'])) {
9414 - $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
9415 - }
9416 - if (isset($input['live_agent_secret_key'])) {
9417 - $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
9418 - }
9419 5392
9420 - // Live Agent Integration
9421 - if (isset($input['live_agent_bot_token'])) {
9422 - $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
9423 - }
5393 + if (isset($input['live_agent_webhook_url'])) {
5394 + $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']);
5395 + }
5396 + if (isset($input['live_agent_secret_key'])) {
5397 + $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']);
5398 + }
9424 5399
9425 - if (isset($input['live_agent_user_ids'])) {
9426 - $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']);
9427 - }
5400 + // Live Agent Integration
5401 + if (isset($input['live_agent_bot_token'])) {
5402 + $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']);
5403 + }
9428 5404
9429 - if (isset($input['live_agent_status'])) {
9430 - $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
9431 - }
5405 +if (isset($input['live_agent_status'])) {
5406 + $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off';
5407 +}
9432 5408 if (isset($input['live_agent_away_message'])) {
9433 5409 $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']);
9434 5410 }
9435 - if (isset($input['live_agent_notification_message'])) {
5411 + if (isset($input['live_agent_notification_message'])) {
9436 5412 $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']);
9437 5413 }
9438 5414
9439 - // Telegram Integration
9440 - if (isset($input['telegram_status'])) {
9441 - $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off';
9442 - }
9443 - if (isset($input['telegram_bot_token'])) {
9444 - $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']);
9445 - }
9446 - if (isset($input['telegram_group_id'])) {
9447 - $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']);
9448 - }
9449 - if (isset($input['telegram_webhook_secret'])) {
9450 - $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']);
9451 - }
9452 - if (isset($input['telegram_notification_message'])) {
9453 - $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']);
9454 - }
9455 - if (isset($input['telegram_away_message'])) {
9456 - $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']);
9457 - }
9458 5415
9459 - // Sanitize script loading strategy
9460 - if (isset($input['script_loading_strategy'])) {
9461 - $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
9462 - $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies)
9463 - ? $input['script_loading_strategy']
9464 - : 'default';
5416 + return $new_input;
9465 5417 }
9466 5418
9467 - // Sanitize debug mode
9468 - if (isset($input['debug_mode'])) {
9469 - $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off';
9470 - }
9471 5419
9472 - // Content Generator Settings
9473 - if (isset($input['content_model'])) {
9474 - $new_input['content_model'] = sanitize_text_field($input['content_model']);
9475 - }
9476 - if (isset($input['content_image_model'])) {
9477 - $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']);
9478 - }
9479 - if (isset($input['content_image_quality'])) {
9480 - $q = sanitize_text_field($input['content_image_quality']);
9481 - $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto';
9482 - }
9483 - if (isset($input['content_enable_images'])) {
9484 - $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off';
9485 - }
9486 - if (isset($input['content_use_placeholders'])) {
9487 - $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off';
9488 - }
9489 - if (isset($input['content_internal_linking'])) {
9490 - $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off';
9491 - }
9492 - if (isset($input['content_tool_use'])) {
9493 - $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off';
9494 - }
9495 -
9496 - // SEO Optimize toggle fields
9497 - foreach (array('seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $seo_key) {
9498 - if (isset($input[$seo_key])) {
9499 - $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off';
5420 + // Method to append the chatbot to the body
5421 + public function mxchat_append_chatbot_to_body() {
5422 + $options = get_option('mxchat_options');
5423 + if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
5424 + echo do_shortcode('[mxchat_chatbot floating="yes"]');
9500 5425 }
9501 5426 }
9502 5427
9503 - // Preserve content generator settings when saving from main settings page
9504 - // (where content fields are not in the form submission)
9505 - $existing = get_option('mxchat_options', array());
9506 - foreach (array('content_model', 'content_image_model', 'content_image_quality', 'content_enable_images', 'content_use_placeholders', 'content_internal_linking', 'content_tool_use', 'seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $key) {
9507 - if (!isset($new_input[$key]) && isset($existing[$key])) {
9508 - $new_input[$key] = $existing[$key];
9509 - }
9510 - }
9511 5428
9512 - return $new_input;
9513 -}
9514 5429
9515 -/**
9516 - * Log a debug message if debug mode is enabled
9517 - *
9518 - * @param string $type The type of log entry (settings_save, api_error, activation, etc.)
9519 - * @param string $message The log message
9520 - * @param array $data Optional additional data to log
9521 - * @return bool Whether the message was logged
9522 - */
9523 -public static function mxchat_log_debug( $type, $message, $data = array() ) {
9524 - $options = get_option( 'mxchat_options', array() );
5430 +private static function mxchat_extract_main_content($html) {
5431 + $dom = new DOMDocument;
5432 + libxml_use_internal_errors(true); // Suppress HTML parsing errors
5433 + @$dom->loadHTML($html);
5434 + libxml_clear_errors();
9525 5435
9526 - // Check if debug mode is enabled
9527 - if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) {
9528 - return false;
9529 - }
5436 + $xpath = new DOMXPath($dom);
9530 5437
9531 - // Get current log
9532 - $log = get_option( 'mxchat_debug_log', array() );
9533 - if ( ! is_array( $log ) ) {
9534 - $log = array();
9535 - }
5438 + // Simplified selectors focusing on common content areas
5439 + $selectors = [
5440 + '//article',
5441 + '//*[@id="content"]',
5442 + '//*[@class="entry-content"]',
5443 + '//main',
5444 + ];
9536 5445
9537 - // Add new entry
9538 - $entry = array(
9539 - 'time' => current_time( 'Y-m-d H:i:s' ),
9540 - 'type' => sanitize_key( $type ),
9541 - 'message' => sanitize_text_field( $message ),
9542 - );
9543 -
9544 - if ( ! empty( $data ) ) {
9545 - $entry['data'] = $data;
9546 - }
9547 -
9548 - // Add to beginning of array (newest first)
9549 - array_unshift( $log, $entry );
9550 -
9551 - // Keep only last 100 entries
9552 - if ( count( $log ) > 100 ) {
9553 - $log = array_slice( $log, 0, 100 );
9554 - }
9555 -
9556 - // Save log
9557 - update_option( 'mxchat_debug_log', $log, false );
9558 -
9559 - return true;
9560 -}
9561 -
9562 -/**
9563 - * Get the debug log entries
9564 - *
9565 - * @return array The debug log entries
9566 - */
9567 -public static function mxchat_get_debug_log() {
9568 - $log = get_option( 'mxchat_debug_log', array() );
9569 - return is_array( $log ) ? $log : array();
9570 -}
9571 -
9572 -/**
9573 - * Clear the debug log
9574 - *
9575 - * @return bool Whether the log was cleared
9576 - */
9577 -public static function mxchat_clear_debug_log() {
9578 - return delete_option( 'mxchat_debug_log' );
9579 -}
9580 -
9581 -/**
9582 - * Export settings as JSON with masked API keys
9583 - *
9584 - * @return array The sanitized settings array
9585 - */
9586 -public static function mxchat_export_settings() {
9587 - $options = get_option( 'mxchat_options', array() );
9588 -
9589 - if ( ! is_array( $options ) ) {
9590 - return array();
9591 - }
9592 -
9593 - // List of API key fields to mask
9594 - $api_key_fields = array(
9595 - 'api_key',
9596 - 'xai_api_key',
9597 - 'claude_api_key',
9598 - 'deepseek_api_key',
9599 - 'voyage_api_key',
9600 - 'gemini_api_key',
9601 - 'openrouter_api_key',
9602 - 'loops_api_key',
9603 - 'brave_api_key',
9604 - 'live_agent_secret_key',
9605 - 'live_agent_bot_token',
9606 - 'telegram_bot_token',
9607 - 'telegram_webhook_secret',
9608 - 'woocommerce_consumer_key',
9609 - 'woocommerce_consumer_secret',
9610 - );
9611 -
9612 - // Mask API keys (show only last 4 characters)
9613 - foreach ( $api_key_fields as $field ) {
9614 - if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) {
9615 - $value = $options[ $field ];
9616 - if ( strlen( $value ) > 4 ) {
9617 - $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 );
9618 - } else {
9619 - $options[ $field ] = '****';
5446 + foreach ($selectors as $selector) {
5447 + $nodes = $xpath->query($selector);
5448 + if ($nodes->length > 0) {
5449 + $content = '';
5450 + foreach ($nodes as $node) {
5451 + $content .= $dom->saveHTML($node);
9620 5452 }
5453 + return $content;
9621 5454 }
9622 5455 }
9623 5456
9624 - // Add metadata
9625 - $export = array(
9626 - 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown',
9627 - 'export_date' => current_time( 'Y-m-d H:i:s' ),
9628 - 'wordpress_version' => get_bloginfo( 'version' ),
9629 - 'php_version' => phpversion(),
9630 - 'settings' => $options,
9631 - );
9632 -
9633 - return $export;
5457 + // Fallback: Return the entire body content if no specific selector matches
5458 + $body = $dom->getElementsByTagName('body');
5459 + return $body->length > 0 ? $dom->saveHTML($body->item(0)) : $html;
9634 5460 }
9635 -
9636 -/**
9637 - * Reset all settings to defaults
9638 - *
9639 - * @return bool Whether the reset was successful
9640 - */
9641 -public static function mxchat_reset_all_settings() {
9642 - // Delete main options
9643 - $deleted = delete_option( 'mxchat_options' );
9644 -
9645 - // Also clear the debug log
9646 - delete_option( 'mxchat_debug_log' );
9647 -
9648 - // Log the reset (will create new log since we just cleared it)
9649 - // We need to temporarily enable debug mode to log this
9650 - $temp_options = array( 'debug_mode' => 'on' );
9651 - update_option( 'mxchat_options', $temp_options );
9652 -
9653 - self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' );
9654 -
9655 - // Now delete again to trigger re-initialization
9656 - delete_option( 'mxchat_options' );
9657 -
9658 - return $deleted;
9659 -}
9660 -
9661 - // Method to append the chatbot to the body
9662 - public function mxchat_append_chatbot_to_body() {
9663 - $options = get_option('mxchat_options');
9664 - if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') {
9665 - echo do_shortcode('[mxchat_chatbot floating="yes"]');
9666 - }
9667 - }
9668 -
9669 -
9670 -
9671 -
9672 -
9673 5461 private function mxchat_fetch_loops_mailing_lists($api_key) {
9674 5462 $url = 'https://app.loops.so/api/v1/lists';
9675 5463 $response = wp_remote_get($url, array(
9676 5464 'headers' => array(
@@ -9688,8 +5476,12 @@
9688 5476
9689 5477 return isset($lists) && is_array($lists) ? $lists : array();
9690 5478 }
9691 5479
5480 +
5481 +
5482 +
5483 +
9692 5484 function mxchat_calculate_cosine_similarity($vec1, $vec2) {
9693 5485 if (empty($vec1) || empty($vec2)) {
9694 5486 return 0.0;
9695 5487 }
@@ -9710,435 +5502,8 @@
9710 5502 return $dot_product / (sqrt($norm_a) * sqrt($norm_b));
9711 5503 }
9712 5504 }
9713 5505
9714 -/**
9715 - * Validates nonce and deletes all chat prompts
9716 - */
9717 -public function mxchat_handle_delete_all_prompts() {
9718 - //error_log('=== DELETE ALL DEBUG START ===');
9719 -
9720 - // Verify nonce
9721 - if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) {
9722 - //error_log('DEBUG: Nonce verification failed');
9723 - wp_die(__('Nonce verification failed.', 'mxchat'));
9724 - }
9725 -
9726 - // Check permissions
9727 - if (!current_user_can('manage_options')) {
9728 - //error_log('DEBUG: Permission check failed');
9729 - wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat'));
9730 - }
9731 -
9732 - // Get bot_id and content type filter from POST data
9733 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default';
9734 - $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : '';
9735 -
9736 - $success = true;
9737 - $error_messages = array();
9738 -
9739 - // Get bot-specific Pinecone configuration
9740 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
9741 - $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id);
9742 -
9743 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
9744 -
9745 - if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) {
9746 - // Delete from Pinecone (with optional content type filter)
9747 - $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter);
9748 -
9749 - if (!$result['success']) {
9750 - $success = false;
9751 - $error_messages[] = $result['message'];
9752 - }
9753 -
9754 - } else {
9755 - // Delete from WordPress database
9756 - global $wpdb;
9757 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
9758 -
9759 - // Build WHERE conditions
9760 - $where_clauses = array();
9761 - $where_values = array();
9762 -
9763 - // Bot filter
9764 - if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) {
9765 - $where_clauses[] = 'bot_id = %s';
9766 - $where_values[] = $bot_id;
9767 - }
9768 -
9769 - // Content type filter
9770 - if (!empty($content_type_filter)) {
9771 - $where_clauses[] = 'content_type = %s';
9772 - $where_values[] = $content_type_filter;
9773 - }
9774 -
9775 - if (!empty($where_clauses)) {
9776 - $where_sql = implode(' AND ', $where_clauses);
9777 - $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values));
9778 - } else {
9779 - // No filters — delete all
9780 - $result = $wpdb->query("DELETE FROM {$table_name}");
9781 - }
9782 -
9783 - if ($result === false) {
9784 - $success = false;
9785 - $error_messages[] = 'Failed to delete from WordPress database';
9786 - }
9787 - }
9788 -
9789 - // Redirect back with a success message and bot_id
9790 - $redirect_url = add_query_arg(array(
9791 - 'page' => 'mxchat-prompts',
9792 - 'bot_id' => $bot_id,
9793 - 'all_deleted' => $success ? 'true' : 'false'
9794 - ), admin_url('admin.php'));
9795 -
9796 - wp_safe_redirect($redirect_url);
9797 - exit;
9798 -}
9799 -
9800 -
9801 -
9802 - /**
9803 - * Handles deletion prompt with nonce validation
9804 - */
9805 - public function mxchat_handle_delete_prompt() {
9806 - // Sanitize and validate nonce
9807 - $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
9808 - if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) {
9809 - wp_die(esc_html__('Nonce verification failed.', 'mxchat'));
9810 - }
9811 -
9812 - // Check permissions
9813 - if (!current_user_can('manage_options')) {
9814 - wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat'));
9815 - }
9816 -
9817 - // Get ID and source parameters
9818 - $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : '';
9819 - $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
9820 -
9821 - if (empty($id)) {
9822 - wp_die(esc_html__('Invalid prompt ID.', 'mxchat'));
9823 - }
9824 -
9825 - $success = false;
9826 - $error_message = '';
9827 -
9828 - // Check if Pinecone is enabled and determine source automatically if not specified
9829 - $pinecone_options = get_option('mxchat_pinecone_addon_options', array());
9830 - $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1';
9831 -
9832 - // If source is not specified, determine based on Pinecone configuration
9833 - if (empty($source)) {
9834 - $source = $use_pinecone ? 'pinecone' : 'wordpress';
9835 - }
9836 -
9837 - if ($source === 'pinecone' || $use_pinecone) {
9838 - //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id);
9839 -
9840 - // Handle Pinecone deletion
9841 - if (empty($pinecone_options['mxchat_pinecone_host']) ||
9842 - empty($pinecone_options['mxchat_pinecone_api_key'])) {
9843 - wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat'));
9844 - }
9845 -
9846 - // Delete from Pinecone using the vector ID directly
9847 - $pinecone_manager = MxChat_Pinecone_Manager::get_instance();
9848 - $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id(
9849 - $id,
9850 - $pinecone_options['mxchat_pinecone_api_key'],
9851 - $pinecone_options['mxchat_pinecone_host']
9852 - );
9853 - if ($result['success']) {
9854 - $success = true;
9855 -
9856 - // Remove from vector cache
9857 - $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id);
9858 - $pinecone_manager->mxchat_remove_from_processed_content_caches($id);
9859 -
9860 - set_transient('mxchat_admin_notice_success',
9861 - esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30);
9862 - } else {
9863 - $error_message = $result['message'];
9864 - set_transient('mxchat_admin_notice_error',
9865 - esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30);
9866 - }
9867 - } else {
9868 - //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id);
9869 -
9870 - // Handle WordPress database deletion
9871 - global $wpdb;
9872 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
9873 -
9874 - // Clear cache and delete prompt
9875 - wp_cache_delete('prompt_' . $id, 'mxchat_prompts');
9876 -
9877 - $result = $wpdb->delete(
9878 - $table_name,
9879 - array('id' => intval($id)),
9880 - array('%d')
9881 - );
9882 -
9883 - if ($result !== false) {
9884 - $success = true;
9885 - set_transient('mxchat_admin_notice_success',
9886 - esc_html__('Entry deleted successfully.', 'mxchat'), 30);
9887 - } else {
9888 - set_transient('mxchat_admin_notice_error',
9889 - esc_html__('Failed to delete entry from database.', 'mxchat'), 30);
9890 - }
9891 - }
9892 -
9893 - // Redirect back to the prompts page
9894 - wp_safe_redirect(add_query_arg(
9895 - array(
9896 - 'page' => 'mxchat-prompts',
9897 - 'deleted' => $success ? 'true' : 'false'
9898 - ),
9899 - admin_url('admin.php')
9900 - ));
9901 - exit;
9902 - }
9903 -
9904 -
9905 -
9906 -
9907 - /**
9908 - * Averages multiple vectors into a single vector
9909 - */
9910 - private function mxchat_average_vectors($vectors) {
9911 - $vector_length = count($vectors[0]);
9912 - $sum_vector = array_fill(0, $vector_length, 0);
9913 -
9914 - foreach ($vectors as $vector) {
9915 - for ($i = 0; $i < $vector_length; $i++) {
9916 - $sum_vector[$i] += $vector[$i];
9917 - }
9918 - }
9919 -
9920 - // Divide each component by the number of vectors to get the average
9921 - $num_vectors = count($vectors);
9922 - for ($i = 0; $i < $vector_length; $i++) {
9923 - $sum_vector[$i] /= $num_vectors;
9924 - }
9925 -
9926 - return $sum_vector;
9927 - }
9928 -
9929 -
9930 -
9931 -
9932 - /**
9933 - * Generates embeddings from input text for MXChat
9934 - */
9935 - public function mxchat_generate_embedding($text) {
9936 - // Enable detailed logging for debugging
9937 - //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes');
9938 - //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...');
9939 -
9940 - $options = get_option('mxchat_options');
9941 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
9942 - //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model);
9943 -
9944 - // Determine provider and endpoint
9945 - if (strpos($selected_model, 'voyage') === 0) {
9946 - $api_key = $options['voyage_api_key'] ?? '';
9947 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
9948 - $provider_name = 'Voyage AI';
9949 - //error_log('[MXCHAT-EMBED] Using Voyage AI API');
9950 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
9951 - $api_key = $options['gemini_api_key'] ?? '';
9952 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
9953 - $provider_name = 'Google Gemini';
9954 - //error_log('[MXCHAT-EMBED] Using Google Gemini API');
9955 - } else {
9956 - $api_key = $options['api_key'] ?? '';
9957 - $endpoint = 'https://api.openai.com/v1/embeddings';
9958 - $provider_name = 'OpenAI';
9959 - //error_log('[MXCHAT-EMBED] Using OpenAI API');
9960 - }
9961 -
9962 - //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint);
9963 -
9964 - if (empty($api_key)) {
9965 - $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name);
9966 - //error_log('[MXCHAT-EMBED] Error: ' . $error_message);
9967 - return $error_message;
9968 - }
9969 -
9970 - // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75)
9971 - $estimated_tokens = ceil(str_word_count($text) / 0.75);
9972 - //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens);
9973 -
9974 - if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) {
9975 - //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)');
9976 - // Consider truncating text here
9977 - }
9978 -
9979 - // Prepare request body based on provider
9980 - if (strpos($selected_model, 'gemini-embedding') === 0) {
9981 - // Gemini API format
9982 - $request_body = array(
9983 - 'model' => 'models/' . $selected_model,
9984 - 'content' => array(
9985 - 'parts' => array(
9986 - array('text' => $text)
9987 - )
9988 - )
9989 - );
9990 -
9991 - // Set output dimensionality to 1536 for consistency with other models
9992 - $request_body['outputDimensionality'] = 1536;
9993 - } else {
9994 - // OpenAI/Voyage API format
9995 - $request_body = array(
9996 - 'model' => $selected_model,
9997 - 'input' => $text
9998 - );
9999 -
10000 - // Add output_dimension for voyage-3-large model
10001 - if ($selected_model === 'voyage-3-large') {
10002 - $request_body['output_dimension'] = 2048;
10003 - }
10004 - }
10005 -
10006 - //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model);
10007 -
10008 - // Prepare headers based on provider
10009 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10010 - // Gemini uses API key as query parameter
10011 - $endpoint .= '?key=' . $api_key;
10012 - $headers = array(
10013 - 'Content-Type' => 'application/json'
10014 - );
10015 - } else {
10016 - // OpenAI/Voyage use Bearer token
10017 - $headers = array(
10018 - 'Authorization' => 'Bearer ' . $api_key,
10019 - 'Content-Type' => 'application/json'
10020 - );
10021 - }
10022 -
10023 - // Make API request
10024 - //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint);
10025 - $response = wp_remote_post($endpoint, array(
10026 - 'body' => wp_json_encode($request_body),
10027 - 'headers' => $headers,
10028 - 'timeout' => 60 // Increased timeout for large inputs
10029 - ));
10030 -
10031 - // Handle wp_remote_post errors
10032 - if (is_wp_error($response)) {
10033 - $error_message = $response->get_error_message();
10034 - //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message);
10035 - return 'Connection error: ' . $error_message;
10036 - }
10037 -
10038 - // Get and check HTTP response code
10039 - $http_code = wp_remote_retrieve_response_code($response);
10040 - //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code);
10041 -
10042 - if ($http_code !== 200) {
10043 - $error_body = wp_remote_retrieve_body($response);
10044 - //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body);
10045 -
10046 - // Try to parse error for more details
10047 - $error_json = json_decode($error_body, true);
10048 - if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) {
10049 - $error_type = $error_json['error']['type'] ?? 'unknown';
10050 - $error_message = $error_json['error']['message'] ?? 'No message';
10051 - //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type);
10052 - //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message);
10053 -
10054 - // Customize error message for common API errors
10055 - if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) {
10056 - $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name);
10057 - } elseif ($error_type === 'authentication_error') {
10058 - $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name);
10059 - }
10060 -
10061 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
10062 - return $error_message;
10063 - }
10064 -
10065 - $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code);
10066 - //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message);
10067 - return $error_message;
10068 - }
10069 -
10070 - // Parse response body
10071 - $response_body = wp_remote_retrieve_body($response);
10072 - //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes');
10073 -
10074 - $response_data = json_decode($response_body, true);
10075 -
10076 - if (json_last_error() !== JSON_ERROR_NONE) {
10077 - $error = json_last_error_msg();
10078 - //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error);
10079 - //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200));
10080 - return "Failed to parse API response: $error";
10081 - }
10082 -
10083 - // Handle different response formats based on provider
10084 - if (strpos($selected_model, 'gemini-embedding') === 0) {
10085 - // Gemini API response format
10086 - if (isset($response_data['embedding']['values'])) {
10087 - $embedding_dimensions = count($response_data['embedding']['values']);
10088 - //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions');
10089 -
10090 - // Check if embedding dimensions are as expected (should be 1536)
10091 - if ($embedding_dimensions !== 1536) {
10092 - //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions);
10093 - }
10094 -
10095 - MxChat_Utils::stamp_active_embedding_model($selected_model);
10096 - return $response_data['embedding']['values'];
10097 - } else {
10098 - //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response');
10099 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
10100 -
10101 - if (isset($response_data['error'])) {
10102 - $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']);
10103 - //error_log('[MXCHAT-EMBED] ' . $error_message);
10104 - return $error_message;
10105 - }
10106 -
10107 - $error_message = "Invalid Gemini API response format: No embedding found";
10108 - //error_log('[MXCHAT-EMBED] ' . $error_message);
10109 - return $error_message;
10110 - }
10111 - } else {
10112 - // OpenAI/Voyage API response format
10113 - if (isset($response_data['data'][0]['embedding'])) {
10114 - $embedding_dimensions = count($response_data['data'][0]['embedding']);
10115 - //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions');
10116 -
10117 - // Check if embedding dimensions are as expected
10118 - if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) ||
10119 - ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) {
10120 - //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions');
10121 - }
10122 -
10123 - MxChat_Utils::stamp_active_embedding_model($selected_model);
10124 - return $response_data['data'][0]['embedding'];
10125 - } else {
10126 - //error_log('[MXCHAT-EMBED] Error: No embedding found in response');
10127 - //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data)));
10128 -
10129 - if (isset($response_data['error'])) {
10130 - $error_message = "API Error in response: " . wp_json_encode($response_data['error']);
10131 - //error_log('[MXCHAT-EMBED] ' . $error_message);
10132 - return $error_message;
10133 - }
10134 -
10135 - $error_message = "Invalid API response format: No embedding found";
10136 - //error_log('[MXCHAT-EMBED] ' . $error_message);
10137 - return $error_message;
10138 - }
10139 - }
10140 - }
10141 5506
10142 5507
10143 5508
10144 5509 }